Q: Why can't update my form even though my session is working php So i want a very simple update page like this example:
<?php
            $sql_article = "SELECT* FROM articles WHERE article_unique_id = '".  $_SESSION['article_unique_id']."' ";
            $result_article = $conn->query($sql_article);
            if ($result_article->num_rows > 0) {
              while($row = $result_article->fetch_assoc())
{?>
         <form action="trry15.php" method="post">
           <input type="text" name="title" value="<?php echo $row['title'] ?>">
         <input type="submit" name="submitUpdate" value="Submit"></form> <?php }}?>

and to this point code works fine session works and ect.
but when I write my update code
if (isset($_POST['submitUpdate'])) {
    $update_title=$_POST['title'];

    $sql_update_title = "UPDATE `articles` SET title='$update_title' WHERE article_unique_id = '".  $_SESSION['article_unique_id']."'";
    $result_update_title=$conn->query($sql_update_title);

}

This dosent work.
But if change article_unique_id = '".  $_SESSION['article_unique_id']."'"; to
article_unique_id = '12'";

The code works. And I don't what is happening. I have session start function and  $_SESSION['article_unique_id']=$_GET['article_id'];


Q: How to add known_hosts for passwordless ssh within docker container in docker-compse.yml? I want to have passwordless ssh within two docker containers. How to add known_hosts entry for that using docker-compose.yml file
I want to implement ansible on docker env. To deploy and run rpm on deployment node, I need passwordless ssh from container1 to container2. For that I have to add known_hosts key of container1 in container2 node.
How to do this ???

A: I don't know any solution using docker-compose.yml. The solution I propose implies create a Dockerfile and execute (creating a shellscript as CMD):
ssh-keyscan -t rsa whateverdomain >> ~/.ssh/known_hosts

Maybe you can scan /ect/hosts or pass a variable as ENV.

A: try to mount it from host to container. .
--volume local/path/to/known_hosts:/etc/ssh/ssh_known_hosts
in case it didnt work, take a look at some similar case related to ssh key in docker like : this
and this


Q: Is it a good practice to use alternate exchange in RabbitMQ as dead letter exchange? I know that RabbitMQ has alternative and dead letter exchange types.
Since we don't have mapped queues for some message, from my perspective it is some kind of problem when we don't know what the message is. In this case we use alternative exchange to rout the message to another exchange by default (that can solve our routing problem).
Is it a good practise to use alternative exchange as dead letter exchange simultaneously?


Q: Where do I merge or add the drop down menu script on the header. Jsfiddle I'm trying to merge 2 codes. I found the two codes I'm looking for. I'm really new @ this so please under stand.
This is the header footer & background:
http://jsfiddle.net/F6dez/
This is the drop down menu:
http://jsfiddle.net/Mrdel/Wxs5n/2/
This is my attempt to merge the two:
I tried to leave a link but it won't let me leave more then 2 links :/
Heres the code for the menu:
HTML:

    Music

New Tracks

Old Tunes

Downloads

Upcoming

And the css:
ul { list-style: none; padding: 0; margin: 0;}

/* Style */

a {
  color: #000;
 display: block;
 font-size: 14px;
 text-decoration: none;
 font-family: 'Open Sans', serif;
 }
 nav {
 width: 100%;
 height: 45px;
 }
 #nav ul li:hover,
 #nav > li:hover {
 background: #2e98d5;
 }
 #nav ul > li:hover > a,
#nav > li:hover > a {
 color: #fff;
 }
 #nav > li {
 float: left;
  position: relative;
  }
  #nav > li > a {
  padding: 13px 30px;
   height: 20px;
  }

#nav > li:hover ul {
visibility: visible;
-webkit-transition-delay: 0s;
-moz-transition-delay: 0s;
-o-transition-delay: 0s;
transition-delay: 0s;
}
#nav ul {
 top: 46px;
width: 170px;
position: absolute;
background-color: #eee;
z-index: 1;
visibility: hidden;
-webkit-transition-property: visibility;
 -moz-transition-property: visibility;
 -o-transition-property: visibility;
 transition-property: visibility;

 -webkit-transition-duration: 0s;
 -moz-transition-duration: 0s;
 -o-transition-duration: .0s;
 transition-duration: 0s;

 -webkit-transition-delay: .25s;
 -moz-transition-delay: .25s;
 -o-transition-delay: .25s;
 transition-delay: .25s;
 }

/* The slide */
#nav li li a {
height: 0px;
padding: 0px 30px;
opacity: 0;
-webkit-transition-property: height, padding, opacity;
-moz-transition-property: height, padding, opacity;
-o-transition-property: height, padding, opacity;
transition-property: height, padding, opacity;

-webkit-transition-duration: .25s, .25s, .08s;
-moz-transition-duration: .25s, .25s, .08s;
-o-transition-duration: .25s, .25s, .08s;
 transition-duration: .25s, .25s, .08s;

-webkit-transition-delay: 0s, 0s, .05s;
 -moz-transition-delay: 0s, 0s, .05s;
 -o-transition-delay: 0s, 0s, .05s;
 transition-delay: 0s, 0s, .05s;
 }
 #nav li:hover li a {
 height: 20px;
  padding: 13px 30px;
 opacity: 1;
 }

Heres the code for the background:
HTML:
<!Doctype html>

    <link rel="stylesheet" type="text/css" href="css/style.css"/>

            This is header

First line...............

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Last line................

            This is footer

And the css:
 html {
 height:100%;
 max-height:100%;
 padding:0;
 margin:0;
 border:0;
 overflow: hidden;
 }
 body {
 height:100%;
 max-height:100%;
 overflow:hidden;
 padding:0;
 margin:0;
 border:0
 font: 12px Verdana, Helvetica, sans-serif;
 color: #F3F3F3;
 }
 .container {
 width : 100%;
 height: 100%;
 max-height:100%;
 }
 .header {
 position:absolute;
 margin:0;
 top:0;
 display:block;
 width:100%;
 height:80px;
 z-index:5;
 background-color: #656565;
 text-align : center;
 right:18px;
 line-height: 80px;
 font-size:2em;
   }
 .footer {
 position:absolute;
 margin:0;
 bottom:-1px;
 display:block;
 width:100%;
 z-index:4;
 height : 80px;
 background-color: #656565;
 text-align : center;
 right:18px;
 line-height: 80px;
 font-size:2em;
 }
 .content {
 display:block;
 height:100%;
 max-height:100%;
 overflow:auto;
 position:relative;
 z-index:3;
 background-color: #909090;
 text-align : center;
 }
 .gap {height : 80px;}

A: I'm not entirely sure I understand what you're looking for here, since it should be as easy as copying the menu code:

    Music

New Tracks

Old Tunes

Downloads

Upcoming

and pasting it into the head container:
http://jsfiddle.net/LH5TC/


Q: Server to Server communication with IBM SBT I would  like to use the IBM SBT for server to server communication instead of displaying data from , for instance, connections at the user. In this particular usecase I would like to have data updated in Connections whenever a user saves or edits data.
Because we are not using oAuth we would like to use Basic authentication without prompting the user for authentication. Are there any examples how to do is?

A: yes there are some examples of using Pure Java, no J2EE.
http://bastide.org/2014/01/28/how-to-develop-a-simple-java-integration-with-the-ibm-social-business-toolkit-sdk/
and
https://github.com/OpenNTF/SocialSDK/blob/master/samples/java/sbt.sample.app/src/com/ibm/sbt/sample/app/BlogServiceApp.java
Essentially, you'll need the dependent jar files.
once, you have the jar files you need to configure your class so you can get an Endpoint
once you have the endpoint you can use the endpoint in one of the top level services such
as ForumsService
then you can use the ForumsService to call back to Connections


Q: Number of Pairs of Subsets Find the number of Pairs $(A,B)$ of subsets of $[n]$ such that $A ⊆ B$?
I just need clarification in my thought process. My professor's wording at times can through me off. I just want to know if I am on the right track.
We will have $3$ regions:
1.Outside $B$
2.Inside $A$
3. Inside $B$, Outside $A$
I believe the number of pairs is $3^n$ but I am not sure. Any help would be appreciated.

A: You are right; for each element in $[n]$, you have 3 choices:
1) Include it in A $\hspace{.2 in}$ 2) Include it in B, but not in A $\hspace{.2 in}$ 3) Include it in neither; so this gives $3^n$ pairs.

Another way to do this would be to let $k$ be the number of elements in A, where $0\le k\le n$.
There are $\binom{n}{k}$ ways to choose the elements of A, and then there are
$2^{n-k}$ ways to select a subset of the remaining $n-k$ elements to include with A to get B;
so this gives a total of $\displaystyle\sum_{k=0}^n2^{n-k}\binom{n}{k}=3^n$ pairs using the Binomial Theorem.

A: Using your approach you can first decide the number of elements, $k$, that we want $B$, we can the place $k$ elements into $B$ in $\binom{n}{k}$ ways and for each of these elements we have the option of putting it in $A$ or putting it outside of $A$. This gives that for each given $k$ there are $\binom{n}{k}2^k$ such pairs of subsets. Summing over all valid $k$ and applying the binomial theorem gives the result of $3^n$.


Q: JS - function take a double result I got problem with this script:

<button onclick="clearInterval(stop)">stop!</button>

On marks! Start!

The script counts down from 400 to 0, with a variable interval = 40. When the script runs it subtracts 80 instead of 40. The result is double and I don't know why.
Can you help me?

A: You're calling counter() twice, subtracting 40 each time, call it just once
var start = 400;
var interval = 40;

function counter() {
    return start -= interval;
}

var stop = setInterval(function() {
    var count = counter();
    if (count > 0) {
        document.getElementById("test").innerHTML = count;
    } else {
        clearInterval(stop);
    }
}, 1000);


Q: Does Git merge to master delete unchanged files? I have a two branch first one "master" second one "newFeature"
In the master branch, I add some file and change some functions it does not exist in newFeature branch and the same in newFeature have added some new files/code AND Change file it exists in two branches and I want to apply when merged
Now when I want to merge newFeature to master,
Should I lose something in the master or other branch?

A: Git's merge operation considers exactly three points when doing a merge: the two heads (usually branches) that you want to merge, and the merge base, which is usually the point at which one was forked from the other.
When a merge occurs, Git considers the changes computed between each head and the merge base.  It then produces a result exactly like the merge base, but with both sets of changes added.  In other words:

*

*If you made a change on one side and not the other, Git will include the change.  A change in this case includes the addition, removal, or modification of a file or part of it.

*If you made a change to the same location on both sides, Git will produce a conflict.

*If you made no changes to a file or part of it, Git will include those portions unchanged.

So in your case, you've only added and modified things, so the merge result will include only additions and modifications, not removals.  It is possible you'll see a conflict, though.


