Q:

sed: How to delete second match in a file

I have a file that's looking like this (pseudocode):
---
foo: bar
bar: baz
---
baz: quz
---
Some text
Some text
Some text

I need to delete the second --- row, and only that. I know that sed can do this, but I have never been able to make heads nor tails out of any sed documentation I could find...

A:

With sed the easiest way would be to first read the whole file into the pattern space and work on that:
sed ':a $!{N; ba}; s/\(^\|\n\)---\n/\n/2' filename

This does
:a                       # jump label for looping
$!{                      # if the end of input is not reached
  N                      # fetch the next line, append it to the pattern space
  ba                     # go back to :a
}                        # after this, the whole file is in the pattern space.
s/\(^\|\n\)---\n/\n/2    # then: remove the second occurrence of a line that
                         # consists only of ---

@mklement0 points out that the \| only works with GNU sed. A way to work around that, since the \| is only necessary to catch --- in the first line, would be
sed ':a $!{ N; ba; }; s/^/\n/; s/\n---\n/\n/2; s/^\n//' filename

This does:
:a $!{ N; ba; }  # read file into the pattern space
s/^/\n/          # insert a newline before the first line
s/\n---\n/\n/2   # replace the second occurrence of \n---\n with \n
s/\n//           # remove the newline we put in at the beginning.

This way, the first line is no longer a special case.
Without reading the whole file into a buffer, you'll have to construct a counter from characters:
sed '/^---$/ { x; s/.*/&_/; /^__$/ { x; d; }; x; }' filename

That is:
/^---$/ {    # if a line is ---
  x          # exchange pattern space and hold buffer
  s/.*/&_/   # append a _ to what was the hold buffer
  /^__$/ {   # if there are exactly two in them
    x        # swap back
    d        # delete the line
  }
  x          # otherwise just swap back.
}

...or just use awk:
awk '!/^---$/ || ++ctr != 2' filename


Q:

Switching between Forms in Winforms

How to switch between forms in winforms ?
I tried below code:
this.hide();
   Form1 f = new Form1();
   f.Show();

Here the result was not as expected, the new panel displayed with different location from parent panel. Any ways to make the navigation perfect ?

A:

You can use CenterParent flag, providing your parent window in Show function.
var frm = new Form2();
frm.StartPosition = FormStartPosition.CenterParent;
frm.Show(this);


Q:

Run a remote .sh script from a local .bat script

I must write a script on windows (a bat file) which has to run a shell script on a Linux server. That would be the most linear way to achieve my goal, but I need to know if running a remote shell script from a local batch is even possible (given the server address and the credentials, of course), and then how that could be done.
Best regards.

A:

You can user WinSCP
for example put_file.bat
"C:\Program Files\WinSCP\winscp.com" /ini=nul /script="C:\Program Files\WinSCP\ticket_upload.sftp"
for example ticket_upload.sftp
open sftp://login:password@192.168.0.9/ -hostkey="ssh-rsa 2048 d9:e6:2d:ab:0c:72:86:b8:5d:02:7c:c0:80:64:0d:7d"
cd /oracle/app/oracle/bb/abak
mput "C:\bb\abak\DBF.RAR"
call /oracle/app/oracle/extract_bb.sh
exit


Q:

Network traffic saturation causing failover

I have a Windows failover cluster and every time I take a remote robocopy backup from this cluster it seems like it's causing such high network saturation that the cluster monitor thinks the NIC is unresponsive and then fails over.
This is my assumption based on the time of day this usually happens.
I've tried adding the /IPG flag to robocopy to allow some space between packets.  Is there anything else I could consider to space traffic out?  I've had similar problems that aren't robocopy related.  Perhaps a network interface tweak?
Thanks.

A:

Take a look at the network during normal hours when you're not running the Robocopy job. Do you see congestion? Do you see a high volume of broadcast traffic? Are links saturated? Take a look at link speed and duplex settings.
In general, take a look at the network as a whole before you start tweaking server and/or switch settings. The key to knowing when something isn't working normally is to know what it looks like when it is working normally. If the network is performing poorly in it's normal state then the added load of your Robocopy job is only going to exacerbate it.
EDIT
In addition, depending on your configuration you can prevent cluster communication (heartbeat traffic) from transiting the network that you're doing the Robocopy job over. If the
Robocopy job is running over an iSCSI network then you shouldn't have cluster communication enabled on that network to begin with.


Q:

How to get object with key and value using Jquery each method..?

I am not able to get a key and value pairs using the each function of jquery. How to get the key and values object using jQuery each function..?
my try:
var result = '{"FirstName":"John","LastName":"Doe","Email":"johndoe@johndoe.com","Phone":"123 dead drive"}';

$.each($.parseJSON(result), function(n, v) {
    console.log({n: v});
});

result i am getting as:
Object {n: "John"}
Object {n: "Doe"}
Object {n: "johndoe@johndoe.com"}
Object {n: "123 dead drive"}

but i am looking for :
    Object {FirstName: "John"}
    Object {LastName: "Doe"}
    Object {Email: "johndoe@johndoe.com"}
    Object {Phone: "123 dead drive"}

what is the correct approach to get this done..?
Thanks in advance.

A:

$.each($.parseJSON(result), function(n, v) {
    console.log('{'+n +': '+ v +'}');
});


Q:

How to remove previous selected option when selecting new option

Task:
To create dropdown list with options, and will reflect selected option based on selection.
Issue
Have managed to create the dropdown list and also the syntax to display the selected option. However, I am facing an issue, whereby, when user were to select "Option1", "Option_1" will be displayed and when the user continues to select "Option2", "Option_2" will also be displayed ontop of "Option_1". "Option_1" will not be remove and only "Option_2" will be displayed. Hence, if the user is to select all 5 options, user will see all 5 options being displayed and not the latest option being displayed.
I have tried using $("(id_name)").empty() in my function val(x) and when I do that, none of the option selected is being displayed.
Code:

Dropdown list code:

<select name ="Agency" id="AgencyDetails" onchange = "return val(this.value);">
<option value ="0" selected = "selected"> Select Agency..</option>
<option value ="Name 1"> Bob</option>
<option value ="Name 2"> Amanda</option>
<option value ="Name 3"> Gen</option>
<option value = "Others"> Others</option>
</select>

ExtraDiv code:

                            Person Name:
                            <input type="text" class="fieldInput" id="Name" value="" title="Address" />

                            Name Registration Number:
                            <input type="text" class="fieldInput" id="nameCompanyAddress" value="" title="Address" />

                            Name Address:
                            <input type="text" class="fieldInput" id="nameCompanyAddress" value="" title="Address" />

Name1:

Name:Name1

Name Registration Number:Name Registration Num 1

Name Address:Name Address 1

Hence, Name1 and Name2 and Name2 format are the same.
Can anyone please help

A:

You could try something like this
function val(x) {
    document.getElementById("extradiv").style.display = x == "Others" ? "block" : "none";
    document.getElementById("Name1").style.display = x == "Name 1" ? "block" : "none";
    document.getElementById("Name2").style.display = x == "Name 2" ? "block" : "none";
    document.getElementById("Name3").style.display = x == "Name 3" ? "block" : "none";
}


Q:

Sqlite Database gets deleted from Documents Folder

We have an iOS application for the iphone that is having strange behavior. I store some data of the app in an SQLite Database file in the documents folder. Every once in a while i realize that when the application crashes the file on the disk gets deleted. And i can´t figure out why the app would do this...Any Ideas?!

A:

Found the Solution...If i save my database in the Cache Directory instead of the Documents directory, it works...:)


Q:

2 onclick events on 1 Div ? (ASP.NET / HTML)

I'm using Div's, now I have to handle 2 Events with one Div-Click..
On the Button I would take, once onclick="" and OnClientClick.. but if I use a Div I can't use OnClientClick :(
Can you guys tell me, what I shall do, to get this? (there is one JavaScript method and one codebehind method, which I want to call) - till now I can call only one.
after wizards help:
got this:
<asp:Button ID="fakeButton" runat="server" Text="dummy" onclick="dummyButton_Click" style="display:none" />
and JS:
alert("div clicked");
document.getElementById("<%=fakeButton.ClientID%>").click();
So but he dont enters the Method:
protected void dummyButton_Click(object sender, EventArgs e) { } ..
i putted a breakpoint, he never entered, only showed the alert.. –

A:

First, add dummy hidden button with the proper server side click event:
<asp:Button id="fakeButton" runat="server" OnClick="MyMethod" Text="dummy" style="display: none;" />

Second, have such code for the DIV:

text here...

And finally such client side code:
function DivClick() {
    //your client side code here...
    //e.g.
    alert("div clicked");

    //now invoke server side click as well:
    document.getElementById("<%=fakeButton.ClientID%>").click();
}

This will first execute your client side code e.g. the alert, then "auto click" the button and by this causing post back and the server side code to execute.
If you don't want full reload, try putting it all inside UpdatePanel.


Q:

Why does Theano print "cc1plus: fatal error: cuda_runtime.h: No such file or directory"?

I am trying to use the GPU with Theano. I've read this tutorial.
However, I can't get theano to use the GPU and I don't know how to continue.
Testing machine
$ cat /etc/issue
Welcome to openSUSE 12.1 "Asparagus" - Kernel \r (\l).
$ nvidia-smi -L
GPU 0: Tesla C2075 (S/N: 0324111084577)
$ echo $LD_LIBRARY_PATH
/usr/local/cuda-5.0/lib64:[other]:/usr/local/lib:/usr/lib:/usr/local/X11/lib:[other]
$ find /usr/local/ -name cuda_runtime.h
/usr/local/cuda-5.0/include/cuda_runtime.h
$ echo $C_INCLUDE_PATH
/usr/local/cuda-5.0/include/
$ echo $CXX_INCLUDE_PATH
/usr/local/cuda-5.0/include/
$ nvidia-smi -a
NVIDIA: could not open the device file /dev/nvidiactl (Permission denied).
Failed to initialize NVML: Insufficient Permissions
$ echo $PATH
/usr/lib64/mpi/gcc/openmpi/bin:/home/mthoma/bin:/usr/local/bin:/usr/bin:/bin:/usr/bin/X11:/usr/X11R6/bin:/usr/games:/usr/lib/mit/bin:.:/home/mthoma/bin
$ ls -l /dev/nv*
crw-rw---- 1 root video 195,   0  1. Jul 09:47 /dev/nvidia0
crw-rw---- 1 root video 195, 255  1. Jul 09:47 /dev/nvidiactl
crw-r----- 1 root kmem   10, 144  1. Jul 09:46 /dev/nvram
# nvidia-smi -a

