text:
Q: ObservableCollection does not refresh even if INotifyProperty interface is implemented I have an ObservableCollection binded to a listbox
public ObservableCollection<InsertionVM> Insertions
{
    get
    {
        return _insertions;
    }
    set
    {
        _insertions = value;
        base.OnPropertyChanged("ChromosomeList");
    }
}

Its member, InsertionVM implements INotifyPropertyChanged. It has a property that will be updated.
public bool IsChecked
{
    get
    {
        return _isChecked;
    }
    set
    {
        _isChecked = value;
        base.OnPropertyChanged("IsChecked");
    }
}

Why doesn't the ObservableCollection refresh even though I implement the INotifyPropertyChanged interface for each property?

Update:
I tried the link given below, but the "more sensitive collection" is only updated when objects are removed / added.
if (e.Action == NotifyCollectionChangedAction.Remove)
{
    foreach (InsertionVM item in e.NewItems)
    {
        //Removed items
        item.PropertyChanged -= EntityViewModelPropertyChanged;
    }
}
else if (e.Action == NotifyCollectionChangedAction.Add)
{
    foreach (InsertionVM item in e.NewItems)
    {
        //Added items
        item.PropertyChanged += EntityViewModelPropertyChanged;
    }
}

public void EntityViewModelPropertyChanged(object sender, PropertyChangedEventArgs e)
{
    //Debugger does not reach here
}

Constructor:
public ChromosomeVM(Chromosome _chr, string insertionFilePath)
{
    Chr = _chr;
    _insertions.CollectionChanged += ContentCollectionChanged;
}

A: Always remember the following:
ObservableCollection<T> only notifies when number of items (it may stay same, when one item is added and one is removed, but you get the point) in it changes.
If an item in ObservableCollection<T> changes, collection is not responsible for propagating change notifications.

A: This is your code: (please see the comment also, made by me)
public ObservableCollection<InsertionVM> Insertions // propertyName == Insertions
{
    get
    {
        return _insertions;
    }
    set
    {
        _insertions = value;
        base.OnPropertyChanged("ChromosomeList"); // What is ChromosomeList??
    }
}

Can you see the problem now?  Change ChromosomeList to Insertions. Hope some problem at least will be fixed!

A: be sure to put the [Insertions] in the path of the binding and it will work
[Insertions] will be updated only if you change the reference like.
Insertions = new ObservableCollection<InsertionVM>( Items);

To make your code more effective add check if the value change in the set like
public ObservableCollection<InsertionVM> Insertions
    {
        get
        {
            return _insertions;
        }
        set
        {
       if(_insertions != value)
           {
               _insertions = value;
               base.OnPropertyChanged("Insertions");
           }
        }
    }


text:
Q: Positioning vertically .tooltip-inner in bootstrap By default the arrow is aligned vertically 50% of the .tooltip-inner height or from the element to the top of the window:

But what I really want to do is having the arrow around 20px to the top of the .tooltip-inner class or tooltip's content:

I guess it can't be done with .css because the height of the tooltip content is calculated dynamically by javascript. Any help on this? Thanks. JSFIDDLE

A: setting margin on top will also work:
.tooltip-arrow{margin-top:-13px}
.tooltip-inner{margin-top: 65px}

fiddle
no !important required

A: You can override those with css using the !important.
div.tooltip {
    top: 4px !important;
}

div.tooltip-arrow {
    top: 15px !important;
}

Fiddle

redpajama_set_name: RedPajamaStackExchange


text:
Q: Como pegar o valor de vários itens e mudar segundo meu if Tenho uma listagem de itens (que vem do banco de dados), preciso comparar cada item de um desses e se o valor for 0 mudar o texto.
Abaixo está a função que estou tentando usar para trocar o valor do item.
function isFree(){
    var preco = document.getElementsByClassName('comprar');
    for(n = 0; n < preco.length; n++){
      var validaPreco = preco[n].innerHTML;
      if(validaPreco == '$ 0'){
        validaPreco = 'Grátis'
      }
    }
  }

Quando utilizo a linha document.getElementsByClassName('comprar')[0].innerHTML no console do navegador tenho retornado o valor que quero usar para comparar, porém quero comparar todos os itens que são trazidos do banco.
E esta é a linha de código onde aparece o preço
<button class="comprar">$ {{item.originalValue}}</button>

Só para deixar claro, estou usando polymer 2, o elemento firebase-query para trazer os dados.

A: No seu código:
function isFree(){
    var preco = document.getElementsByClassName('comprar');
    for(n = 0; n < preco.length; n++){
      var validaPreco = preco[n].innerHTML;
      if(validaPreco == '$ 0'){
        validaPreco = 'Grátis'
      }
    }
  }

Você define o valor de validaPreco como "Grátis", mas isso não irá se refletir no DOM, pois validaPreco e preco[n].innerHTML são objetos diferentes, mesmo que um seja cópia do outro. O que você precisa fazer é modificar o objeto no DOM:
function isFree(){
    var preco = document.getElementsByClassName('comprar');
    for(n = 0; n < preco.length; n++){
      var validaPreco = preco[n].innerHTML;
      if(validaPreco == '$ 0'){
        preco[n].innerHTML = 'Grátis'
      }
    }
  }

Veja um exemplo:

function isFree() {
  var preco = document.getElementsByClassName('comprar');
  for (n = 0; n < preco.length; n++) {
    var validaPreco = preco[n].innerHTML;
    if (validaPreco == '$ 0') {
      preco[n].innerHTML = 'Grátis'
    }
  }
}

isFree();

$ 10,00

$ 0

$ 99,99

$ 0


text:
Q: How to align text in Wordpress? Have a look at my site.
I want to align the text. For example:
Day 4              Visit Gulmarg. Around 2 hours drive. Enjoy the majestic view while on
way. Visit the magnificient snow covered hills. Skating can also be done. You can also
take ride in the Rope ways (Gondola) to reach    upper Gulmarg where you can enjoy more
snow clad mountains. Get back to Srinagar and night stay in the hotel.

Should be:
Day 4              Visit Gulmarg. Around 2 hours drive. Enjoy the majestic view while on
                   way. Visit the magnificient snow covered hills. Skating can also be
                   done. You can also take ride in the Rope ways (Gondola) to reach
                   upper Gulmarg where you can enjoy more snow clad mountains. Get back to
                   Srinagar and night stay in the hotel.

Does anyone have any suggestions on how to do this?

A: By having a look at the code from your site it seems that you have manually given spaces through wordpress wysiwyg editor. Try removing those extra spaces and give a margin or padding through css.


text:
Q: Add SQLite function with Android architecture components I've implemented various distance and bearing functionality between GPS coordinates in iOS using sqlite3_create_function. Porting it to Android I've started to look at the Android architecture components such as Room and was wondering if there was a way to use sqlite functions in this?
I've seen references to using the NDK and write them in C/C++ but I was wondering whether the architecture components had addressed sqlite functions in Java.
Or perhaps it would be better to move the functionality outside the database but it would mean tricky searching for nearby points in a certain direction.


text:
Q: how to find string in sentence using for-loop I'm trying find word in the sentence, what i should do in order to find string in the sentence instead of each character of the string in sentence?
Note: i'm trying to achieve this using for loop.  I don't want to use split() or in-build functions.
def word_in_sen(sentence, word):
result = ''
for i in word:
    for j in sentence:
        if i == j:
            result += i
            break
if result == word:
    return True

else:
    return False

print(word_in_sen("Welcome to python programming ", "python"))
print(word_in_sen("Welcome to python programming ", "long"))
'''
Scenario: 1
checking whether the word "Python" available in the big string.
Expected result: True
Actual result: True
'''
'''
Scenario: 1
checking whether the word "long" available in the big string.
Expected result: False
Actual result: True
'''


text:
Q: $(this).parent("tr").remove(); doe not delete the tablerow from the view This is a question that follows on from my previous question; MVC: Button not firing click event in a tablecell
Because I am creating a grid dynamically, I have to use a jquery delegate in order to attach an event to a button in the grid.
So I have this section in my view;

        <fieldset>
            <legend>Select Other Materials</legend>
            <form method="get" action="@Url.Action("CreateOtherMaterials", "DataService")"
                  data-scd-ajax="true" data-scd-target="#otherMaterialList">

Select a Material: <input type="search" name="searchOtherMaterial" id="searchOtherMaterial" data-scd-autocomplete="@Url.Action("AutocompleteOtherMaterial", "DataService")" style = "width: 300px;" class="submitOtherMaterialSelectionNew" data-scd-add-other-material="@Url.Action("AddOtherMaterialNew", "DataService")"/>
                    @Html.DialogFormButton("Add New Material", Url.Action("AddMaterial", "Popup"), "Add New Material", null, Url.Action("Create"))

            </form>

            @Html.Partial("_OtherMaterials", Model.SupplierMaterialList.Where(x => x.PrimaryMaterialFlag == false).ToList())

        </fieldset>

The Partial View _OtherMaterials looks like
@model IList<SupplierMaterial>

These materials have now been added for this supplier

        @Html.DisplayForModel()

And my display template;
@model SupplierMaterial

    @Model.Material.MaterialName

        <form class="shrinkwrap" method="get" action="@Url.Action("RemoveOtherMaterial", "DataService", new { id = Model.MaterialId })">
            <input type="button" id="btnRemove" value="Remove" class="removeItem"/>
        </form>

I use this query remove a row in the grid when the Remove button is clicked;
 $('body').delegate('.removeItem', 'click', function () {
    var $form = $(this).closest("form");
    var options = {
        url: $form.attr("action"),
        type: $form.attr("method")
    };

    $.ajax(options).done(function (data) {
        $(this).parent("tr").remove();
    });

    return false;
});

I tried replacing the body element with something closer such as #tableOtherSupplierList but that did not work. I would like to use on() instead of delegate but so far only the above code seems to work.
The main issue I have however is that the line $(this).parent("tr").remove(); does not modify my view and remove the tablerow.
How do I fix this?

A: I think this is what you want:
var removeItemEl = $(this);
$.ajax(options).done(function (data) {
    removeItemEl.closest("tr").remove();
});

parent only travels up 1 level. And since .removeItem is within the form, you need closest.
And like foxx was saying, by using this inside the done callback, you're not targetting the dom element. So you have to assign it as a local variable (var removeItemEl = $(this);).

A: $(this) inside your done() function didn't refer to the original dom element anymore..
$('body').delegate('.removeItem', 'click', function () {
    var element = $(this);

    $.ajax(options).done(function (data) {
        element.parent("tr").remove();
    });

});

If it still doesn't work, then tr is not the parent of .removeItems, just do some console.logging to see if the element.parent("tr") is matching the element you want to remove.
You might want to check this as well Difference between jQuery parent(), parents() and closest() functions

A: Try this instead:
$('body').delegate('.removeItem', 'click', function () {
    var $form = $(this).closest("form");
    var $elem = $(this);
    var options = {
        url: $form.attr("action"),
        type: $form.attr("method")
    };

    $.ajax(options).done(function (data) {
        $elem.closest("tr").remove();
    });

    return false;
});


text:
Q: Show that $x^2 \equiv 1 \pmod{n}$ can have arbitrarily many solutions? Equivalently, show that for every $m$, there exists some $n$ such that $x^2 \equiv 1 \pmod{n}$ has at least $m$ solutions.
Would appreciate any help or hints. I have a feeling this may be a pretty simple proof, but right now I am stuck. Thanks!