Q: Symfony All blank pages after cache clear I recently was making changes to my Symfony 2 site and then did a clear cache command on the site. Afterwards when I returned to the site the pages were blank.
Here's the command I ran
app/console cache:clear --env=prod

I've heard that it might be related to file permissions on the cache folder, but I'm not sure.
I logged in at the root level to be able to run the run the above command becuase I was getting an 'access denied' error when i was logged in at the user level.
Any helped/insight would be greatly appreciated.

A: You seem to have run cache:clear as root user without the --no-warmup flag.
Now symfony has warmed the cache after clearing it using the root account which would result in the newly created cache files being owned by your root user. Depending on your umask the webserver-user now might not have r+w access to these files.
Make sure your webserver-user / cgi-user has read and write access to your cache folder or give the ownership back to this user.
sudo chown webserver_user:webserver_group -R app/cache
sudo chmod 770 -R app/cache  # or use acl to permit read/write to your webserver-user

A: Make sure the permissions for the app/cache and app/logs are set correctly for both the web server user and the CLI user.
The Symfony Book has instructions on how to do it.
If your OS supportschmod +a (OSX) you can do the following:
$ rm -rf app/cache/*
$ rm -rf app/logs/*
$ sudo chmod +a "www-data allow delete,write,append,file_inherit,directory_inherit" app/cache app/logs
$ sudo chmod +a "`whoami` allow delete,write,append,file_inherit,directory_inherit" app/cache app/logs

If your OS supports setfacl (Ubuntu, for example) and ACL support is enabled, you can do the following:
$ sudo setfacl -R -m u:www-data:rwX -m u:`whoami`:rwX app/cache app/logs
$ sudo setfacl -dR -m u:www-data:rwx -m u:`whoami`:rwx app/cache app/logs

Note: both examples assume that the username for the web server user is www-data


Q: How can I test this async piece of code in Flutter using Mockito? I am trying to write some test for an app, but I can't test values stored in a provider. I am relatively new to testing, so there might be something that I am doing wrong, but anyway. What I want to test is to verify is two values are not the same, which should be the expected behavior, but I just can't make it pass.
This is the code that I want to test:
class RSAKeysProvider {
    KeyPair? _keyPair;

    KeyPair? get keyPair => _keyPair;
    set setKeyPair(KeyPair keyPair) => _keyPair = keyPair;

    Future<void> generate(String bits) async {
        var keyPair = await RSA.generate(int.parse(bits));
        _keyPair = keyPair;
        notifyListeners();
    }
}

I need to first call the generate() function, which will set the keyPair to actual values, and then check if keyPair.publicKey is different than keyPair.privateKey, but it gives me an error when I try to call generate() with await inside a test.
This is what I have for now, but it doesn't work. The test breaks when it cames to the line "await rsaKeys.generate('2048'). What can I do to make it work? I know the condition is not checking if both are different, but it is just a placeholder, I can't make the code arrive there!
test('Public and private key should be different', () async {
      final MockRSAKeysProvider rsaKeys = MockRSAKeysProvider();

      when(rsaKeys.generate(any)).thenAnswer((value) async {
        KeyPair keyPair = await RSA.generate(2048);
        rsaKeys.setKeyPair = keyPair;
      });

      await rsaKeys.generate('2048');

      expect(rsaKeys.keyPair?.privateKey, isNotNull);
      expect(rsaKeys.keyPair?.publicKey, isNotNull);
    });

When it arrives at "await rsaKeys.generate('2048'), it gives me this error:
Invalid argument(s): Failed to load dynamic library 'librsa_bridge.dylib': dlopen(librsa_bridge.dylib, 0x0001): tried: 'librsa_bridge.dylib' (no such file), '/System/Volumes/Preboot/Cryptexes/OSlibrsa_bridge.dylib' (no such file), '/opt/homebrew/Caskroom/flutter/3.7.3/flutter/bin/cache/artifacts/engine/darwin-x64/./librsa_bridge.dylib' (no such file), '/opt/homebrew/Caskroom/flutter/3.7.3/flutter/bin/cache/artifacts/engine/darwin-x64/../../../librsa_bridge.dylib' (no such file), '/opt/homebrew/Caskroom/flutter/3.7.3/flutter/bin/cache/artifacts/engine/darwin-x64/Frameworks/librsa_bridge.dylib' (no such file), '/opt/homebrew/Caskroom/flutter/3.7.3/flutter/bin/cache/artifacts/engine/darwin-x64/./librsa_bridge.dylib' (no such file), '/opt/homebrew/Caskroom/flutter/3.7.3/flutter/bin/cache/artifacts/engine/darwin-x64/../../../librsa_bridge.dylib' (no such file), '/opt/homebrew/Caskroom/flutter/3.7.3/flutter/bin/cache/artifacts/engine/darwin-x64/Frameworks/librsa_bridge.dylib' (no such file), '/usr/lib/librsa_bridge.dylib' (no such file, not in dyld cache), 'librsa_bridge.dylib' (no such file), '/usr/lib/librsa_bridge.dylib' (no such file, not in dyld cache)
  dart:ffi                                     new DynamicLibrary.open
  package:fast_rsa/bridge/binding.dart 117:33  Binding.openLib
  package:fast_rsa/bridge/binding.dart 26:16   new Binding._internal
  package:fast_rsa/bridge/binding.dart 17:45   Binding._singleton
  package:fast_rsa/bridge/binding.dart         Binding._singleton
  package:fast_rsa/bridge/binding.dart 22:12   new Binding
  package:fast_rsa/fast_rsa.dart 40:32         RSA.bindingEnabled
  package:fast_rsa/fast_rsa.dart               RSA.bindingEnabled
  package:fast_rsa/fast_rsa.dart 43:9          RSA._call
  package:fast_rsa/fast_rsa.dart 79:22         RSA._keyPairResponse
  package:fast_rsa/fast_rsa.dart 437:18        RSA.generate
  test/rsa_keys.test.dart 32:37                main.<fn>.<fn>.<fn>
  package:mockito/src/mock.dart 185:45         Mock.noSuchMethod
  test/rsa_keys.test.mocks.dart 75:53          MockRSAKeysProvider.generate
  test/rsa_keys.test.dart 36:21                main.<fn>.<fn>

A: Your stub calls RSA.generate, so it depends on the RSA.generate implementation which involves FFI and loading a dynamically-loaded library on whatever platform you run tests on.  Unless you're trying to test package:fastrsa itself, you should avoid calling things such as RSA.generate anyway; that is what you should be replacing with a stub.
The point of a Mock is to test how other code interacts with the mocked object. You cannot use a MockRSAKeysProvider to test the behavior of an RSAKeysProvider itself.  If you want to test the behavior of your RSAKeysProvider class, you could change it to accept a stub for RSA.generate:
class RSAKeysProvider {
  KeyPair? _keyPair;

  KeyPair? get keyPair => _keyPair;
  set setKeyPair(KeyPair keyPair) => _keyPair = keyPair;

  Future<void> generate(String bits, {Future<KeyPair> Function(int)? generate}) async {
    generate ??= RSA.generate;
    var keyPair = await generate(int.parse(bits));
    _keyPair = keyPair;
    notifyListeners();
  }
}

and then in your test:
Future<KeyPair> fakeGenerate(int bits) async {
  return KeyPair('fakePublicKey', 'fakePrivateKey'); // Or use precomputed values.
}

test('Public and private key should not be null when generated', () async {
  final RSAKeysProvider rsaKeys = RSAKeysProvider();
  await rsaKeys.generate('2048', generate: fakeGenerate);
  expect(rsaKeys.keyPair?.privateKey, isNotNull);
  expect(rsaKeys.keyPair?.publicKey, isNotNull);
});


Q: MVVM Sync Collections Is there a standardized way to sync a collection of Model objects with a collection of matching ModelView objects in C# and WPF?  I'm looking for some kind of class that would keep the following two collections synced up assuming I only have a few apples and I can keep them all in memory.
Another way to say it, I want to make sure if I add an Apple to the Apples collection I would like to have an AppleModelView added to the AppleModelViews collection.  I could write my own by listening to each collections' CollectionChanged event.  This seems like a common scenario that someone smarter than me has defined "the right way" to do it.
public class BasketModel
{
    public ObservableCollection<Apple> Apples { get; }
}

public class BasketModelView
{
    public ObservableCollection<AppleModelView> AppleModelViews { get; }
}

A: I use lazily constructed, auto-updating collections:
public class BasketModelView
{
    private readonly Lazy<ObservableCollection<AppleModelView>> _appleViews;

    public BasketModelView(BasketModel basket)
    {
        Func<AppleModel, AppleModelView> viewModelCreator = model => new AppleModelView(model);
        Func<ObservableCollection<AppleModelView>> collectionCreator =
            () => new ObservableViewModelCollection<AppleModelView, AppleModel>(basket.Apples, viewModelCreator);

        _appleViews = new Lazy<ObservableCollection<AppleModelView>>(collectionCreator);
    }

    public ObservableCollection<AppleModelView> Apples
    {
        get
        {
            return _appleViews.Value;
        }
    }
}

Using the following ObservableViewModelCollection<TViewModel, TModel>:
namespace Client.UI
{
    using System;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.Collections.Specialized;
    using System.Diagnostics.Contracts;
    using System.Linq;

    public class ObservableViewModelCollection<TViewModel, TModel> : ObservableCollection<TViewModel>
    {
        private readonly ObservableCollection<TModel> _source;
        private readonly Func<TModel, TViewModel> _viewModelFactory;

        public ObservableViewModelCollection(ObservableCollection<TModel> source, Func<TModel, TViewModel> viewModelFactory)
            : base(source.Select(model => viewModelFactory(model)))
        {
            Contract.Requires(source != null);
            Contract.Requires(viewModelFactory != null);

            this._source = source;
            this._viewModelFactory = viewModelFactory;
            this._source.CollectionChanged += OnSourceCollectionChanged;
        }

        protected virtual TViewModel CreateViewModel(TModel model)
        {
            return _viewModelFactory(model);
        }

        private void OnSourceCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            switch (e.Action)
            {
            case NotifyCollectionChangedAction.Add:
                for (int i = 0; i < e.NewItems.Count; i++)
                {
                    this.Insert(e.NewStartingIndex + i, CreateViewModel((TModel)e.NewItems[i]));
                }
                break;

            case NotifyCollectionChangedAction.Move:
                if (e.OldItems.Count == 1)
                {
                    this.Move(e.OldStartingIndex, e.NewStartingIndex);
                }
                else
                {
                    List<TViewModel> items = this.Skip(e.OldStartingIndex).Take(e.OldItems.Count).ToList();
                    for (int i = 0; i < e.OldItems.Count; i++)
                        this.RemoveAt(e.OldStartingIndex);

                    for (int i = 0; i < items.Count; i++)
                        this.Insert(e.NewStartingIndex + i, items[i]);
                }
                break;

            case NotifyCollectionChangedAction.Remove:
                for (int i = 0; i < e.OldItems.Count; i++)
                    this.RemoveAt(e.OldStartingIndex);
                break;

            case NotifyCollectionChangedAction.Replace:
                // remove
                for (int i = 0; i < e.OldItems.Count; i++)
                    this.RemoveAt(e.OldStartingIndex);

                // add
                goto case NotifyCollectionChangedAction.Add;

            case NotifyCollectionChangedAction.Reset:
                Clear();
                for (int i = 0; i < e.NewItems.Count; i++)
                    this.Add(CreateViewModel((TModel)e.NewItems[i]));
                break;

            default:
                break;
            }
        }
    }
}

A: Well first of all, I don't think there is a single "right way" to do this. It depends entirely on your application. There are more correct ways and less correct ways.
That much being said, I am wondering why you would need to keep these collections "in sync." What scenario are you considering that would make them go out of sync? If you look at the sample code from Josh Smith's MSDN article on M-V-VM, you will see that the majority of the time, the Models are kept in sync with the ViewModels simply because every time a Model is created, a ViewModel is also created. Like this:
void CreateNewCustomer()
{
    Customer newCustomer = Customer.CreateNewCustomer();
    CustomerViewModel workspace = new CustomerViewModel(newCustomer, _customerRepository);
    this.Workspaces.Add(workspace);
    this.SetActiveWorkspace(workspace);
}

I am wondering, what prevents you from creating an AppleModelView every time you create an Apple? That seems to me to be the easiest way of keeping these collections "in sync," unless I have misunderstood your question.

A: You can find an example (and explanations) here too : http://blog.lexique-du-net.com/index.php?post/2010/03/02/M-V-VM-How-to-keep-collections-of-ViewModel-and-Model-in-sync
Hope this help

A: I may not exactly understand your requirements however the way I have handled a similar situation is to use CollectionChanged event on the ObservableCollection and simply create/destroy the view models as required.
void OnApplesCollection_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
  // Only add/remove items if already populated.
  if (!IsPopulated)
    return;

  Apple apple;

  switch (e.Action)
  {
    case NotifyCollectionChangedAction.Add:
      apple = e.NewItems[0] as Apple;
      if (apple != null)
        AddViewModel(asset);
      break;
    case NotifyCollectionChangedAction.Remove:
      apple = e.OldItems[0] as Apple;
      if (apple != null)
        RemoveViewModel(apple);
      break;
  }

}

There can be some performance issues when you add/remove a lot of items in a ListView.
We have solved this by: Extending the ObservableCollection to have an AddRange, RemoveRange, BinaryInsert methods and adding events that notify others the collection is being changed. Together with an extended CollectionViewSource that temporary disconnects the source when the collection is changed it works nicely.
HTH,
Dennis

A: The «Using MVVM to provide undo/redo. Part 2: Viewmodelling lists» article provides the MirrorCollection<V, D> class to achieve the view-model and model collections synchronization.
Additional references

*

*Original link (currently, it is not available): Notify Changed » Blog Archive » Using MVVM to provide undo/redo. Part 2: Viewmodelling lists.

A: OK I have a nerd crush on this answer so I had to share this abstract factory I added to it to support my ctor injection.
using System;
using System.Collections.ObjectModel;

namespace MVVM
{
    public class ObservableVMCollectionFactory<TModel, TViewModel>
        : IVMCollectionFactory<TModel, TViewModel>
        where TModel : class
        where TViewModel : class
    {
        private readonly IVMFactory<TModel, TViewModel> _factory;

        public ObservableVMCollectionFactory( IVMFactory<TModel, TViewModel> factory )
        {
            this._factory = factory.CheckForNull();
        }

        public ObservableCollection<TViewModel> CreateVMCollectionFrom( ObservableCollection<TModel> models )
        {
            Func<TModel, TViewModel> viewModelCreator = model => this._factory.CreateVMFrom(model);
            return new ObservableVMCollection<TViewModel, TModel>(models, viewModelCreator);
        }
    }
}

Which builds off of this:
using System.Collections.ObjectModel;

namespace MVVM
{
    public interface IVMCollectionFactory<TModel, TViewModel>
        where TModel : class
        where TViewModel : class
    {
        ObservableCollection<TViewModel> CreateVMCollectionFrom( ObservableCollection<TModel> models );
    }
}

And this:
namespace MVVM
{
    public interface IVMFactory<TModel, TViewModel>
    {
        TViewModel CreateVMFrom( TModel model );
    }
}

And here is the null checker for completeness:
namespace System
{
    public static class Exceptions
    {
        /// <summary>
        /// Checks for null.
        /// </summary>
        /// <param name="thing">The thing.</param>
        /// <param name="message">The message.</param>
        public static T CheckForNull<T>( this T thing, string message )
        {
            if ( thing == null ) throw new NullReferenceException(message);
            return thing;
        }

        /// <summary>
        /// Checks for null.
        /// </summary>
        /// <param name="thing">The thing.</param>
        public static T CheckForNull<T>( this T thing )
        {
            if ( thing == null ) throw new NullReferenceException();
            return thing;
        }
    }
}

A: While Sam Harwell's solution is pretty good already, it is subject to two problems:

*

*The event handler that is registered here this._source.CollectionChanged += OnSourceCollectionChanged is never unregistered, i.e. a this._source.CollectionChanged -= OnSourceCollectionChanged is missing.

*If event handlers are ever attached to events of view models generated by the viewModelFactory, there is no way of knowing when these event handlers may be detached again. (Or generally speaking: You cannot prepare the generated view models for "destruction".)

Therefore I propose a solution that fixes both (short) shortcomings of Sam Harwell's approach:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Diagnostics.Contracts;
using System.Linq;

namespace Helpers
{
    public class ObservableViewModelCollection<TViewModel, TModel> : ObservableCollection<TViewModel>
    {
        private readonly Func<TModel, TViewModel> _viewModelFactory;
        private readonly Action<TViewModel> _viewModelRemoveHandler;
        private ObservableCollection<TModel> _source;

        public ObservableViewModelCollection(Func<TModel, TViewModel> viewModelFactory, Action<TViewModel> viewModelRemoveHandler = null)
        {
            Contract.Requires(viewModelFactory != null);

            _viewModelFactory = viewModelFactory;
            _viewModelRemoveHandler = viewModelRemoveHandler;
        }

        public ObservableCollection<TModel> Source
        {
            get { return _source; }
            set
            {
                if (_source == value)
                    return;

                this.ClearWithHandling();

                if (_source != null)
                    _source.CollectionChanged -= OnSourceCollectionChanged;

                _source = value;

                if (_source != null)
                {
                    foreach (var model in _source)
                    {
                        this.Add(CreateViewModel(model));
                    }
                    _source.CollectionChanged += OnSourceCollectionChanged;
                }
            }
        }

        private void OnSourceCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            switch (e.Action)
            {
                case NotifyCollectionChangedAction.Add:
                    for (int i = 0; i < e.NewItems.Count; i++)
                    {
                        this.Insert(e.NewStartingIndex + i, CreateViewModel((TModel)e.NewItems[i]));
                    }
                    break;

                case NotifyCollectionChangedAction.Move:
                    if (e.OldItems.Count == 1)
                    {
                        this.Move(e.OldStartingIndex, e.NewStartingIndex);
                    }
                    else
                    {
                        List<TViewModel> items = this.Skip(e.OldStartingIndex).Take(e.OldItems.Count).ToList();
                        for (int i = 0; i < e.OldItems.Count; i++)
                            this.RemoveAt(e.OldStartingIndex);

                        for (int i = 0; i < items.Count; i++)
                            this.Insert(e.NewStartingIndex + i, items[i]);
                    }
                    break;

                case NotifyCollectionChangedAction.Remove:
                    for (int i = 0; i < e.OldItems.Count; i++)
                        this.RemoveAtWithHandling(e.OldStartingIndex);
                    break;

                case NotifyCollectionChangedAction.Replace:
                    // remove
                    for (int i = 0; i < e.OldItems.Count; i++)
                        this.RemoveAtWithHandling(e.OldStartingIndex);

                    // add
                    goto case NotifyCollectionChangedAction.Add;

                case NotifyCollectionChangedAction.Reset:
                    this.ClearWithHandling();
                    if (e.NewItems == null)
                        break;
                    for (int i = 0; i < e.NewItems.Count; i++)
                        this.Add(CreateViewModel((TModel)e.NewItems[i]));
                    break;

                default:
                    break;
            }
        }

        private void RemoveAtWithHandling(int index)
        {
            _viewModelRemoveHandler?.Invoke(this[index]);
            this.RemoveAt(index);
        }

        private void ClearWithHandling()
        {
            if (_viewModelRemoveHandler != null)
            {
                foreach (var item in this)
                {
                    _viewModelRemoveHandler(item);
                }
            }

            this.Clear();
        }

        private TViewModel CreateViewModel(TModel model)
        {
            return _viewModelFactory(model);
        }
    }
}

To deal with the first of the two problems, you can simply set Source to null in order to get rid of the CollectionChanged event handler.
To deal with the second of the two problems, you can simply add a viewModelRemoveHandler that allows to to "prepare your object for destruction", e.g. by removing any event handlers attached to it.

A: I've written some helper classes for wrapping observable collections of business objects in their View Model counterparts here

A: I really like 280Z28's solution. Just one remark. Is it necessary to do the loops for each NotifyCollectionChangedAction? I know that the docs for the actions state "one or more items" but since ObservableCollection itself does not support adding or removing ranges, this can never happen I would think.

A: Resetting an collection to a default value or to match a target value is something i've hit quite frequently
i Wrote a small helper class of Miscilanious methods that includes
public static class Misc
    {
        public static void SyncCollection<TCol,TEnum>(ICollection<TCol> collection,IEnumerable<TEnum> source, Func<TCol,TEnum,bool> comparer, Func<TEnum, TCol> converter )
        {
            var missing = collection.Where(c => !source.Any(s => comparer(c, s))).ToArray();
            var added = source.Where(s => !collection.Any(c => comparer(c, s))).ToArray();

            foreach (var item in missing)
            {
                collection.Remove(item);
            }
            foreach (var item in added)
            {
                collection.Add(converter(item));
            }
        }
        public static void SyncCollection<T>(ICollection<T> collection, IEnumerable<T> source, EqualityComparer<T> comparer)
        {
            var missing = collection.Where(c=>!source.Any(s=>comparer.Equals(c,s))).ToArray();
            var added = source.Where(s => !collection.Any(c => comparer.Equals(c, s))).ToArray();

            foreach (var item in missing)
            {
                collection.Remove(item);
            }
            foreach (var item in added)
            {
                collection.Add(item);
            }
        }
        public static void SyncCollection<T>(ICollection<T> collection, IEnumerable<T> source)
        {
            SyncCollection(collection,source, EqualityComparer<T>.Default);
        }
    }

which covers most of my needs
the first would probably be most applicable as your also converting types
note: this only Syncs the elements in the collection not the values inside them

A: This is a slight variation on Sam Harwell's answer, implementing IReadOnlyCollection<> and INotifyCollectionChanged instead of inheriting from ObservableCollection<> directly. This prevents consumers from modifying the collection, which wouldn't generally be desired in this scenario.
This implementation also uses CollectionChangedEventManager to attach the event handler to the source collection to avoid a memory leak if the source collection is not disposed at the same time as the mirrored collection.
/// <summary>
/// A collection that mirrors an <see cref="ObservableCollection{T}"/> source collection
/// with a transform function to create it's own elements.
/// </summary>
/// <typeparam name="TSource">The type of elements in the source collection.</typeparam>
/// <typeparam name="TDest">The type of elements in this collection.</typeparam>
public class MappedObservableCollection<TSource, TDest>
    : IReadOnlyCollection<TDest>, INotifyCollectionChanged
{
    /// <inheritdoc/>
    public int Count => _mappedCollection.Count;

    /// <inheritdoc/>
    public event NotifyCollectionChangedEventHandler CollectionChanged {
        add { _mappedCollection.CollectionChanged += value; }
        remove { _mappedCollection.CollectionChanged -= value; }
    }

    private readonly Func<TSource, TDest> _elementMapper;
    private readonly ObservableCollection<TDest> _mappedCollection;

    /// <summary>
    /// Initializes a new instance of the <see cref="MappedObservableCollection{TSource, TDest}"/> class.
    /// </summary>
    /// <param name="sourceCollection">The source collection whose elements should be mapped into this collection.</param>
    /// <param name="elementMapper">Function to map elements from the source collection to this collection.</param>
    public MappedObservableCollection(ObservableCollection<TSource> sourceCollection, Func<TSource, TDest> elementMapper)
    {
        if (sourceCollection == null) throw new ArgumentNullException(nameof(sourceCollection));
        _mappedCollection = new ObservableCollection<TDest>(sourceCollection.Select(elementMapper));

        _elementMapper = elementMapper ?? throw new ArgumentNullException(nameof(elementMapper));

        // Update the mapped collection whenever the source collection changes
        // NOTE: Use the weak event pattern here to avoid a memory leak
        // See: https://learn.microsoft.com/en-us/dotnet/framework/wpf/advanced/weak-event-patterns
        CollectionChangedEventManager.AddHandler(sourceCollection, OnSourceCollectionChanged);
    }

    /// <inheritdoc/>
    IEnumerator<TDest> IEnumerable<TDest>.GetEnumerator()
        => _mappedCollection.GetEnumerator();

    /// <inheritdoc/>
    IEnumerator IEnumerable.GetEnumerator()
        => _mappedCollection.GetEnumerator();

    /// <summary>
    /// Mirror a change event in the source collection into the internal mapped collection.
    /// </summary>
    private void OnSourceCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        switch (e.Action) {
            case NotifyCollectionChangedAction.Add:
                InsertItems(e.NewItems, e.NewStartingIndex);
                break;
            case NotifyCollectionChangedAction.Remove:
                RemoveItems(e.OldItems, e.OldStartingIndex);
                break;
            case NotifyCollectionChangedAction.Replace:
                RemoveItems(e.OldItems, e.OldStartingIndex);
                InsertItems(e.NewItems, e.NewStartingIndex);
                break;
            case NotifyCollectionChangedAction.Reset:
                _mappedCollection.Clear();
                InsertItems(e.NewItems, 0);
                break;
            case NotifyCollectionChangedAction.Move:
                if (e.OldItems.Count == 1) {
                    _mappedCollection.Move(e.OldStartingIndex, e.NewStartingIndex);
                } else {
                    RemoveItems(e.OldItems, e.OldStartingIndex);

                    var movedItems = _mappedCollection.Skip(e.OldStartingIndex).Take(e.OldItems.Count).GetEnumerator();
                    for (int i = 0; i < e.OldItems.Count; i++) {
                        _mappedCollection.Insert(e.NewStartingIndex + i, movedItems.Current);
                        movedItems.MoveNext();
                    }
                }

                break;
        }
    }

    private void InsertItems(IList newItems, int newStartingIndex)
    {
        for (int i = 0; i < newItems.Count; i++)
            _mappedCollection.Insert(newStartingIndex + i, _elementMapper((TSource)newItems[i]));
    }

    private void RemoveItems(IList oldItems, int oldStartingIndex)
    {
        for (int i = 0; i < oldItems.Count; i++)
            _mappedCollection.RemoveAt(oldStartingIndex);
    }
}


Q: ui-grid columnDefs error I have a general purpose angular controller, which displays a grid view of data. I use it in multiple places of the page by providing different data.
I want to customize the column definition in html using ng-init like this:

However, I get
Error: Cannot parse column width '60px' for column named 'c_partno'.
Very appreciated if anyone can help.

A: You should write width: 60 instead of width: '60px'
you can check this on the Documentation, hope it helps.
https://github.com/angular-ui/ui-grid/wiki/Defining-columns


Q: I want to display a picture

function rpsGame() {
  var textAnswer = document.createTextNode('You chose a paper');
  document.getElementById('this').appendChild("textAnswer");
}

The error I get is:

Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'.

I want it to show the text on the div called this.


Q: Why does chrome sometimes fail to redraw the page when I expand the browser window? I'm currently working on a responsive design site prototype. So far so good, but for one really strange thing which I can only seem to reproduce in Chrome. When expanding the window, sometimes the browser seems to get trapped between states, showing duplicate elements, and two scrollbars - that is, until I click somewhere outside of the browser window, then everything gets redrawn and looks just fine.
Screenshot:

I've tried a plethora of "tricks" to get chrome to "re-jig" the interface programmatically, such as changing the padding of the body element, modifying the scrollY position, and about 10 or so others, but nothing seems to do the trick. Does anyone have any experience with this? Any advice?

A: This looks like a bug in Chrome.
I searched Chromium bugs and found a few that are similar:

*

*Issue 516127:    Rendering artifacts on osx when something moves above the browser (dock, other windows, etc)

*Issue 473933:    Visual rendering issue

*Issue 476909:    Page didn't redraw correctly

*Issue 245946:    Content isn't layout correctly when resizing window
But actually none of them seems to describe your problem exactly. If you think so too, you can report your bug here.
Note that this might be as well an issue related to your old Mac OS version or even the graphics card.

A: Try adding this just after <head> tag
<meta name="viewport"
content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">

A: I had the same problem using cordova (hybrid html5/css3 mobile platform), when rotating the device the internal browser did not refresh correctly. I had a div containing everything with a fixed position. After some tries, I used style width/height: 100% and when rotating the browser refreshed correctly.

A: I second the suggestion to check plugins installed in case there's a conflict.
Looking on Google's forums, the issue has arisen before and was scheduled for a bugfix. Noticed while reading there that they also removed the support for browser window resizing via javascript :/

A: I'm guessing you have a retina display Mac and another external display connected? I see this sometimes on my setup and have tentatively narrowed it down to this situation. When using just the native screen I never see it and not in all screen configurations either.
Try and see if it happens when you use only the built in screen. If that works try switching which screen is the main screen or switch to another external screen altogether.
Sorry for the no fix, but maybe it will get you closer to a solution in your setup at least.


Q: How to Find the Matrix of a Linear Map If a map $f$ from the set of polynomials of degree 3 to the real numbers is given by $f(u) = u'(-2)$, how do I find the matrix that represents $f$ with respect to the bases $[1, t, t^2, t^3]$ and $[1]$?
I have worked out $f(1) = 0$, $f(t) = 1$, $f(t^2) = -4$ and $f(t^3) = 12$ and now I'm at a loss.
Any help appreciated.

A: Actually you are done already:
$$f \equiv \pmatrix{0&1&-4&12}$$


Q: Read JSON data in JavaScript I Have method in my controller which returns json data.
public JsonResult Data()
{
    return Json(model, JsonRequestBehavior.AllowGet);
}

Now how do i read and store above returned data using jQuery? I am trying belwo
$("#btn").click(function () {
    $.getJSON("Controller/Data", function(result) {
           alert(result.Name + " ");
    });
});

Data returned
It returns multiple list,which has multiple items
eg : [0] {MyList} and then it has Name,Region etc
     [1] {MyList} and then it has Name,Region etc

A: From the look of your returned JSON, you are returning an array of objects. To access these you can use the index of the object within the array. For example:
$.getJSON("Controller/Data", function(result) {
    console.log(result[0].Name);
});

Alternatively, you can loop through all the returned items:
$.getJSON("Controller/Data", function(result) {
    for (var i = 0; i < result.length; i++) {
        console.log(result[i].Name);
    }
});

A: Try this:
 $.ajax({
        cache: false,
        type: "POST",
        data: {},
        async: true,
        url: "/Controller/Data/",
        datatype: "json",
        success: function (data) {
            $.each(data, function (key, data) {
                alert(data.Name);
                alert(data.Region);
            });
        }
    });

A: you could do
$.getJSON("Controller/Data", function(result) {
    console.log('result');
    $.each(result, function(key,value) {
       console.log(value.name);
       // all other computations
    });
});


Q: ‘There is a double yolk in the egg.’
‘There is a double yolk in the egg.’

If one of two yolks is red, should I say ‘part of a double yolk’ is red or ‘one of a double yolk’ is red? (Part of a double helix is damaged, etc.)

A: In general, I would only use "Part of the double [x]..." if the thing I was describing affected a portion of each element of [x].
For example, there could be a double rainbow, but one sector of the double rainbow could be invisible due to shadows or something. Then I could say: Part of the double rainbow is not visible.
Or there could be a double helix (for example two intertwining staircases), and a segment of both has been painted red. Then I could say: Part of the double helix is red.
But if only one of the helices was painted red, I would say that instead: One of the two helices is red.
So in your case, no, I would not describe a single yolk as being red. I would say One of the two yolks is red.

A: No need to overthink this.

One of the yolks is red.

Don't say "part of the double yolk" or "one of the double yolk".
Don't worry about the fact that the egg has a double yolk, so it has two yolks.  Similarly DNA has a double helix, which means it is made of two helices; a double whisky has two shots of whisky... etc.


Q: Class name is marked as 'not covered' while running code coverage in Android Studio I have tried AndroidStudio's code coverage feature and I have met a strange issue:
It is marks the tested class's name as 'not covered' code.
How is that possible? Is that a bug?
Picture here:

As you can see it has one method with 4 lines and each one of them is covered. So why is the red line at the class's name?

A: You are using a static method, so the class itself is never created as an object, therefore never testing that ability.

A: I tried the lombok @UtilityClass, it helped to ignore the class name and code coverage was improved to be 100%.

A: Since also a class with a static function has a default no-argument constructor, your code coverage tool will complain. A good way to solve this, is by adding a private constructor.
private EmailValidator() {
}


Q: Can't update ContentVersion. My code create new file every time I had such issue. I created method that save attachent to my Opportunity.
    public PageReference attachInvoicePDF() {
        /* Get the page definition */
        PageReference pdfPage = Page.Invoice_PDF_V2;

        pdfPage.getParameters().put('id', oppId);
        /* generate the pdf blob */
        Blob pdfBlob;
        if(Test.isRunningTest()) {
            pdfBlob = blob.valueOf('Unit.Test');
          } else {
            pdfBlob = pdfPage.getContentAsPDF();
          }
        Attachment attach;
        Attachment[] a;
        //Get attachment
        a = [SELECT Id, Name, Body, ContentType, ParentId From Attachment WHERE parentId = :oppId];
        /* create the attachment for opportunity*/
        if (a.size() == 0) {
             attach = new Attachment(parentId = oppId, name=opportun.Invoice_Number__c + '.pdf', body = pdfBlob);
             insert attach;
        } else {
            attach = a[0];
        }

        //Insert ContentVersion
        ContentVersion cVersion = new ContentVersion();
        cVersion.ContentLocation = 'S';
        cVersion.PathOnClient = attach.Name;
        cVersion.Origin = 'C';
        //cVersion.OwnerId = attach.OwnerId;
        cVersion.Title = attach.Name;
        cVersion.VersionData = pdfBlob;
        Insert cVersion;

        //After saved the Content Verison, get the ContentDocumentId
        Id conDocument = [SELECT ContentDocumentId FROM ContentVersion WHERE Id =:cVersion.Id].ContentDocumentId;

        //Insert ContentDocumentLink
        ContentDocumentLink cDocLink = new ContentDocumentLink();
        cDocLink.ContentDocumentId = conDocument;
        cDocLink.LinkedEntityId = attach.ParentId;
        cDocLink.ShareType = 'V';
        cDocLink.Visibility = 'AllUsers';
        Insert cDocLink;

        return pdfPage;
    }