==============NVSMI LOG==============

Timestamp                       : Wed Jul 30 05:13:52 2014
Driver Version                  : 304.33

Attached GPUs                   : 1
GPU 0000:04:00.0
    Product Name                : Tesla C2075
    Display Mode                : Enabled
    Persistence Mode            : Disabled
    Driver Model
        Current                 : N/A
        Pending                 : N/A
    Serial Number               : 0324111084577
    GPU UUID                    : GPU-7ea505ef-ad46-bb24-c440-69da9b300040
    VBIOS Version               : 70.10.46.00.05
    Inforom Version
        Image Version           : N/A
        OEM Object              : 1.1
        ECC Object              : 2.0
        Power Management Object : 4.0
    PCI
        Bus                     : 0x04
        Device                  : 0x00
        Domain                  : 0x0000
        Device Id               : 0x109610DE
        Bus Id                  : 0000:04:00.0
        Sub System Id           : 0x091010DE
        GPU Link Info
            PCIe Generation
                Max             : 2
                Current         : 1
            Link Width
                Max             : 16x
                Current         : 16x
    Fan Speed                   : 30 %
    Performance State           : P12
    Clocks Throttle Reasons     : N/A
    Memory Usage
        Total                   : 5375 MB
        Used                    : 39 MB
        Free                    : 5336 MB
    Compute Mode                : Default
    Utilization
        Gpu                     : 0 %
        Memory                  : 5 %
    Ecc Mode
        Current                 : Enabled
        Pending                 : Enabled
    ECC Errors
        Volatile
            Single Bit
                Device Memory   : 0
                Register File   : 0
                L1 Cache        : 0
                L2 Cache        : 0
                Texture Memory  : N/A
                Total           : 0
            Double Bit
                Device Memory   : 0
                Register File   : 0
                L1 Cache        : 0
                L2 Cache        : 0
                Texture Memory  : N/A
                Total           : 0
        Aggregate
            Single Bit
                Device Memory   : 133276
                Register File   : 0
                L1 Cache        : 0
                L2 Cache        : 0
                Texture Memory  : N/A
                Total           : 133276
            Double Bit
                Device Memory   : 203730
                Register File   : 0
                L1 Cache        : 0
                L2 Cache        : 0
                Texture Memory  : N/A
                Total           : 203730
    Temperature
        Gpu                     : 58 C
    Power Readings
        Power Management        : Supported
        Power Draw              : 33.83 W
        Power Limit             : 225.00 W
        Default Power Limit     : N/A
        Min Power Limit         : N/A
        Max Power Limit         : N/A
    Clocks
        Graphics                : 50 MHz
        SM                      : 101 MHz
        Memory                  : 135 MHz
    Applications Clocks
        Graphics                : N/A
        Memory                  : N/A
    Max Clocks
        Graphics                : 573 MHz
        SM                      : 1147 MHz
        Memory                  : 1566 MHz
    Compute Processes           : None

Cuda sample
Compiling and executing worked as a super user (tested with cuda/C/0_Simple/simpleMultiGPU):
# ldconfig /usr/local/cuda-5.0/lib64/
# ./simpleMultiGPU
[simpleMultiGPU] starting...

CUDA-capable device count: 1
Generating input data...

Computing with 1 GPUs...
  GPU Processing time: 27.814000 (ms)

Computing with Host CPU...

Comparing GPU and Host CPU results...
  GPU sum: 16777296.000000
  CPU sum: 16777294.395033
  Relative difference: 9.566307E-08

[simpleMultiGPU] test results...
PASSED

> exiting in 3 seconds: 3...2...1...done!

When I try this as normal user, I get:
$ ./simpleMultiGPU
[simpleMultiGPU] starting...

CUDA error at simpleMultiGPU.cu:87 code=38(cudaErrorNoDevice) "cudaGetDeviceCount(&GPU_N)"
CUDA-capable device count: 0
Generating input data...

Floating point exception

How can I get cuda to work with non-super users?
Testing code
The following code is from "Testing Theano with GPU"
#!/usr/bin/env python
from theano import function, config, shared, sandbox
import theano.tensor as T
import numpy
import time

vlen = 10 * 30 * 768  # 10 x #cores x # threads per core
iters = 1000

rng = numpy.random.RandomState(22)
x = shared(numpy.asarray(rng.rand(vlen), config.floatX))
f = function([], T.exp(x))
print f.maker.fgraph.toposort()
t0 = time.time()
for i in xrange(iters):
    r = f()
t1 = time.time()
print 'Looping %d times took' % iters, t1 - t0, 'seconds'
print 'Result is', r
if numpy.any([isinstance(x.op, T.Elemwise) for x in f.maker.fgraph.toposort()]):
    print 'Used the cpu'
else:
    print 'Used the gpu'

The error message
The complete error message is much too long to post it here. A longer version is on http://pastebin.com/eT9vbk7M, but I think the relevant part is:
cc1plus: fatal error: cuda_runtime.h: No such file or directory
compilation terminated.
ERROR (theano.sandbox.cuda): Failed to compile cuda_ndarray.cu: ('nvcc return status', 1, 'for cmd', 'nvcc -shared -g -O3 -m64 -Xcompiler -DCUDA_NDARRAY_CUH=bcb411d72e41f81f3deabfc6926d9728,-D NPY_ARRAY_ENSURECOPY=NPY_ENSURECOPY,-D NPY_ARRAY_ALIGNED=NPY_ALIGNED,-D NPY_ARRAY_WRITEABLE=NPY_WRITEABLE,-D NPY_ARRAY_UPDATE_ALL=NPY_UPDATE_ALL,-D NPY_ARRAY_C_CONTIGUOUS=NPY_C_CONTIGUOUS,-D NPY_ARRAY_F_CONTIGUOUS=NPY_F_CONTIGUOUS,-fPIC -Xlinker -rpath,/home/mthoma/.theano/compiledir_Linux-3.1.10-1.16-desktop-x86_64-with-SuSE-12.1-x86_64-x86_64-2.7.2/cuda_ndarray -Xlinker -rpath,/usr/local/cuda-5.0/lib -Xlinker -rpath,/usr/local/cuda-5.0/lib64 -I/usr/local/lib/python2.7/site-packages/Theano-0.6.0rc1-py2.7.egg/theano/sandbox/cuda -I/usr/local/lib/python2.7/site-packages/numpy-1.6.2-py2.7-linux-x86_64.egg/numpy/core/include -I/usr/include/python2.7 -o /home/mthoma/.theano/compiledir_Linux-3.1.10-1.16-desktop-x86_64-with-SuSE-12.1-x86_64-x86_64-2.7.2/cuda_ndarray/cuda_ndarray.so mod.cu -L/usr/local/cuda-5.0/lib -L/usr/local/cuda-5.0/lib64 -L/usr/lib64 -lpython2.7 -lcublas -lcudart')
WARNING (theano.sandbox.cuda): CUDA is installed, but device gpu is not available

The standard stream gives:
['nvcc', '-shared', '-g', '-O3', '-m64', '-Xcompiler', '-DCUDA_NDARRAY_CUH=bcb411d72e41f81f3deabfc6926d9728,-D NPY_ARRAY_ENSURECOPY=NPY_ENSURECOPY,-D NPY_ARRAY_ALIGNED=NPY_ALIGNED,-D NPY_ARRAY_WRITEABLE=NPY_WRITEABLE,-D NPY_ARRAY_UPDATE_ALL=NPY_UPDATE_ALL,-D NPY_ARRAY_C_CONTIGUOUS=NPY_C_CONTIGUOUS,-D NPY_ARRAY_F_CONTIGUOUS=NPY_F_CONTIGUOUS,-fPIC', '-Xlinker', '-rpath,/home/mthoma/.theano/compiledir_Linux-3.1.10-1.16-desktop-x86_64-with-SuSE-12.1-x86_64-x86_64-2.7.2/cuda_ndarray', '-Xlinker', '-rpath,/usr/local/cuda-5.0/lib', '-Xlinker', '-rpath,/usr/local/cuda-5.0/lib64', '-I/usr/local/lib/python2.7/site-packages/Theano-0.6.0rc1-py2.7.egg/theano/sandbox/cuda', '-I/usr/local/lib/python2.7/site-packages/numpy-1.6.2-py2.7-linux-x86_64.egg/numpy/core/include', '-I/usr/include/python2.7', '-o', '/home/mthoma/.theano/compiledir_Linux-3.1.10-1.16-desktop-x86_64-with-SuSE-12.1-x86_64-x86_64-2.7.2/cuda_ndarray/cuda_ndarray.so', 'mod.cu', '-L/usr/local/cuda-5.0/lib', '-L/usr/local/cuda-5.0/lib64', '-L/usr/lib64', '-lpython2.7', '-lcublas', '-lcudart']
[Elemwise{exp,no_inplace}(<TensorType(float32, vector)>)]
Looping 1000 times took 3.25972604752 seconds
Result is [ 1.23178029  1.61879337  1.52278066 ...,  2.20771813  2.29967761
  1.62323284]
Used the cpu

theano.rc
$ cat .theanorc
[global]
device = gpu
floatX = float32
[cuda]
root = /usr/local/cuda-5.0

A:

As some comments told, the problem is the permissio of /dev/nvidia*. As some told this mean during your startup, it don't get initialized correctly. Normally, this is done correctly when the GUI is started. My guess is that you didn't enable it or install it. So you probably have an headless server.
To fix this, just run as root nvidia-smi. This will detect that it isn't started correctly and will fix it. root have the permission to fix things. Normal user don't have the permission to fix this. That is why it work with root (it get automatically fixed), but not as normal user.
This fix need to be done each time the computer boot. To automatise this, you can create as root this file /etc/init.d/nvidia-gpu-config with this content:
#!/bin/sh
#
# nvidia-gpu-config    Start the correct initialization of nvidia GPU driver.
#
# chkconfig: - 90 90
# description:  Init gpu to wanted states

# sudo /sbin/chkconfig --add nvidia-smi
#

case $1 in
'start')
nvidia-smi
;;
esac