A: Expanding on my comment:
Let $k$ be some positive integer such that $2^k \geq m$. Let $p_1, p_2, p_3, \cdots, p_k$ be $k$ distinct odd primes. (It's possible to choose $k$ distinct odd primes since there are infinitely many primes.)
Consider $n = p_1 p_2 p_3 \cdots p_k$, and look at the system of congruences
$$\begin{align*}
x \equiv \pm 1 & \pmod{p_1} \\
x \equiv \pm 1 & \pmod{p_2} \\
x \equiv \pm 1 & \pmod{p_3} \\
& \vdots \\
x \equiv \pm 1 & \pmod{p_k}
\end{align*}$$
where we choose either $+1$ or $-1$ for each prime. There are two choices for each prime, and so there are $2^k \geq m$ possible systems that can arise in this way.
by the Chinese Remainder Theorem, each one of these $2^k$ systems has some solution $x$ modulo $p_1 p_2 p_3 \cdots p_k = n$. No two systems give us the same value for $x$ modulo $n$, since if $x_1$ and $x_2$ arise from two different systems of congruences then there is some prime $p_i$ such that
$$ \begin{align*}
x_1 & \equiv \pm 1 \pmod {p_i} && \text{ but } & x_2 & \equiv \mp 1 \pmod {p_i}
\end{align*} $$
(i.e. $x_1$ and $x_2$ have different remainders modulo some prime factor of $n$)
This shows that $x_1$ and $x_2$ are not congruent modulo $n$, and so we in fact get $2^k$ distinct values of $x$ by looking at systems of congruences of the form given above.
Now for any such solution $x$, we have that
$$\begin{align*}
x^2 \equiv (\pm 1)^2 & \equiv 1 \pmod{p_1} \\
x^2 \equiv (\pm 1)^2 & \equiv 1 \pmod{p_2} \\
x^2 \equiv (\pm 1)^2 & \equiv 1 \pmod{p_3} \\
& \vdots \\
x^2 \equiv (\pm 1)^2 & \equiv 1 \pmod{p_k}
\end{align*}$$
and so we see (since the $p_i$ are pairwise relatively prime) that
$x^2 \equiv 1 \pmod n$.
Thus each of the $2^k \geq m$ possible values for $x$ are a solution to $x^2 \equiv 1 \pmod n$.


text:
Q: How to control colorbar color ranges in Matlab plots? I have the following code:
[X,Y,Z] = peaks(30);
crange = 1.5;

[maxval dummy] = max(Z(:));
[minval dummy] = min(Z(:));

% green, yellow, red
cmap = [0 1 0; 1 1 0; 1 0 0];

figure
colormap(cmap);
surf(X,Y,Z);
caxis([30 55]);
cbh=colorbar;
set(cbh,'Ytick',[30 32 38 55]);

My goal is to set the limits of the color bar so that the colors are like this:

*

*green from 30 to 32

*yellow from 32 to 38

*red from 38 to 55

I believe I should somehow change the CData variable, so I used these lines of code without success:
i = findobj(cbh,'type','image');
set(i,'cdata',[30 32 38]','YData',[30 55]);

A: Your custom colorbar consists of (32-30 = ) 2 + (38-32 = ) 6 + (55-38 = ) 17 = 25 "units" of color. So a simple trick would be replicating each color the required number of "units":
function q58097577
[X,Y,Z] = peaks(30); Z = (Z - min(Z(:)))*5;

% green, yellow, red
nG = 32-30; nY = 38-32; nR = 55-38;
cmap = [ repmat([0 1 0], [nG 1]); repmat([1 1 0], [nY,1]); repmat([1 0 0], [nR,1]) ];

figure()
colormap(cmap);
surf(X,Y,Z);
caxis([30 55]);
cbh=colorbar;
set(cbh,'Ytick',[30 32 38 55]);

Resulting in:


text:
Q: Ant: read filenames, create folder based on names, move files into folders Using Ant tasks, I want to read all filenames in a directory and copy each of the files into one folder, with the folder name the same as the file but without the extension.
Starting with:
converted/aa_aa.dita
converted/bb_bb.dita
converted/cc_cc.dita

and ending up with:
aa_aa/aa_aa.dita
bb_bb/bb_bb.dita
cc_cc/cc_cc.dita

and so on.
So far I've got this, which reads the filenames with their path and puts them in a .txt file:
<target name="move_dita_to_folder">
  <pathconvert pathsep=","
    property="my.files">
   <path>
     <fileset dir=".">
       <include name="*.dita"/>
     </fileset>
   </path>
 </pathconvert>

<echo file="my.files.txt" append="true">
my.files=${my.files}</echo>

This makes a file containing the filenames contained in the full path, separated by commas.
Update:
Now I have this extracting the filenames from the txt file and rewriting the txt file to put each of them on a new line:
   <replaceregexp byline="false" flags="gis">
     <regexp pattern="(C:)(.*?)converted\\(.*?).dita"/>
     <substitution expression="${line.separator}\3"/>
     <fileset dir=".">
     <include name="**/*.txt"/>
     </fileset>
   </replaceregexp>

The result being:
    my files=
aa_aa
bb_bb
cc_cc

So now I need to use those to create folder names, and copy the files into the appropriate ones.
I saw  this post about using regex and mapper however which seems like a better way-- but I can't replicate what's being described there at all. Any help appreciated.

A: You may use a nested scriptmapper with builtin (since Java 1.6.0_06) javascript engine :
<copy todir="..." verbose="true">
 <fileset dir="..." includes="**/*.dita"/>
 <scriptmapper language="javascript">
  self.addMappedName(source.replace(source.split('.')[0], source.split('.')[0] + "/" + source.split('.')[0]));
 </scriptmapper>
</copy>


text:
Q: Hide file extension out of folders with .htaccess My website is like organized like this:

*

*index.php

*products.php

*files

*

*file_manager.php

*another_file.php

I want to remove the extensions only from my files at root. So in this case, index.php should be index and products.php should be products but I don't want to touch on the file extensions inside folders. So file_manager.php and another_file.php should stay with the extensions
At this point my code is like this:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*?)/?$ $1.php

but this code removes extensions from folders do.
How can I change this?

A: Tweak your regex to ensure that it affects root files only:
RewriteEngine on

RewriteCond %{THE_REQUEST} \s/+([^/]+?)\.php[\s?] [NC]
RewriteRule ^ /%1 [R=301,NE,L]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^([^/]+?)/?$ $1.php [L]


text:
Q: Normalizing my nested JSON with normalizr I'm having the following JSON from my service:
[
   {
      "name":"Voter1",
      "id":1,
      "votingCard":{
         "verificationCodes":[
            "3I08jA",
            "3x0eyE",
            "2_i69I"
         ],
         "votingCode":"7zCOelDnjfBm7TtFydc4QodgonG",
         "finalizationCode":"jyYu",
         "confirmationCode":"4ACfcpBVH45iAXqg7hJ0tbEe_tV"
      }
   },
    .....
   {
      "id":5,
      "name":"Voter5",
      "votingCard":{
         "verificationCodes":[
            "2c9I9a",
            "3bEeEa",
            "1gPKx2"
         ],
         "confirmationCode":"4Z7wNG35VR2UMO6-W-0aZVEhbLM",
         "votingCode":"6YQ2x-c8LXJZF05gh3zTajU79ct",
         "finalizationCode":"S0CY"
      }
   }
]

And would like to get it normalized, so a list of votingCards and a list of voters with a "votingCard" property referencing the votingCard by id.
import { normalize, schema } from 'normalizr';

const votingCard = new schema.Entity('votingCard');

const voter = new schema.Entity('voter', {
    votingCard: votingCard,
});

const votersSchema = new schema.Array(voter);

const mutations = {
    SOCKET_SYNCVOTERS: (state, data) => {
        var input = JSON.parse(data);
        const normalizedData = normalize(input, votersSchema);
        console.log(normalizedData);
    },
};

However, I'm not getting what I want:
Why is there an "undefined"?

A: I think you need to specify an 'idAttribute' in the options for the votingCard entity - the problem is that normalizr can't find an 'id' field in those objects so they are all being picked up as id undefined and overwriting each other in entities.  See: https://github.com/paularmstrong/normalizr/blob/master/docs/api.md#schema


text:
Q: CockroachDB C++ transaction retry issue I'm trying to run the basic C++ example, basically:
void executeTx(
    pqxx::connection *c, function<void (pqxx::dbtransaction *tx)> fn) {
  pqxx::work tx(*c);
  while (true) {
    try {
      pqxx::subtransaction s(tx, "cockroach_restart");
      fn(&s);
      s.commit();
      break;
    } catch (const pqxx::pqxx_exception& e) {
      // Swallow "transaction restart" errors; the transaction will be retried.
      // Unfortunately libpqxx doesn't give us access to the error code, so we
      // do string matching to identify retryable errors.
      if (string(e.base().what()).find("restart transaction:") == string::npos) {
        throw;
      }
    }
  }
  tx.commit();
}

However, transactions never get retried correctly, I'm getting this error:
current transaction is aborted, commands ignored until end of transaction block
Looks like the top level transaction pqxx::work tx(*c); gets poisoned? The second iteration of the loop always fails


text:
Q: AsyncCommand CanExecute handler I am using the @Stephen-Cleary AsyncCommand implementation in WPF (.NET 4.0) and now I am trying to find out how to specify the CanExecute handler during command definition.
Usually I create the command like this:
            SaveCommandAsync = AsyncCommand.Create(async token =>
            {
                //async code
            });

I don't see any Create overload so I can specify CanExecute logic.
Thank you,
Igor

A: Use Stephen Cleary's Nito.Mvvm.Async project to achieve what you need.
Add nuget reference to the package:
<package id="Nito.Mvvm.Async" version="1.0.0-eta-05" targetFramework="net45" />
Create Xaml binding:
<Button Content="Toggle" Command="{Binding MyAsyncCommand}"></Button>
Create CustomAsyncCommand, specifying CanExecute function
MyAsyncCommand = new CustomAsyncCommand(AsyncAction, x=> !_isWorking);
Do some async work in AsyncAction
private async Task AsyncAction(object obj) {
    _isWorking = true;
    MyAsyncCommand.OnCanExecuteChanged();
    await Task.Delay(2000);
    _isWorking = false;
    MyAsyncCommand.OnCanExecuteChanged();
}

And finally: enjoy.

A: Just for update this topic.
Currently actual reference implementation of AsyncCommand is in CommunityToolkit.Mvvm.Input project that could be referenced with apropriate NuGet. And in code it could be written something like this:
// In properties declaration
public IAsyncRelayCommand MyCommand { get; }
// In ctor
MyCommand = new AsyncRelayCommand(MyAction, () => MyCanExecute());
// Action declaration
private async Task MyAction() // Also could be a (CancellationToken token)
{ }
// Can exectute declaration
private bool DownloadTextCanExecute()
{ return !MyCommand.IsRunning; }

Make attention that CanExecute do not enables or disables a button that have a binding to apropriate Command. It just enables execution of a Command. In case if you want to represent a CanExecute by enabling or disabling a button, you could use something like the following in your XAML:
<Button
        Content="Click me!"
        Command="{Binding MyCommand}"
        IsEnabled="{Binding MyCommand.IsRunning, Converter={StaticResource InverseBooleanConverter}, Mode=OneWay}"/>

Implementation of a InverseBooleanConverter you could find in other answers. Or you could see a full code of a demo project WpfAsyncCommandExample


text:
Q: Certificate verify failing when running python under supervisord I have a program that runs successfully in my user/virtualenv. The program access an API using requests. For the purposes of this post, the whole program can be read as:
requests.get("https://example.com")

This works totally fine when I call it from the command line. However I'm trying to get it to run under supervisord and for whatever reason when I do it this way it is failing with an SSL Error like the below:
SSLError("bad handshake: Error([('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')],)")

It is using the same user, python environment, directory etc. Any idea what else to check / what else could be causing this?
Edit: I think this might be a firewall rule type of thing. Exploring that option.

A: Are the SSL certificates available in the supervisord environment? I assume you use requests.certs, so are the certificates there where expected requests.certs.where()?

A: So it turns out this was a network proxy thing. The machine I was running on uses a squid proxy and I had to add the following line to set the right environment variables in my supervisor config for it to work:
environment=http_proxy=http://proxy.server:3128/,https_proxy=http://proxy.server:3128/


text:
Q: How to get data from MS SQL Server 2008 into Mapserver? I need to create some layers in my map from a Microsoft SQL 2008 database.  I am using Openlayers and Mapserver.  The Mapserver instance is running on SUSE linux, so the Mapserver documentation on MSSQL that discusses the plugin for Windows is not very helpful.
I know it is possible because I have in the past gotten it to work, however I scrapped that project in favor for something else.  I now have a need for it once again and have been unsuccessful finding any clear and concise examples.
Any help or direction would be greatly appreciated.

A: To confirm the Windows plugin you are referring to is the MSSQL Plugin at http://mapserver.org/input/vector/mssql.html?
Does the OGR driver work on Linux when connecting to Linux? http://www.gdal.org/ogr/drv_mssqlspatial.html
It makes reference to a different ODBC driver that can be used in the connection string:

The connection may contain the optional Driver parameter if a custom
  SQL server driver should be loaded (like FreeTDS). The default is {SQL
  Server}

FreeTDS is

a set of libraries for Unix and Linux that allows your
  programs to natively talk to Microsoft SQL Server and Sybase
  databases.

So maybe this driver can also work with the MapServer SQL Server 2008 plugin? If not you could try creating an OGR Layer.


text:
Q: Prevent Visual Studio Code or IDE From Revealing Python Class Private Methods just want to ask a quick question;
Essentially, I want to know if it's possible to hide Python class private methods from the list of suggestions that Visual Studio Code or other IDEs provide.
For instance, suppose that we have a class "A":
# Creating a class
class A:

    # Declaring public method
    def fun(self):
        print("Public method")

    # Declaring private method
    def __fun(self):
        print("Private method")

    # Calling private method via
    # another method
    def Help(self):
        self.fun()
        self.__fun()

Now, we don't want Visual Studio Code or other IDEs to show the method "__fun" in the list of suggestions provided by the IDE, how can we do that?
I can see that even though "__fun" has been declared as private method inside class "A", Visual Studio code will still suggest it in its snippet:

Would it be possible to get rid of this?

A: I may have found a partial solution to your question, which may help
There is a python language setting in vscode that, if enabled, reports an usage of 'protected' function (started with underscore) outside of the class.
Press CTRL+SHIFT+P, type "Configure Language Specific Settings" and select Python. In JSON object add the following property:
"python.analysis.diagnosticSeverityOverrides": {
    "reportPrivateUsage": "error"
}

source: code.visualstudio.com/docs/python/settings-reference

A: You could simulate private methods using a method registration class but it will require tagging both the private methods and the public methods that are allowed to access them:
class PrivateMethods:

    def __init__(self):
        self.methods = dict()

    def __call__(self,f):
        name = inspect.getsource(f).split("def ",1)[-1]
        name = name.split("(")[0].strip()
        self.methods[name]=f              # register private method
        del(f)                            # and remove it from class

    def access(self,f):
        def withAccess(obj,*args,**kwargs):
            obj.__inPrivate += 1                  # internal depth counter
            try: result = f(obj,*args,**kwargs)   # around public calls
            finally: obj.__inPrivate -= 1
            return result
        return withAccess

    def method(self,instance,name):
        if name == '_PrivateMethods__inPrivate': return 0
        if name in self.methods and instance.__inPrivate:
            f = self.methods[name]
            return lambda *args,**kwargs:f(instance,*args,**kwargs)
        else:
            raise AttributeError(f'{type(instance)} has no {name} attribute')

You class will need to have an instance of PrivateMethods to hold the names and code of the private methods outside of the class itself.  By defining the __getattr__ to access the private methods, you prevent any use of these methods outside of the class's code.  The PrivateMethods object stores the name and code of private methods. It also removes them from the class (after being defined).
With this, you don't need to use the double underline naming convention to hide private methods (although it is still a good practice to do so)
Usage:
class myClass:

    # boiler plate code to use in your class
    private = PrivateMethods()
    def __getattr__(self,name):
        return myClass.private.method(self,name)

    def privMethod(self,a):
        print('in private',a,type(self))
    private(privMethod)                   # register/remove private

    @private.access                       # allow access to privates
    def pubMethod(self):
        self.privMethod("from pubMethod")

c = myClass()
c.pubMethod()
# in private from pubMethod <class '__main__.myClass'>

c.privMethod("from outside")
# AttributeError: <class '__main__.myClass'> has no privMethod attribute


text:
Q: MVC Routing not working as expected I'm trying to get to grips with the MVC Routing system but its not working as I would expect.
Say I have this route defined:
context.MapRoute(
        "NewCertificates",
        "NewQuote/GetCertificate/{date}/{id}",
        new { area = "NewQuote", controller = "Quote", action = "GetCertificate" },
        new[] { "Acme.Areas.NewQuote.Controllers" }
    );

And this Action Link in my View:
@Html.ActionLink("Click Here", "GetCertificate", new { controller = "Quote", area = "NewQuote", date = "20121219", id = "acme" })

I'd expect the generated URL to look like:
http://localhost:50582/NewQuote/GetCertificate/20121219/acme

but instead I get:
http://localhost:50582/NewQuote/GetCertificate/acme?date=20121219

Can anyone tell me why this is happening?
Edit to show routes which precede the one mentioned above:
        context.MapRoute(
                "NewQuoteValidation",
                "NewQuote/Validation/{action}/{id}",
                new { area = "NewQuote", controller = "Validation", action = "IsImeiAvailable", id = UrlParameter.Optional },
                new[] { "Acme.Areas.NewQuote.Controllers" }
            );

        context.MapRoute(
                "NewAjax",
                "NewQuote/Ajax/{action}/{id}",
                new { area = "NewQuote", controller = "Ajax", action = "Index", id = UrlParameter.Optional },
                new[] { "Acme.Areas.NewQuote.Controllers" }
            );

        context.MapRoute(
                "NewQuote",
                "NewQuote/{action}/{id}",
                new { area = "NewQuote", controller = "Quote", action = "Select", id = UrlParameter.Optional },
                new[] { "Acme.Areas.NewQuote.Controllers" }
            );

A: It's likely that another, prior route definition is claiming ownership of the ActionLink definition.  You might want to try:

*

*Putting the "NewCertificates" route definition first, or higher in the list.

*Constructing the link explicitly based on the route, using Html.RouteLink

@Html.RouteLink("Click Here",
      // route name
    "NewCertificates",
      // route attributes
    new { controller = "Quote", area = "NewQuote", date = "20121219", id = "acme" })

A: try this for calling your Route:
@Html.RouteLink("Click Here", "NewCertificates", new { controller = "Quote", area = "NewQuote", id = "acme" })


text:
Q: Transfer data from Excel to Word using Visual Studio 2010 - C# this is my first question here. I am using Visual Studio 2010 and I want to design an Excel Addin for a sales catalog. It has two forms and I got one of them working but the other one not. What I want to achieve is that I open up a Windows form through the Addin and through the form I get data from my Access database. I import the data into a datagrid and then I export the data to Excel.
I got this part working but I have problems with my next form. In that form I want to open up a Word template ( when I press a button) and then the data from the open Excel file is transferred into my Word document.
Does anybody know what would be the best way to do this?
I use OleDBConnection to get the data from the database to the datagrid. I am designing this for Office 2007 and I am programming in C#.
Here is part of my code. I use this part to get the data from the Excel file into a DataGrid but I want to be able to bring that data into a WordDocument.
Does anybody know what is the best way to do that.
DataSet da = new DataSet();
OleDbDataAdapter adapter = new OleDbDataAdapter();
string workbookPath = "C:myfile.xlsx";

Excel.Workbook wb = Globals.ThisAddIn.Application.Workbooks.Add(workbookPath);
string ConnectionString =
    @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + workbookPath
    + @";Extended Properties=""Excel 12.0 Macro;HDR=Yes;ImpoertMixedTypes=Text;TypeGuessRows=0""";

OleDbConnection conn = new OleDbConnection(ConnectionString);
string strCmd = " select * from [Sheet1$A1:D4]"; //Or some other range
OleDbCommand cmd = new OleDbCommand(strCmd, conn);

conn.Open();
da.Clear();
adapter.SelectCommand = cmd;
adapter.Fill(da);
dataGridView1.DataSource = da.Tables[0];

Thanks in advance.

A: Ok, so with the help I got from jmh_gr I managed to get this working. This is how it looks. It basically does what it is supposed to do, copies data from Excel and pastes it to Word.
object fileName = "C:\\Template_1.docx";
string workbookPath = "C:\\Book1.xlsx";
Excel.Workbook wb = Globals.ThisAddIn.Application.Workbooks.Add(workbookPath);
Excel.Worksheet ws = wb.Worksheets[1];
ws.Range["A1:D4"].Copy();

object missing = System.Reflection.Missing.Value;
Word.Application wordApp = Marshal.GetActiveObject("Word.Application") as Word.Application;
Word.Document doc;
Word.Range rng;
doc = wordApp.ActiveDocument;
rng = wordApp.Selection.Range;

object objDataTypeMetafile = Word.WdPasteDataType.wdPasteRTF;
rng.PasteSpecial(ref missing, ref missing,
ref missing, ref missing, ref objDataTypeMetafile,
ref missing, ref missing);

A: Since you're copying between two Office applications I would recommend you use the built-in PasteExcelTable Method. Just add a reference to the Microsoft Word 1x.0 Object Library:
using Word = Microsoft.Office.Interop.Word;
...

string workbookPath = @"C:\temp\example.xlsx";
Excel.Workbook wb = Globals.ThisAddIn.Application.Workbooks.Add(workbookPath);
Excel.Worksheet ws = wb.Worksheets[1];
Word.Application wdApp = new Word.Application();
Word.Document wdDoc = wdApp.Documents.Add();
ws.Range["A1:D4"].Copy();
wdDoc.ActiveWindow.Selection.PasteExcelTable(false, false, false);

A: Follow below code to  Copy Active Cells from Excel to Word( Source Formatting will remain same)
var applicationWord = new Microsoft.Office.Interop.Word.Application();
            applicationWord.Visible = true;
            Word.Document wordDoc = applicationWord.Documents.Add();
            var cells = getCells();
            var last_row = cells.Row;
            var last_col = cells.Column;
            var firstcell = activeWorksheet1.get_Range("A1", Type.Missing);
            var lastcell = (Excel.Range)activeWorksheet1.Cells[last_row, last_col];

            activeWorksheet.Range[firstcell, lastcell].Copy(); // All Active cell will get copied
            wordDoc.ActiveWindow.Selection.PasteExcelTable(false, false, false);

Below Code to get active cells in the WorkSheet:
dynamic getCells()
        {
        activeWorksheet1 = ((Excel.Worksheet)Application.ActiveSheet);
        var CellZ = activeWorksheet1.Cells.Find(
                "*",
                System.Reflection.Missing.Value, Excel.XlFindLookIn.xlValues,
                Excel.XlLookAt.xlWhole,
                Excel.XlSearchOrder.xlByRows,
                Excel.XlSearchDirection.xlPrevious,
                false,
                System.Reflection.Missing.Value,
                System.Reflection.Missing.Value);
            return CellZ;
        }


text:
Q: how to see oneself edges using java3d transparency When setting an object's transparency on in Java3D, I cant see the other objects through that object but I can't see this very object geometry through it. Is that possible ?
(example: I have a transparent cube that is lit a way that the faces have different colors, however, I can only see at most 3 faces of the cube at the same time)

A: This probably has something to do with Culling.
Check out this example: http://java.sun.com/developer/onlineTraining/java3d/j3d_tutorial_ch2.pdf
Go to page 2-42, section 2.6.4. I have a feeling it has to do with that.


text:
Q: json file not loading frim Visual Studio 2013 I am attempting to create a drag-able network diagram using d3.js and have run into an unusual problem.  When I attempt to run the page from Visual Studios 2013 I get the following error:
"Unhandled exception at line 25, column 13 in http://localhost:58771/HtmlPage1.html
0x800a138f - Microsoft JScript runtime error: Unable to get value of the property 'links': object is null or undefined"
If I move the HTML page and the .json file to my local drive the page opens with no problem.
Here is the d3 code:
     d3.json("graph.json", function (error, graph) {
        graph.links.forEach(function (d) {
            d.source = graph.nodes[d.source];
            d.target = graph.nodes[d.target];
        });

the json file is rather large so I am not posting it.  The question is why it works from my local c: drive but not from the asp project in visual studio.  The graph will be part of an ASP.net application so I can not use a different format for the website.
Thanks for any help with this.

A: The ASP.NET project runs at IIS Web Server and its behavior doesn't like windows   directory, so you should set the d3.json() url property just same as json file URL, Actually you are running your project at a virtual server, so you should follow these steps:

*

*Add this code inside web.config file <configuration></configuration> tag  to allow IIS to serve the json file as well, without this code IIS thinks the json file is a path of URL.
<system.webServer>
 <handlers>
   <remove name="BlockViewHandler"/>
   <add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />
   </handlers>
    <staticContent>
     <mimeMap fileExtension=".json" mimeType="application/json" />
    </staticContent>
    </system.webServer>

*Get the json file URL and give it to the d3.json() function
If you are using Razor View Engine you can get the url like this:
'I suggest you keep graph.json inside a folder that is named Data'
 var url = "@Url.Content("~/Data/graph.json")";
 d3.json(url, function (error, graph) {
       graph.links.forEach(function (d) {
        d.source = graph.nodes[d.source];
        d.target = graph.nodes[d.target];
    });

If you are using ASP.NET Webforms just convert d3.json() to this:
   d3.json("~/Data/graph.json", function (error, graph) {
       graph.links.forEach(function (d) {
        d.source = graph.nodes[d.source];
        d.target = graph.nodes[d.target];
       });

Start from solution explorer and follow the folders to find the graph.json and save it like a windows directory. I'm always using ~ to remove all the path and begin from the top.
Hope this helps.

A: Here is the entire code for review:
!DOCTYPE html>
<html>
<head>
<title></title>
<script src="http://d3js.org/d3.v2.js"></script>
<style>
    .link {
        stroke: #ccc;
    }

    .nodetext {
        pointer-events: none;
        font: 10px sans-serif;
    }
</style>
</head>
<body>
<script type="text/javascript">

    var w = 1280,
        h = 1024;

    var color = d3.scale.category20();

    var vis = d3.select("body").append("svg:svg")
        .attr("width", w)
        .attr("height", h);

    d3.json("graph3-copy.json", function (json) {
        var force = self.force = d3.layout.force()
            .nodes(json.nodes)
            .links(json.links)
            .gravity(.05)
            .distance(100)
            .charge(-100)
            .size([w, h])
            .start();

        var link = vis.selectAll("line.link")
            .data(json.links)
            .enter().append("svg:line")
            .attr("class", "link")
           .attr("x1", function (d) { return d.source.x; })
           .attr("y1", function (d) { return d.source.y; })
           .attr("x2", function (d) { return d.target.x; })
           .attr("y2", function (d) { return d.target.y; });

        var node_drag = d3.behavior.drag()
            .on("dragstart", dragstart)
            .on("drag", dragmove)
            .on("dragend", dragend);

        function dragstart(d, i) {
        force.stop() // stops the force auto positioning before you  start dragging
        }

        function dragmove(d, i) {
            d.px += d3.event.dx;
            d.py += d3.event.dy;
            d.x += d3.event.dx;
            d.y += d3.event.dy;
            tick(); // this is the key to make it work together with updating both px,py,x,y on d !
        }

        function dragend(d, i) {
            d.fixed = true; // of course set the node to fixed so the force doesn't include the node in its auto positioning stuff
            tick();
            force.resume();
        }

        var node = vis.selectAll("g.node")
            .data(json.nodes)
          .enter().append("svg:g")
            .attr("class", "node")
            .call(node_drag);

        node.append("svg:image")
            .attr("class", "circle")
            .attr("xlink:href", "https://github.com/favicon.ico")
            .attr("x", "-8px")
            .attr("y", "-8px")
            .attr("width", "16px")
            .attr("height", "16px");

        node.append("svg:text")
            .attr("class", "nodetext")
            .attr("dx", 12)
            .attr("dy", ".35em")
            .text(function (d) { return d.name });

        force.on("tick", tick);

        function tick() {
            link.attr("x1", function (d) { return d.source.x; })
                .attr("y1", function (d) { return d.source.y; })
                .attr("x2", function (d) { return d.target.x; })
                .attr("y2", function (d) { return d.target.y; });

            node.attr("transform", function (d) { return "translate(" + d.x + "," + d.y + ")"; });
        };

    });

</script>
</body>
</html>

The firefox console is telling me the json file is empty.  That is not correct I have verified the data is there and the page runs outside visual studio.


text:
Q: Why doesn't this give Jefimenko's equations? By the Lorentz guage $\displaystyle \nabla \cdot \mathbf A = -\frac{1}{c^2}\partial_t \varphi\ $ one gets the inhomogeneous wave equations for the potentials
$$
\square^2 \varphi =  -\frac{1}{\epsilon_0}\rho, \qquad \square^2 \mathbf A =  -\mu_0\mathbf J \tag{I}
$$
where $\displaystyle \square^2 \equiv \nabla^2 - \frac{1}{c^2}\partial^2_t\ $. The solution are (the retarded potentials)
$$
\varphi = \frac{1}{4\pi\varepsilon_0}\int\frac{\rho(\mathbf r',t_r)}{\ell}d\tau', \qquad
\mathbf A = \frac{\mu_0}{4\pi}\int\frac{\mathbf J(\mathbf r',t_r)}{\ell}d\tau'
$$
where $$\ell = |\boldsymbol{\ell}|, \quad
\boldsymbol{\ell} = \mathbf {r - r'}, \quad
\boldsymbol{\hat \ell} = \frac{\boldsymbol{\ell}}{\ell}, \quad
\displaystyle t_r = t - \frac{\ell}{c}
$$
Maxwell's equations can be decoupled for $\mathbf E$ and $\mathbf B$ to get the two equations
$$
\square^2 \mathbf E =  \frac{1}{\epsilon_0}\nabla\rho + \mu_0\partial_t\mathbf J,\qquad
\square^2 \mathbf B =  -\mu_0\nabla\times \mathbf J \tag{II}
$$
Now these two equtions are similar to the that of $\mathbf A$, with the $-\mu_0 \mathbf J$ in (I) replaced by $\frac{1}{\epsilon_0}\nabla\rho + \mu_0\partial_t\mathbf J$ and $-\mu_0\nabla\times \mathbf J$ in (II) respectively. So I think that it is possible to solve (II) by a retartded potential solution as for the case of (I).
If one attempts a retarded potential solution for $\mathbf B$ one gets
$$
\mathbf B(\mathbf r,t) = \frac{\mu_0}{4\pi} \int\left[ \frac{\nabla'_1\times \mathbf J(\mathbf r',t_r)}{\ell} \right]\, d\tau'  \tag{*}
$$
where $\displaystyle \nabla'_1$ denotes the differentiation wrt the first argument in $\mathbf J(\mathbf r',t_r)$ only, (as it should, right ?)
On the other hand, I expect the solution to be the Jefimenko's equation for magnetic field (as in Griffiths)
$$
\mathbf B(\mathbf r,t) = \frac{\mu_0}{4\pi} \int\left[ \frac{\mathbf J(\mathbf r',t_r)}{\ell^2} + \frac{\mathbf{ \dot{ J}}(\mathbf r',t_r)}{c\ell} \right] \times \boldsymbol{\hat{\ell}}\, d\tau'  \tag{**}
$$
but it doesn't seem that these two solutions are the same, not even in the static case!

So why solving
$$
\square^2 \mathbf A =  -\mu_0\mathbf J \tag{I}
$$
with retarded potential is correct but solving the similar equation (i.e. of the same mathematical form)
$$
\square^2 \mathbf B =  -\mu_0\nabla\times \mathbf J \tag{II}
$$
is not correct ?

A: If there is something wrong please comment!
Taking total rotation gives
$$
\nabla'\times \mathbf J(\mathbf r',t_r) = \nabla'_1\times \mathbf J(\mathbf r',t_r) - \frac{1}{c}\mathbf{\dot J}(\mathbf r',t_r)\times \boldsymbol{\hat \ell}
$$
which implies
$$
\nabla'_1\times \mathbf J(\mathbf r',t_r) =  \nabla'\times \mathbf J(\mathbf r',t_r) + \frac{1}{c}\mathbf{\dot J}(\mathbf r',t_r)\times \boldsymbol{\hat \ell} \tag{1}
$$
On the other hand we have the product rule (with differentiation wrt $\mathbf r$)
$$
\nabla \times (f \mathbf A) = f(\nabla\times\mathbf A) - \mathbf A\times(\nabla f)
$$
If it is a (total) differentiation of $\displaystyle \frac{\mathbf J(\mathbf r',t_r)}{\ell}$ wrt $\mathbf r'$ then
$$
\nabla' \times \left(\frac{\mathbf J(\mathbf r',t_r)}{\ell}\right) = \frac{\nabla' \times\mathbf J(\mathbf r',t_r)}{\ell} - \mathbf J(\mathbf r',t_r)\times\left(\nabla' \frac{1}{\ell}\right)
$$
Which imples
$$
\frac{\nabla' \times\mathbf J(\mathbf r',t_r)}{\ell}  =  \nabla' \times \left(\frac{\mathbf J(\mathbf r',t_r)}{\ell}\right) + \mathbf J(\mathbf r',t_r)\times\left(\nabla' \frac{1}{\ell}\right) \tag{2}
$$
First substituting ($1$) in the integrand of ($*$) it becomes
$$
\frac{\nabla_1' \times\mathbf J(\mathbf r',t_r)}{\ell} = \frac{\nabla' \times\mathbf J(\mathbf r',t_r)}{\ell} + \frac{\mathbf{\dot J}(\mathbf r',t_r)}{c\ell} \times \boldsymbol{\hat \ell}
$$
Now substituting ($2$) we get
$$
\frac{\nabla_1' \times\mathbf J(\mathbf r',t_r)}{\ell} = \nabla' \times \left(\frac{\mathbf J(\mathbf r',t_r)}{\ell}\right) + \mathbf J(\mathbf r',t_r)\times\left(\nabla' \frac{1}{\ell}\right)  + \frac{\mathbf {\dot J}(\mathbf r',t_r)}{c\ell} \times \boldsymbol{\hat \ell}
$$
Since the integral is over all the space the integral of the first term will vanish (see below). Moreover $\displaystyle \nabla' \frac{1}{\ell} = -\nabla \frac{1}{\ell} = \frac{\boldsymbol{\hat \ell}}{\ell^2}$, that means the significant integrand is
$$
\frac{\mathbf J(\mathbf r',t_r)}{\ell^2}\times \boldsymbol{\hat \ell} + \frac{\mathbf{\dot J}(\mathbf r',t_r)}{c\ell} \times \boldsymbol{\hat \ell}
= \left[ \frac{\mathbf J(\mathbf r',t_r)}{\ell^2} + \frac{\mathbf{\dot{ J}}(\mathbf r',t_r)}{c\ell} \right] \times \boldsymbol{\hat{\ell}}
$$
which is the integrand of ($**$), and therefore the equations ($*$) and ($**$) are equivalent. That is the retarded potential solution of (II) coincides with the Jefimenko's equation for $\mathbf B$.

The volume integral of the neglected term is transformed into a surface integral via
$$
\int_V \nabla'\times\mathbf F(\mathbf r') \,d\tau' = -\oint_{S(V)} \mathbf F\times d\mathbf a', \qquad \mathbf F(\mathbf r') = \frac{\mathbf J(\mathbf r',t_r)}{\ell}
$$
For the the integral (*) to exist, one should have $r^2|\nabla\times\mathbf J| \to 0 $ as $r \to \infty$, which implies (but I'm not sure) that $r^2|\mathbf J| \to 0 $ as $r \to \infty$ and it follows that the surface integral vanishes.

A: The electric and magnetic fields don't just obey the wave equations you wrote down, but also constraint equations
\begin{equation}
\nabla \cdot \mathbf{E}=\rho, \ \ \nabla \cdot \mathbf{B}=0
\end{equation}
Simultaneously satisfying the wave equation and the constraint equations modifies the solution you would naively guess from the unconstrained wave equation.
Additionally, the sources obey a continuity equation, which you may need to use to show equivalence with the standard form of  Jefimenko's equation.
Appendix A of these notes provides an argument to derive Jefimenko's equations without using the potentials.

A: Complete turn-around edit. Eqs. * and ** are indeed equivalent by partial integration.
As a side note, indeed the rotation only works on the unretarded current. The source of the wave equation for B is the retarded rotation of the current (at the source position), not to be confused with the rotation of the retarded current that is the source of the wave equation for A.

A: I post here relevant pages 58-59,515-516 from Electricity and Magnetism, 2nd Edition 1989, by Oleg Jefimenko :
pages 58-59,515-516


text:
Q: 2010 List Grouping not staying expanded after edit I have a list that I am grouping.  In the previous version, when an edit was made, the group I was working in would stay expanded so I could just move onto the next item.  In the 2010 version, it collapses each time an edit is made. Is there a way to fix this?

A: The view you are currently using is corrupted. This might have happened because of editing in designer or something else.
Create a new view based on the existing view and delete the existing view.


text:
Q: How to grant Oauth access to API without cut-and-pasting the consumer key? The documentation about the OAuth API looks very fuzzy on one point: how the client app is supposed to get the consumer key in the first place?
Indeed, let's say we have a webapp (SaaS) named FooX which need to pull data from the Magento API. After the registration within FooX, teh webapp would forward the merchant (aka the admin of the Magento instance) toward its Magento store, initiating the OAuth process.
However, looking at the documentation, it seems to me that the merchant is supposed to first to manually create a consumer app and then, manually move - aka cut-and-paste - those keys into FooX; which seems to completely defeat the purpose of having OAuth in the first place.
Could someone shed some light on the expected user experience associated to an OAuth integration with Magento? Is the merchant really expected to copy and paste keys around manually? Thanks!


text:
Q: Maven - How to tell Maven to run integration tests with application-integration.properties under src/test/resources? small question regarding Maven and how to run integration test, but with a different default path for the profile properties file.
Currently, integration tests phase runs fine in the application-integration.properties found under src/main/resources.
   <profiles>
        <profile>
            <id>integration</id>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.springframework.boot</groupId>
                        <artifactId>spring-boot-maven-plugin</artifactId>
                        <configuration>
                            <wait>1000</wait>
                            <maxAttempts>180</maxAttempts>
                            <jmxPort>${random.jmx.port}</jmxPort>
                            <jvmArguments>
                                -Dspring.application.admin.enabled=true
                            </jvmArguments>
                        </configuration>
                        <executions>
                            <execution>
                                <id>pre-integration-test</id>
                                <goals>
                                    <goal>start</goal>
                                </goals>
                            </execution>
                            <execution>
                                <id>post-integration-test</id>
                                <goals>
                                    <goal>stop</goal>
                                </goals>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>

</project>

I just want to tell Maven, "hey, don't look at the default localtion under src/main/resources, I moved it under src/test/resources, please read it from there".
How to configure this please?
Thank you

A: You can set in the configuration section profile to "integration" by adding
<profiles><profile>integration</profile></profiles>


text:
Q: Why are OpenMP Reduction Clauses Non-deterministic for Statically Scheduled Loops? I have been working on a multi-GPU project where I have had problems with obtaining non-deterministic results. I was surprised when it turned out that I obtained non-deterministic results due to a reduction clause executed on the CPU.
In the book Using OpenMP - The Next Step it is written that

"[...] the order in which threads combine their value to construct the
value for the shared result is non-deterministic."

Maybe I just don't understand how the reduction clauses are implemented. Does it mean that if I use schedule(monotonic:static) in combination with a reduction clause each thread will execute its chunk of the iterations in a deterministic order, but that the order in which the partial results are combined at the end of the parallel region is non-deterministic?

A:
Does it mean that if I use schedule(monotonic:static) in combination
with a reduction clause each thread will execute its chunk of the
iterations in a deterministic order, but that the order in which the
partial results are combined at the end of the parallel region is
non-deterministic?

It is known that the end result is non-determinist, detailed information can be found in:
What Every Computer Scientist Should Know about Floating Point Arithmetic. For instance:

Another grey area concerns the interpretation of parentheses. Due to roundoff errors, the associative laws of algebra do not necessarily hold for floating-point numbers. For example, the expression (x+y)+z has a totally different answer than x+(y+z) when x = 1e30, y = -1e30 and z = 1 (it is 1 in the former case, 0 in the latter).

Now regarding the order in which the threads perform the reduction action, as far as I know, the OpenMP standard does not enforce any order, or requires that the order has to be deterministic. Hence, this is an implementation detail that is left up to the compiler that is implementing the OpenMP standard to decide, and consequently, it is something that your code should not reply upon.

A: Programming language semantics usually declares that a+b+c+d is evaluated as ((a+b)+c)+d. This is not parallel, so an OpenMP reduction is probably evaluated as (a+b)+(c+d). And so on for larger numbers of summands.
So you immediately have that, because of the non-associativity of floating point arithmetic, the result may be subtly different from the sequential value.
But more importantly, the exact value will depend on precisely how the combination is done. Is it a+(b+c) (on 2 threads) or (a+b)+c? So the result is at least "indeterministic" in the sense that you can not reconstruct how it was formed. It could probably even be done in two different ways, if you run the same reduction twice. That's what I would call "non-deterministic", but look in the standard for the exact definition of the term.
By the way, if you want to get some idea of how OpenMP actually does it, write your own reduction operator, and let each invocation print out what it computes. Here is a decent illustration: https://victoreijkhout.github.io/pcse/omp-reduction.html#Initialvalueforreductions
By the way, the standard actually doesn't use the word "non-deterministic" for this case. The following passage explains the issue:

Furthermore, using different numbers of threads may result in
different numeric results because of changes in the association of
numeric operations. For example, a serial addition reduction may have
a different pattern of addition associations than a parallel
reduction.


text:
Q: Using sequence-type functions with lists from user input I am currently writing a program where user user would input a list of cities they have lived in. Next the code will return the number of cities they have lived in. I am having trouble generating the number of cities the user has lived in. I am using len(). Below is my code.
#stores the user input in a string call myfirst_string
myfirst_string = (input("Hello, What is your name: "))

#Returns the first 2 letters of the user's name
print("The first two letters of your name is: ", myfirst_string[0] + myfirst_string[1])

#stores the lists of cities where the user has lived into a variable call places_lived_list
places_lived_list = [input("Which cities have you lived in: ")]

#outputs the cities the user has lived in and then returns the number of cities lived in based on the cities the user has input and are separated by commas.
print("You have lived in these cities: ",places_lived_list)
print("you have lived in", len(places_lived_list), 'City')

Screenshot of output

A: The third line should be somthing like:
places_lived_list = input("Which cities have you lived in: ").split(",")

Note that this only works if the cities are provided in the format "city1,city2,city3"

A: You asked a few follow-up questions in the comments, here's your code with some corrections and the problem resolved:
# no parentheses required around the call to `input`
myfirst_string = input('Hello, What is your name: ')

# nothing is returned here, the string is indexed twice and print
# technically returns `None`, but this isn't captured
print("The first two letters of your name is:", myfirst_string[0] + myfirst_string[1])

# here's the answer
places_lived_list = input('Which cities have you lived in (with commas): ').split(',')

# still a list
print('You have lived in these cities:', places_lived_list)

# so the length is correct
print('You have lived in', len(places_lived_list), 'cities')

You were also using both ' and " to delimit your strings, it's generally best to pick one and ' is the Python default.
Running the script now:
Hello, What is your name: Grismar
The first two letters of your name is: Gr
Which cities have you lived in (with commas): Den Haag, Brisbane
You have lived in these cities: ['Den Haag', ' Brisbane']
You have lived in 2 cities


text:
Q: Unable to route from one web page to other page in an application I have been trying to route from one web page to other web pages with the help of nodejs express, HTML, and MongoDB. But unable to route the page. I a, following GitHub link to develop the application.
I have analyzed the code using some references.
I am providing the code.
GitHub & reference link: https://github.com/mschwarzmueller/nodejs-basics-tutorial/tree/master/09-mongodb
Code:
routing link

Home

Registration

Event Schedule

Event Guidelines

Contact Details

Routing link in index.js
router.get('/registration', function(req, res, next) {
  console.log("kumari1");
  res.render('event_schedule');
});

Kindly help me out of this

A: you can't provide link to template page like this ....
waht you want to do is :
create new routes which will serve your template pages.
So you'll have something like this :
router.get("/contact",(req,res)=>{res.render("contact-detail.hbs)}); and this for all your template pages.
then in your routing link file Contact >Details


text:
Q: Spring Boot Test: Expected request don't persist using ExpectedCount.manyTimes() I'm trying to run some integration tests on my code and I use a MockRestServiceServer from spring-boot-test in order to set up the expected requests.
I have one call that is called many times while running my test, but it seems not to persist during the test. My test looks like this:
@Test
    void getHealthStatus() {
        try {
            RequestBuilder request = get("/actuator/hc").contentType("application/json");

            MockServerBinder.bindPersistentThingworxPropertiesCall(
                    mockServer,
                    requestTo(new URI(String.format("%sProperties/TestProp", thingworxUrl))),
                    objectMapper.writeValueAsString(new PingResponse(DashboardIndicator.HEALTHY, 200))
            );

            DashboardStatusModel expectedResult = new DashboardStatusModel();
            expectedResult.addResult("spring",service.getAppHealth());
            expectedResult.addResult("thingworx", service.getThingworxAvailability());

            assertOpenUrl(request);
            MvcResult result = mockMvc.perform(get("/actuator/hc").contentType("application/json"))
                    .andExpect(status().isOk())
                    .andReturn();

            DashboardStatusModel actualResult = objectMapper.readValue(result.getResponse().getContentAsString(), DashboardStatusModel.class);

            assertEquals(expectedResult.getResults().get("spring"), actualResult.getResults().get("spring"));
            assertEquals(expectedResult.getResults().get("thingworx").getStatus(),actualResult.getResults().get("thingworx").getStatus());
            assertEquals(expectedResult.getResults().get("thingworx").getData().get("url"), actualResult.getResults().get("thingworx").getData().get("url"));
        } catch (Exception e) {
            fail("Unable to perform REST call on GDP-API", e);
        }
    }

As additional information:

*

*mockServer is created in a superclass like this:
protected static MockRestServiceServer mockServer;
    @BeforeEach
    public void configureMockServer() {
        mockServer = MockRestServiceServer.bindTo(restTemplate).ignoreExpectOrder(true).build();
    }

*

*MockServerBinder.bindPersistentThingworxPropertiesCall() is a helper class that looks like this:
public static void bindPersistentThingworxPropertiesCall(MockRestServiceServer mockServer, RequestMatcher request, String responseJSONasString){
        mockServer.expect(ExpectedCount.once(), request)
                .andExpect(method(HttpMethod.GET))
                .andRespond(withStatus(HttpStatus.OK)
                        .contentType(MediaType.APPLICATION_JSON)
                        .body(responseJSONasString));
    }

*

*assertOpenUrl(request); is a function that checks if a URL doesn't have any authentication by using a MockMVC:
public void assertOpenUrl(RequestBuilder request){
        try{
            mockMvc.perform(request).andExpect(status().isOk());
        } catch (Exception e) {
            fail("Unable to perform REST call on GDP-API", e);
        }
}

When I run this test, the expectedResult.addResult("thingworx", service.getThingworxAvailability()); will be able to use the MockRestServiceServer, but the assertOpenUrl(request); line will fail, because MockRestServiceServer doesn't expect anymore calls to the endpoint binded in MockServerBinder.bindPersistantThingworxPropertyCall(). This does not happen if I Copy & Paste MockServerBinder.bindPersistantThingworxPropertyCall() under the existing one, so I think it's a problem with how I binded the request in the first place.
From what I understand ExpectedCount.manyTimes() should keep this request during the test.
Is this not true or is there another way I should bind my request so that it stays available during the entire test?

A: PEBCAK issue.
As you can see in the bindPersistentThingworxPropertiesCall(), I actually didn't use ExpectedCount.manyTimes(). I didn't catch that. Changed it and now it works.


text:
Q: How to use Posix Extended Regular Expressions in the shebang of sed interpreter script? I've written a sed interpreter script:
#!/usr/bin/sed -E -f
s/ +/_/g
s/[.':]//g
s/&/and/g

However, when I run it:
$ echo "Bob Dylan" | shscrub.sed
sed: unknown option --
usage: sed [-aEnru] command [file ...]
       sed [-aEnru] [-e command] [-f command_file] [file ...]

I need the -E option because I'm using the Extended Regular Expression syntax '+'.
Any ideas what I'm doing wrong?
Edit
A workaround:
#!/usr/bin/sed -f
s/ \{1,\}/_/g
s/[.':]//g
s/&/and/g

But, I'd still like to know how I can pass two parameters in the shebang (#!) line.

A: The error message was saying that the space character isn't an option.  So I guess, you need to mash all the arguments together in the shebang:
#!/usr/bin/sed -Ef
s/ +/_/g
s/[.':]//g
s/&/and/g

Strange, because this works fine:
$ echo "Bob  Dylan" | sed -E -f ~/bin/shscrub.sed
Bob_Dylan

A: The problem is the shebang #! multiple CLI arguments which get treated as a single '-E -f' argument by the Linux kernel through binfmt_misc: https://stackoverflow.com/a/1667855/895245
As mentioned in: How to use multiple arguments with a shebang (i.e. #!)? there seems to be no nice way to get around that except with a wrapper.
And since you mentioned POSIX, also note that there here is no mention of -E in POSIX 7: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/sed.html

A: Works with the default sed on OSX 10.6;
[~]> echo "Bob Dylan"|./test.sed
Bob_Dylan

Using plain sh works too;
[~]> sh -c "echo \"Bob Dylan\" | ./test.sed"
Bob_Dylan

Update: Doesn't work with Gnu sed indeed, seems to be a compatibility problem.
With GNU sed it works if you don't use the -f parameter, note that you have to use -r instead of -E;
[~]> echo "Bob Dylan"|sed -r "s/ +/_/g;s/[.':]//g;s/&/and/g"
Bob_Dylan


text:
Q: Grouping pages in chapters when using biblatex and backref=true I have used etoolbox to reset the page counter in each non-starred chapter, and I've changed \thepage to print both the chapter number and the page number:
\pretocmd{\@chapter}{\setcounter{page}{1}}{}{}
\renewcommand*{\thepage}{\thechapter-\arabic{page}}

Besides that I'm using biblatex to print partial (in a chapter, if wanted) and global bibliographies (as a chapter* at the end). When a reference is cited in several pages of a chapter and in different chapters the backref option prints quite an ugly result, because of the chosen page numbering format (see MWE). I'd like to:

*

*Make biblatex group the pages into chapters in the backrefs when the [heading=bibliography] option is used to print it.

*Make biblatex show just the list pages (without the chapter number) in the backref, when then [heading=subbibliography] option is used to print it.
In the MWE the backref of [ODO95] we show the following backrefs:

*

*In page I: [cit. on chapters 1 (pp. 1, 3), 2 (p. 1)]

*In page 1-3: [cit. on pp. 1, 3];

*In page 2-1: [cit. on p. 1].
When a citation is made out of any chapter, the backref in the global bibliography should show the pages too. Say we uncomment the three lines after \begin{document} in the MWE, the backref in page I would be [cit. on chapters 1 (pp. 1, 3), 2 (p. 1); and page i].
MWE:
\documentclass[a4paper,titlepage,10pt,twoside,openright]{report}

\usepackage[backend=biber,style=ieee-alphabetic,natbib=true,backref=true]{biblatex}
\addbibresource{IEEEfull.bib}
\addbibresource{IEEEexample.bib}
\usepackage{lipsum}
\usepackage{etoolbox}
\makeatletter
\pretocmd{\@chapter}{\setcounter{page}{1}}{}{}
\makeatother

\begin{document}

%\renewcommand*{\thepage}{\roman{page}}
%\cite{IEEEexample:articledualmonths}
%\clearpage
\renewcommand*{\thepage}{\thechapter-\arabic{page}}

 \chapter{Introduction}
  \begin{refsegment}
   \cite{IEEEexample:articledualmonths} \lipsum[1-10] \cite{IEEEexample:articledualmonths}
  \printbibliography[segment=\therefsegment,heading=subbibliography]
  \end{refsegment}

 \chapter{Second chapter}
  \begin{refsegment}
   \cite{IEEEexample:articledualmonths}
   \cite{IEEEexample:IEEEwebsite}
   \nocite{IEEEexample:book_typical,IEEEexample:article_typical}
  \printbibliography[segment=\therefsegment,heading=subbibliography]
  \end{refsegment}

\cleardoublepage
\setcounter{page}{1}
\renewcommand*{\thepage}{\Roman{page}}
\printbibliography[heading=bibliography]

\end{document}

I've read some questions about formatting the backrefs with biblatex [a, b], but they don't target changing the "content" of the list, just the format. However, I took one of those answers as a reference to achieve this format:
\newbibmacro*{pageref}{\iflistundef{pageref}{}
 {\finentrypunct\addspace\renewcommand\finentrypunct{}%
  \printtext[parens]{%
   \ifnumgreater{\value{pageref}}{1}%
    {\bibstring{backrefpages}\ppspace}%
    {\bibstring{backrefpage}\ppspace}%
   \printlist[pageref][-\value{listtotal}]{pageref}}}}

I believe that the content is shown with \printlist[pageref][-\value{listtotal}]{pageref}. I read about it and about \DeclareListFormat in the documentation of biblatex. I feel that I should declare a new list format, but I don't how to do it, neither how the content is fed into pageref or read from it.

I asked another question to know how to show just the backrefs inside a segment when [heading=subbibliography] is used, instead of showing the occurrences in the whole document.
However, if a new \DeclareListFormat has to be described, both answers may be merged.

A: It is very possible that not be the best form, but this works in the form that the questions suggests. The bibentries are generics.
The code is comments. Read it, please.
MWE:
\documentclass[a4paper,titlepage,10pt,twoside,openright]{report}

\begin{filecontents}{IEEEexample.bib}
@inBook{Wolff1962,
  Title                    = {Philosophia prima sive Ontologia},
  Author                   = {Wolff, Christian von},
  Editor                   = {Jean Ecole},
  Publisher                = {Olms},
  Address                  = {Hildesheim},
  Year                     = {1962},
  Part                     = {Abt. 2: Lateinische Schriften},
  Maintitle                = {Gesammelte Werke},
  Volume                   = {3},
  langid                   = {german}
}

@inBook{other1999,
  Title                    = {The title in english},
  Author                   = {Last, Name},
  Editor                   = {Editor Name},
  Publisher                = {Springer},
  Address                  = {New York},
  Year                     = {1999},
  Part                     = {1},
  Maintitle                = {The Maintitle},
  Volume                   = {3},
}

@techreport{Natarajan2011,
author = {Natarajan, Nagarajan and Singh-Blom, Ulf Martin and Tewari, Ambuj and Woods, John O and Dhillon, Inderjit S and Marcotte, Edward M},
file = {:Users/jwoods/Downloads/Papers/Natarajan2011.pdf:pdf},
journal = {UTCS Technical Report},
title = {{Predicting gene\textendash disease associations using multiple species data.}},
volume = {TR-11-37},
year = {2011},
type = {techreport},
keywords = {Technical Report}}

@phdthesis{thesis000,
author = {Author Name},
title = {Title of the thesis},
type= {phdthesis},
year = {2011}}
\end{filecontents}

\usepackage[backend=biber,style=ieee-alphabetic,natbib=true,backref=true]{biblatex}
\addbibresource{IEEEexample.bib}
\usepackage{lipsum}
\makeatletter
\pretocmd{\@chapter}{\setcounter{page}{1}}{}{}
\makeatother

\DeclareListParser*{\forpageref}{-} %A parser for the newpage X-x X:chapter and x:the real page

\newcounter{cbcrfpg}%        Counter for how many times is cited by chapter
\providetoggle{chorpg}%      True: Chapter part (X). False: Page part (x) (chapter or page)
\providetoggle{ifbrefcchap}% if backref is into currentchapter
\togglefalse{ifbrefcchap}%

\newcounter{lastchap}%       It is used in the whole bibliograpy. save the last chapter.
\setcounter{lastchap}{0}

\newcommand{\onlycurrentchapter}[1]{%
  \iftoggle{chorpg}%                    %If is chapter part. (X)
    {\ifnumequal{#1}{\value{chapter}}      % if chapter part is equal to current chapter.
      {\toggletrue{ifbrefcchap}%                % True the backref into currentpage
       \togglefalse{chorpg}}%                   % The next part will be page part (x)
      {\togglefalse{ifbrefcchap}}%         % else: False the backref into currentpage
    }
    {\iftoggle{ifbrefcchap}             %If is page part and backref into currentpage
       {\stepcounter{cbcrfpg}%             % +1 counter of how many times is cited by chapter
        \listgadd{\mylistofpages}{#1}}%    % Add the page into a internal list.
       {}}}

\DeclareListFormat{selectitemsforprint}{%  A format for manage every element of backref list.
\toggletrue{chorpg}%                       This is used for select only the elements into current
\forpageref{\onlycurrentchapter}{#1}} %    chapter.

\DeclareListFormat{printallitems}{%  A format for manage every element of backref list.
  \toggletrue{chorpg}%            %  This is used to classify the backref by chapters and print the
  \forpageref{\printallitems}{#1}%%  of the n-1 of total chapters (n).
}

\newcommand{\printallitems}[1]{%
  \iftoggle{chorpg}%                                         %If chapter part (X)
     {\ifnumequal{\value{lastchap}}{#1}%                       %If the last chapter is equal to current chapter **
         {}%                                                      %nothing
         {\ifnumequal{\value{cbcrfpg}}{0}                      %if the last chapter is different to current chapter and
             {}                                                     % if counter is zero: Nothing
             {\printtext{\addspace\thelastchap\addspace}%           % if different to zero: Prints!! 1. The chapter numbers
              \usebibmacro{printitems}{parens}{pages}{page}%                             % And the items: it means page of the backref.
              \setcounter{cbcrfpg}{0}\undef{\mylistofpages}}%       % And restart the list of pages and counter
         }%seimprimen
      \setcounter{lastchap}{#1}%                               %Save the last chapter**
     }
     {\stepcounter{cbcrfpg}\listgadd{\mylistofpages}{#1}}%     %If is page part: +1 counter and add to list of pages.
      \togglefalse{chorpg}}%

%**(into backref list: exaple [1-1, 1-2] equals chapters)

\renewbibmacro*{pageref}{\iflistundef{pageref}{}                         %The new pageref bibmacro
 {\setcounter{cbcrfpg}{0}\undef{\mylistofpages}\setcounter{lastchap}{0}  % start list of pages, cunters and last chapter
  \printunit{\adddot\space}                                              % Print a dot
  \ifnumequal{\value{refsegment}}{0}                                     % If refsegment is zero, this means global bibliography
     {\printtext[brackets]{\printtext{cite on \chaptername}%             % Print the part: cite on chapter
      \printlist[printallitems][-\value{listtotal}]{pageref}%            % Find and Print the backref of all n-1 chapters
      \printtext{\addspace\thelastchap\addspace}%                        % Print the backref of only n chapter***
      \usebibmacro{printitems}{parens}{pages}{page}%                                          %*** (not print fortwo below line)
     }}
     {\printlist[selectitemsforprint]{pageref}                           % If refsegment different to zero, is a internal bibliography
      \usebibmacro{printitems}{brackets}{backrefpages}{backrefpage}}%
     }}

\newbibmacro*{printitems}[3]{%
  \printtext[#1]{%                                                        % Print into brackets
  \ifnumgreater{\value{cbcrfpg}}{1}%                                      % If counter greater to 1
    {\bibstring{#2}}                                                            %Print cite #2 bibstring
    {\bibstring{#3}}                                                      % else: %Print cite #2 bibstring
  \forlistloop{\printtext\newunit}{\mylistofpages}}}                      %Print the listofpages items.using \printtext{\newunit\thepagepart}

\begin{document}
\renewcommand*{\thepage}{\thechapter-\arabic{page}}
 \chapter{Introduction}
  \begin{refsegment}
   \cite{Wolff1962} \lipsum[1-10]
    \cite{Wolff1962}
  \printbibliography[segment=\therefsegment,heading=subbibliography]
  \end{refsegment}

 \chapter{Second chapter}
  \begin{refsegment}
   \cite{Wolff1962}
   \cite{other1999}
   \nocite{Natarajan2011,thesis000}
  \printbibliography[segment=\therefsegment,heading=subbibliography]
  \end{refsegment}

\cleardoublepage
\setcounter{page}{1}
\renewcommand*{\thepage}{\Roman{page}}
\printbibliography[heading=bibliography]

\end{document}

IMAGES
page 1-3.

page 2-1.

page I.


text:
Q: Java server client Was writing a server for my X O game. The basic idea was that I have one computer run as a server wit ha static ip and others could connect to it.
It needs to be able to send the state of the game to all the connected clients, but I ran into a blocking problem.
If you take a look at the client side
Scanner input = new Scanner();
int test = input.nextInt();

is blocking the code.
The server is able to send the message to all the clients but it is being prevented by the nextInt() as it waits for the Int to be passed in order to echo the state of the game(jsut a set of ints, coordinates).
Could anyone help me out here, I am really stuck, have been reading up on blocking problems, on the net and here on the forums I found that some people were saying that I have to check the inputStream on the client side whether it contains something or not but I could not implement it.
Any idea, suggestions are welcomed.
Thank you all for your time.
-------SERVER-----------
import java.net.*;
import java.io.*;

public class Server extends SerResponse {

    public static void main(String[] args) {
        int port = 1234;
        int cliNum = 1;

        try {
            ServerSocket sock = new ServerSocket(port);
            System.out.println("SERVER WORKING......");
            int index0 = 0;

            while (true) {
                SerResponse ser = new SerResponse();
                Socket connection = sock.accept();
                soc[index0] = connection;
                index0++;

                if (connection != null) {
                    System.out.println("Client " + cliNum + " connected " + connection);
                    cliNum++;
                }

                Runnable runnable = new Server(connection, ++ser.count);
                Thread t = new Thread(runnable);
                t.start();
            }
        } catch (Exception e) {
            System.out.println("SERVER FAIL " + e);
        }
    }

    public Server(Socket s, int count) {
        this.connection = s;
        this.ID = count;
    }
}

------SERVER RESPONSE--------------
import java.io.*;
import java.net.Socket;

public class SerResponse implements Runnable {

    public static Socket connection;
    public int ID;
    public final static int size = 10;
    public static Socket[] soc = new Socket[size];
    public int count = 0;
    public int test;

    public void run() {
        try {
            while (true) {
                DataInputStream in = new DataInputStream(connection.getInputStream());
                test = in.readInt();
                System.out.println("Recieved from " + connection + " " + test + "\n");

                for (int index0 = 0; index0 < size; index0++) {
                    if (soc[index0] != null) {
                        DataOutputStream out = new DataOutputStream(soc[index0].getOutputStream());
                        out.writeInt(test);
                        System.out.println("Sent to client " + soc[index0] + " " + test);
                    }
                }
            }
        } catch (Exception e) {
            System.out.println("Runnable FAIL " + e);
        }
    }
}

-----CLIENT--------
import java.net.*;
import java.util.Scanner;
import java.io.*;

public class client {

    public static void main(String[] args) {
        int[][] arr = {{3, 4}, {6, 2}, {9, 2}};
        int[][] arr1 = new int[3][2];
        int port = 1234;
        int test;
        int test1;

        try {
            System.out.println("Starting client");
            Socket sock = new Socket("localhost", port);

            DataOutputStream out = new DataOutputStream(sock.getOutputStream());
            DataInputStream in = new DataInputStream(sock.getInputStream());

            Scanner input = new Scanner(System.in);
            int turn = 0;

            while (true) {
                test = input.nextInt();
                out.writeInt(test);
                System.out.println(test);
                test1 = in.readInt();
                System.out.println(test1);
                turn++;
            }
        } catch (Exception e) {
            System.out.println("CLIENT FAIL " + e);
        }
    }
}

A: Here's a rework of your client class that should give the asynchronous behaviour that you're looking for.
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket;
import java.util.Scanner;

public class Client extends Thread {
    private final Socket sock;
    private boolean shutdown = false;

    public Client(Socket sock) {
        this.sock = sock;
    }

    public void shutdown() {
        shutdown = true;
    }

    public void writeDataToServer(int test) {
        try {
            synchronized(Client.class) {
                //don't allow reading and writing at the same time.
                DataOutputStream out = new DataOutputStream(sock.getOutputStream());
                out.writeInt(test);
                sock.getOutputStream().flush();
            }
        }catch(Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        try {
            BufferedInputStream bis = new BufferedInputStream(sock.getInputStream());
            while(!shutdown) {
                if(bis.available() > 0) {
                    synchronized(Client.class) {
                        DataInputStream in = new DataInputStream(bis);
                        int test = in.readInt();
                        //you can do something with test hereafter.... but since the example just had it printing out
                        System.out.println(test);
                    }
                } else {
                    Thread.sleep(500); //sleep for 500ms before polling again.
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                sock.close();
            } catch(Exception ignored){}
        }
    }

    public static void main(String[] args) {
        int[][] arr = {{3, 4}, {6, 2}, {9, 2}};
        int[][] arr1 = new int[3][2];
        int port = 1234;
        int test;

        try {
            System.out.println("Starting client");
            Client client = new Client(new Socket("localhost", port));
            client.start();

            Scanner input = new Scanner(System.in);
            int turn = 0;

            while(turn < 10) {
                test = input.nextInt();
                client.writeDataToServer(test);
                System.out.println(test);
                turn++;
            }

            client.shutdown();
        } catch(Exception e) {
            System.out.println("CLIENT FAIL " + e);
        }
    }
}


text:
Q: Unable to access port forwarded by ssh tunnel on public interface I used the following command:
ssh root@58.36.132.124 -N -R *:11222:127.0.0.1:11222

To forward a server running locally on port 11222, to the server with the aforementioned public IP.
However, I can't the application by calling 58.36.132.124:11222, I can only access localhost:11222 (when ssh-ed into 58.36.132.124).
What am I doing wrong here ?

A: From https://superuser.com/a/591963/365431
You must set sshd server config to allow GatewayPorts
ssh root@58.36.132.124 -N -R 0.0.0.0:11222:127.0.0.1:11222
on the server, add GatewayPorts yes
use ss -apln | grep 11222 to test that it is listening on :: or * and not ::1


text:
Q: How to add JsonDeserializer to Kafka consumer in Kotlin? How can i add JsonDeserializer to my Kafka consumer. I'm receiving now a Json string and want to convert it into a data class object.
This is my consumer :
ConsumerConfig :
@EnableKafka
@Configuration
class KafkaConsumerConfig {
@Value("\${kafka.host:localhost}")
private val host: String? = null

@Value("\${kafka.port:9092}")
private val port: Int = 0

@Bean
fun userConsumerConfigs(): ConsumerFactory<String, String> {
    val props = HashMap<String, Any>()
    props[ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG] = "$host:$port"
    props[ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG] = StringDeserializer::class.java
    props[ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG] = StringDeserializer::class.java
    props[ConsumerConfig.GROUP_ID_CONFIG] = "helloworld"
    val mapper = ObjectMapper()
    return DefaultKafkaConsumerFactory(props, StringDeserializer(), StringDeserializer())

    //return props
}

@Bean
fun kafkaListenerContainerFactory():
KafkaListenerContainerFactory<ConcurrentMessageListenerContainer<String,
String>> {
    val factory = ConcurrentKafkaListenerContainerFactory<String, String>()
    factory.consumerFactory = userConsumerConfigs()
    return factory
}

@Bean
fun kafkaConsumer(): Consumerz {
    return Consumerz()
}

companion object {
    const val TOPIC = "test"
}
}

Consumer :
class Consumerz {
@KafkaListener(topics = ["usertest"])
fun receive(message: String) {
     LOGGER.info("Received payload= $message")

}

companion object {
    private val LOGGER = LoggerFactory.getLogger(Consumerz::class.java)
}
}

I'm using at the moment only StringDeserializer. How could i implement JsonDeserializer in this case.
Current output is : Received payload= { "firstName": "Jack", "lastName" : "Adam" }
Thanks in advance.
@ this is a Spring project .

A: You can directly use org.springframework.kafka.support.serializer.JsonDeserializer.class as below
props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, JsonDeserializer.class);

So, the consumer configuration will be :
private ConsumerFactory<String, MyDomainModel> myMessageFactory() {
    Map<String, Object> props = new HashMap<>();
    props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, SERVERS);
    props.put(ConsumerConfig.GROUP_ID_CONFIG, "KAPP");
    props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, JsonDeserializer.class);

    return new DefaultKafkaConsumerFactory<>(props, new StringDeserializer(), new JsonDeserializer<>(MyDomainModel.class));
}

@Bean
public ConcurrentKafkaListenerContainerFactory<String, MyDomainModel> myMessageListenerContainerFactory() {
    ConcurrentKafkaListenerContainerFactory<String, MyDomainModel> factory = new ConcurrentKafkaListenerContainerFactory<>();
    factory.setConsumerFactory(myMessageFactory());
    return factory;
}


text:
Q: java.lang.RuntimeException: Unable to start activity ComponentInfo Android Eclipse I know a bunch of people have asked this same thing but I just don't know what's going on. I'm trying to make a calculator in Eclipse, but I keep getting a list of errors.
There are no errors in the file that the program notices, although there is an error in the layout.xml but it hasn't caused a problem before so that shouldn't cause a problem.
07-30 08:19:50.470: D/AndroidRuntime(2071): Shutting down VM
07-30 08:19:50.470: W/dalvikvm(2071): threadid=1: thread exiting with uncaught
exception (group=0x40a421f8)
07-30 08:19:50.480: E/AndroidRuntime(2071): FATAL EXCEPTION: main
07-30 08:19:50.480: E/AndroidRuntime(2071): java.lang.RuntimeException: Unable to start
activity
ComponentInfo{com.example.se.miun.chris.calculator/com.example.se.miun.chris.
calculator.MainActivity}: java.lang.NullPointerException
07-30 08:19:50.480: E/AndroidRuntime(2071):     at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
07-30 08:19:50.480: E/AndroidRuntime(2071):     at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
07-30 08:19:50.480: E/AndroidRuntime(2071):     at
android.app.ActivityThread.access$600(ActivityThread.java:123)
07-30 08:19:50.480: E/AndroidRuntime(2071):     at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147
07-30 08:19:50.480: E/AndroidRuntime(2071):     at
android.os.Handler.dispatchMessage(Handler.java:99)
07-30 08:19:50.480: E/AndroidRuntime(2071):     at
android.os.Looper.loop(Looper.java:137)
07-30 08:19:50.480: E/AndroidRuntime(2071):     at
android.app.ActivityThread.main(ActivityThread.java:4424)
07-30 08:19:50.480: E/AndroidRuntime(2071):     at
java.lang.reflect.Method.invokeNative(Native Method)
07-30 08:19:50.480: E/AndroidRuntime(2071):     at
java.lang.reflect.Method.invoke(Method.java:511)
07-30 08:19:50.480: E/AndroidRuntime(2071):     at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
07-30 08:19:50.480: E/AndroidRuntime(2071):     at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
07-30 08:19:50.480: E/AndroidRuntime(2071):     at
dalvik.system.NativeStart.main(Native Method)
07-30 08:19:50.480: E/AndroidRuntime(2071): Caused by: java.lang.NullPointerException
07-30 08:19:50.480: E/AndroidRuntime(2071):     at
com.example.se.miun.chris.calculator.MainActivity.onCreate(MainActivity.java:60)
07-30 08:19:50.480: E/AndroidRuntime(2071):     at
android.app.Activity.performCreate(Activity.java:4465)
07-30 08:19:50.480: E/AndroidRuntime(2071):     at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
07-30 08:19:50.480: E/AndroidRuntime(2071):     at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
07-30 08:19:50.480: E/AndroidRuntime(2071):     ... 11 more

This is my coding. It doesn't really do anything yet, but I wanted to just run it to see if it encountered any errors. This is the mainActivity.java file.
import android.os.Bundle;
import android.app.Activity;
import android.text.Editable;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity implements OnClickListener {
Button Seven;
Button Eight;
Button Nine;
Button Four;
Button Five;
Button Six;
Button One;
Button Two;
Button Three;
Button Zero;
Button Point;
Button Negative;
TextView TextBox;
int x;
int y;
String z;

@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Seven = (Button)findViewById(R.id.NumberSeven);
    Seven.setOnClickListener(this);
    Eight = (Button)findViewById(R.id.NumberEight);
    Eight.setOnClickListener(this);
    Nine = (Button)findViewById(R.id.NumberNine);
    Nine.setOnClickListener(this);
    Four = (Button)findViewById(R.id.NumberFour);
    Four.setOnClickListener(this);
    Five = (Button)findViewById(R.id.NumberFive);
    Five.setOnClickListener(this);
    Six = (Button)findViewById(R.id.NumberSix);
    Six.setOnClickListener(this);
    One = (Button)findViewById(R.id.NumberOne);
    One.setOnClickListener(this);
    Two = (Button)findViewById(R.id.NumberTwo);
    Two.setOnClickListener(this);
    Three = (Button)findViewById(R.id.NumberThree);
    Three.setOnClickListener(this);
    Zero = (Button)findViewById(R.id.NumberZero);
    Zero.setOnClickListener(this);
    Point = (Button)findViewById(R.id.Point);
    Point.setOnClickListener(this);
    Negative = (Button)findViewById(R.id.NNegative);
    Negative.setOnClickListener(this);
    TextBox = (TextView)findViewById(R.id.Screen);
    x = (Integer) null;
    y = (Integer) null;

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}

public void onClick(View One) {
    if(z == null){
        x = 1;
            TextBox.setText(x);
            TextBox.setText("diggity");
        }
        else if(z != null) {
            y = 1;
            TextBox.setText(x);
            TextBox.setText(z);
            TextBox.setText(y);
        }

    }
}

A: line 60: x = (Integer) null;
This line will compile to this bytecode (disassembled by javap):

*

*aconst_null

*checkcast #2; //class java/lang/Integer

*invokevirtual #3; //Method java/lang/Integer.intValue:()I
Third line will cause a NullPointerException becouse Integer object is actually your null constant :)
Primitive data types (int, long etc.) is the only non-object types in Java. null is used to show that the current variable (Object variable) is not backed by the actual object (no memory was allocated). For primitive types memory allocates immediately so they cant have this null state.
So you should check for "if(x == 0)" or define it as Integer.
P.S. And don't cast null to anything :)

A: It's like this
you're not getting much errors because the application can't launch. it cannot launch because it's onCreate() cannot finish.
onCreate() cannot finish because of a nullPointerException.
you cast null into integer twice, instead of simply instantiating a new integer which will default to 0. once you get rid of that, it should work.
see?
E/AndroidRuntime(2071): Caused by: java.lang.NullPointerException
E/AndroidRuntime(2071):     at
MainActivity.onCreate(MainActivity.java:60)

and i bet that this is line 60
x = (Integer) null;

so change it to
x = new Integer();


text:
Q: When to use and not to use Mockito Argument Matchers. difference between any(), anyString(), Mockito.anyString(), Mockito.any()? Hi I am very new to mockito framework. Can you please explain in lay man term why we need argument matchers and what is the need of any(), anyString() and what if I use a correct string instead of anyString() will it logically correct? And why these methods are static?
import static  org.mockito.ArgumentMatchers.anyString;
import static  org.mockito.ArgumentMatchers.any;

resourceLoader.getResource(anyString())// returns a input stream
ObjectMapper.readValue(Mockito.any(), Mockito.any())  // takes a input stream and an object

Also what is the difference in using directly and Mockito.anyString() and directly anyString()?


text:
Q: Android NFC reading Following the tutorial: http://code.tutsplus.com/tutorials/reading-nfc-tags-with-android--mobile-17278
I'm wondering if it is possible to only respond to NFC requests when the application is open AND is on the current activity that handles those events?
Currently I have in my manifest (inside the activity that responds):
<!-- NFC Reader -->
<intent-filter>
  <action android:name="android.nfc.action.TAG_DISCOVERED" />
  <category android:name="android.intent.category.DEFAULT" />
</intent-filter>

In the activity onCreate
// Responds to NFC Device Reader
 resolveIntent(getIntent());

And
@Override
public void onNewIntent(Intent intent) {
    setIntent(intent);
    resolveIntent(intent);
}

private void resolveIntent(Intent intent) {
    String action = intent.getAction();
    if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)
            || NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)
            || NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {

        Parcelable tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);

        processInformation(tag);

    }
}

The reson being I have an authentication process which is being bypassed as the application loads this activity directly.

A: I'm the author of the tutorial. Simply remove the IntentFilter in the manifest and only implement the foreground dispatch. Then it should work that way.


text:
Q: Why use use #define in an enum block? In /usr/include/net/if.h I have found the following enum usage:
enum
{
    IFF_UP = 0x1,           /* Interface is up.  */
# define IFF_UP IFF_UP
    IFF_BROADCAST = 0x2,    /* Broadcast address valid.  */
# define IFF_BROADCAST  IFF_BROADCAST
    IFF_DEBUG = 0x4,        /* Turn on debugging.  */
# define IFF_DEBUG  IFF_DEBUG
    IFF_LOOPBACK = 0x8,     /* Is a loopback net.  */
# define IFF_LOOPBACK   IFF_LOOPBACK
    IFF_POINTOPOINT = 0x10, /* Interface is point-to-point link.  */
# define IFF_POINTOPOINT IFF_POINTOPOINT
};

My questions:

*

*What's the point in making an enumerated type without a type? So I won't be able to use them in a typesafe way.

*What's the point in making an enum variable then use its value in a #define directive with the same name in the next line?

Thank you


text:
Q: Activating a button within a Python spider program I am absolutely stuck on this one.  I am scraping restaurant URLs from a webpage and there is a button at the bottom to reveal more restaurants.  The website button code is below (i believe):

Show more
Back to top

It is the "Show more" button i am trying to activate.  The url within the "data-url" does not reveal more of the page.
It all seems a bit odd on what do do to activate the button from within the python spider?
The code i am trying to use to make this work is:
import scrapy

from hungryhouse.items import HungryhouseItem
from selenium import webdriver

class HungryhouseSpider(scrapy.Spider):
    name = "hungryhouse"
    allowed_domains = ["hungryhouse.co.uk"]
    start_urls = ["https://hungryhouse.co.uk/takeaways/westhill-ab10",
                      ]
    def __init__(self):
        self.driver = webdriver.Chrome()

    def parse(self,response):
        self.driver.get(response.url)

        while True:
            next =self.driver.find_element_by_xpath('//*[@id="restsPages"]/a[@class="next"]')
            try:
                next.click()
            except:
                break
        self.driver.close()

.... rest of the code follows

The error i get is: 'chromedriver' executable needs to be in PATH

A: This was resolved at Pressing a button within python code with reference to the answer at Error message: "'chromedriver' executable needs to be available in the path"
But specifically
self.driver = webdriver.Chrome()

needed to change to
self.driver = webdriver.Chrome("C:/Users/andrew/Downloads/chromedriver_win32/chromedriver.exe")

in my case.
i.e. I needed to add the path to chromedriver.exe.