I wrote test for this method and debug it. T\I see the problem here:
        a = [SELECT Id, Name, Body, ContentType, ParentId From Attachment WHERE parentId = :oppId];

I call two times my method in test. First time my method should use if block.
        if (a.size() == 0) {
             attach = new Attachment(parentId = oppId, name=opportun.Invoice_Number__c + '.pdf', body = pdfBlob);
             insert attach;
        } else {
            attach = a[0];
        }

And second call should use else block but it use if block again. Can you help me why my second call don't see inserted Attachment after first call?
Also I have two VF pages:
Page.Invoice_PDF and
Page.Invoice_PDF_V2
Because when I use one page, it creates infinite loop. Maybe the problem is here?

A: To add a new ContentVersion for an existing File, you have to provide the existing ContentDocumentId before insert as below.
<Identify the Existing ContentVersion based on some criteria>
<get the ContentDocumentId of the existing ContentVersion>

ContentVersion cv = new ContentVersion();
....
....
if(<match found>){
    cv.ContentDocumentId = <existing ContentDocumentId>;
    insert cv;
} else {
    insert cv;
    <get the ContentDocumentId>
    <Insert ContentDocumentLink with the ContentDocumentId>
}


Q: Inverter causing RCD to trip I have an offgrid inverter/charger - an MPPSolar PIP4048MS (4000W inverter, 48V system). By and large it has worked well for 7 years.
Recently I bought an MPPSolar PIP5048MS (5000W inverter, 48V system) as a replacement.
However, it keeps on tripping the RCD in the distribution panel. (The radial circuits for the lights work fine, there is no problem).
This RCD controls 7 MCB circuits. Each MCB circuit is a ring circuit with maybe 7 or 8 sockets (outlets) on it.
When I connect up the inverter and turn it on (in battery mode, with no ac input connection), I then go to the distribution panel and turn on each MCB at a time in order not to overload the inverter. This is when the problem begins.
If there is no load on the MCB circuit the MCB lifts and the RCD remains 'up'. However, if there is a load on the circuit - such as a 'fridge, freezer, etc. the RCD trips. On one particular circuit there is a small pump that controls a reverse osmosis system. The pump only needs to be in standby (not actively running) to cause the RCD to trip. I have tried a variety of loads - toaster, 100W coffee grinder, electric drill. As soon as the load is applied the RCD trips. The only thing (that I have tried) that doesn't cause a trip is a small table lamp.
In both models of the inverter there is a neutral-ground bond in the inverter while the inverter is in battery mode - this is the only mode that I have tried the new inverter in.
Because of the time involved in exchanging the 2 inverters and vica versa (in order to test the PIP5048) I decided to set up a small replica of the distribution panel out in the shed. The same result - the RCD trips in the same circumstances as above.
At the behest of the MPPSolar support I removed the screw inside the inverter responsible for the neutral-ground bond. It made no difference. As a result they say that the problem isn't caused by earth leakage from inverter. The earth leakage must be coming from the loads. However, I put the following to them:

In the meanwhile can you answer this one question please?  If there is
leakage current coming from the laptop or 'fridge or toaster, etc.,
etc. then why doesn't the RCD drop right now when any one of these
appliances is used (now that I am using the 'old' PIP4048 or if I use
the EPEVER). Why does the RCD wait to trip until the PIP5048 is used?

They haven't answered the question - they just keep repeating that I need to measure the leakage coming from the loads. (By the way, I did use a 5kW EPEVER inverter/charger for a few weeks at the start of summer with no RCD trips).
The RCD is a 63A 30mA DP type A RCD.
Where do I go from here?


Q: Change certain matrix entry with probability I really appreciate some help in this problem:
Now I have a diagonal matrix A with only 0 and 1 and its diagonal entries are all 0.
From first row onwards, for each row I hope to change 1 into 0 with probability p (probability that this 1 is changed into 0 is p). I tried:
ReplacePart[A,RandomSample[Position[A[[1]],1],p*Length[A]]—>0]
But it seems Position doesn’t recognize row of matrix. I wonder if there is any other command can be used or any correction suggested. Thanks a lot!

A: Here is an example:
We first create a diagonal matrix with 0 and 1:
n = 4;
mat = DiagonalMatrix[Table[ RandomInteger[{0, 1}], n]]

Then we change the 1's with probability p to zero:
p = 1/2;
Do[mat[[i, i]] = RandomChoice[{p, 1 - p} -> {0, mat[[i, i]]}], {i, n}];
mat