Then as root run this command: /sbin/chkconfig --add nvidia-gpu-config.
UPDATE: This work for OS that use the init system SysV. If your system use the init system systemd, I don't know if it work.


Q:

Upwork/Odesk API desktop application development

I'm develop application that should use Upwork API (Winforms + C#).
To have access to Upwork data, need to authorize there. But in https://developers.upwork.com I don't see how can I login via web request/desktop application.

A:

In order to use upwork api, there are more requirements:

Obtain api key https://www.upwork.com/services/api/apply
Obtain token
Api key need to be authorized to access the specific resource

For authentication by default probably you will use OAuth1 so when your apiKey was enabled, to request your token you will have to follow this steps


Q:

Line height changing in UIWebView

I'm working on two different apps. Most of the app is already done, I just have a few things to change.
I'm working on a page that has to be the exact same on the two apps ("Help page"). Therefore, I've copied and past my 3 files : help.h, help.m, help.xib
In this page, I have a UIWebview that displays a html local file. I've copied and past it too.
The problem is that in the two apps, the line height of the content of my UIWebView is different. Even though I have the exact same help.h, help.m, help.xib, help.html
It's general to the app because I have the same problem on an other view.
What property is supposed to control this ? Maybe a UIScrollView property as I know a lot of work has been done on UIScrollViews here.
As you can see below, the space between the last black box and the separator is different:

Thanks for your help !

A:

After looking EVERYWHERE, I've finally found where the problem came from : the typography. The "line height" was different.


Q:

In a String, how can I separate & store the characters and integers?

My task is to create a Bubble Breaker type game, I broke my task into several smaller tasks, and I hit a wall.
I created a 2D Array Grid which will, whenever the program starts, be randomized with different coloured Bubbles. Each Line and Each Column is numbered, Lines range in Numbers, Columns range in Letters.
My goal is to have the user input choosing a String (Note I can only use String, as I'm programming in a pre-designed console), for example B10, B9 or 10B.
I'm able to check if the characters are numbers or letters via
command.charAt(i) >= '0' && command.charAt(i) <= '9' // i is a counter in a for

The above allows me to find if it's a digit or a number, the problem is that to select the Exact grid position, I need to, and can't:

Separate the String into Integrers AND character
Join the two Integrers
(note they can be B9, B10 or 10B)

This is an example of the duality B10 and 10B

A:

You only need two lines:
int num = Integer.parseInt(str.replaceAll("\\D", ""));
String letter = str.replaceAll("\\d", "");

The order of letters and digits in the string is irrelevant - this will work either way.
Edited to cater for requirements as per comments below
To process a series of letter-digit pairs in larger string, parsing the letter to an int x (where A=1, B=2, etc) and assigning the digit(s) to int y, you can split the string up on whitespace and use code similar to above:
for (String pair : command.toUpperCase().split("\\s+")) {
    int x = pair.replaceAll("\\d", "").charAt(0) - '@';
    int y = Integer.parseInt(pair.replaceAll("\\D", ""));
}

Using split() means not having to sully yourself with the tedium  of using a loop variable.
The reason for subtracting '@' is that is the character one before 'A', so subtracting that will convert A to 1, B to 2, etc.

Here's some test code:
String command = "A5 B10 11C 20D";
for (String pair : command.split("\\s+")) {
    int x = pair.replaceAll("\\d", "").charAt(0) - '@';
    int y = Integer.parseInt(pair.replaceAll("\\D", ""));
    System.out.format("X = %d, Y = %d\n", x, y);
}

Output:
X = 1, Y = 5
X = 2, Y = 10
X = 3, Y = 11
X = 4, Y = 20


Q:

Реализация классической игры крестики-нолики

Добрый день! У меня возникла задача реализовать многопользовательские крестики-нолики в классическом виде на языке PHP с использованием JQuery, CSS3, AJAX, JSON по принципам MVC и ООП. Так вот вопрос у меня такой есть на JQuery какие-то удобные плагины позволяющие реализовать такую игру.
Интересует следующее:

Как реализовать нанесение аппликаций на изображение (например кресты которые пересекли диагональ перечёркнуты будут еще сплошной линией сверху и завершится игра)?
Как будет происходить обработка событий щелчков на зоне свободного поля, для прорисовки последующего креста или кружка игрока (в базу будет заноситься эти данные и передаваться другому игроку2 за другим компьютером, что игрок1 походил)?
Как отследить что игрок не закрыл браузер, что оба участника игры в игре (обработка также событий досрочного завершения игры кем-то, выход из браузера например)?

По ходу дела может еще возникнуть пара вопросов, но пока только это. Кто реализовал подобное отзовитесь, как можно эффективно и правильно реализовать такую игрушку без перезагрузок браузерного окна в режиме реального времени. Буду благодарен, за все советы, замечания и пожелания...

A:

крестики нолики -.- жжесть....
1) дивами и наложениями слоев друг на друга
2) способы реализации разные, либо на прямую либо через БД и будет стоять таймер который срабатывает каждую секунду и получает текущее поле.
3) так-же, либо прямое подключение к серверу по принципу клиент-сервер, либо черз БД. (тот таймер который срабатывает каждую секунду, будет передавать статус)
будут вопросы пиши в скайп - Manitikyl


Q:

Is it safe to use async/await inside akka.net actor

In the following code, I am using the syntactic sugar provided by .net, the async/await approach, but read that this is not a good way of handling asynchronous operations within akka, and I should rather use PipeTo().
public class AggregatorActor : ActorBase, IWithUnboundedStash
{
    #region Constructor
    public AggregatorActor(IActorSystemSettings settings, IAccountComponent component, LogSettings logSettings) : base(settings, logSettings)
    {
        _accountComponent = component;
        _settings = settings;
    }
    #endregion

    #region Public Methods

    public override void Listening()
    {

        ReceiveAsync<ProfilerMessages.ProfilerBase>(async x => await HandleMessage(x));
        ReceiveAsync<ProfilerMessages.TimeElasped>(async x => await HandleMessage(x));
    }
    public override async Task HandleMessage(object msg)
    {
        msg.Match().With<ProfilerMessages.GetSummary>(async x =>
        {
            _sender = Context.Sender;
            //Become busy. Stash
            Become(Busy);

            //Handle different request
            await HandleSummaryRequest(x.UserId, x.CasinoId, x.GamingServerId, x.AccountNumber, x.GroupName);
        });
        msg.Match().With<ProfilerMessages.RecurringCheck>(x =>
        {
            _logger.Info("Recurring Message");
            if (IsAllResponsesReceived())
            {
                BeginAggregate();
            }
        });
        msg.Match().With<ProfilerMessages.TimeElasped>(x =>
        {
            _logger.Info("Time Elapsed");
            BeginAggregate();
        });
    }
    private async Task HandleSummaryRequest(int userId, int casinoId, int gsid, string accountNumber, string groupName)
    {
        try
        {
            var accountMsg = new AccountMessages.GetAggregatedData(userId, accountNumber, casinoId, gsid);
            //AskPattern.AskAsync<AccountMessages.AccountResponseAll>(Context.Self, _accountActor, accountMsg, _settings.NumberOfMilliSecondsToWaitForResponse, (x) => { return x; });
            _accountActor.Tell(accountMsg);

            var contactMsg = new ContactMessages.GetAggregatedContactDetails(userId);
            //AskPattern.AskAsync<Messages.ContactMessages.ContactResponse>(Context.Self, _contactActor, contactMsg, _settings.NumberOfMilliSecondsToWaitForResponse, (x) => { return x; });
            _contactActor.Tell(contactMsg);

            var analyticMsg = new AnalyticsMessages.GetAggregatedAnalytics(userId, casinoId, gsid);
            //AskPattern.AskAsync<Messages.AnalyticsMessages.AnalyticsResponse>(Context.Self, _analyticsActor, analyticMsg, _settings.NumberOfMilliSecondsToWaitForResponse, (x) => { return x; });
            _analyticsActor.Tell(analyticMsg);

            var financialMsg = new FinancialMessages.GetAggregatedFinancialDetails(userId.ToString());
            //AskPattern.AskAsync<Messages.FinancialMessages.FinancialResponse>(Context.Self, _financialActor, financialMsg, _settings.NumberOfMilliSecondsToWaitForResponse, (x) => { return x; });
            _financialActor.Tell(financialMsg);

            var verificationMsg = VerificationMessages.GetAggregatedVerification.Instance(groupName, casinoId.ToString(), userId.ToString(), gsid);
            _verificationActor.Tell(verificationMsg);

            var riskMessage = RiskMessages.GeAggregatedRiskDetails.Instance(userId, accountNumber, groupName, casinoId, gsid);
            _riskActor.Tell(riskMessage);

            _cancelable = Context.System.Scheduler.ScheduleTellOnceCancelable(TimeSpan.FromMilliseconds(_settings.AggregatorTimeOut), Self, Messages.ProfilerMessages.TimeElasped.Instance(), Self);
            _cancelRecurring = Context.System.Scheduler.ScheduleTellRepeatedlyCancelable(_settings.RecurringResponseCheck, _settings.RecurringResponseCheck, Self, Messages.ProfilerMessages.RecurringCheck.Instance(), Self);
        }
        catch (Exception ex)
        {
            ExceptionHandler(ex);
        }
    }
    #endregion
}

As you can see in the example code, I am making use of async/await, and using the ReceiveAsync() method procided by Akka.net.
What is the purpose of ReceiveAsync(), if we cannot use async/await within an actor?

A:

You can use async/await within an actor, however this requires a little bit of orchestration necessary to suspend/resume actor's mailbox until the the asynchronous task completes. This makes actor non-reentrant, which means that it will not pick any new messages, until the current task is finished. To make use of async/await within an actor you can either:

Use ReceiveAsync which can take async handlers.
Wrapping your async method call with ActorTaskScheduler.RunTask. This is usually useful in context of actor lifecycle methods (like PreStart/PostStop).

Keep in mind that this will work if a default actor message dispatcher is used, but it's not guaranteed to work, if an actor is configured to use different types of dispatchers.
Also there is a performance downside associated with using async/await inside actors, which is related to suspend/resume mechanics and lack of reentrancy of your actors. In many business cases it's not really a problem, but can sometimes be an issue in high-performance/low-latency workflows.


Q:

custom of setting the corpse adrift