Q: Post a Facebook Story as map with C# is not working I am trying to post a Facebook story with a map attachement. I can post the story successfully, but the attachement is not shown as map.
I am using the Facebook C# SDK (http://facebooksdk.net/).
This is how I set up the story:

The custom object is set up with a custom property called geolocation, on which i reffer in the attachement configuration of my story:

And this is how I set the parameters for the FB post call:
parameters["location"] = new Dictionary<string, object>();
((Dictionary<string, object>)parameters["location"])["title"] = "Title";
((Dictionary<string, object>)parameters["location"])["geolocation:latitude"] = pokk.Location.Latitude.ToString(CultureInfo.InvariantCulture);
((Dictionary<string, object>)parameters["location"])["geolocation:longitude"] = pokk.Location.Longitude.ToString(CultureInfo.InvariantCulture);

The story is posted successfully, but this is how it looks like:

I hope you can help me..
Thanx in advance!
Greets!

A: I have spent the last couple hours trying to diagnose this issue and came up with a solution however the code changes quite abit. Basically the first thing you can do is actually set the property "location" to be required. You will notice that once you set it as required that the Graph API is failing due to a required property missing.
This is a good sign, it means that something is not quite right with the submission. After digging around and manually creating objects in the Object Browser I came up with a solution. Now it is worth noting that I am using dnyamic ExpandoObjects instead of dictionaries but the concept is the same. Review the commented code
//create our location object
dynamic locationData = new ExpandoObject();
locationData.title = "sample app testing " + DateTime.Now.ToString();

//create our geolocation object
dynamic geoData = new ExpandoObject();
geoData.latitude = 37.416382;
geoData.longitude = -122.152659;
geoData.altitude = 42; //<-- important altitude figure

//create our geo data item container and add the geoData object to the geolocation property
dynamic geoDataItem = new ExpandoObject();
geoDataItem.geolocation = geoData;

//set the data property of our location data to the geo data item container
locationData.data = geoDataItem;

//create our root object setting the location property to the location data object
dynamic objItem = new ExpandoObject();
objItem.location = locationData;

var response = context.Client.Post("me/<my_app_name>:<app_action>", objItem);

Really all we are doing is creating a simple structure using the expando object. Where I personally got stuck what not understanding how the complete GeoPoint operates. If you notice we have to create 2 containers.
One container so we can set the geolocation property on the data property of the location object.
The final structure resembles
--- MyStory
    --- location
        --- title : 'Sample app testing....'
        --- data
            --- geolocation
                --- latitude  : 37.416...
                --- longitude : -122.1526...
                --- altitude  : 42

This does seem rather complex but here is a final output preview.


Q: custom taxonomy sort order not working I have created a custom taxonomy named product_categories.
It has three fields :

*

*for banner image

*for category image and

*for sort order.
I have added 10 categories in it giving its sort order input also.
Now i want to show this in sorting order but it is not working.
In pt-categories input for sort order is this

<?php _e('Product Sort Order'); ?>

    <input id="banner-url" name="term_meta[sort_order]" type="text" style="width: 100%;" value="<?php echo $term_meta['sort_order'] ? $term_meta['sort_order'] : ''; ?>" />
    <?php _e(' '); ?>

Saving funtion is this
    function save_product_categories_custom_fields($term_id)
    {
    if (isset($_POST['term_meta'])) {
        $t_id = $term_id;
        $term_meta = get_option("taxonomy_term_$t_id");
        $cat_keys = array_keys($_POST['term_meta']);
        foreach ($cat_keys as $key) {
            if (isset($_POST['term_meta'][$key])) {
                $term_meta[$key] = $_POST['term_meta'][$key];
            }
        }
     //save the option array
        update_option("taxonomy_term_$t_id", $term_meta);
    }
}