I read a custom of setting a corpse in water; this was read in a novel Moby Dick. What do we call the custom of setting the corpse adrift in the sea? Is there any particular name of this custom?

A:

I think that you are talking about a burial at sea [wikipedia]

Burial at sea is the disposal of human remains in the ocean, normally
  from a ship or boat. It is regularly performed by navies, and is done
  by private citizens in many countries.

For those that do not read the comments thoroughly, @James K has found a web page where you can read an excerpt of Moby Dick (by Herman Melville) with a quite detailed description of a burial at sea
The Pequod Meets the Delight


Q:

Floating Action Button is not displaying android

This is my layout file.
<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:orientation="vertical">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:background="@color/primary"
            android:elevation="6dp"
            android:minHeight="?attr/actionBarSize"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

        <android.support.design.widget.TabLayout
            android:id="@+id/tab_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/toolbar"
            android:background="@color/primary"
            android:elevation="6dp"
            android:minHeight="?attr/actionBarSize"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/>

        <android.support.v4.view.ViewPager
            android:id="@+id/pager"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/tab_layout"
            android:paddingTop="20dp"
            android:background="@color/windowBackground"
            android:layout_above="@id/bottomButtons"
            >
        </android.support.v4.view.ViewPager>

        <android.support.design.widget.FloatingActionButton
            xmlns:app="http://schemas.android.com/apk/res-auto"
            android:id="@+id/fab"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:clickable="true"
            android:src="@drawable/cart"
            android:layout_margin="16dp"
            app:elevation="6dp" />

    </LinearLayout>

    <fragment
        android:id="@+id/fragment_navigation_drawer"
        android:name="com.wokoshop.sony.app.FragmentDrawer"
        android:layout_width="@dimen/nav_drawer_width"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        app:layout="@layout/fragment_navigation_drawer"
        tools:layout="@layout/fragment_navigation_drawer" />

</android.support.v4.widget.DrawerLayout>

In this layout Floating action button is not displaying.
Can anyone help me on this?

A:

The view pager is being set to wrap_content and in this case the rest of the view is what its saying it needs to contain its content.  If you change the root viewgroup to Relative layout your problems are solved.
<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:orientation="vertical">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:background="#456786"
            android:elevation="6dp"
            android:minHeight="?attr/actionBarSize"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

        <android.support.design.widget.TabLayout
            android:id="@+id/tab_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/toolbar"
            android:background="#456786"
            android:elevation="6dp"
            android:minHeight="?attr/actionBarSize"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/>

        <android.support.v4.view.ViewPager
            android:id="@+id/pager"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingTop="20dp"
            android:background="#765876"
            android:layout_below="@id/tab_layout"/>

        <android.support.design.widget.FloatingActionButton
            android:id="@+id/fab"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:clickable="true"
            android:src="@android:drawable/ic_input_add"
            android:layout_margin="16dp"
            app:elevation="6dp"
            android:layout_alignParentBottom="true"
            android:layout_alignParentRight="true"/>

    </RelativeLayout>

</android.support.v4.widget.DrawerLayout>


Q:

Get Property by String Force Uppercase?

I am using the C# GetPropertymethod using reflection.

obj.GetType().GetProperty("columnName")

However I cannot guarantee the exact casing of the column name as it is being based in from an external source.  It maybe ColumnName or columnname
I was thinking if I could just force the string column name to uppercase, but how would I then deal with the Property on the object itself?  The getProperty method looks like it needs to be the EXACT casing?

A:

You can use
var prop = GetProperty("columnname",
                       BindingFlags.Instance |
                       BindingFlags.Public |
                       BindingFlags.IgnoreCase);

Note that you'll still need the Instance and Public bit (assuming that this is a public instance property) as otherwise it won't find anything.

A:

You can ignore the case when looking up the property.
GetProperty(fieldname, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);


Q:

Purpose of ammine in Tollens' reagent

In this previous question the mechanism for the reaction of Tollens' reagent was outlined. As I understand it the oxidising agent in Tollens' is the diamminesilver(I) complex $\ce{[Ag(NH3)2]+}$ but the mechanism only showed the silver ion.
What is the purpose of adding ammonia to the silver nitrate to form the diamminesilver(I) complex: why not just use silver nitrate? Is it purely to provide a source of hydroxide ions or is the structure of the complex ion actually important?

A:

The formation of the diamminesilver(I) complex $\ce{[Ag(NH3)2]+}$ due to addition of ammonia has mainly three functions.
1.
The Tollens test takes place under alkaline aqueous conditions. The complexation of $\ce{Ag+}$ with $\ce{NH3}$ prevents precipitation of brown $\ce{Ag2O}$:
$$\ce{2Ag+ + 2OH- <=> 2 AgOH <=> Ag2O + H2O}$$
2.
The Tollens test shall be selective for aldehydes. $\ce{[Ag(NH3)2]+}$ is a milder oxidising agent than $\ce{Ag+}$.
$$\begin{alignat}{2}
\ce{Ag+ + e- \;&<=> Ag}\quad &&E^\circ = +0.799\ \mathrm{V}\\
\ce{[Ag(NH3)2]+ + e- \;&<=> Ag + 2 NH3}\quad &&E^\circ = +0.373\ \mathrm{V}
\end{alignat}$$
The difference in redox potential can be explained using the stability constant of $\ce{[Ag(NH3)2]+}$:
$$K_\text{B} = \frac{\left[\ce{[Ag(NH3)2]+}\right]}{\left[\ce{Ag+}\right]\left[\ce{NH3}\right]^2}$$
$$\begin{aligned}
E&=E_{\ce{Ag+}}^\circ+\frac{RT}{F}\cdot\ln\left[\ce{Ag+}\right]\\
&=E_{\ce{Ag+}}^\circ+\frac{RT}{F}\cdot\ln\frac{\left[\ce{[Ag(NH3)2]+}\right]}{K_\text{B}\cdot\left[\ce{NH3}\right]^2} \\
E_{\ce{[Ag(NH3)2]+}}^\circ&=E_{\ce{Ag+}}^\circ+\frac{RT}{F}\cdot\ln\frac{1}{K_\text{B}} \\
&\approx E_{\ce{Ag+}}^\circ-0.059\ \mathrm{V}\cdot\log K_\text{B}
\end{aligned} $$
3.
The complex formation equilibrium slows down the overall reaction. A slow, controlled reaction is important for creating the desired silver mirror. If $\ce{Ag+}$ is reduced too quickly, colloidal silver metal would appear, which would create a black cloudy liquid.


Q:

Groovy XmlSlurper with special characters in node names

I am trying to use the groovy xml slurper to slurp the following XML, with the goal being getting to the:
<message>ARoute</message>

tag.
<org.kie.server.api.model.ServiceResponse>
<type>SUCCESS</type>
<msg>Container container2 successfully called.</msg>
<result class="string">
    <execution-results>
    <result identifier="helloWorld">
<com.me.testproject.HelloWorld>
  <message>ARoute</message>
</com.me.testproject.HelloWorld>
</result>
<fact-handle identifier="helloWorld" external-form="0:1:1985641387:1985641387:2:DEFAULT:NON_TRAIT:com.me.testproject.HelloWorld"/>
</execution-results></result>
</org.kie.server.api.model.ServiceResponse>

When I just use the following gpath:
def response = new XmlSlurper().parseText(payload)
def result = response.result
println( "Output is " + result)

I get the following (which I expect)
Output is <execution-results>
 <result identifier="helloWorld">
<com.me.testproject.HelloWorld>
  <message>ARoute</message>
</com.me.testproject.HelloWorld>
</result>
<fact-handle identifier="helloWorld" external-  form="0:37:1288414012:1288414012:74:DEFAULT:NON_TRAIT:com.me.testproject.HelloWorld"/>
</execution-results>

However when I attempt to parse the execution-results something appears to be off, my understanding was becuase of the hyphon in the xml node name, I should put it in characters but that doesnt seem to do the trick:
def response = new XmlSlurper().parseText(payload)
def result = response.result.'execution-results'
println( "The type is " + result)

Outputs:
     The type is
How would I go about drilling deeper into the XML message to get to the message tag?

A:

By default, the toString() of a gpath expression is equivalent to the text() method: it only show the text content of the nodes matched by the expression. In short: the expression has worked, but your println didn't show what you expected.
If you wants the content as xml, you can use groovy.xml.XmlUtil.serialize(result)


Q:

The number of positive integral solutions to the system of equations.

The number of positive integral solutions to the system of equations
$$\begin{align} & a_{1}+a_{2}+a_{3}+a_{4}+a_{5}=47\\
&a_{1}+a_{2}=37,\ \ \{a_{1},a_{2},a_{3},a_{4},a_{5}\} \in \mathbb{N}\end{align}$$
is

$a.)\ 2044\quad \quad \quad \quad \quad b.)\ 2246\\
c.)\ 2024\quad \quad \quad \quad \quad \color{green}{d.)\ 2376}$
I know my something like stars and bars for $a_{1}+a_{2}+a_{3}+a_{4}+a_{5}=47$ ,
the non-negative solutions are $\dbinom{47+4}{4}$ and
for $a_{1}+a_{2}=37$
the non-negative solutions are $\dbinom{37+1}{1}$
But the non-negative solutions will include zero and it is not needed here.
Also there are two cases combined I am confused on how to solve this question.
Also this question was given in chapter quadratic equations I don't know how.
I look for a short and simple way.
I have studied maths up to $12$th grade.Thanks.

A:

I think there is no correct option.
The system is equivalent to
$$a_1+a_2=37$$
$$a_3+a_4+a_5=10$$
Let $b_i=a_i-1$. Then, $b_i$ are non-negative integers. So, the system is equivalent to
$$b_1+b_2=37-2=35$$
$$b_3+b_4+b_5=10-3=7$$
Then, here you can use the method you wrote, so we have
$$\binom{36}{1}\times\binom{9}{2}=\color{red}{1296}.$$


Q:

Setting fixed length with python

I have str that are like '60' or '100'.
I need the str to be '00060' and '00100',
How can i do this?
code is something like this:
I was using  '0'+'0'+'0' as plug. now need to fix
d==0006000100
  a4 ='60'
  a5 ='100'

  d=('0'+'0'+'0'+a4+'0'+'0'+a5)

A:

Since you are manipulating strings, str.zfill() does exactly what you want.
>>> s1, s2 = '60', '100'
>>> print s1.zfill(5), s2.zfill(5)
00060 00100