Here is the categories called
function getLatestProducts() {
$args = array(
  'post_status' => 'publish',
  'post_type' => 'products',
  'posts_per_page' => 12,
  'meta_key'        => '_cus_sort_order',
  'orderby'         => 'meta_value_num',
  'order' => 'ASC'
);
?>
<?php
                $args = array(
                'orderby' => 'name',
                );
                $terms = get_terms('product_categories', $args);
                foreach($terms as $term) {
               $prod_meta = get_option("taxonomy_term_".$term->term_id);
                    ?>
                <a href="<?php echo get_term_link($term->slug, 'product_categories') ?>">
                <?php
                    echo '';    ?>

                <a href="<?php echo get_term_link($term->slug, 'product_categories') ?>">
                <?php echo $term->name;?>

It is showing the categories names and images but not in sorted order.

A: You have a mistake in your code of Categories Called
Corrected Code
function getLatestProducts() {
    $args = array(
    'post_status' => 'publish',
    'post_type' => 'products',
    'posts_per_page' => 12,
    'meta_key'        => '_cus_sort_order',
    'orderby'         => 'meta_value_num, name',
    'order' => 'ASC'
);
            $terms = get_terms('product_categories', $args);
            foreach($terms as $term) {
           $prod_meta = get_option("taxonomy_term_".$term->term_id);
                ?>
            <a href="<?php echo get_term_link($term->slug, 'product_categories') ?>">
            <?php
                echo '';    ?>

            <a href="<?php echo get_term_link($term->slug, 'product_categories') ?>">
            <?php echo $term->name;?>

I have removed an array of argument which is called after main arguments array. As the below mentioned argument array is overriding the above mentioned arguments array.
Removed Arguments Array
$args = array(
    'orderby' => 'name',
);

Hope this helps!

A: Extending on Mehul's answer, your saving function has also some mistakes.
Have you checked previously saved sort orders of your categories ?
"taxonomy_term_$t_id" should be "taxonomy_term_" . $t_id . Otherwise you are saving everything as taxonomy_term_$t_id option and not with a dynamic term id.
function save_product_categories_custom_fields($term_id)
{
if (isset($_POST['term_meta'])) {
    $t_id = $term_id;
    $term_meta = get_option("taxonomy_term_" . $t_id);
    $cat_keys = array_keys($_POST['term_meta']);
    foreach ($cat_keys as $key) {
        if (isset($_POST['term_meta'][$key])) {
            $term_meta[$key] = $_POST['term_meta'][$key];
        }
    }
 //save the option array
    update_option("taxonomy_term_" . $t_id, $term_meta);
}

}


Q: How to Optimize Animation.Sample I'm trying to optimize the animation. As I see in profiler, about 20% of my CPU used for 'Animation.Sample'. Is there any way to reduce the sampling accuracy to gain performance.

A: Unless you want to write your own animation system for Unity, which would be probably slower due to Unity's optimizations. You can't do anything about it except tweaking the animation yourself.

*

*Use fewer bones

*Remove redundant curves

*Ensure that any bones that have colliders attached also have rigidbodies.


Q: 404 ошибка при перенаправлении Ajax-запроса Делаю сайт, в котором локализация работает через параметр:
http://sitename.com/team.php?lang=ru

Для того, что бы привести URL к понятному виду, использую следующий .htaccess:
RewriteEngine on
RewriteBase /
RewriteRule ^(.*)/(.*)$ $2?lang=$1
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php

Он переводит ссылки в формат:
http://sitename.com/ru/team

Но возникла проблема: если с одной из страниц я Ajax-ом пытаюсь обратиться к другому скрипту, то сервер возвращает 404 ошибку (файл не найден).
Адрес ajax-запроса выглядит следующим образом:
url: '../core/backend/backapi.php'

Структура папок у меня организована подобным образом:

JS-файлы находятся в папке js. Если я оттуда попытаюсь отправить Ajax-запрос к файлу backapi.php, то получу ошибку. При удалении строки
RewriteRule ^(.*)/(.*)$ $2?lang=$1

Запрос отправляется нормально, но пропадает понятный человеку URL.

A: Проверил Ваш htaccess и правила конечно работает на эту ссылку тоже
сейчас Вас htaccess создает ссылку так
http://site.com/core/backend/backapi.php => http://site.com/backapi.php?lang=core/backend

Из этого не работает ваш Ajax запрос
debugging info
1       RewriteEngine on
2       RewriteBase /

3       RewriteRule ^(.*)/(.*)$ $2?lang=$1
            Это правило совпадает и дает результат http://site.com/backapi.php?lang=core/backend

4       RewriteCond %{REQUEST_FILENAME} !-d
            Переменная не поддерживается : %{REQUEST_FILENAME}

5       RewriteCond %{REQUEST_FILENAME}\.php -f
            Переменная не поддерживается: %{REQUEST_FILENAME}\.php

6       RewriteRule ^(.*)$ $1.php
            Правило не сработало, один из ситуаций не совпадает

проверил на сайте http://htaccess.madewithlove.be/ попробуйте

A: вероятно, вот эта строка:
RewriteRule ^(.*)/(.*)$ $2?lang=$1

должна звучать несколько иначе. например, так (для двух языковых версий):
RewriteRule ^(ru|en)/(.*)$ $2?lang=$1


Q: Print result if statement to exec is an expression In python, if I exec a statement which prints a value, I will see the output, e.g., exec("print 10") gives me output 10. However, if I do exec("10") I got nothing as output, where as if I type 10 in the interactive shell I got 10 as output. How do I get this output when using exec? That is if the statement to be executed is an expression, I print its result.
My question is how I can decide whether the statement to execute is an expression. Am I supposed to do the following:
def my_exec(script):
  try:
    print eval(compile(script, '<string>', 'eval'))
  except SyntaxError:
    exec(script)

# Prints 10.
my_exec("print(10)")

# Prints 10 as well.
my_exec("10")

UPDATE:
Basically I want the behavior of executing a cell in a jupyter notebook.

A: First of all, executing 10 doesn't make sense in real life. How can you execute a number? But, you can execute a command like exec("print(10)"). I don't see the need of creating a my_exec function. It behaves the same as the normal exec. In the interactive shell, everything works differently, so don't try to compare. Basically, exec("print(10)") is the command you are looking for. Another way not using exec is print(10).


Q: A bead on a spinning wire hoop (Taylor)

Hello, I'm trying to figure out how to get the Lagrangian of a bead on a frictionless wire hoop that is spinning about it's vertical axis with angular velocity $\omega$.

Taylor claims that the kinetic energy is
$T = \frac{1}{2}mR^{2}\dot{\theta}^{2} + \frac{1}{2}mR^{2}\omega^{2}\sin^{2}\theta$,
where the first term comes from tangential velocity and the second term is from velocity normal to the hoop.
For the first term, if we call the axis of rotation $z$, I'm sure that the tangential velocity refers to the circular motion traced out on the $xy$-plane ($v_{\text{tan}}^{2} = a_{\text{rad}}R = \dot{\theta}^{2}R^{2}$, right?). The second term, however, escapes me. How do I find the velocity normal to the rotating hoop? The text mentions "centrifugal" force but I'm not familiar with it (other than past professors demonizing it, lol) or how it creates the second term in the kinetic energy. I thought maybe that the second term was in fact the rotational kinetic energy but I can't come up with anything in finding it that way. Thanks in advance.

A: Write
$$
z=-R(1-\sin\theta)\, ,\qquad x=R\cos\theta\cos\omega t\, ,\qquad
y= R\cos\theta\sin\omega t
$$
and compute
$$
T=\frac{1}{2m}(\dot{x}^2+\dot{y}^2+\dot{z}^2)\, .
$$
This should produce the desired result.


Q: Wix Bootstrap prevent temp directory use I have builded "HelloWord" installer with the Bootstrapper Project for Wix v3 project type.
My bundle.wxs is
    <?xml version="1.0" encoding="UTF-8"?>
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi"
     xmlns:util="http://schemas.microsoft.com/wix/UtilExtension"
     xmlns:bal="http://schemas.microsoft.com/wix/BalExtension">

  <Bundle Name="Bundle_name"
          Version="1.0.0.0"
          Manufacturer="Producter"
          UpgradeCode="C82A383C-751A-43B8-90BF-A250F7BC2863"
          IconSourceFile="..\WpfForms\Assets\my_lovely.ico"  >

    <BootstrapperApplicationRef Id="ManagedBootstrapperApplicationHost">
      <Payload SourceFile="..\WpfForms\BootstrapperCore.config"/>
      <Payload SourceFile="..\WpfForms\bin\Debug\WpfForms.dll"/>
      <Payload SourceFile="..\WpfForms\bin\Debug\GalaSoft.MvvmLight.dll"/>
      <!--<Payload SourceFile="..\WpfForms\bin\Debug\Microsoft.Practices.ServiceLocation.dll"/>
      <Payload SourceFile="..\WpfForms\bin\Debug\Microsoft.WindowsAPICodePack.dll"/>
      <Payload SourceFile="..\WpfForms\bin\Debug\Microsoft.WindowsAPICodePack.Shell.dll"/>-->

      <Payload SourceFile="C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5\System.ServiceProcess.dll"/>
      <Payload SourceFile="C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5\System.Configuration.Install.dll"/>
      <Payload SourceFile="C:\Program Files (x86)\WiX Toolset v3.11\SDK\Microsoft.Deployment.WindowsInstaller.dll"/>
    </BootstrapperApplicationRef>

    <Chain>
      <PackageGroupRef Id='Netfx4Full'/>
      <MsiPackage SourceFile="..\WixSetupProject\bin\Debug\WixSetupProject.msi" Id="InstallationPackageId" Cache="yes" Visible="no"/>
    </Chain>
  </Bundle>

  <Fragment>
    <WixVariable Id="WixMbaPrereqPackageId" Value="Netfx4Full" />
    <WixVariable Id="WixMbaPrereqLicenseUrl" Value="NetfxLicense.rtf" />

    <util:RegistrySearch Root="HKLM" Key="SOFTWARE\Microsoft\Net Framework Setup\NDP\v4\Full" Value="Version" Variable="Netfx4FullVersion" />
    <util:RegistrySearch Root="HKLM" Key="SOFTWARE\Microsoft\Net Framework Setup\NDP\v4\Full" Value="Version" Variable="Netfx4x64FullVersion" Win64="yes" />

    <PackageGroup Id="Netfx4Full">
      <ExePackage Id="Netfx4Full" Cache="no" Compressed="yes" PerMachine="yes" Permanent="yes" Vital="yes" Name="DotNet_4"
                  SourceFile="../WixBootstrapper/DotNet/NDP462-KB3151800-x86-x64-AllOS-ENU.exe"
                  DownloadUrl="http://go.microsoft.com/fwlink/?LinkId=164193"
                  DetectCondition="Netfx4FullVersion AND (NOT VersionNT64 OR Netfx4x64FullVersion)" />
    </PackageGroup>
  </Fragment>
</Wix>

My problem is that the work station's antivirus configured to block any activity from temp directories and the builded installer.exe make copy of itself as "C:\Windows\Temp{74EA5B2A-DA46-4B3F-A8E9-4FCEC4B4523C}.cr\WixBootstrapper.exe" and run it by default. So it get locked by antivirus so instalation is over on start.
Do somebody know how can i prevent WiX components from create a cache or something in temp directories and set to run any nested executable and themselfs from the curent folder, not from the temp?

A:
After checking Windows's group policy settings this turned out to be
  an anti-virus blocking problem.

Group Policy?: Does the log contain something like this:
Error 0x800704ec: Failed to launch clean room process: "C:\WINDOWS\Temp\{AB10C981-0D7D-4AA6-857F-CC37696DB4BE}\.cr\Bundle.exe" -burn.clean.room="C:\Test\Bundle.exe" -burn.filehandle.attached=652 -burn.filehandle.self=656 -log "C:\Test\bundle.log"
Error 0x800704ec: Failed to run untrusted mode.

Or does it say something else? There is a group policy that can cause similar issues. See WiX issue 5856.
Anti-Virus Grace Period?: If you are administrator, there should be a possiblity to get a temporary grace period from your anti virus I would think. So you can perform your testing. I would give your own support desk a call first and then hit the Kaspersky user forums if unsuccessful. Perhaps you have a Kaspersky support agreement with priority support available?
False Positives: I also insist that you upload your binaries to virustotal.com to test for false positives. That you should do no matter what. Antivirus Whitelisting Pains by Bogdan Mitrache.

False positives can actually be worse than actual malware at times (so far as the malware isn't devastating)
  because you cannot just tell the user to rebuild their machine(s). Instead you actually have
  to fix the problem for them in a general sense. Not only does the user have a problem to fix, you have one as the vendor as well. How do you whitelist your product with 60+ anti-malware suites? You try virustotal.com first I think (not affiliated) - to check if you actually have such a problem.


Q: Sequelize: can attribute have value from relation attribute data? i don't know if this is possible, there are 2 models which are associated through relation, and models are defined this way:
sequelize.define('account_has_plan', {
        account_id: {
            type: DataTypes.INTEGER(10),
            allowNull: false,
            primaryKey: true,
            references: {
                model: 'account',
                key: 'id'
            }
        },
        plan_id: {
            type: DataTypes.INTEGER(10),
            allowNull: false,
            primaryKey: true,
            references: {
                model: 'plan',
                key: 'id'
            }
        },
        type_id: {
            type: DataTypes.INTEGER(10),
            allowNull: false,
            primaryKey: true,
            references: {
                model: 'type',
                key: 'id'
            }
        },
        create_at: {
            type: DataTypes.DATE,
            allowNull: true,
            defaultValue: 'CURRENT_TIMESTAMP'
        },
        update_at: {
            type: DataTypes.DATE,
            allowNull: true,
            defaultValue: 'CURRENT_TIMESTAMP'
        }
    }, {
        tableName: 'account_has_plan',
        underscored: true,
        freezeTableName: true,
        timestamps: false
    });

sequelize.define('type', {
        id: {
            type: DataTypes.INTEGER(10),
            allowNull: false,
            primaryKey: true,
            autoIncrement: true
        },
        name: {
            type: DataTypes.STRING,
            allowNull: false
        },
        element: {
            type: DataTypes.ENUM('Meal','Workout','Status'),
            allowNull: false
        }
    }, {
        tableName: 'type',
        freezeTableName: true,
        timestamps: false
    });

the code on which calls the models and execute the query to DB is this:
var model = $.loadModel("account_has_plan");
var type  = $.loadModel("type");

model.belongsTo(type);

var query = {
    where: {
        account_id: $.params.accountId
    },
    limit: $.query.limit || 12,
    offset: $.query.offset || 0,
    attributes:["account_id"],
    include: [{
        model: type
    }]
};

model.findAll(query)
    .then(function(data){
        $.data = data;
        $.json();
    })
    .catch(function(err){
        console.log(err);
        errorHandler.throwStatus(500, $);
    });

this way the data from the server responds like this:
{
    "account_id": 1,
    "type": {
      "id": 2,
      "name": "Arms",
      "element": "Workout"
    }
  }

there is actually no problem with this data, but i am forced to follow a pattern from docs i was provided with, which the difference there is that type is actually a string value rather than object value as presented in the example, so in the end the data structure i try to get has to be like this:
{
    "account_id": 1,
    "type": "Arms"
}

i have actually how idea on how to achieve this, i know i have little practice with sequelize, maybe this has to be defined through a model method or using through in the reference (which i have tried but returns error)
but the point is.. i need to know if it can be possible before i have to report a change on the REST documentation which is big

A: First of all, since what you'll be getting through a sequelize query are instances, you need to convert it to "plain" object. You could do that by using a module called sequelize-values.
Then you should be able to manually map the value to the one you're looking for.
model.findAll(query)
.then(function(data){
    return data.map(function(d){
        var rawValue = d.getValues();
        rawValue.type = rawValue.type.name;
        return rawValue;
    });
})
.then(function(data){
    $.data = data;
    $.json();
})
.catch(function(err){
    console.log(err);
    errorHandler.throwStatus(500, $);
});


Q: Site title not showing. What can I do? My WordPress site's title not showing. It's just displaying the domain like,  www.example.com.
Please suggest how to display the proper title tag.

A: Add this code to your functions.php
if ( !function_exists( 'yourtheme_setup' ) ) {
    function yourtheme_setup() {
        /*
         * Let WordPress manage the document title.
         * By adding theme support, we declare that this theme does not use a
         * hard-coded <title> tag in the document head, and expect WordPress to
         * provide it for us.
         */
        add_theme_support( 'title-tag' );
    }

    add_action( 'after_setup_theme', 'yourtheme_setup' );
}

Or, if your functions.php already have after_setup_theme, just add the line add_theme_support( 'title-tag' ); into your  after_setup_theme. (Source)


Q: handle null from database I need to round and print a price like below, but this does not handle null values.
How can I handle null values on one line of code?
DBRSet is an SQLDataReader and the price is money type in SQL.
<%= Math.Round(DBRSet("price"))%>

I have about 200 .aspx pages of this so I could also use some tips on how to change these in an easy way?  Can I do a search and replace with a reg-exp or something like that?

A: You have to handle the DbNull case explicitly, for example:
<%= DbNull.Equals(DBRSet["price"]) ? "null" : Math.Round(DBRSet["price"]).ToString() %>

This is unwieldy, so it makes sense to have a helper method something like this somewhere:
static class FormatDbValue {
    public static string Money(object value)
    {
        if (DbNull.Equals(value)) {
             return "0";
        }

        return Math.Round((decimal)value);
    }
}

Which would allow
<%= FormatDbValue.Money(DBRSet["price"]) %>

Of course finding and changing all such code to use the helper method would be... unpleasant. I would do it by searching throughout the project (maybe in smaller chunks of the project) for something indicative (maybe Math.Round?) and review it manually before replacing.

A: If you don't want to change the aspx's, but can easily change the definition of the DBRSet property, you can put there a wrapper over the SqlDataReader and implement your own indexer that would first check for null and go into the inner dataReader to get the value if not null.


Q: How to collect a List to a Map> using Java lambdas? I have an object Foo that has references to Bar and Baz objects:
public class Foo {
    private Bar bar;
    private Baz baz;

    public Foo(Bar bar, Baz baz) {
       this.bar = bar;
       this.baz = baz;
    }
}

I have a List<Foo> that I'd like to convert into a Map.  I'd like the key to be Bar and the value to be a List<Baz>.
I can create a Map where Bar is the key and the value is a List<Foo>:
Map<Bar, List<Foo>> mapBarToFoos = foos.stream().collect(Collectors.groupingBy(Foo::getBar));

I don't know how to take that last step and turn the value List into a List<Baz>.  Is there a lambda conversion on the value that I'm not seeing?

A: I think you want
list.stream().collect(groupingBy(Foo::getBar,
    mapping(Foo::getBaz, toList())));

Where getBaz is the "downstream collector" which transforms the grouped Foos, then yet another which creates the list.

A: You're close, you'll need to supply a "downstream" collector to further refine your criteria. in this case the groupingBy approach along with a mapping downstream collector is the idiomatic approach i.e.
list.stream().collect(groupingBy(Foo::getBar, mapping(Foo::getBaz, toList())));

This essentially works by applying a mapping downstream collector to the results of the classification (Foo::getBar) function.
basically what we've done is map each Foo object to Baz and puts this into a list.

Just wanted to show another variant here, although not as readable as the groupingBy approach:
foos.stream()
    .collect(toMap(Foo::getBar, v -> new ArrayList<>(singletonList(v.getBaz())),
            (l, r) -> {l.addAll(r); return l;}));

*

*Foo::getBar is the keyMapper function to extract the map keys.

*v -> new ArrayList<>(singletonList(v)) is the valueMapper
function to extract the map values.

*(l, r) -> {l.addAll(r); return l;} is the merge function used to
combine two lists that happen to have the same getBar value.

A: To change the classic grouping to a Map<Bar, List<Foo>> you need to use the method which allows to change the values of the map :

*

*the version with a downstream Collectors.groupingBy(classifier, downstream)

*which is a mapping operation Collectors.mapping(mapper, downstream)

*which requires another operation to set the container Collectors.toList()
//Use the import to reduce the Collectors. redundancy
//import static java.util.stream.Collectors.*;

Map<Bar, List<Baz>> mapBarToFoos =
         foos.stream().collect(groupingBy(Foo::getBar, mapping(Foo::getBaz, toList())));

//without you'll get
Map<Bar, List<Baz>> mapBarToFoos =
         foos.stream().collect(Collectors.groupingBy(Foo::getBar, Collectors.mapping(Foo::getBaz, Collectors.toList())));


Q: how to add `alt + mouse left click` as shortcut key in key map of android studio 3.0 (Ubuntu 16.4 LTS) I am trying to add alt + mouse left click as shortcut key in keymap but it only take alt or mouse-click and It takes nothing when try to add both.
Please help to resolve this issue.Below is the screen:

A: You should use not "Keyboard shortcut" but rather "Mouse shortcut" from a popup menu (number 2 at the picture):
https://developer.android.com/studio/images/intro/keymap-options_2-2_2x.png
Also by default on most linux desktop environments alt+mouse click is already assigned to window dragging. OS shortcuts have more priority. If it's the case for you then either use different shortcut in Android Studio or reassign OS shortcut (in this case Unity): https://askubuntu.com/questions/521423/how-can-i-disable-altclick-window-dragging
After that you should be able to use the shortcut in Android Studio


Q: Angular CLI: Generate htaccess using base-href With Angular CLI the base href in index.html can be set on build, e.g. ng --base-href /folder/someproject/. This is very useful for automatic deployment processes.
But projects like this may require a .htaccess also setting a base like so: RewriteRule ^(.*) /folder/someproject/index.html [NC,L]
Is it possible (with Webpack?) to set the path within htaccess also by use of base-href?


Q: Serilogs not working in linux server in aspnet core 2.1 I'm creating dotnet core 2.1 project.I used serilogs.In my windows machine it's working fine.But after hosted it,serilogs not working.Not creating logs folder and log file.I hosted it in ubuntu 18.04 version server.
I tried it by creating logs folder manually and gave it to read write permissions
   sudo chmod 775 /var/app/logs
   sudo chown www-data /var/app/logs

here is the code in program class
public class Program
{
    public static void Main(string[] args)
    {
        Log.Logger = new LoggerConfiguration()
            .MinimumLevel.Verbose()
            .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
            .MinimumLevel.Override("System", LogEventLevel.Warning)
            .MinimumLevel.Override("Microsoft.AspNetCore.Authentication", LogEventLevel.Information)
            .Enrich.FromLogContext()
            .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level}] {SourceContext}{NewLine}{Message:lj}{NewLine}{Exception}{NewLine}", theme: AnsiConsoleTheme.Literate)
            .WriteTo.RollingFile(@"logs\log-{Date}.log", fileSizeLimitBytes: null, retainedFileCountLimit: null)
            .CreateLogger();
        CreateWebHostBuilder(args).Build().Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
        .ConfigureLogging(builder =>
                 {
                     builder.SetMinimumLevel(LogLevel.Warning);
                     builder.AddFilter("ApiServer", LogLevel.Debug);
                     builder.AddSerilog();
                 })
        .UseContentRoot(Directory.GetCurrentDirectory())
        .UseStartup<Startup>();
}

here is my startup class code
 public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<DataContext>(s => s.UseMySql(Configuration.GetConnectionString("DefaultConnection"))
        .ConfigureWarnings(warnings => warnings.Ignore(CoreEventId.IncludeIgnoredWarning)));
        services.AddMvc()
                    .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
                    .AddJsonOptions(opt =>
                    {
                        opt.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
                    });
       services.AddCors();
        services.AddAutoMapper();
        services.AddTransient<Seed>();
        services.AddScoped<IAuthRepository, AuthRepository>();
        services.AddScoped<IDatingRepository, DatingRepository>();
        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(options =>
        {
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII
                  .GetBytes(Configuration.GetSection("AppSettings:Token").Value)),
                ValidateIssuer = false,
                ValidateAudience = false
            };
        });
        services.AddScoped<LogUserActivity>();

        IdentityBuilder builder = services.AddIdentityCore<User>(opt =>
        {
            opt.Password.RequireDigit = false;
            opt.Password.RequiredLength = 4;
            opt.Password.RequireNonAlphanumeric = false;
            opt.Password.RequireUppercase = false;

        });

        builder = new IdentityBuilder(builder.UserType, typeof(Role), builder.Services);
        builder.AddEntityFrameworkStores<DataContext>();
        builder.AddRoleValidator<RoleValidator<Role>>();
        builder.AddRoleManager<RoleManager<Role>>();
        builder.AddSignInManager<SignInManager<User>>();

        // services.AddAuthorization(options => {
        //     options.AddPolicy("RequireAdminRole", policy => policy.RequireRole("Admin"));
        //     options.AddPolicy("SuperAdminPhotoRole", policy => policy.RequireRole("SuperAdmin"));
        // });

        // services.AddCors();

    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, Seed seeder, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"))
            .AddDebug();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {

            app.UseExceptionHandler(builder =>
            {
                builder.Run(async context =>
                {
                    context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;

                    var error = context.Features.Get<IExceptionHandlerFeature>();
                    if (error != null)
                    {
                        context.Response.AddApplicationError(error.Error.Message);
                        await context.Response.WriteAsync(error.Error.Message);
                    }
                });
            });

            // app.UseHsts();
        }

        // app.UseHttpsRedirection();
        seeder.SeedUsers();
        //  app.UseCors(x => x.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin().AllowCredentials());
        app.UseCors(x => x.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());
        app.UseAuthentication();
        app.UseDefaultFiles();
        app.UseStaticFiles();
        app.UseMvc(routes =>
        {
            routes.MapSpaFallbackRoute(
                name: "spa-fallback",
                defaults: new { controller = "Fallback", action = "Index" }
            );
        });
    }
}

here is the way I used logs
public class PhotosController : ControllerBase
{
    private readonly ILogger<PhotosController> _logger;

    public PhotosController(ILogger<PhotosController> logger
    )
    {
        _logger = logger;

    }

     [HttpPost("{id}/setMain")]
      public async Task<IActionResult> SetMainPhoto(Guid id)
    {
        try
        {
             _logger.LogDebug("Starting to change main photo");
        }
        catch(Exception e) {
     _logger.LogError("An error occurs while changing photo");
      }}}

Please help me to solve this problem.this is working fine in windows machine.Only this happened after hosting

A: In your Program.cs file you need
        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
          WebHost.CreateDefaultBuilder(args).UseStartup<Startup>().UseSerilog();

the important part is .UseSerilog()


Q: Modify PDF file uploaded in the request body in nodejs I'm trying to modify a pdf file that I get from the request then saving it in my server, I achieved to save it first as I received it from the request body and then modifying it, and once more saving it again with the modified version, but I was looking for another approach to modify it in the fly directly after receiving it from the request body then saving it only once in the server. I need to add a logo to the uploaded file, thanks in advance
This is my code
'''
const mongoose = require("mongoose");
const path = require("path");
const ErrorResponse = require("../utils/errorResponse");
const fs = require("fs");

// Form submition with photo
exports.uploadPdf = (req, folderPath, next) => {
  if (!req.files) {
    console.log("No file");
    return next(new ErrorResponse("Please Upload a file", 400));
  }

  const file = req.files.pdf;

  const extention = file.name.split(".").at(-1);

  if (extention !== "pdf") {
    console.log("It's not a valid PDF file");

    return next(new ErrorResponse("Please Upload an pdf file", 400));
  }

  //Check image size
  if (file.size > process.env.MAX_FILE_UPLOAD) {
    return next(
      new ErrorResponse(
        `Please Upload an PDF file less than ${process.env.MAX_PDF_FILE_UPLOAD}`,
        400
      )
    );
  }

  //Create custom filename
  let id;
  if (!req.params.id) {
    id = mongoose.Types.ObjectId();
  } else {
    id = req.params.id;
  }
  file.name = `document_${id}${path.parse(file.name).ext}`;

  var dir = `${process.env.FILE_UPLOAD_PATH}/${folderPath}`;

  if (!fs.existsSync(dir)) {
    fs.mkdirSync(dir, { recursive: true });
  }

  file.mv(
    `${process.env.FILE_UPLOAD_PATH}/${folderPath}/${file.name}`,
    async (err) => {
      if (err) {
        console.log(err);
        return next(new ErrorResponse(`Problem with file upload`, 500));
      }
    }
  );

  req.body = {
    _id: id,
    ...req.body,
    pdf: file.name,
  };
};

'''


Q: Linux Mint kernel damage First off: I am running Linux Mint 18.2 on an External HDD with Gnome 3 as my desktop.
Recently, I was trying to figure out how to compress my OS so I could move it to a different system. So, I ran:
sudo gzip -r -1 /

Of course not adding the -k option, a lot of my files got compressed into *.gz files. I was going to use find to find them all and decompress them, but that was too complicated for me to understand which options to use and what not.
So, I went through manually and decompressed as many as I could. I believe I got them all. But there was a problem with my kernel.
It ended up compressing some of the files and I couldn't get them decompressed. So, I took what I could get, which was mostly kernel 4.8.0-53-generic, and the parts I didn't have I took from the kernel in a bootable USB stick.
Now, I can get my system to boot to recovery, and that's it. What's more is X11 is having issues which I assume is also causing the issues I am seeing for lightdm.
I tried running
sudo apt-get update && sudo apt-get upgrade

In an effort to fix what I could but came up empty. I am now out of ideas. What else can I do to attempt to fix my system?
Re-installation is out of the question due to the amount of time I have put into this system, unless there is a way to reinstall and keep my configuration, apps, and files intact and in use.
Many Thanks!
EDIT : By issues for lightdm and x11, I mean I have no GUI. Just a command line.

A: As you're unclear about the actual problem and damage, the best option is reinstalling the operating system.
Diagnosing a full operating system is not that easy and specially when you don't know the actual damage.
So, boot the system with a live disk, backup all your files and reinstall the system..
The issue you're seeing is a X11 and lightdm issue, but it's not actually clear what has gone. Trying to diagnose a broken system is always good, but if you like to save time the best way is reinstallation.
And infuture always keep a backup and be extra careful while typing anything as root user.


Q: How to combine basename and filepath into a specialized list - R? I have a folder containing a variety of .img files.  I can list all of the files in the folder using the following method:
files = "C:/imagery/Landsat"

rlist=list.files(path = files, pattern="img$", full.names=TRUE)

> rlist
[1] "C:/imagery/Landsat/image1.img"
[2] "C:/imagery/Landsat/image2.img"
[3] "C:/imagery/Landsat/image3.img"

I know how to extract the basename from the file paths, using the following approach:
> strsplit(basename(rlist[1]), '\\.')[[1]][1]
[1] "image1"

However, I am in need of a special list following this format:
rlist2 = list(image1 = "C:/imagery/Landsat/image1.img",
              image2 = "C:/imagery/Landsat/image2.img",
              image3 = "C:/imagery/Landsat/image3.img")

How should I put these disjointed pieces together to form the specialized list in rlist2?

A: First, you need to assign names to the entries in your vector (each entry will get the corresponding file name), as follows:
> library(tools)
> names(rlist) <- basename(file_path_sans_ext(rlist))

Then, to get a list in the format that you specified, you can simply do:
rlist2 <- as.list(rlist)

This is the output:
> rlist2

$image1
[1] "C:/imagery/Landsat/image1.img"

$image2
[1] "C:/imagery/Landsat/image2.img"

$image3
[1] "C:/imagery/Landsat/image3.img"

And you can access individual entries in the list, as follows:
> rlist2$image1
[1] "C:/imagery/Landsat/image1.img"

You can read more about the as.list function and its behavior here.