A:

Like this:
num = 60
formatted_num = u'%05d' % num

See the docs for more information about formatting numbers as strings.
If your number is already a string (as your updated question indicates), you can pad it with zeros to the right width using the rjust string method:
num = u'60'
formatted_num = num.rjust(5, u'0')


Q:

Does the LEGO company sell LEGO brick organization bins?

Possible Duplicate:
What are some storage options?

Are there official LEGO brick storage and organization bins available?  If not, then what good 3rd party options are there?  I'm looking to transition away from just having large plastic boxes filled with LEGO bricks that require me digging through, and going to having a way to quickly access specific bricks I need when building.

A:

The LEGO company has indeed regularly issued storage solutions. They may be great for kids (the latest ones are brick-shaped), but let's face it, for serious fans they are mostly pointless. And expensive.
Depending on the size of your collection and your sorting method (which is another debate, but remember to sort by form first, not by color), you'll want to switch to do-it-yourself storage racks (the ones with lots of plastic drawers) or whatever you fancy. If using drawers, make sure they are translucid, or have a sticker with the image of the part on them. (LEGOland designers glue one specimen of the actual part).
Some people just buy translucid boxes, try to find some shop which sells them in bulk (like, by 100 pieces), ask a caterer where he finds his for example.
It will require some experimenting anyway, so don't buy too much of an expensive item before being sure it's right for you.


Q:

vim as editor for mutt: specify to open newline under header as command line option

I use vim as editor for mail in mutt (edit_headers enabled) and I pass options to it using the editorvariable in muttrc:
set editor="nvim  \"+set tw=80\"  \"+set fo=aw\" \"+set nonumber\" \"+set spell\" +/^$/ \"+nohl\" +o"

This gets the cursor into the line separating header from body, but the actual body text would of course start in a new line underneath. So I press "o" to open a newline and can start typing.
Is there a way to tell vim to do the "press o" automatically so that I can start typing right away?

A:

+startinsert or +"normal o"
startinsert starts Insert mode in the current line, not the next line. normal o simulates pressing o in Normal mode.


Q:

Можно ли в git посмотреть историю изменений одного файла?

Хотелось бы такую фичу:
11.05.2017 14:22:02
Строка: ...
Было: ...
Стало: ...

A:

Можно.
git log -p -- path/filename.txt

Подробнее:

Параметр -p нужен для того, чтобы git log показал построчный дифф.
-- отделяет параметры от передаваемых путей к файлам. После -- — только пути.
path/filename.txt – путь к файлу, историю изменений которого вы хотите посмотреть.


Q:

iPhone - error loading view controller

I load view controllers all the time in the following format:
-(void)loadSelectUser {
    MyViewController *nextController = [[MyViewController alloc] initWithStyle:UITableViewStyleGrouped];

    MyAppDelegate *delegate = [[UIApplication sharedApplication] delegate];
    [delegate.navigationController pushViewController:nextController animated:YES];
    [nextController release];
}

And I've never had an issue with that.  But right now I'm dealing with the issue that the next view doesn't load completely.  The navigation bar shows up and the viewDidLoad and the numberOfSectionsInTableView methods are both called.  That is it.  The table doesn't show up, it still shows the previous view.
I imagine this means there is a memory leak or something not connected properly.  Is this the right path to be looking?  If so, what is your best suggestion for debugging this issue.  My code has no error messages so I'm not sure where to start.  I load the view properly in a different controller, but for some reason it doesn't do it after this particular view*.
*This view happens to do a lot data manipulation with downloading objects, saving them and such.  But again, it looks like it is all working properly.  What would mess up the navigation controller loading the next view completely?
Oh, and just to mess things up more, some times, it works properly.  But I run it one more time and it doesn't do it again.
Update: TechZen comment about the proper way to push a new view controller seemed to help a little. There is a higher rate of it working, unless I am pushing a tableviewcontroller.  Depending on the action my view will push a UITableViewController or a UIViewController with a nib file.  The second usually (not always) works.
Also, in a different view I am adding a modal view.  But when I try to dismiss it using [self dismissModalViewControllerAnimated:YES]; it doesn't always work.  Again it's hit or miss on it.  Anyone have an idea of what would be causing the transition of windows to be finicky?

A:

Calling the app delegate to get the navigation controller is unnecessary and risky. Any view controller on a navigation controller stack has a populated navigationController property so you can just use self.navigationController.
It's risky to call the app delegate's navigation controller because you have no guarantee that you will get the same navigation controller as the one that currently holds the view controller calling the push. You could in theory end up with two overlapping and conflict navigation controllers.
Switch the code to self.navigationController and see if that fixes the problem.


Q:

Check  contains specific  without JQuery

Is it possible to check that the <head> contains a specific <link> tag?
For example I would add a link to the head:
let link = document.createElement('link');
link.href = 'https://my.path.css';
link.type = 'text/css';
link.rel = 'stylesheet';
document.head.append(link);

Is it then possible to check that it is present within the head?
I know that I can get an HTMLCollection with
const headChildren = document.getElementsByTagName('head')[0].children;

But I can't seem to navigate this to check...

A:

The suggestions for the loop were only half of the solution I required.
I wanted a simple way to check that the exact  tag that I had created and pushed into the  was present.
I attempted all the different types of equality to no avail. '==' and '===' wouldn't work I'm assuming because of referring to object identities etc like Strings suffer from.
I found the solution with `.isEqualNode' which equates two nodes.
Therefore my solution in the end was:
const headChildren = document.getElementsByTagName('head')[0].children;

for (let child or headChildren) {
    if (child.isEqualNode(myLinkNode) {
        // Do something
    }
}


Q:

Permission Denial : permission.MAPS_RECEIVE due to sender com.google.android.apps.maps

I imported a map sample and run the application, Upon running the application it showing a white map screen.
I found a warning in Locat saying
W/BroadcastQueue(306): Permission Denial: receiving Intent { act=com.google.android.maps.api.action.TOKEN_RESPONSE flg=0x10 pkg=com.example.mapdemo (has extras) } to ProcessRecord{42554900 5306:com.example.mapdemo/u0a216} (pid=5306, uid=10216) requires com.example.mapdemo.permission.MAPS_RECEIVE due to sender com.google.android.apps.maps (uid 10031)
I checked the manifest thouroughly and unable to trace any issues. Please find my manifest permissions below.

 <permission
    android:name="com.example.mapdemo.permission.MAPS_RECEIVE"
    android:protectionLevel="signature"/>
  <uses-permission android:name="com.example.mapdemo.permission.MAPS_RECEIVE"/>
  <uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="16"/>
  <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
  <uses-permission android:name="android.permission.INTERNET"/>
  <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

  <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
  <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

Please let me know the possible solutions
Update: I'm able to get rid of that warning.The mistake is I am using v1 api key.
But still I'm unable to get the map. Showing white screen without any warnings or errors.
Regards,
Sha

A:

Make sure your manifest has
<permission
        android:name="com.example.mapdemo.permission.MAPS_RECEIVE"
        android:protectionLevel="signature"/>
<uses-permission android:name="com.example.mapdemo.permission.MAPS_RECEIVE"/>

Also make sure that you have your key (debug or release) set in the maps api console.


Q:

Asymptotic efficiency of maximum likelihood estimate

Let us consider a simple statistical model $\{f_{\theta}\}$ where $\theta\in U$, an open subset of $\mathbb{R}$. Let $X_1,\dots,X_n$ be sample drawn from $f_{\theta}$. I know, under some regularity assumptions, that $$ n \text{Var}_{\theta}\left(\hat{\theta}_{MLE}(X_1,\dots.X_n)\right)\to 1/I_{\theta},$$ where $I_{\theta}$ is the Fisher information. Can someone provide a proof (or a link to a reference) to the above result? In the books I have, I could find only proof of the following (relevant) result which is actually called asymptotic normality: $$\sqrt{n}\left(\hat{\theta}_{MLE}(X_1,\dots.X_n)-\theta\right)\stackrel{d}{\to} \mathcal{N}(0,1/I_{\theta}).$$ Thank you.

A:

By hypothesis, $\sqrt{n}\hat\theta_n=\sqrt{n}\theta+Z_n$ where $Z_n$ converges in distribution to a centered normal random variable $Z$ with variance $1/I_\theta$, and you are asking whether one can deduce that $E[Z_n^2]\to E[Z^2]$. Obviously, some supplementary hypothesis is needed, which, by uniform integrability, might be that $E[|Z_n|^3]$ is bounded uniformly in $n$.


Q:

Android - Cannot create ListView within custom Dialog

With my app, what happens is that when a user clicks a certain button, the custom dialog displays. The custom dialog consists of two widgets:

Edit Text field
ListView

This is supposed to work similar to how autocomplete would work. When the user has entered a certain number of characters (3) or more, I want to display a filtered ListView of the results. I get the text value from the EditText and I use it in an SQLite statement (works fine). I then add it to an ArrayList (no problem), but when I try and set the ArrayAdapter, I get the following message:
    08-11 11:49:20.552 8045-8045/com.example.maindec.sme E/AndroidRuntime: FATAL EXCEPTION: main
                                                                       Process: com.example.maindec.sme, PID: 8045
                                                                       java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference
                                                                           at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:401)
                                                                           at android.widget.ArrayAdapter.getView(ArrayAdapter.java:369)
                                                                           at android.widget.AbsListView.obtainView(AbsListView.java:2346)
                                                                           at android.widget.ListView.makeAndAddView(ListView.java:1875)
                                                                           at android.widget.ListView.fillDown(ListView.java:702)
                                                                           at android.widget.ListView.fillFromTop(ListView.java:763)
                                                                           at android.widget.ListView.layoutChildren(ListView.java:1684)
                                                                           at android.widget.AbsListView.onLayout(AbsListView.java:2148)
                                                                           at android.view.View.layout(View.java:16630)
                                                                           at android.view.ViewGroup.layout(ViewGroup.java:5437)
                                                                           at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1743)
                                                                           at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1586)
                                                                           at android.widget.LinearLayout.onLayout(LinearLayout.java:1495)
                                                                           at android.view.View.layout(View.java:16630)
                                                                           at android.view.ViewGroup.layout(ViewGroup.java:5437)
                                                                           at android.widget.FrameLayout.layoutChildren(FrameLayout.java:336)
                                                                           at android.widget.FrameLayout.onLayout(FrameLayout.java:273)
                                                                           at android.view.View.layout(View.java:16630)
                                                                           at android.view.ViewGroup.layout(ViewGroup.java:5437)
                                                                           at android.widget.FrameLayout.layoutChildren(FrameLayout.java:336)
                                                                           at android.widget.FrameLayout.onLayout(FrameLayout.java:273)
                                                                           at android.view.View.layout(View.java:16630)
                                                                           at android.view.ViewGroup.layout(ViewGroup.java:5437)
                                                                           at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1743)
                                                                           at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1586)
                                                                           at android.widget.LinearLayout.onLayout(LinearLayout.java:1495)
                                                                           at android.view.View.layout(View.java:16630)
                                                                           at android.view.ViewGroup.layout(ViewGroup.java:5437)
                                                                           at android.widget.FrameLayout.layoutChildren(FrameLayout.java:336)
                                                                           at android.widget.FrameLayout.onLayout(FrameLayout.java:273)
                                                                           at android.view.View.layout(View.java:16630)
                                                                           at android.view.ViewGroup.layout(ViewGroup.java:5437)
                                                                           at android.widget.FrameLayout.layoutChildren(FrameLayout.java:336)
                                                                           at android.widget.FrameLayout.onLayout(FrameLayout.java:273)
                                                                           at android.view.View.layout(View.java:16630)
                                                                           at android.view.ViewGroup.layout(ViewGroup.java:5437)
                                                                           at android.widget.FrameLayout.layoutChildren(FrameLayout.java:336)
                                                                           at android.widget.FrameLayout.onLayout(FrameLayout.java:273)
                                                                           at com.android.internal.policy.PhoneWindow$DecorView.onLayout(PhoneWindow.java:2678)
                                                                           at android.view.View.layout(View.java:16630)
                                                                           at android.view.ViewGroup.layout(ViewGroup.java:5437)
                                                                           at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2171)
                                                                           at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1931)
                                                                           at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1107)
                                                                           at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6013)
                                                                           at android.view.Choreographer$CallbackRecord.run(Choreographer.java:858)
                                                                           at android.view.Choreographer.doCallbacks(Choreographer.java:670)
                                                                           at android.view.Choreographer.doFrame(Choreographer.java:606)
                                                                           at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:844)
                                                                           at android.os.Handler.handleCallback(Handler.java:739)
                                                                           at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                           at android.os.Looper.loop(Looper.java:148)
                                                                           at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                           at java.lang.reflect.Method.invoke(Native Method)
                                                                           at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
08-11 11:52:36.596 8045-8053/com.example.maindec.sme W/art: Suspending all threads took: 5.267ms
08-11 11:54:20.640 8045-8045/com.example.maindec.sme I/Process: Sending signal. PID: 8045 SIG: 9

That message only display when I try to set the adapter. I've debugged and this is definitely the problem.
Here's my code:
final AlertDialog.Builder builder = new AlertDialog.Builder(this);

    builder.setTitle("Smoke weed everyday...");

    builder.setPositiveButton("Try Again", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
        }
    })
            .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    //dialog.cancel();
                }
            });

    builder.setView(getLayoutInflater().inflate(R.layout.item_list_dialog, null));

   final Dialog dialog = builder.create();

// THIS IS THE NAME OF THE BUTTON
itemListSelection.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                dialog.setCanceledOnTouchOutside(false);

                dialog.show();

                final EditText itemNumberInputField = (EditText) dialog.findViewById(R.id.item_number_input_field);

                final ListView filteredItemNumberList = (ListView) dialog.findViewById(R.id.item_number_list);

                itemNumberInputField.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {
                        currentValue = itemNumberInputField.getText().toString();

                        smeDatabase = openOrCreateDatabase("SME", MODE_PRIVATE, null);
                        if (currentValue.length() > 2) {
                            keyNumbersList.clear();
                             Cursor itemResultSet = smeDatabase.rawQuery("SELECT * " +
                                    "FROM item_list", null);

                            for (int i = 0; i < itemResultSet.getCount(); i++) {
                                itemResultSet.moveToPosition(i);
                                keyNumbersList.add(itemResultSet.getString(0));
                                System.out.println("Test: " + itemResultSet.getString(0));
                            }
                            ArrayAdapter<String> itemNumbersAdapter = new ArrayAdapter<String>(NewKeyNumber.this, android.R.layout.simple_list_item_1, keyNumbersList);
        //THIS IS THE LINE THAT FAILS            filteredItemNumberList.setAdapter(itemNumbersAdapter);
                        }
                    }

                    @Override
                    public void afterTextChanged(Editable s) {

                    }

                });
            }
        });

Any help with this would be appreciated. Thanks.

A:

It turned out that the reason why it kept failing was because I had a null value inside my ArrayList, so I did this to solve it:
if (currentItem != null) {
          keyNumbersList.add(itemResultSet.getString(0));
          System.out.println("Test: " + itemResultSet.getString(0));
}

Filtering out any null values. Works great.


Q:

Autoprefixer for partially prefixed CSS

I need to manipulate CSS files on the server and I recently discovered Autoprefixer library.
My issue is - my css files have prefix depending on the browser which was used.
For eg. My css code is something like this -
.newclass
{
    -moz-transition:.3s all;
}

Autoprefixer doesn't work here and requires the css to be
.newclass
{
    transition:.3s all;
}

to generate
.newclass
{
    transition:.3s all;
    -moz-transition:.3s all;
    -ms-transition:.3s all;
    -o-transition:.3s all;
    -webkit-transition:.3s all;
}

Is there any way I can achieve the same result with my original CSS (a prefixed property instead of non-prefixed one)?
Or is there any other library that can help me achieve the same thing other than Autoprefixer?

A:

This is by design. Autoprefixer deliberately ignores any prefixes that don't precede an unprefixed declaration so they can be used if they are absolutely necessary without being overwritten, which would lead to undesired side effects.
For example, the output you've given in your question is not the output that would be generated if you ran Autoprefixer right now with the default settings. Assuming it did overwrite your -moz- prefix, it'd discard it entirely because the prefix is no longer needed as of Firefox 16 which came out almost two years ago. The actual output would be:
.newclass
{
    -webkit-transition:.3s all;
            transition:.3s all;
}

Now, you could just run Autoprefixer with an option to accommodate older versions of Firefox (Firefox >= 4) and other browsers, but you will still have to remove the prefix(es) from your CSS if you want Autoprefixer to process it. You cannot expect Autoprefixer to assume it can do whatever it wants with prefixes explicitly declared in your CSS.
This section of the documentation has a different example, but the principle is the same:

Disabling
Autoprefixer was designed to have no interface – it just works. If you need some browser specific hack just write prefixed property after unprefixed.
a {
    transform: scale(0.5);
    -moz-transform: scale(0.6);
}


Q:

Year of passage of Massachusetts age of consent law

Massachusetts has an idiosyncratic age of consent law, which states that it is illegal to have sex with "any person under 18 years of age of chaste life": https://malegislature.gov/Laws/GeneralLaws/PartIV/TitleI/Chapter272/Section4
I was discussing with some friends the supposition that this law sounded fairly archaic. I'd like to find out when this law was passed, but some googling did not turn up a result. How do I find out when the law was passed.

A:

The phrase "of chaste life" appears in a bill passed on June 25, 1886:

Whoever induces any person under the age of eighteen years of chaste life and conversation to have unlawful sexual intercourse shall be punished by imprisonment in the state prison, common jail, or house of correction not exceeding three years or by fine not exceeding one thousand dollars or by both fine and imprisonment in the jail or house of correction.

Note that this language is substantially similar to the language that is currently in effect;  the main changes are that the penalty was changed a little, and that the phrase "chaste life and conversation"1 was replaced with "chaste life".
Combined with the 1836 law found by user6726, this narrows it down to a range of about 50 years.

1 "Conversation" in the above context appears to be an archaic sense of the word meaning one's "manner of conducting oneself in the world or in society; behaviour, mode or course of life."


Q:

How can I load data in combo item property when another changed, in propertygrid c#?

I have two property in my class: MyCountry & MyCity. I set this class to sourceobject of a property grid. I want load cities i combo when select a country. for example I have 2 Country data:
Country1
Country2

And For Country1, I have (city data)
City11
City12
City13

And For Country2, I have (city data)
city21
City22
City23

When I change select country item in propertygrid, I want load cities of it in city item. this mean, when select Country1, display City11,City12,City13 in City item and when select Country2 Display City21,Cityy22,City23 in City Item.
How can I It ?
my class is :
public class KeywordProperties
{
    [TypeConverter(typeof(CountryLocationConvertor))]
    public string MyCountry { get; set; }
    [TypeConverter(typeof(CityLocationConvertor))]
    public string MyCity { get; set; }
}

and I use below class for load countries data for display in combo :
public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
    {
        HumanRoles Db = new HumanRoles();
        List<LocationsFieldSet> Items = new List<LocationsFieldSet>();
        Items = Db.LoadLocations(0);
        string[] LocationItems = new string[Items.Count];
        int count = 0;
        foreach (LocationsFieldSet Item in Items)
        {
            LocationItems[count] = Item.Title;
            count++;
        }
        return new StandardValuesCollection(LocationItems);
    }

    public override bool GetStandardValuesExclusive(ITypeDescriptorContext context)
    {
        return true;
    }
}

A:

The ITypeDescriptorContext interface provides a property called Instance
which lets you access the object to which the type descriptor request is connected.
You can use this property to determine the current value of the MyCountry property
the user selected. Depending on the value you can load the cities for this country.
Furthermore, in the setter of the MyCountry property I check whether or not the
new value is different from the old one and if this is the case I reset the MyCity property
(to not get an invalid combination of country and city).
Here is a small code sample. For the sake of simplicity I only use one type converter
for both properties.
public class KeywordProperties
{
  public KeywordProperties()
  {
    MyCountry = "Country1";
  }

  private string myCountry;
  [TypeConverter(typeof(ObjectNameConverter))]
  public string MyCountry
  {
    get { return myCountry; }
    set
    {
      if (value != myCountry)
        MyCity = "";

      myCountry = value;
    }
  }

  private string myCity;
  [TypeConverter(typeof(ObjectNameConverter))]
  public string MyCity
  {
    get { return myCity; }
    set { myCity = value; }
  }
}

public class ObjectNameConverter : StringConverter
{
  public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
  {
    return true;
  }

  public override TypeConverter.StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
  {
    KeywordProperties myKeywordProps = context.Instance as KeywordProperties;

    if (context.PropertyDescriptor.Name == "MyCountry")
    {
      List<string> listOfCountries = new List<string>();
      listOfCountries.Add("Country1");
      listOfCountries.Add("Country2");

      return new StandardValuesCollection(listOfCountries);
    }

    List<string> listOfCities = new List<string>();
    if (myKeywordProps.MyCountry == "Country1")
    {
      listOfCities.Add("City11");
      listOfCities.Add("City12");
      listOfCities.Add("City13");
    }
    else
    {
      listOfCities.Add("City21");
      listOfCities.Add("City22");
      listOfCities.Add("City23");
    }

    return new StandardValuesCollection(listOfCities);
  }
}

In the example above there is one side effect I do not like.
Setting the MyCountry property leads to settting also the MyCity property.
To workaround this side effect you could also use the PropertyValueChanged event
of the PropertyGrid to handle invalid country/city selections.
private void propertyGrid1_PropertyValueChanged(object s, PropertyValueChangedEventArgs e)
{
  if (e.ChangedItem.Label == "MyCountry")
  {
    if(e.ChangedItem.Value != e.OldValue)
      m.MyCity = "";
  }
}

If you use this event, just repalce the code in the setter of the MyCountry property with:
myCountry = value;


Q:

Dynamic variable from function in Python

var 1 is constantly changing with every new line that is written in the csv file. Any suggestion how can I get the value outside of the function. This example does not work for me.
I updated my code and added second function which is exactly the same but is reading another file. Now I only get print from the first function only. If I disable the first function I can get the print from the second function. Is there a way to print both of them or maybe three or four if I add later new functions ?
import sys
import time
import datetime
import os

class Application():

    def loop_one(self):

       filename = 'Test.csv'
       mycsv = open(filename, 'r')
       mycsv.seek(0, os.SEEK_END)

       while 1:
            time.sleep(1)
            where = mycsv.tell()
            line = mycsv.readline()

       if not line:
            mycsv.seek(where)

       else:
           arr_line = line.split(',')
           var1 = arr_line[5]
           mydate = datetime.datetime.now()
           print var1, mydate.strftime("%H:%M:%S:%f")
           return var1

    def loop_two(self):

       filename2 = 'Test2.csv'
       mycsv2 = open(filename2, 'r')
       mycsv2.seek(0, os.SEEK_END)

       while 1:
            time2.sleep(1)
            where2 = mycsv2.tell()
            line2 = mycsv2.readline()

       if not line2:
            mycsv2.seek(where2)

       else:
           arr_line2 = line2.split(',')
           var2 = arr_line2[5]
           mydate2 = datetime.datetime.now()
           print var2, mydate.strftime("%H:%M:%S:%f")
           return var2

s = Application()
var1 = s.loop_one()
var2 = s.loop_two()

A:

You can declare a variable inside the init function so you can use that anywhere
class A(object):
    def __init__(self):
        self.x = 'Hello'

    def method_a(self, foo):
        print self.x + ' ' + foo

In your case you can do something like this (not tested)
class Application():

    def __init__(self):

       self.filename = 'Test.csv'
       self.mycsv = open(self.filename, 'r')
       self.mycsv.seek(0, os.SEEK_END)
       self.var1 = ''

    def loop_one(self):
        while 1:
            time.sleep(1)
            where = self.mycsv.tell()
            line = self.mycsv.readline()

            if not line:
                self.mycsv.seek(where)
                # you need a break here or somewhere :D

            else:
                arr_line = line.split(',')
                self.var1 = arr_line[5]
                mydate = datetime.datetime.now()
                print self.var1, mydate.strftime("%H:%M:%S:%f")
                return self.var1

s = Application()
s.loop_one()


Q:

Как сделать блок резиновым

Как сделать, чтобы главный блок с контентом растягивался по высоте сайта, в зависимости от разрешения экрана.

A:

var contentHeight = $(document).height() - 60;

$('#content').css('height', contentHeight);
body,
html {
  width: 100%;
  height: 100%;
}
section {
  width: 100%;
  background: #000;
  padding: 30px 0;
}
#content {
  width: 300px;
  height: 1px;
  margin: 0 auto;
  overflow-x: hidden;
  overflow-y: auto;
  background-color: black;
  color: #fff;
}

    Lorem ipsum — dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex
    ea commodo consequat.[1] Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum
    dolor sit amet, consectetuer adipiscing elit. Maecenas porttitor congue massa. Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada libero, sit amet commodo magna eros quis urna. Nunc viverra imperdiet enim. Fusce est. Vivamus a tellus.
    Pellentesque habitant morbi tristique senectus et netus[2] et malesuada fames ac turpis egestas. Proin pharetra nonummy pede. Mauris et orci. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore
    magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat
    cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum — dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim
    ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.[1] Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat
    non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas porttitor congue massa. Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada libero, sit
    amet commodo magna eros quis urna. Nunc viverra imperdiet enim. Fusce est. Vivamus a tellus. Pellentesque habitant morbi tristique senectus et netus[2] et malesuada fames ac turpis egestas. Proin pharetra nonummy pede. Mauris et orci. Lorem ipsum
    dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit
    in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Вот здесь посмотрите.
Урок о том как прижать footer к низу экрана, ну и Ваш вопрос затрагивается.
Удачи.
Ps: Можно с помощью jQuery рассчитать высоту, вот здесь накидал на скорую руку, посмотри.
UPD: http://jsfiddle.net/Alex83/WTtQu/31/
Вот, вроде как-то так.


Q:

Multiple headers in get_file_contents not functioning

I am trying to pass multiple headers through to a URL (API server) using file_get_contents. The code I have below echos out a HTTP 500 error:
$userdetails = http_build_query(
array(
    'userdetails' => '

                        {

                "jobId": null, "collectionOnDelivery": false, "invoice": null,

                "collectionDate": "2014-08-27T09:11:00", "consolidate": false,

                "consignments": [{ "collectionDetails":{

                "contactDetails":{ "contactName":"Mr David Smith" "telephone":"0121 500 2500"

                },

                "address":{

                "organisation":"GeoPost UK Ltd", "property":"",

                "street":"Roebuck Lane", "locality":"Smethwick", "town":"Birmingham", "county":"West Midlands", "postcode":"B66 1BY", "countryCode":"GB",

                }

                },

                "deliveryDetails":{

                "contactDetails":{ "contactName":"Mr David Smith"

                "telephone":"0121 500 2500"

                },

                "notificationDetails":{ "mobile":"07921 123456" "email":"david.smith@acme.com"

                },

                "address":{ "organisation":"ACME Ltd",

                "property":"Miles Industrial Estate", "street":"42 Bridge Road", "locality":"",

                "town":"Birmingham", "county":"West Midlands", "postcode":"B1 1AA", "countryCode":"GB",

                }

                },

                "networkCode":"1^12",

                "numberOfParcels":1,

                "totalWeight":5, "shippingRef1":"Catalogue Batch 1", "shippingRef2":"Invoice 231", "shippingRef3":"", "customsValue":0,

                "deliveryInstructions":"Please deliver to industrial gate A", "parcelDescription":"",

                "liabilityValue":0,

                "liability":false,

                "parcel":[]

                }]

                }

    '

    )
 );

$content = array('http' =>
    array(
         'method'  => 'POST',
         'header'  => "GEOSESSION: ".$geosession,
          "Accept: application/json",
           "Content-Type: application/json",
            'content' => $userdetails

     )
  );

   $context2  = stream_context_create($content);

   $result_userdetails = file_get_contents('https://api.interlinkexpress.com/shipping/shipment', false, $context2);

 echo $result_userdetails;

The thing is I have tried/tested the headers on POSTMAN and I am getting a response back however when I pass it through the code above I get the error. I am unsure why this is and was wondering if I am actually passing all three headers across or not? Could someone please clarify whether this is the case or if there is an error?
UPDATE:
I have tried changing the userdetails to the below as someone pointed out it was already in JSON format however the API does not seem to be liking the 'content' => $userdetails now?
$userdetails = $userdetails = http_build_query(
array(
    'userdetails' => '

                   {
"job_id": null,
"collectionOnDelivery": false,
"invoice": null,
"collectionDate": "",
"consolidate": false,
"consignment": [{
    "consignmentNumber": null,
    "consignmentRef": null,
    "parcels": [],
    "collectionDetails": {
        "contactDetails": {
            "contactName": "My Contact",
            "telephone": "0121 500 2500"
        },
        "address": {
            "organisation": "GeoPostUK Ltd",
            "countryCode": "GB",
            "postcode": "B66 1BY",
            "street": "Roebuck Lane",
            "locality": "Smethwick",
            "town": "Birmingham",
            "county": "West Midlands"
        }
    },
    "deliveryDetails": {
        "contactDetails": {
            "contactName": "My Contact",
            "telephone": "0121 500 2500"
        },
        "address": {
            "organisation": "GeoPostUK Ltd",
            "countryCode": "GB",
            "postcode": "B66 1BY",
            "street": "Roebuck Lane",
            "locality": "Smethwick",
            "town": "Birmingham",
            "county": "West Midlands"
        },
        "notificationDetails": {
            "email": "my.email@geopostuk.com",
            "mobile": "07921000001"
        }
    },
    "networkCode": "2^12",
    "numberOfParcels": 1,
    "totalWeight": 5,
    "shippingRef1": "My Ref 1",
    "shippingRef2": "My Ref 2",
    "shippingRef3": "My Ref 3",
    "customsValue": null,
    "deliveryInstructions": "Please deliver with neighbour",
    "parcelDescription": "",
    "liabilityValue": null,
    "liability": false
}]

}

A:

Multiple headers should be connected using CRLF
$content = array('http' =>
    array(
        'method'  => 'POST',
        'header'  => "GEOSESSION: " . $geosession . "\r\n" .
                     "Accept: application/json\r\n" .
                     "Content-Type: application/json",
        'content' => $userdetails

    )
);

To encode the data properly, first create a PHP containing the data, and then use json_encode to format it:
$data = array("jobId" => null, "collectionOnDelivery" => false, "invoice" => null,

              "collectionDate" => "2014-08-27T09:11:00", "consolidate" => false,

              "consignments" => array(array( "collectionDetails" =>
                                             array("contactDetails" => array( "contactName" => "Mr David Smith" "telephone" => "0121 500 2500"),
                                                   "address" => array("organisation" => "GeoPost UK Ltd", "property" => "",
                                                                      "street" => "Roebuck Lane", "locality" => "Smethwick", "town" => "Birmingham",
                                                                      "county" => "West Midlands", "postcode" => "B66 1BY", "countryCode" => "GB",)
                                                   ),
                                             "deliveryDetails" => array("contactDetails" => array( "contactName" => "Mr David Smith"
                                                                                "telephone" => "0121 500 2500"
                                                                                ),
                                                                        "notificationDetails" => array( "mobile" => "07921 123456" "email" => "david.smith@acme.com"),
                                                                        "address" => array( "organisation" => "ACME Ltd",
                                                                                "property" => "Miles Industrial Estate", "street" => "42 Bridge Road", "locality" => "",
                                                                                "town" => "Birmingham", "county" => "West Midlands", "postcode" => "B1 1AA", "countryCode" => "GB",)
                                                                        ),
                                             "networkCode" => "1^12",
                                             "numberOfParcels" => 1,
                                             "totalWeight" => 5, "shippingRef1" => "Catalogue Batch 1", "shippingRef2" => "Invoice 231", "shippingRef3" => "", "customsValue" => 0,
                                             "deliveryInstructions" => "Please deliver to industrial gate A", "parcelDescription" => "",
                                             "liabilityValue" => 0,
                                             "liability" => false,
                                             "parcel" => array()
                                             ))
              );
$userdetails = json_encode($data);


Q:

Marker interface - what's a practical code example of 'communicating a semantic constraint/guarantee that doesn't otherwise change the API

Let's start with a loose definition of 'marker interface' (please correct me or dispute this if you disagree):

If applied to a type, a marker interface doesn't provide any contract
  of methods to implement for that type. A marker interface gives
  semantic meaning.

So, OK, that's fine. However giving something a meaning has to ultimately have a practical consumption or usage elsewhere to be of benefit, right? So we may have two types that are different, but that are (for example) types related to 'scheduled tasks' in a system, so we may 'decorate' them both with an 'IAmTask' interface.
OK, so how do we then put that to practical use? I've read that:

One of the benefits of a marker interface is to 'communicate a
  semantic constraint/guarantee that doesn't otherwise change the API'.

OK, well a marker interface isn't defining a contract for methods that must be present on the type, so what's a practical example in code of how a semantic constraint/guarantee can be ultimately be returned to the user and consumed in a way that tightens up the intended guarantee to the consumer, without enforcing methods on the API? There must be a way to do this, otherwise we're simply declaring an essentially useless meaning.

A:

Since marker interfaces provide semantic meaning, they can be used like annotations to decorate a type, and you can use reflection to make decisions based on the semantics. The marker interface doesn't provide any compiler-enforceable contract.
For example, you have an interface UserRepository, and you have two implementations InMemoryUserRepository that stores users in memory and DatabaseUserRepository that stores users in a database.
interface UserRepository { def storeUser(user) }
class InMemoryUserRepository implements UserRepository { ... }
class DatabaseUserRepository implements UserRepository { ... }

I could introduce a marker interface to describe the semantics of the implementations. For example if I wanted to dynamically find implementations of UserRepository that have local semantics, I could introduce LocalRepository marker interface and have InMemoryUserRepository implement LocalRepository
interface UserRepository { def storeUser(user) }
interface LocalRepository {}
class InMemoryUserRepository implements UserRepository, LocalRepository { ... }
class DatabaseUserRepository implements UserRepository { ... }

The usefulness is that I can now distinguish the two repository classes from each other and decide to use the one with local semantics via reflection.
Some other examples of usages of marker interfaces:

Big(O) complexity of implementation e.g. java.util.RandomAccess (from @immibis comment). Maybe you have a dozen different sort algorithms. You could introduce marker interfaces with worst case and best case complexities.
Local vs. Remote. This is useful for dynamically picking a configuration for your system for testing. You could configure your dependency injection system to prefer local marked implementations when testing.
Serialization format. I may have a couple different serializers for different file formats that all have the same interface. I could introduce a marker interface to distinguish Json serializers and XML serializers, and use runtime preferences to use the file format. Or use a marker interface to describe their size footprint and choose the best serializer for network transfer based on size.


Q:

Como detectar se o valor do JSpinner foi alterado?

Eu quero realizar uma ação sempre que o valor do JSpinner for alterado. Como faço isso?

A:

Basta aplicar o evento ChangeListener ao componente:
spinner.addChangeListener(e -> {
    //faça algo quando o valor alterar
});

Demonstração:


Q:

SharePoint 2013 Popularity trends mystery

In our sharepoint 2013 root site we have a pages library which also contains the home page for the site collection as well.Popularity trends reports are getting updated daily for the home page but other pages in the same pages library are not showing any page views. Timer jobs, event receivers etc are all working. I have looked in the logging db and I can see the pages showing 0 views in the reprots have been accessed number of times by different users. Home page is getting around 140 views every day and other pages in the same page library are getting around 15 views every day. Other subsites in the same site collection are showing page views even if numbers are around 2-3 views per day.   What could be the reason for this behaviour?

A:

I have solved this mystry now. Issue was that the seach index was not getting updated due to low disk space on my app server.


Q:

Android - Actionbar Sherlock - Search Filter

I am trying to implement Action Bar using ActionBar Sherlock. I have three Action Button one of which is a Search Button. On Clicking of the Search Button the Search input field should be displayed which i have already implemented. But i want it to take the full width of the Action Bar. Any idea how i can achieve the same.

A:

first make a editTextLayout
layout_search.xml
<?xml version="1.0" encoding="utf-8"?>
<EditText xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/search_edit_text"
    android:cursorVisible="true"
    android:hint="@string/search_friend_hint"
    android:imeOptions="actionDone"
    android:inputType="text"
    android:textColor="@android:color/black"
    android:textCursorDrawable="@android:color/black" />

In you menu xml add android:actionLayout and android:showAsAction="always|collapseActionView"
for Search option.
For other option make android:showAsAction="ifRoom"
menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:icon="@drawable/ic_action_sort"
        android:orderInCategory="1"
        android:showAsAction="ifRoom"
        android:title="@string/menu_sort"/>
    <item
        android:id="@+id/menu_search"
        android:actionLayout="@layout/layout_search"
        android:icon="@drawable/search"
        android:orderInCategory="0"
        android:showAsAction="always|collapseActionView"
        android:title="@string/search"/>

</menu>

in your activity or fragment override onCreateOptionsMenu like this
fragment.java
@Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.menu, menu);

        final EditText editText = (EditText) menu.findItem(
                R.id.menu_search).getActionView();
        editText.addTextChangedListener(textWatcher);

        MenuItem menuItem = menu.findItem(R.id.menu_search);
        menuItem.setOnActionExpandListener(new OnActionExpandListener() {
            @Override
            public boolean onMenuItemActionCollapse(MenuItem item) {
                // Do something when collapsed
                return true; // Return true to collapse action view
            }

            @Override
            public boolean onMenuItemActionExpand(MenuItem item) {
                editText.clearFocus();
                return true; // Return true to expand action view
            }
        });
    }

and add textWatcherListener
private TextWatcher textWatcher = new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                int count) {

            if (null != mAdapter) {
                mAdapter.getFilter().filter(s);
            }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub

        }
    };


Q:

Dropdown menu causes scrollbar

I used this example from W3C:

    <button class="btn btn-sm dropdown-toggle" type="button" id="menu1" data-toggle="dropdown">

    </button>

HTML

CSS

JavaScript

About Us

And it all works, except for one thing. Whenever dropdown is opened it outfits the page making a horizontal scrollbar to appear. Ref screenshot below (note horizontal scrollbar at the bottom of the images):

What would be most "official" way to fix this?
EDIT:

Added fiddle: https://jsfiddle.net/aav5f25g/3/

A:

Could you try this?

    <button class="btn btn-sm dropdown-toggle" type="button" id="menu1" data-toggle="dropdown">

    </button>

HTML

CSS

JavaScript

About Us

I added dropdown-menu-right to the dropdown-menu
You may find that pull-right works if you're using an older version.


Q:

How to get the value from input and split them based on chars and numbers Js

I'm working on some exercise and I need help.
I have an input field where user can enter name and Id, with or without delimiters:

what I'm achieving is when I type "Jack123", it should identify the chars and numeric and separate it out and display in the following format:
Name: Jack
Id: 123

there could be a scenario where the user typed string will be "Jack 123" or "Jack-123" in all cases it should display the above o/p.
html:

  <input type="text" >

  Name:

  Id:

  <button onclick="changeText()">Submit
  </button>

css:
.name, .id {
  display:none; // will be displayed only when users inputs some text
}

js:
function: input (value) {
   value.split() // I'm not sure on what bases to split as this could have spaces,"-","." or even nothing
}

any idea on this approach.
thx

A:

To isolate only letters or numbers from a string I would use a regular expression.
var input = 'abc123';

// replace anything that isn't a-z or A-Z with ""
var letters = input.replace(/[^a-zA-Z]/g, '');

// replace anything that isn't 0-9 with ""
var numbers = input.replace(/[^0-9]/g, '');

console.log('letters', letters);
console.log('numbers', numbers)

This will result in

letters abc
numbers 123


Q:

Find 2D peak prominence using Python

I found this scipy function scipy.signal.peak_prominences that finds the topographic prominence of specified local maxima in a 1d sequence.
But my application requires locating important peaks in a 2D array. I'm aware of some peak finding methods, such as doing a maximum filtering, which both scipy and skimage have their implementations. Also skimage's h_maxima() allows filtering local peaks that have a minimal relative height. But these only give the coordinates of the peaks, not their prominence .
So how do I compute peak prominence on a 2d array?
Any help would be appreciated.

A:

I've cooked a python module using enclosing contour method, following wiki's definition:

The prominence of a peak is the height of the peak’s summit above the
  lowest contour line encircling it but containing no higher summit
  within it.

optionally one can filter out local peaks that have small cross section area or low prominence values.
I've put the code here: https://github.com/Xunius/python_peak_promience2d, if anyone finds any issue or possible improvement please fire an issue or PR.
A demo graph: