text:
Q: ASP.NET 5: Is localization with DisplayAttribute gone? I am migrating an application from previous ASP.NET version to ASP.NET 5(vNext, MVC 6). Previously I localized forms with DisplayAttribute attached to ViewModel's properties:
[Required(ErrorMessageResourceName = "FieldIsRequired", ErrorMessageResourceType = typeof(Resources.Validation))]
[Display(Name = "UserName", ResourceType = typeof(Resources.Common))]
public string UserName { get; set; }

I added DataAnnotations service:
public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc()
            .AddViewLocalization(options => options.ResourcesPath = "Resources/Views")
            .AddDataAnnotationsLocalization();
}

When I submit an invalid form, an error message gets localized (as specified in the [Required] attribute).
But trying to display the form, I got an exception (No public property "UserName" in the resource class), until I commented out [Display] attribute.
Seems like input labels can't be localized with [DisplayAttribute] anymore?
Thank you!

A: It is indeed gone. According to the documentation:

The runtime doesn't look up localized strings for non-validation attributes. In the code above, "Email" (from [Display(Name = "Email")]) will not be localized.

Update 20.03.2017:
Localization of non-validation attributes was re-enabled with the new .NET Core SDK, according to the updated documentation:

DataAnnotations error messages are localized with IStringLocalizer<T>.
  Using the option ResourcesPath = "Resources", the error messages in RegisterViewModel can be stored in either of the following paths:

*

*Resources/ViewModels.Account.RegisterViewModel.fr.resx

*Resources/ViewModels/Account/RegisterViewModel.fr.resx


text:
Q: Why I get segmentation fault when I the signal I got segmentation fault when I deal with the signalSIGALARM.
Here is my code.
class UThread{
public:
    UThread(){}
    ~UThread(){
        signal(SIGALRM,SIG_IGN);
        for(size_t i=0;i<thread_list.size();i++){
            delete thread_list[i]->uc_stack.ss_sp;
            delete thread_list[i];
            thread_list[i]=NULL;
        }
    }
    int create_thread(void (*callback)(void *),void *args){
        ucontext_t *new_context= new ucontext_t;

        assert(getcontext(new_context) != -1);
        new_context->uc_stack.ss_sp=new char[1024];
        new_context->uc_stack.ss_size=1024;
        new_context->uc_flags=0;
        new_context->uc_link=0;
        assert(new_context->uc_stack.ss_sp!=NULL);

        makecontext(new_context,(void (*)())callback,1,args);//make a context
        size_t n=thread_list.size();

        //find a position to save the pointer.
        int i=0;
        for(;i<n;i++){
            if(thread_list[i]==NULL)
                break;
        }
        if(i<n)
            thread_list[i]=new_context;
        else{
            thread_list.push_back(new_context);
        }
        return i;
    }

    void start_thread(){
        ucontext_t *main_context= new ucontext_t;
        getcontext(main_context);
        thread_list.push_back(main_context);

        struct sigaction sa;
        sa.sa_handler=schedule;
        sigemptyset(&sa.sa_mask);
        sigaddset(&sa.sa_mask,SIGALRM);
        sigaction(SIGALRM,&sa,NULL);

        struct itimerval tick;
        tick.it_value.tv_sec = 0;
        tick.it_value.tv_usec = 1;

        tick.it_interval.tv_sec = 0;
        tick.it_interval.tv_usec = 1000;//send a SIGALRM
        setitimer(ITIMER_REAL,&tick,NULL);
    }

private:
    static void schedule(int signo){//deal with the signal
        int last_id=current_id;
        int n=thread_list.size();

        int i=rand()%n;//get a random number.
        while(thread_list[i]==NULL){
            i=rand()%n;
        }
        current_id=i;
        if(thread_list[last_id]==NULL){//if it has been cancelled,just setcontext.
            setcontext(thread_list[i]);
            return;
        }
        swapcontext(thread_list[last_id],thread_list[current_id]);//swap the context.
    }

    static int current_id;
    static vector<ucontext_t*> thread_list;
};
vector<ucontext_t*> UThread::thread_list;
int UThread::current_id=0;

this is what the class define.And it will get segmentation fault if I call more than two function.
void f2(void *){
    const char *buf="I am f2.\n";;
    while(true){
        write(STDOUT_FILENO,buf,strlen(buf));
    }
}

void f3(void *){
    const char *buf="I am------- f3.\n";
    while(true){
        write(STDOUT_FILENO,buf,strlen(buf));
    }
}

int main(){
    UThread t;
    t.start_thread();
    int thread_id2=t.create_thread(f2,NULL);
    int thread_id3=t.create_thread(f3,NULL);
    const char *buf="I am main.\n";
    while(true){
        write(STDOUT_FILENO,buf,strlen(buf));
    }
    return 0;
}

this is the function call
if I delete one of t.create_thread(f3,NULL);in the main function,it will run successfully without error.But If I add two t.create_thread(func,NULL); to the main function,it will get segmentation fault after swapcontext(thread_list[last_id],thread_list[current_id]); is done.

A: The shown code installs a signal handler:
    struct sigaction sa;
    sa.sa_handler=schedule;
    sigemptyset(&sa.sa_mask);
    sigaddset(&sa.sa_mask,SIGALRM);
    sigaction(SIGALRM,&sa,NULL);

This schedule() function attempts to access various C++ library containers, and invoke their methods:
static void schedule(int signo){//deal with the signal
    int last_id=current_id;
    int n=thread_list.size();

The thread_list reference here is a std::vector.
None of the C++ library containers are signal-safe. Attempting to access them in a signal handler is undefined behavior. Your segmentation fault is the inevitable result. The bottom line is that the only thing that a signal handler can do safely is call a limited number of system calls. It can't even call malloc or new. This applies not just to SIGALRM, but to any signal.
The bottom line is none of what you're attempting to do in your signal handler can be done.
You indicated that you're using Linux. The signal-safety(7) Linux manual page lists the only system calls that you can make from your signal handler. If the system call is not on the list, it cannot be invoked from the signal handler. Note that there's nothing related to C++ on that list. Nothing in the C++ library is signal safe. That's it, end of story, full stop.
However, on Linux, there is a way to handle signals safely, in C++ code using signal file descriptors. Review the contents of that manual page, perhaps you can adapt your code to use signal file descriptors.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Load another HTML page to create an JavaScript array using .get and .each So I've banged my head on this all day. I'm updating the code.
I'm trying to pull an array based off of an HTML page (we'll call this switcher1.html) where there is a list.
Based on this array, the javascript will randomly load one item of the array onto the page where the javascript is called (we'll call this index.html).
//
// Random Profile

//

function randomProfile() {
var profilePages = [];

$.get( "/js/switcher1.html #featured-faculty", function() {
    $("ul li").each(function( index ) {
        profilePages.push($(this).text())
        });

    });

var randomPage = Math.floor(Math.random() * profilePages.length);
$('#featured-profile').load(profilePages[randomPage]);

}

// Run these functions as soon as this script is loaded,
// instead of waiting for the DOM to finish loading
randomProfile();

Hopefully you can see that the goal is to pull in a list from another source so I won't have to type it in to the JavaScript doc manually. My array is turning up blank no matter what I try.
FYI - I can use JQuery but not other code libraries. Also, I'm doing it this way due to a (slightly annoying & convoluted) CMS. The CMS can output an HTML list, so this is the best solution I was able to come up with.
Thanks in advance for your help!


text:
Q: Elasticsearch: aggregation min_doc_count for weeks doesn't work I've the following aggregation with interval=week and min_doc_count=0
{
  "aggs": {
    "scores_by_date": {
      "date_histogram": {
      "field": "date",
      "format": "yyyy-MM-dd",
      "interval": "week",
      "min_doc_count": 0
    }
  }
}

and date filter from Jan-01-2015 to Feb-23-2015
{
  "range": {
    "document.date": {
      "from": "2015-01-01",
      "to": "2015-02-23"
    }
  }
}

I expected Elasticsearch to fill seven weeks even if empty and return buckets but end up only with one item in it
{
  "aggregations": {
    "scores_by_date": {
      "buckets": [
        {
          "key_as_string": "2015-01-05",
          "key": 1420416000000,
          "doc_count": 5
        }
      ]
    }
  }
}

Elasticsearch version: 1.4.0
What is wrong with my aggregation or how can I say Elasticsearch to fill missing weeks?

A: You can try specifying extended bounds (there's documentation discussing this feature on the official doc page for histogram aggregations).  The most relevant nugget from those docs is this:

With extended_bounds setting, you now can "force" the histogram aggregation to start building buckets on a specific min values and also keep on building buckets up to a max value (even if there are no documents anymore). Using extended_bounds only makes sense when min_doc_count is 0 (the empty buckets will never be returned if min_doc_count is greater than 0).

So your aggregation may have to look something like this to force ES to return empty buckets in that range:
{
  "aggs": {
    "scores_by_date": {
      "date_histogram": {
      "field": "date",
      "format": "yyyy-MM-dd",
      "interval": "week",
      "min_doc_count": 0,
      "extended_bounds" : {
        "min" : "2015-01-01",
        "max" : "2015-02-23"
      }
    }
  }
}


text:
Q: MS ACCESS Counting Records from table based on multiple criteria I want a text box in Access to update with the number of records found where a manager has an "overdue" record in the table dependent on the manager selected in a combo box, I have the following code but am getting an error:
Private Sub Combo26_AfterUpdate()

Dim rs As DAO.Recordset

Set rs = CurrentDb.OpenRecordset("SELECT Advisor FROM tbltargets WHERE manager = '" & Me.Combo26.Column(0) & "' AND overdue = 'Overdue'")
If rs.EOF Then
Me.Text35 = 0
MsgBox "no overdue records", vbOKOnly
Else
rs.MoveLast
Me.Text35 = rs.RecordCount
rs.Close
End If

End Sub

When I select an option from the combo box it gives me an error "Too few parameters. Expected 1"...
I have similar code which works so am unsure why the above is resulting in an error, could anyone help?
Thank you,

A: Check like this
Private Sub Combo26_AfterUpdate()

Dim rs As DAO.Recordset

If IsNull(Combo26.value) Then Exit Sub

Set rs = CurrentDb.OpenRecordset("SELECT COUNT(*) AS CNT FROM tbltargets WHERE manager = '" & Combo26.value & "' AND overdue = 'Overdue'")

If Not rs.BOF Then

    If Nz(rs!CNT, 0) = 0 Then
        Me.Text35 = 0
        MsgBox "no overdue records", vbOKOnly
    Else
        Me.Text35 = rs!CNT
    End If
End If

End Sub

*

*Used combobox.value instead of combobox.column

*Changed the SQL to COUNT(*) and adapted the code accordingly to improve perfs.

*Added some protection against NULL values (you should really add an Error Handler in this sub)


text:
Q: Change google map icon with jQuery drop down menu So I have a google map with a number of different marker icons available for a user to select via a drop down menu:

  Select a Country

Item I

Item II

Item III

Right now, when the drop down menu is selected, it changes the text of the button via this bit of jquery:
$(window).load(function () {
            $("#location-type-menu li a").click(function () {
                $("#location-type-menu-button:first-child").text($(this).text());
                $("#location-type-menu-button:first-child").val($(this).text());
            });

        });

but I would also like it to instantly change the icon on the google map. The google map marker is created by, and is initially set as a question mark icon.
 var customIcons = {
            ItemI: {
                icon: 'http://...'
            },
            ItemII: {
                icon: 'http://...'
            },
            ItemIII: {
                icon: 'https:...'
            },
            question: {
                icon: 'https:...'
            }
};
var icon = customIcons['question'] || {};
var marker = new google.maps.Marker({
                position: location,
                icon: icon.icon,
                map: map,
                draggable: true
            });

As the icon variable is only called in when creating a new marker, I suspect changing the icon variable is not the way to do this.
I have tried a couple of different things, but have opted not to include them here as I don't think they are along the right path to a solution. I sincerely thank you for any help. It is greatly appreciated!

A: make sure your marker is defined in 'click' event, then you can just simply update the icon,
e.g.:
marker.setIcon(customIcons['ItemI'].icon);


text:
Q: lxml classic: Get text content except for that of nested tags? This must be an absolute classic, but I can't find the answer here. I'm parsing the following tag with lxml cssselect:

3 Detroit

I want to get the content of the
 tag without the content of the  tag.
Currently I have:
stop_list = doc.cssselect('ol#stations li a')
start = stop_list[0].text_content().strip()

But that gives me 3 Detroit. How can I just get Detroit?

A: For your example, I think going with XPath is cleaner and easier than CSS:
>>> xml = '
3 Detroit
'
>>> root = etree.fromstring(xml)
>>> print( root.xpath('/li/a/text()'))
[' Detroit']

>>> xml = '
I FooBar! love 3 Detroit
'
>>> root = etree.fromstring(xml)
>>> print( root.xpath('/li/a/text()'))
['I ', ' love ', ' Detroit']

>>> ' '.join([x.strip() for x in root.xpath('/li/a/text()')])
'I love Detroit'

A: itertext method of an element returns an iterator of node's text data. For your  tag, ' Detroit' would be the 2nd value returned by the iterator. If structure of your document always conforms to a known specification, you could skip specific text elements to get what you need.
from lxml import html

doc = html.fromstring("""
3 Detroit
""")
stop_nodes = doc.cssselect('li a')
stop_names = []
for start in stop_list:
    node_text = start.itertext()
    node_text.next() # Skip '3'
    stop_names.append(node_text.next().lstrip())
    continue

You can combine css selector with the xpath text() function mentioned in Zachary's answer like this (If you're more comfortable with using CSS selectors than xpath):
stop_names = [a.xpath('text()').lstrip() for a in doc.cssselect('li a')]


text:
Q: An array to assign even and odd numbers I was thinking of an array to find how to assign even and odd numbers in two successive arrays.
#include <stdio.h>
#include <math.h>

    int main()
    {
    int a[100],odd[100],even[100],i,j,n;
    for(i=0;i<=n;i++)
    {
    a[i]=0;
    odd[i]=0;
    even[i]=0;
    }
    printf("Enter the number of elements which you want to check as even or odd");
    scanf("%d",&n);
    for(i=0;i<n;i++)
    {
    if(a[i]%2==0)
    a[i]=even[i];
    else
    a[i]=odd[i];
    }
    for(i=0;i<n;i++)
    printf("The set of even numbers is %d"),even[i];
    for(i=0;i<n;i++)
    printf("The set of even numbers is %d"),odd[i];
    return 0;
    }

The program does not run. I can not spot the mistake right now. Can anyone spot the mistake? The compiler shows out
**Segmentation fault

...Program finished with exit co
de 139
Press ENTER to exit console.
**

A: I am try to point some mistakes of the code by using the comment .
And I think this code also has logical problem is that you want to put a list of numbers to odd-array and even-array,but the initial vaule of the even and odd array is all zero.
When you divide the list of number into tow array,you are not overwrite all of the initial value,that will cause there are some zero value be printed at last but they are not belong to odd neither even.
    #include <stdio.h>
    #include <math.h>

        int main()
        {
        int a[100],odd[100],even[100],i,j,n;
    //you should first assign a vaule to n and then use n
    //and be careful for the value of the n,
    //it should not larger than the size of the array,or it will overflow.
        for(i=0;i<=n;i++)
        {
        a[i]=0;
        odd[i]=0;
        even[i]=0;
        }
    //put below two lines to the front of the above for-loop
        printf("Enter the number of elements which you want to check as even or odd");
        scanf("%d",&n);
        for(i=0;i<n;i++)
        {
        if(a[i]%2==0)
        a[i]=even[i];
        else
        a[i]=odd[i];
        }
        for(i=0;i<n;i++)
    //you type a wrong 'printf' satement,here is the right way
    //printf("The set of even numbers is %d",even[i]);
        printf("The set of even numbers is %d"),even[i];
        for(i=0;i<n;i++)
        printf("The set of even numbers is %d"),odd[i];//you type a wrong 'printf' satement
        return 0;
        }


text:
Q: How to do alignment between objects in header with fancyhdr?

These two objects are in the header, but I can not align the line so that it is at the bottom of the box.
The line and an image, it has this degrade in the left part, is it possible to make a line with degrade in the latex?
Is it possible to create a makebox that is scaled according to the text and that is 1cm before and after the centralized text?
File "logo"
File "line"
\documentclass[12pt,a4paper]{article}

\usepackage{fancyhdr}

\fancyhf{}%

\pagestyle{fancy}

\thispagestyle{plain}

\fancypagestyle{plain}{

\fancyhead[C]{\vspace{3.cm}\includegraphics[width=14.5cm]{Logo/Line}}

\fancyhead[R]{\colorbox{gray}{\makebox[5.0cm]{\textbf{\textcolor{white}{RESEARCH ARTICLE}}}}}
\renewcommand{\headrulewidth}{0pt}
}

\title{\vspace{2cm}Zootherapy and rural livestock farmers in semiarid Patagonia: the transfer of animal aptitudes for health}

\date{}

\begin{document}
\maketitle

\end{document}

A: With TikZ and page style fancyplain:
\documentclass[12pt,a4paper]{article}
\usepackage{lipsum}% only for dummy text

\usepackage{tikz}
\usetikzlibrary{shadings}

\usepackage{fancyhdr}
\pagestyle{fancyplain}
\fancyhf{}

\fancyhead[C]{%
  \fancyplain
    {%
      \raisebox{-\dp\strutbox}{%
      \begin{tikzpicture}
        \node[anchor=south east,gray,fill,text=white,font=\bfseries,inner xsep=1cm,outer sep=0pt](n)at(\headwidth,0){RESEARCH ARTICLE};
        \useasboundingbox(0,0)--(n.south east);
        \shade[left color=white,right color=gray](0.3,0)rectangle([yshift=2pt]n.south west);
        \node[anchor=south west] at (0,0){\includegraphics[width=.33\textwidth]{logo}};
      \end{tikzpicture}%
      }%
  }
  {Header on pages with fancy style}% settings for page style fancy
}
\fancyfoot[C]{\thepage}% page number on both plain and fancy pages

\setlength\headheight{16.06573pt}

\title{\vspace{2cm}Zootherapy and rural livestock farmers in semiarid Patagonia: the transfer of animal aptitudes for health}
\author{}
\date{}

\begin{document}
\maketitle
\lipsum
\end{document}

Result:

A: You can do box placement.
\documentclass[12pt,a4paper]{article}
\usepackage{xcolor,graphicx}
\usepackage{fancyhdr}

\fancypagestyle{first}{%
  \fancyhf{}%
  \fancyhead[L]{\maketop}%
  \renewcommand{\headrulewidth}{0pt}%
}

\newcommand{\maketop}{%
  \leavevmode\smash{\makebox[\textwidth][l]{%
    \includegraphics[width=0.5\textwidth]{ethnologo}\hfill
    \makebox[0pt][r]{\includegraphics[width=0.6\textwidth]{ethnoline}}%
    \colorbox{gray}{\bfseries\textcolor{white}{RESEARCH ARTICLE}}%
  }}%
}

\setlength{\headheight}{14.5pt}

\title{Zootherapy and rural livestock farmers in semiarid Patagonia:
       the transfer of animal aptitudes for health}

\author{A. Uthor}

\date{}

\begin{document}

\maketitle\thispagestyle{first}

\end{document}


text:
Q: Surefire report plugin generates empty report I have one test, which I run from command line
mvn clean site

I see that the test completed successfully.
-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running smoketest.DummyTest
Configuring TestNG with: TestNG652Configurator
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.311 sec - in smoketest.DummyTest

Results :

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0

However the surefire-report.html shows all zeros. 0 tests, 0 skipped etc. I've probably broken something accidentially, as it used to work last week. Here're my build and reporting sections from pom.xml:
<build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.17</version>
                <configuration>
                    <properties>
                        <property>
                            <name>usedefaultlisteners</name>
                            <value>false</value>
                        </property>
                    </properties>
                    <includes>
                        <include>smoketest/DummyTest.java</include>
                    </includes>
                    <reportsDirectory>target/site/</reportsDirectory>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.2</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <reporting>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-project-info-reports-plugin</artifactId>
                <version>2.0</version>
            <configuration>
                <dependencyLocationEnabled>false</dependencyLocationEnabled>
            </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-report-plugin</artifactId>
                <version>2.18.1</version>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-site-plugin</artifactId>
                <version>3.4</version>
            </plugin>
        </plugins>
    </reporting>


text:
Q: Common File System Attributes on Linux, Mac and Windows I am looking for the some document/presentation which will give me an idea about different File and Directory attributes available on Windows, Mac and Linux file system. Also wanted to know Common attributes present across all three Operating systems. I want to cross verify my work.
Thanks,
Omky

A: First, you want to check the File system rather the OS, is mostly a File system feature, not OS, the Operative System can "support" or not all FS features.
On Linux and OSX, there is a UNIX standard, you have the common owner/group/other where a File contains a user owner (just a user) and a group owner (a group contains a list of users).
With that knowledge, you can set permissions like read/write/executable permissions for the owner of file, the group of file and a "non user non member of the group".
Example:
I have a file called hello.out and I want to restrict a "modification" for EVERY user, but my user only can execute it and every user can read it. I will set permission 544. the first value, 5 will provide read and execute to owner, the second value, 4 will provide only read to group, and the third value, another 4, will provide only read to any other user.
You have extended permissions on some UNIX file systems, on EXT2/3/4 and others, you can set permissions for a specific user (File system extended attributes). Also, you have some "flags" with special features, like provide a root execution with the SUID flag or force exclusivity of files on a directory to owner with the sticky flag.
More info about UNIX permissions here: http://en.wikipedia.org/wiki/File_system_permissions
On Windows instead, is hard to say, first, you have FAT16/32, there is no permissions with this File system. Using FAT16/32 on Linux can "emulate" a UNIX permission, but is global for all files and will not be stored on File system.
For File systems like NTFS, is pretty similar to UNIX, but you have a longer list of control for actions on the file or folder, but basically you have read/write/read and execute/list files/modify/full permission.
For more info, you can find every basic and special attributes here: http://technet.microsoft.com/en-us/library/bb727008.aspx


text:
Q: boost daytime7 server example doesn't respond to netcat client I am trying to get the daytime6 server example (Asynchronous UDP daytime  server) in boost working. I compile the below program using
g++ -std=c++11 -g -Wall -pedantic udp_server.cpp -o udp_server -lboost_system

I start the udp_server. I can see port number 13 (UDP) being opened using netstat command.
However If I trying to client to the server using netcat
nc -u localhost 13

it doesn't seem to give any reply.However I can get the asynchronous TCP daytime server to work fine.
#include <ctime>
#include <iostream>
#include <string>
#include <boost/array.hpp>
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/asio.hpp>

using boost::asio::ip::udp;

std::string make_daytime_string()
{
  using namespace std; // For time_t, time and ctime;
  time_t now = time(0);
  return ctime(&now);
}

class udp_server
{
public:
  udp_server(boost::asio::io_service& io_service)
    : socket_(io_service, udp::endpoint(udp::v4(), 13))
  {
    start_receive();
  }

private:
  void start_receive()
  {
    socket_.async_receive_from(
        boost::asio::buffer(recv_buffer_), remote_endpoint_,
        boost::bind(&udp_server::handle_receive, this,
          boost::asio::placeholders::error,
          boost::asio::placeholders::bytes_transferred));
  }

  void handle_receive(const boost::system::error_code& error,
      std::size_t /*bytes_transferred*/)
  {
    if (!error || error == boost::asio::error::message_size)
    {
      boost::shared_ptr<std::string> message(
          new std::string(make_daytime_string()));

      socket_.async_send_to(boost::asio::buffer(*message), remote_endpoint_,
          boost::bind(&udp_server::handle_send, this, message,
            boost::asio::placeholders::error,
            boost::asio::placeholders::bytes_transferred));

      start_receive();
    }
  }

  void handle_send(boost::shared_ptr<std::string> message,
      const boost::system::error_code& error,
      std::size_t bytes_transferred)
  {
  }

  udp::socket socket_;
  udp::endpoint remote_endpoint_;
  boost::array<char, 1> recv_buffer_;
};

int main()
{
  try
  {
    boost::asio::io_service io_service;
    udp_server server(io_service);
    io_service.run();
  }
  catch (std::exception& e)
  {
    std::cerr << e.what() << std::endl;
  }

  return 0;
}

A: The following command does not send a message:
$ nc -u localhost 13

Instead, netcat will wait, reading from stdin until end-of-file.  Upon receiving end-of-file, it will send the message it reads to localhost on port 13 using UDP.
On the other hand, the following command:
$ echo 'msg' | nc -u localhost 13

writes "msg" and end-of-file to netcat's stdin, resulting in netcat sending a UDP datagram containing "msg" to localhost on port 13.
The asynchronous UDP daytime server example responds to any message it receives with the current date and time:
class udp_server
{
public:
  udp_server(...)
  {
    start_receive();
  }

private:
  void start_receive()
  {
    socket_.async_receive_from(...,
        boost::bind(&udp_server::handle_receive, ...));
  }

  void handle_receive(...)
  {
    message = make_daytime_string();

    socket_.async_send_to(boost::asio::buffer(message), ...);
  }

};

As the first command does not write a message, the udp_server never receives a message to which it can respond.  The latter command causes a message to be written, and the udp_server responds with the date and time.
The asynchronous TCP daytime server writes a message upon accepting a connection, then closes the connection.  When using TCP, netcat will attempt to connect to the destination immediately.  In the case of the tcp_server, netcat will establish a TCP connection, receive the date and time, detect that the remote peer has closed the connection and exit.


text:
Q: Error creating bean with name 'entityManagerFactory' with @ notation and no xml files I know that this question has been answered many times on SO but in this case i preferred to use @ notation over actual xml files to configure a hibernate database.
firstly here the error message
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build EntityManagerFactory
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1553)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:973)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:750)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:120)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:683)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:313)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:944)
at web_application.Application.main(Application.java:79)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:53)
at java.lang.Thread.run(Thread.java:695)
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build EntityManagerFactory
    at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:915)
    at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:890)
    at org.hibernate.ejb.HibernatePersistence.createContainerEntityManagerFactory(HibernatePersistence.java:74)
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:336)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:318)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1612)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1549)
    ... 20 common frames omitted
Caused by: org.hibernate.MappingException: Could not determine type for: javax.persistence.Lob, at table: testruns, for columns: [org.hibernate.mapping.Column(result_files)]
    at org.hibernate.mapping.SimpleValue.getType(SimpleValue.java:305)
    at org.hibernate.mapping.SimpleValue.isValid(SimpleValue.java:289)
    at org.hibernate.mapping.Property.isValid(Property.java:238)
    at org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:469)
    at org.hibernate.mapping.RootClass.validate(RootClass.java:270)
    at org.hibernate.cfg.Configuration.validate(Configuration.java:1294)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1736)
    at org.hibernate.ejb.EntityManagerFactoryImpl.<init>(EntityManagerFactoryImpl.java:94)
    at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:905)
    ... 26 common frames omitted

Here is where i configure my hibernate setup
package web_application;

import java.io.IOException;
import java.util.Properties;

import org.apache.commons.dbcp.BasicDataSource;
import org.hibernate.cfg.Environment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@ComponentScan
@EnableTransactionManagement
@EnableAutoConfiguration
public class Application {

@Autowired
private static Environment env;

@Bean
public static PropertySourcesPlaceholderConfigurer propertyPlaceHolderConfigurer() {
    return new PropertySourcesPlaceholderConfigurer();
}

@Bean
public BasicDataSource dataSource() {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName(env.getProperties().getProperty(
            "jdbc.driverClassName"));
    dataSource.setUrl(env.getProperties().getProperty("jdbc.url"));
    dataSource.setUsername(env.getProperties().getProperty("jdbc.user"));
    dataSource.setPassword(env.getProperties().getProperty("jdbc.pass"));
    return dataSource;
}

@Bean
public LocalSessionFactoryBean sessionFactory() {
    LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
    sessionFactory.setDataSource(dataSource());
    sessionFactory.setPackagesToScan(new String[] { "web_application" });
    sessionFactory.setHibernateProperties(hibernateProperties());
    return sessionFactory;
}

@Bean
Properties hibernateProperties() {
    return new Properties() {
        {
            setProperty("hibernate.hbm2ddl.auto", env.getProperties()
                    .getProperty("hibernate.hbm2ddl.auto"));
            setProperty("hibernate.dialect", env.getProperties()
                    .getProperty("hibernate.dialect"));
            setProperty("hibernate.globally_quoted_identifiers", "true");
        }
    };
}

@Bean
public HibernateTransactionManager transactionManager() {
    HibernateTransactionManager txManager = new HibernateTransactionManager();
    txManager.setSessionFactory(sessionFactory().getObject());
    return txManager;
}

@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
    return new PersistenceExceptionTranslationPostProcessor();
}

public static void main(String[] args) throws IOException {
    Object[] sources = { Application.class, NightlySchedule.class };
    SpringApplication.run(sources, args);

}
}

This is where the Entity manager is actually being used
package web_application;

import java.sql.Timestamp;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Lob;

@Entity
@Table(name = "TESTRUNS")
public class RunEntity {
private int ID;
private int testNumber;
private String testName;
private String environment;
private String source;
private String passOrFail;
private Timestamp date;
private Lob resultFiles;

@Id
@Column(name = "ID")
@GeneratedValue
public int getID()
{
    return this.ID;
}
@Column(name="TestNumber")
public int getTestNumber()
{
    return this.testNumber;
}
public void setTestNumber(int testNum){this.testNumber = testNum;}

@Column(name="TestName")
public String testName()
{
    return this.testName;
}
public void setTestName(String testName){this.testName = testName;}

@Column(name="Environment")
public String getEnvironment()
{
    return this.environment;
}
public void setEnvironment(String enviro){this.environment = enviro;}

@Column(name="Source")
public String getSource()
{
    return this.source;
}
public void setSource(String src){this.source = src;}

@Column(name="PassOrFail")
public String getPassOrFail()
{
    return this.passOrFail;
}
public void setPassOrFail(String pOrF){this.passOrFail = pOrF;}

@Column(name="Date")
public Timestamp getDate()
{
    return this.date;
}
public void setDate(Timestamp dates){this.date = dates;}

@Column(name="ResultFiles")
public Lob getResultFiles()
{
    return this.resultFiles;
}
public void setResultFiles(Lob file){this.resultFiles = file;}

}

and here is my build.gradle file
buildscript {
repositories {
    maven { url "http://repo.spring.io/libs-release" }
    mavenLocal()
    mavenCentral()
}
dependencies {
    classpath("org.springframework.boot:spring-boot-gradle-plugin:1.1.3.RELEASE")

}
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'spring-boot'

ext.hibernateVersion='4.1.5.SP1'
ext.hibernateValidatorVersion='4.3.0.Final'

 jar {
baseName = 'gs-rest-service'
version =  '0.1.0'
}

repositories {
mavenLocal()
mavenCentral()
maven { url "http://repo.spring.io/libs-release" }
mavenRepo url: 'http://download.java.net/maven/glassfish/org/glassfish/'
mavenRepo url: 'https://repository.jboss.org/nexus/content/repositories/releases/'

}

dependencies {
compile("org.springframework.boot:spring-boot-starter")
compile("org.springframework.boot:spring-boot-starter-web")
compile("org.springframework.boot:spring-boot-starter-thymeleaf")
compile 'org.eclipse.jgit:org.eclipse.jgit:3.4.1.201406201815-r'
compile("org.springframework:spring-jdbc")
compile 'org.springframework:spring-orm:4.0.5.RELEASE'
compile("com.h2database:h2")

compile 'javax.servlet:javax.servlet-api:3.0.1'
compile "org.apache.commons:commons-lang3:3.1"
compile 'commons-dbcp:commons-dbcp:1.2.2'

compile 'cglib:cglib-nodep:2.2.2'
compile 'org.aspectj:aspectjrt:1.6.12'
compile 'org.aspectj:aspectjweaver:1.6.12'

compile "org.hibernate:hibernate-entitymanager:$hibernateVersion"
compile "org.hibernate:hibernate-core:$hibernateVersion"
compile "org.hibernate:hibernate-validator:$hibernateValidatorVersion"
compile "org.hibernate.javax.persistence:hibernate-jpa-2.0-api:1.0.1.Final"

testCompile("junit:junit")
}

task wrapper(type: Wrapper) {
gradleVersion = '1.11'
}


text:
Q: Add data by increasing mongodb id If the data has been added before and the id number is 1, I want the id number of the new data to be added to be 2. I want it to increase in order.
I want it to read the id number of the previous data in the mongodb database and increase it accordingly.
How can I do it?
I'm coding with python.


text:
Q: Get number of columns created by css column-width
Possible Duplicate:
How to get css3 multi-column count in Javascript

I have a long dynamic text which is going to be split into columns by using CSS
div
{
    -moz-column-width: 500px;
    -moz-column-gap: 20px;
}

Is it possible to get how many columns are created? I'm using jQuery in the client side.

A: Your questions and fiddle ignore vendor prefixes; larssin's answer is a good direction but isn't complete.
I created a small helper function for you, which goes over currently implemented prefixes for these values, fetches the actual values with .css() and returns the correct number. Works cross-browser, including non-supporting browsers which always return 1.
I chose to ignore the iframe case, which just makes things more complicated but as I understand isn't related directly to your question.
Update: Now accounts for border and padding.
Code on jsFiddle and here:
function getColumnsNumber(el){
    var $el = $(el),
        width = $el.innerWidth(),
        paddingLeft, paddingRight, columnWidth, columnGap, columnsNumber;

    paddingLeft = parseInt( $el.css('padding-left'), 10 );
    paddingRight = parseInt( $el.css('padding-right'), 10 );

    $.each(['-webkit-','-moz-',''], function(i, prefix){
        var _width = parseInt( $el.css(prefix+'column-width'), 10 );
        var _gap =   parseInt( $el.css(prefix+'column-gap'), 10 );
        if (!isNaN(_width)) columnWidth = _width;
        if (!isNaN(_gap))   columnGap = _gap;
    });

    columnsNumber = Math.floor( (width - paddingLeft - paddingRight) / (columnWidth + columnGap) );
    if (isNaN(columnsNumber) || columnsNumber < 1) columnsNumber = 1;
    return columnsNumber;
}

A: If the columns are in different elements you can get the number of children with $(selector).length (http://api.jquery.com/length/). Not sure if I understand your problem correctly, but hope it will help.
An example:

some text...

some text...

some text...

var columns = $('#myText').length;
    /* or */
var columns = $('.column').length;

Update:
Ok, I had a look at your jsfiddle example and thought that you can get the resulting width of the iframe with $('#test').width() and then calculate the number of columns:
var width = $('#test').width();
var columns = width/(columnWidth+columnsGap);


text:
Q: How to set the index in an array when filling in data? # the available data
y = array(rnorm(165))
origins = 130:157

# define a vector where result will be saved
x = array(0,c(length(origins),1))

# define the denominator for MASE
for (origin in origins){
  for (t in 2:origin){
  x[] = sum(abs(y[t]-yl[t-1]))
  }
}

Anyone who can help me set the index in "x[]" so that the corresponding cell in "x" could be filled by the calculation in y? In other words, I want to fill in all results in x rather than the last one only. Thank you very much.


text:
Q: MongoDB: Finding to words, then counting the coincidences I have a database of books that looks like this:
{"_id": ObjectID("1"), "title": "Harry Potter", "year": NumberInt(2000), "author": "JK. Rowling", "genres" : [fantasy, drama]},
{"_id": ObjectID("2"), "title": "Harry Potter 99", "year": NumberInt(2020), "author": "JK. Rowling", "genres" : [fantasy, drama]},
{"_id": ObjectID("3"), "title": "Book", "year": NumberInt(2020), "author": "Mr. Author", "genres" : [war, romance]},
{...}

I would like to get the books that have the combination of the genres "fantasy" and "drama", converting their titles to capital letter, counting them, and finally getting an average of their year of publishment. Something like this:
{
  "_id" : ["HARRY POTTER", "HARRY POTTER 99],
  "yearavg" : "2010",
  "count" : "2"
}

I can't get through the grouping, so I've wrote this so far, it is not working though:
query1 = {"genres" : "Fantasy"}
query2 = {"genres" : "Drama"}
logic = {$and : [query1, query2]}
phase1 = {$match : logic}
phase2 = {$group : {"_id" : "$title", "year" : "$year"}}
phase3 = {$project : {"total" : {"$size" : "$genres"}, "genres" : 1}}

steps = [phase1, phase2, phase3]
db.genres.aggregate(steps)

Thanks!

A: You can try,

*

*$match genres are in all ["fantasy", "drama"] array

*$group by null and make titles array after converting to upper case using $toUpper, get average year using $avg, get count using $sum
db.genres.aggregate([
  { $match: { genres: { $all: ["fantasy", "drama"] } } },
  {
    $group: {
      _id: null,
      titles: { $push: { $toUpper: "$title" } },
      yearavg: { $avg: "$year" },
      count: { $sum: 1 }
    }
  }
])

Playground


text:
Q: create database specific user in redshift We are trying to create a user in Amazon Redshift which should only access a specific database. We know how to assign user to specific schema, but I want use public schema.
Till now we tried following commands:
To create user:
create user tt password 'tttt';

To create group:
create group report_group with user tt;

To grant access of database
grant select on  DATABASE demo TO tt;

but its not allowing running select query and fails with

access denied to schema public

any suggestion in this.

A: You need the below two grants to the user or the group
GRANT USAGE ON SCHEMA public TO tt;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO tt;

A: GRANT SELECT, INSERT, UPDATE, DELETE
ON ALL TABLES IN SCHEMA public
TO GROUP report_group;

ALTER DEFAULT PRIVILEGES IN SCHEMA public
GRANT SELECT ON TABLES TO GROUP report_group;


text:
Q: Assign multiple values of the structure in C# Suppose I have the following structure in C#
public struct User
{
    public string name;
    public int ID;
    public bool isAlive;
}

and I want to assign all the values for this structure. The only way I know how to do this is through
User Bill;
Bill.ID = 1;
Bill.name = "Bill";
Bill.isAlive = false;

But is there a faster way to do this? Something like
User Bill = {
  ID : 1,
  name : "Bill",
  isAlive : false
};

A: Yes.
User bill = new User{
  ID = 1,
  name = "Bill",
  isAlive = false
};

A: Make a constructor for your struct :
public struct User
{
    public string name;
    public int ID;
    public bool isAlive;

    public User(string name, int ID, bool isAlive)
    {
        this.name = name;
        this.ID = ID;
        this.isAlive = isAlive;
    }
}

Then use it for initialization :
User bill = new User("Bill", 1, false);

A: Structs behave exactly like classes (just that they are a value type), so you could - for instance - use constructors and methods.

A: While @Somya's answer is correct and works, I tend not to use this construct. IMHO the correct way to do this is to create a constructor for User, that takes the needed parameters, then call new User (1, "Bill", false).
This could easily be considered a spleen.

A: Suppose you don't have that structure .. you can use anonymous type:
var Bill=new {
    ID=1,
    name="Bill",
    isAlive=false
};

var Gates=new {
    ID=2,
    name="Gates",
    isAlive=true
};

Note the remarks:

If two or more anonymous object initializers in an assembly specify a sequence of properties that are in the same order and that have the same names and types, the compiler treats the objects as instances of the same type. They share the same compiler-generated type information.

Structures are immutable, but an instances of anonymous type is read-only once it's assigned:

Anonymous types provide a convenient way to encapsulate a set of read-only properties into a single object without having to explicitly define a type first. The type name is generated by the compiler and is not available at the source code level. The type of each property is inferred by the compiler.

So you gained both of the benefits with anonymous types.


text:
Q: Admin Extension redirects to frontend 404 page after update from 1.9.0.1 to 1.9.2.0 After I updated my Magento Shop from 1.9.0.1 to 1.9.2.0 I have a problem with one extension. When I try to access the plugins backend pages (e.g. "Manage Pin" or "Manage Pin Order" I am always redirected to the frontends 404 page.
This is the plugins config.xml code:
<?xml version="1.0" encoding="UTF-8"?>

            2.0.2

<global>

    <blocks>
         <pin>
            <class>HN_Pin_Block</class>
         </pin>

     <adminhtml>
            <rewrite>
                <sales_order_grid>HN_Pin_Block_Adminhtml_Sales_Order_Grid</sales_order_grid>
            </rewrite>
     </adminhtml>

    </blocks>
    <helpers>
         <pin>
            <class>HN_Pin_Helper</class>
         </pin>
    </helpers>

    <models>
        <pin>
            <class>HN_Pin_Model</class>
            <resourceModel>pin_mysql4</resourceModel>
        </pin>
        <pin_mysql4>
            <class>HN_Pin_Model_Mysql4</class>
            <entities>
                <pin>

pin

                </pin>
                 <orderpin>

orderpin

                </orderpin>
                 <orderpin_status>

orderpin_status

                </orderpin_status>
                <ispinproduct>

ispinproduct

                </ispinproduct>
                <itempinbuy>

itempinbuy

                </itempinbuy>
                <orderpinbuy>

orderpinbuy

                </orderpinbuy>
            </entities>
        </pin_mysql4>
    </models>

    <resources>
        <pin_setup>
            <setup>
                <module>HN_Pin</module>
            </setup>
            <connection>
                <use>core_setup</use>
            </connection>
        </pin_setup>
        <pin_write>
            <connection>
                <use>core_write</use>
            </connection>
        </pin_write>
        <pin_read>
            <connection>
                <use>core_read</use>
            </connection>
        </pin_read>
    </resources>

 <template>
        <email>
           <pin_information_template>
               Game licenses information
               <file>pin_info.html</file>
               <type>html</type>
           </pin_information_template>

           <low_pinstock_template>
               PIN Low stock notification
               <file>pin_low_stock_notification.html</file>
               <type>html</type>
           </low_pinstock_template>
        </email>
    </template>
    <events>
      <customer_save_after>
      <observers>
                <pin_observer>
                    <class>pin/observer</class>
                    <method>customerGroupChangeListener</method>
                </pin_observer>
            </observers>
      </customer_save_after>

        <sales_order_item_save_commit_after>
            <observers>
                <pin_observer>
                    <class>pin/observer</class>
                    <method>savePinOrderItem</method>
                </pin_observer>
            </observers>
        </sales_order_item_save_commit_after>
        <sales_order_save_commit_after>
            <observers>
                <pin_observer>
                    <class>pin/observer</class>
                    <method>orderCommitListener</method>
                </pin_observer>
            </observers>
        </sales_order_save_commit_after>
     </events>
</global>

<frontend>
    <routers>
        <pin>
            <use>standard</use>
            <args>
                <module>HN_Pin</module>
                <frontName>pin</frontName>
            </args>
        </pin>

    </routers>
    <layout>
        <updates>
            <pin>
                <file>hn_pin.xml</file>
            </pin>
        </updates>
    </layout>
</frontend>

<admin>
    <routers>
        <adminhtml>
            <args>
                <modules>
                    <pin before="Mage_Adminhtml">HN_Pin_Adminhtml</pin>
                </modules>
            </args>
        </adminhtml>
    </routers>
</admin>
<adminhtml>
        <menu>
        <pin module="pin">
            <title>Pin management</title>
            <sort_order>171</sort_order>
            <children>
                <items module="pin">
                    <title>Manage PIN</title>
                    <sort_order>0</sort_order>
                    <action>pin/adminhtml_pin/index</action>
                </items>
                <order module="pin">
                    <title>Manage PIN Order</title>
                    <sort_order>0</sort_order>
                    <action>pin/adminhtml_order/index</action>
                </order>
                <pinproduct translate="title" module="catalog">
                        <title>Manage Pin Product</title>
                        <action>pin/adminhtml_pin/pinproduct/</action>
                    </pinproduct>
             </children>
        </pin>
    </menu>
        <layout>
        <updates>
            <pin>
                <file>hn_pin.xml</file>
            </pin>
        </updates>
    </layout>

     <acl>
        <resources>
             <all>
                <title>Allow Everything</title>
            </all>
            <admin>
                <children>
                    <system>
                        <children>
                            <config>
                                <children>
                                    <pin translate="title" module="pin">
                                        <title>Game license delivery Settings</title>
                                    </pin>
                                </children>
                            </config>
                        </children>
                        </system>
                </children>

            </admin>
        </resources>
    </acl>
</adminhtml>
<default>
    <pin>
        <general>
            <change_status>1</change_status>
            <email_sender>sales</email_sender>
            <qty_sync>1</qty_sync>
            <delivery_confirmed>0</delivery_confirmed>
            <low_stock_notification>1</low_stock_notification>
            <low_stock_number>10</low_stock_number>
            <show_pin_successpage>1</show_pin_successpage>
        </general>
    </pin>

</default>
<crontab>
    <jobs>
        <notification_low_pin>
            <schedule>
                <cron_expr>*/5 * * * *</cron_expr>
            </schedule>
            <run>
                <model>pin/observer::scheduledSend</model>
            </run>
        </notification_low_pin>
    </jobs>
</crontab>

I hope you can help me :x
Greetings


text:
Q: Keeping flow from screen resize for media queries, icon locations and font size I've got a couple of problems, Using media queries I change the position and font size for mobile/tablet and desktop, the problem is, if your changing the window size the font size and a couple of social icons are taken out of place.
So mobile 320, tablet 768, desktop 960-1280+ are the sizes I've designed for.
@media only screen and (max-width: 320px) {
    .footer-top ul.links li {
        font-size: 0.60em;
        }
        ul.home-social {
        width:73%;
        margin-left:auto;
    margin-right:auto;
    }
    }

This is the example of font change and social icon position, but if the window is resized by the user the icons are out of place. Any Idea's ? I just want it to flow well or is there no point?

A: First of all I just want to say one thing, that the sizes of phones, tablets, etc are all extremely relative. While you may have designed something for 320 and for 768 the varying sizes of all of the different phones and ALL of the different tablets is going to make it impossible to make a pixel-perfect design for each.
As far as the position of the elements and font sizes being affected by the user changing the size of the window and it being incorrect, you'll have to find a way to align them so that they work well within whatever size they are currently being viewed at. Instead of having text next to the icons and messing with trying to get both Alignment and Font-Size to work based on a lot of screen sizes, try breaking them out so that the icons and the text are on two different horizontal lines, possibly?


text:
Q: How to transfer Yoast SEO plugin data into advanced custom fields My current site used yoast plugin for show meta data. But i want to deactivate the plugin and I want to transfer all meta details in to Advanced custom fields. Any idea.

A: You can use WP All Export plugin to export whole your preferred data, then use WP All Import plugin to import as ACF fields.

URLs of plugins

https://wordpress.org/plugins/wp-all-export/
https://wordpress.org/plugins/wp-all-import/


text:
Q: Discord.js — How to read all users in a voice channel and send a private message to each of them containing a random role I want to make a Wolves/Mafia-esque game on my server. When I write the command !role 1wolf 2villagers, I would like to randomly distribute the specified roles by private message (so 1 person receives the wolf role and 2 people receive the villager role) to all the people in a specified voice channel.
The roles are not literal guild roles but simply a message.

A: You can do it easily:
client.on('message', (message) => {
    if(message.content.startsWith('!role')){
        let channelID = 'your voice channel id';
        message.guild.channels.get(channelID).members.forEach((member) => {
            member.send('Your role is villager!');
        });
    }
});

It will get the voice channels, and for each member, send a message to them.


text:
Q: How to sort a list of lists by an item of the sublist that is a float I'm trying to sort a list of lists by 1 item that is a float.
Problem is, using sort(list, itemgetter(n)) sorts the floats as strings and the output is not what i expect.
list1 = [('1','1',"9999"),('1','1',"9998"),('1','1',"9998.777"),('1','1',"9995111"),('1','1',"110000")]

list2 = sorted(list2, key=itemgetter(2))

print(list2)

actual result :
[('1', '1', '110000'), ('1', '1', '9995111'), ('1', '1', '9998'), ('1', '1', '9998.777'), ('1', '1', '9999')]

Expected result :
[('1', '1', '9998'), ('1', '1', '9998.777'), ('1', '1', '9999'),('1', '1', '110000'),('1', '1', '9995111')]

A: It sorts them as strings because they are strings. itemgetter just returns x[2], as it is. What you want is a function that takes a x and returns float(x[2]). So, just use key= lambda x: float(x[2])

A: If you want to make the float conversion, you can map a function on it:
list2 = list(map(lambda x: (x[0], x[1], float(x[2])), list1))

Then your line list2 = sorted(list1, key=itemgetter(2)) will work as expected.
Otherwise, you can use sorted(list1, key=lambda x: float(x[2])) as Rakesh mentioned in the comments, to sort by 2nd element casting float type on it.


text:
Q: Atom linter-lintr cannot find lintr I am using Atom for writing R code, and attempting to use lintr, but linter-lintr cannot find it. R is on my $PATH and lintr is installed in R.
Whenever I type, the following error happens.
/Users/bfh/.atom/packages/linter/lib/linter-registry.js:159 [Linter] Error running lintr Error: Error in library(lintr) : there is no package called 'lintr'
Calls: suppressPackageStartupMessages -> withCallingHandlers -> library
Execution halted
    at ChildProcess.<anonymous> (/Users/bfh/.atom/packages/linter-lintr/node_modules/sb-exec/lib/index.js:56:20)
    at emitTwo (events.js:106:13)
    at ChildProcess.emit (events.js:191:7)
    at maybeClose (internal/child_process.js:877:16)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:226:5)(anonymous function) @ /Users/bfh/.atom/packages/linter/lib/linter-registry.js:159

I have tried uninstalling and reinstalling linter, linter-lintr, linter-minimap, and the relevant R packages. This setup is working fine on another computer.

A: Start an R session in terminal or iterm2
$ R
and type:
install.packages("lintr")
https://atom.io/packages/linter-lintr


text:
Q: Does Apple StoreKit2 client APIs are susceptible to wrong device clock or jailbreak? I am migrating my subscription logic to new StoreKit2 APIs and I am using APIs below. These APIs provides verified transactions and subscription states.
However, I am worried about validity of these APIs because they are clients-side code. I cannot find any text which mentions about this topic.
Should I trust the .verified state of transactions?
Should I trust Product.SubscriptionInfo.RenewalState of subscriptions? Can modified device clock affect RenewalState?
Or Should I ignore RenewalState and .verified state of transactions and send jws data to my server and validate there?
Product.SubscriptionInfo.Status.updates
Transaction.currentEntitlements
Product.SubscriptionInfo.status


text:
Q: %ERRORLEVEL% is not working incase multiple commands on a Single line I am trying the below commands and want to get exit of my process(%ERRORLEVEL%). But it is  returning previous(last) executed exit code result of sample.exe. I want to get exit code of current command. My requirement is to execute multiple commands in single line*(not batch script)*.
Command:
cmd /c sample.bat "test" > c:\ouput.log & echo %ERRORLEVEL% > c:\returnCode.log

I even tried using "setlocal enableDelayedExpansion" like below. Still It is not returning the exit code of current command
cmd /c setlocal enableDelayedExpansion & sample.bat "test" > c:\ouput.log & echo %ERRORLEVEL% > c:\returnCode.log

Please let me know the way to get current command's exit code.

A: This should work:
cmd /V:ON /c sample.exe "test" > c:\ouput.log ^& echo !ERRORLEVEL! ^> c:\returnCode.log

/V:ON switch have the same effect of setlocal EnableDelayedExpansion. For further details, type: cmd /?
EDIT: Small error fixed, the & character must be escaped with ^, otherwise, the echo !ERRORLEVEL! command is not executed in the cmd /V:ON !!!
EDIT: Escaping the echo redirection via ^> causes just that echo to be piped into the log.  If you do not escape that, the entire command is piped there, i.e. including the stdout stream from "sample.exe".

A: cmd /c sample.exe "test" > c:\ouput.log & call echo %%ERRORLEVEL%% > c:\returnCode.log

Should work for you. See endless SO items related to delayedexpansion

A: Thank for your response. I am able to get the exit code of current executed command with below command, only when I run through WMI class(Win32_Process). Using WMI client, I am executing the below command on Remote machine and it is working fine i.e. able to write exit code in Retrun.txt
Command:
cmd /V:ON /c sample.bat "test" > c:\Output.txt & echo !ERRORLEVEL! > c:\Return.txt
But if I run the same command in command prompt of the same remote machine, it is printing "!ERRORLVEL!" in Return.txt instead of "sample.bat" exit code.
I am curious to know why it is not working if I run from Command prompt of the same machine locally.


text:
Q: No checkbox in wordpress posts list table for CPT I have added a Custom Post Type as follows
add_action( 'init', 'codex_book_init' );
function codex_book_init() {
$args = array(
    'description'        => __( 'Description.', 'your-plugin-textdomain' ),
    'public'             => true,
    'publicly_queryable' => true,
    'show_ui'            => true,
    'show_in_menu'       => true,
    'query_var'          => true,
    'rewrite'            => array( 'slug' => 'book' ),
    'capability_type'    => 'post',
    'capabilities' => array(
            'edit_published_posts' => 'do_not_allow' ), //No permission to edit published post, but have permission to delete post
    'has_archive'        => true,
    'hierarchical'       => false,
    'menu_position'      => null,
    'supports'           => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments' )
);

register_post_type( 'book', $args );
}

Now when a book post type post is added and published, there is no checkbox in post list table to select multiple post at once. I do not have permission to edit but have permission to delete. So i should have checkbox to select multiple posts and delete.
in Wp_Posts_List_Table method which outputs checkbox
public function column_cb( $post ) {
    if ( current_user_can( 'edit_post', $post->ID ) ): ?>
        <label class="screen-reader-text" for="cb-select-<?php the_ID(); ?>"><?php
            printf( __( 'Select %s' ), _draft_or_post_title() );
        ?>
        <input id="cb-select-<?php the_ID(); ?>" type="checkbox" name="post[]" value="<?php the_ID(); ?>" />

    <?php endif;
}

So users must have 'edit_post' capability to get that checkbox, but why? how to overcome this?


text:
Q: Issue with rake gem:install I am using

Rails 2.3.5, Ruby 1.8.7

I am getting the follow error after running the following command. Any ideas?
$ rake gem:install

$ rake/rdoctask is deprecated.  Use rdoc/task instead (in RDoc 2.4.2+)
$ rake aborted!

$ rake gem:install --trace

rake/rdoctask is deprecated.  Use rdoc/task instead (in RDoc 2.4.2+)
rake aborted!
uninitialized constant ActiveSupport::Dependencies::Mutex
/Library/Ruby/Gems/1.8/gems/rake-0.9.2/lib/rake/ext/module.rb:36:in `const_missing'
/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:55
/Library/Ruby/Site/1.8/rubygems/custom_require.rb:36:in `gem_original_require'
/Library/Ruby/Site/1.8/rubygems/custom_require.rb:36:in `require'
/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/active_support.rb:56
/Library/Ruby/Site/1.8/rubygems/custom_require.rb:36:in `gem_original_require'
/Library/Ruby/Site/1.8/rubygems/custom_require.rb:36:in `require'
/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/gems/1.8/gems/rails-2.3.5/lib/tasks/misc.rake:18
/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/gems/1.8/gems/rails-2.3.5/lib/tasks/rails.rb:4:in `load'
/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/gems/1.8/gems/rails-2.3.5/lib/tasks/rails.rb:4
/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/gems/1.8/gems/rails-2.3.5/lib/tasks/rails.rb:4:in `each'
/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/gems/1.8/gems/rails-2.3.5/lib/tasks/rails.rb:4
/Library/Ruby/Site/1.8/rubygems/custom_require.rb:36:in `gem_original_require'
/Library/Ruby/Site/1.8/rubygems/custom_require.rb:36:in `require'
/Users/P/Dev/loginform/unobtrusive-login/Rakefile:10
/Library/Ruby/Gems/1.8/gems/rake-0.9.2/lib/rake/rake_module.rb:25:in `load'
/Library/Ruby/Gems/1.8/gems/rake-0.9.2/lib/rake/rake_module.rb:25:in `load_rakefile'
/Library/Ruby/Gems/1.8/gems/rake-0.9.2/lib/rake/application.rb:495:in `raw_load_rakefile'
/Library/Ruby/Gems/1.8/gems/rake-0.9.2/lib/rake/application.rb:78:in `load_rakefile'
/Library/Ruby/Gems/1.8/gems/rake-0.9.2/lib/rake/application.rb:129:in `standard_exception_handling'
/Library/Ruby/Gems/1.8/gems/rake-0.9.2/lib/rake/application.rb:77:in `load_rakefile'
/Library/Ruby/Gems/1.8/gems/rake-0.9.2/lib/rake/application.rb:61:in `run'
/Library/Ruby/Gems/1.8/gems/rake-0.9.2/lib/rake/application.rb:129:in `standard_exception_handling'
/Library/Ruby/Gems/1.8/gems/rake-0.9.2/lib/rake/application.rb:59:in `run'
/Library/Ruby/Gems/1.8/gems/rake-0.9.2/bin/rake:32
/usr/bin/rake:19:in `load'
/usr/bin/rake:19

A: Look at the first lines in your Rakefile. Change:
require 'rake/rdoctask'

To:
require 'rdoc/task'

Edit:
It looks like you have a Rubygems incompatibility issue, like James suspects. You need to upgrade your Rails version, or downgrade your gem version.
You can change to any gem version with:
gem update --system x.y.z

See more about your problem with
uninitialized constant ActiveSupport::Dependencies::Mutex

Here:
Uninitialized constant ActiveSupport::Dependencies::Mutex (NameError)

A: I am using Ruby 1.8.7 and Rails 2.3.8 and getting the very same error. So I changed my RubyGems version to 1.5.3 and the issue solved. So what you need to do is to write this command:
"gem update --system 1.5.3"
It will update your ruby gems version to 1.5.3 which is fully working with rails 2.3.8.
Hope it helps.

A: Which version of rubygems do you have? To use 2.3.5 you might need to use rubygems that <= 1.4 and rake 0.8.7.


text:
Q: SVN - merging/killing a branch Within our repository we have a trunk that contains our app, a branch for "phase 2" features added on top of the app and then a branch of this branch with some single-sign-on functionality added into the app.
trunk/application
branches/application_phase_2
branches/application_phase_2_with_sso

No work has taken place in the trunk and any updates to application_phase_2 have been merged-up to application_phase_2_with_sso.
The application_phase_2 branch work is now complete and live, but application_phase_2_with_sso branch work is not finished yet.
I've succesfully merged application_phase_2 back into the trunk, but wanted to kill (delete) this branch to stop others in the team from checking in any further work into it.
Will SVN allow me do this given the application_phase_2_with_sso branch?
If I can is there any impact on the application_phase_2_with_sso branch if I kill the branch it was taken from - once work is completed here can I merge this back to trunk directly?

A:
Will SVN allow me do this given the application_phase_2_with_sso branch?

Yes

is there any impact on the application_phase_2_with_sso branch if I kill the branch it was taken from

No. In any case you delete only in "current" state, history doens't affected, stored in repo and can can used, when needed (and, and last, due to ",...any updates to application_phase_2 have been merged-up to application_phase_2_with_sso" application_phase_2_with_sso content is equal to "will be deleted" branch and will want nothing from parent)


text:
Q: Power BI calculated columns depending on each other I have to recreate the formula from Excel in Power BI.
What I try to achieve:
Excel Example Img
Excel Formulas Img
Every row of the column RAND contains calculation (RAND() in this case) plus a value from the previous period.
When I want to make such calculation in Power BI I receive a Circular Dependency Error.
Here is how I calculate columns in 'Bucket Calendar' table:
Col1 = Rand() * 100 + [Col2]
Col2 = CALCULATE(SUM([Col1]), FILTER(ALL('Bucket Calendar'), [Date] = EARLIER([PreviousDate])))

It cannot be done in Power Query because calculation I'll use instead of Rand() comes from other tables
Please help me to solve this.


text:
Q: controlling column widths for side by side base graphic and ggplot2 graphic @Ricardo Saporta has proposed here an easy way to combine base graphics and ggplot graphics in a multiple plots figure.
I use this way to plot a base graphic at left and a ggplot graphic at right which actually contains two graphics (this is an artifical example, not a real one, but it has the same structure as my real example) :
library(ggplot2)
library(gridExtra)
library(plotrix)

Mvalues <- matrix(rpois(9,1), ncol=3)
Mcolors <- matrix(rpois(9,5), ncol=3)

par(mfrow=c(1,2))
color2D.matplot(x=Mvalues, show.values=2, cellcolors=Mcolors,
    xlab="x", ylab="y", axes=FALSE, vcex=0.4)
gg2 <- ggplot(diamonds, aes(clarity, fill=cut)) + geom_bar(position="dodge")
ta <- do.call(arrangeGrob, list(gg2,gg2))
vp.Left <- viewport(height=unit(1, "npc"), width=unit(0.5, "npc"),
    just="left", y=0.5, x=0.5)
print(ta, vp=vp.Left)

Very nice. But now I want the base graphic to have a larger width than the ggplot graphics. How to do ? I have unsuccessfully tried to do so with the layout() function.

A: Here you go:
Use layout with different widths. Notice how I define the first column to be double the width of column 2:
layout(matrix(c(1, 2, 1, 3), ncol=2, byrow=TRUE), widths=c(2, 1))

Set up the graphics
layout(matrix(c(1, 2, 1, 3), ncol=2, byrow=TRUE), widths=c(2, 1))
color2D.matplot(x=Mvalues, show.values=2, cellcolors=Mcolors,
                                xlab="x", ylab="y", axes=FALSE, vcex=0.4)
gg2 <- ggplot(diamonds, aes(clarity, fill=cut)) + geom_bar(position="dodge")
ta <- do.call(arrangeGrob, list(gg2,gg2))

Now define the viewport. Your code was almost there. I simply modified it to be right justified, and changed the width to be 33%:
vp <- viewport(height=unit(1, "npc"), width=unit(0.33, "npc"),
               just="right", x=1, y=0.5)

Finally, print the remaining graphic:
print(ta, vp=vp)


text:
Q: Combine 2 lists with condition in PowerShell? $computerips = 'IP 1','IP 1','IP 3','IP 4'
$computername = "IP 1 NAME","IP 2 NAME","IP 3 NAME","IP 3 NAME"

For ($i=0; $i -lt $computerips.count; $i++) {
    $computerips[$i]+$computername[$i]
}

Lets assume that $computerips is a list of ip addresses and $computername is a list of ip address aliases / names.
How to include condition if else (Test-Connection) to above code based on true or false and use only name of ip address with status OK or NOK?
i.e I need to have something like this:
foreach ($computer in $computerips) {
    if (Test-Connection -ComputerName $computer -Count 3 -EA SilentlyContinue) {
        Write-Host $computername "Online"
    }
    else {
        Write-Host $computername "Offline"
    }
}

I need to somehow match name to IP before send it to output. Any help appreciate.

A: $computerips = '10.10.10.0','10.10.10.1','10.10.10.2'
$computername = "10.10.10.0 Server1","10.10.10.1 Server2","10.10.10.2 Server3"
foreach ($computer in $computerips) {
    if (Test-Connection -ComputerName $computer -Count 3 -EA SilentlyContinue) {
        write-host "$((($computername -match $computer).replace($computer,'')).trim()) Online"
    }
    else {
        write-host "$((($computername -match '$computer').replace('$computer','')).trim()) Offline"
    }
}

Output
Server1 Online
Server2 Offline
Server3 Online


text:
Q: How to trigger setOnClickListener on second consecutive press of the same button so I have this setOnClickListener in my MainActivity.kt and I was wondering how I could upgrade it to set an integer in my code to 1 when the button is pressed two consecutive times
this is my setOnClickListener right now:
        reset.setOnClickListener{
            sum = 1

            Toast.makeText(applicationContext,"enter the number again",Toast.LENGTH_LONG).show()
            stevec.getText().clear()

            sumText.setText("" + sum)
        }

A: var i =0

reset.setOnClickListener{

if(i=0){
i=1
}
else{

            sum = 1

            Toast.makeText(applicationContext,"enter the number again",Toast.LENGTH_LONG).show()
            stevec.getText().clear()

            sumText.setText("" + sum)

i=0

}
        }

There are multiple ways to achieve this.

A: why don't you use a  counter to keep track of your click?. Something like this
var counter= 0
reset.setOnClickListener{
counter +=1
if(counter==2){
// do your work
counter=0
}

}
Now set the initial counter to 0 in case of the press of any other button.. you can also use a boolean in the form var hasResetBeenClickedOnce=false. The logic is the same
otherbutton.setOnClickListener{
counter=0
}


text:
Q: 'Unknown database error' in MySQL after reinstalling So after having some issues with MySQL's connection I decided to re-install it. I re-installed the entirety of MySQL 8.0 with the only difference being that I changed the authentication method (reason why I had to reinstall) and also in the process I gave my root a password.
Now when I log into PhpMyAdmin it for some odd reason allows me to log in with my old credentials (root + no password) and says the new password I chose is incorrect. And on top of that, I tried running a PHP script to connect to a pre-existing database in phpmyadmin and it gave me the following error:

Warning: mysqli_connect(): (HY000/1049): Unknown database 'forum-tutorial' in C:\wamp64\www\forum-tutorial\dbconn.php on line 6

So do I just have two phpmyadmin accounts now? How do I change to the new one? And how do I keep my database that I was using? I'm running WAMP server and they both appear to be using the port 3308 if that helps.
Edit: This is the PHP for the login script I made:
<?php
    $host = 'localhost';
    $username = 'root';
    $password = 'secret';
    $dbname = 'forum-tutorial';
    $con = mysqli_connect($host, $username, $password, $dbname)
?>


text:
Q: Unable to upload files to s3 via aws console. What can I check to find out the cause? I have gone through all the steps and got to the last page.

However the 'upload' button is disabled.
I have checked the browser console and there is no error message. So it is unlikely a front end issue.
Why the upload button is disabled? Is it due to the number of files and/or total size?

A: It could well be the number or total size, the web interface is more suited for a smaller jobs. I suggest you use a dedicated client tool to do that instead:

*

*If on Linux try aws-cli or s3cmd

*On Windows try for example S3 Browser
There are plenty of tools around.


text:
Q: kubernetes persistent volume cannot be created "the server could not find the requested resource" When I try to create an nfs-based persistent volume in our local kubernetes cluster, I get the following error:
# kubectl create -f nfs.yaml
error: error validating "nfs.yaml": error validating data: the server could not find the requested resource; if you choose to ignore these errors, turn validation off with --validate=false

The nfs.yaml has the following content:
apiVersion: v1
kind: PersistentVolume
metadata:
  name: pv-nfs-pv1
  labels:
    type: nfs
spec:
  capacity:
    storage: 1Gi
  accessModes:
    - ReadWriteMany
  nfs:
    server: 192.168.1.3
    path: "/srv/kubedata/"

The kubernetes cluster runs on three virtual machines created in our local openstack cloud (installed with kubespray). The nfs share is on the first node, and could be mounted manually on all nodes.
How can I fix this problem? Is the problem in the yaml file? How can I diagnose the problem? It would be very helpful to know where exactly the error is: is there a debug mode for kubectl?
Update: The original yaml I posted was corrupt, but that was because the stack overflow quote algorithm ate some newlines. I fixed that, now the posted yaml seems to validate on https://kubeyaml.com/, so the yaml seems to be okay (syntax-wise, at least).
Update2:
# kubectl version
Client Version: version.Info{Major:"1", Minor:"6", GitVersion:"v1.6.0", GitCommit:"fff5156092b56e6bd60fff75aad4dc9de6b6ef37", GitTreeState:"clean", BuildDate:"2017-03-28T16:36:33Z", GoVersion:"go1.7.5", Compiler:"gc", Platform:"linux/amd64"}
Server Version: version.Info{Major:"1", Minor:"15", GitVersion:"v1.15.3", GitCommit:"2d3c76f9091b6bec110a5e63777c332469e0cba2", GitTreeState:"clean", BuildDate:"2019-08-19T11:05:50Z", GoVersion:"go1.12.9", Compiler:"gc", Platform:"linux/amd64"}

A: This error means that your yaml file has an error. The easiest way to find it would be to just use one of the online validation tools. In your example there is an error at line 1. Your file should look like that:
apiVersion: v1
kind: PersistentVolume
metadata:
  labels:
    type: nfs
  name: pv-nfs-pv1
spec:
  accessModes:
    - ReadWriteMany
  capacity:
    storage: 1Gi
  nfs:
    path: /srv/kubedata
    server: 192.168.1.3

Please let me know if that helped.
EDIT:
However, a valid yaml does not mean that it has a valid input for Kubernetes.
In order to further investigate you need to upgrade your kubectl version.
After upgrading to version 1.15 you will be able to get a detailed error message showing you the exact line(s) with the validation problem instead of just: the server could not find the requested resource;
In short:

*

*upgrade kubectl to 1.15

*run the command again

*see which lines cause the problem

*correct the lines and run the command again


text:
Q: longitud de un json en angularjs Existe en angular 1.6 alguna funcion para saber el numero de registros que trae el json, lo quiero saber desde mi controlador, he utilizado
$scope.count = Object.keys($scope.data).length; pero me arroja 2, cuando mi json trae 8 registros, también utilice $scope.count=$scope.data.length; y me da 0.
$scope.tecnicos = TecnicoResource.query();

$scope.count = Object.keys($scope.tecnicos).length;
console.log($scope.count);
JSON
{
  "id_usuario": 5,
  "nombre": "Oscar Javier",
  "puesto": "Personal de soporte técnico",
  "perfil_id": 6,
  "empresa_id": 1,
  "nombre_usuario": "ovivas",
  "correo": "ovivas@gmail.com",
  "activo": 1,
  "deleted_at": null,
  "created_at": "2016-07-26 17:50:38",
  "updated_at": "2016-10-05 22:12:51",
  "carga_trabajo": 0
}

A: Recuerda que los objetos JSON solo son una colección de atributos, y por lo tanto, si quieres ver la longitud de un objeto como éste:
{
  "id_usuario": 5,
  "nombre": "Oscar Javier",
  "puesto": "Personal de soporte técnico",
  "perfil_id": 6,
  "empresa_id": 1,
  "nombre_usuario": "ovivas",
  "correo": "ovivas@gmail.com",
  "activo": 1,
  "deleted_at": null,
  "created_at": "2016-07-26 17:50:38",
  "updated_at": "2016-10-05 22:12:51",
  "carga_trabajo": 0
}

La longitud sera 0, sin embargo si quieres tener un array de objetos JSON, debería ser algo como esto:
tecnicos = [
    {
       nombre: Jose,
       apellido: Perez,
       edad: 18
    },
    {
       nombre: Carlos,
       apellido: Garcia,
       edad: 14
    },
    {
       nombre: Maria,
       apellido: Martinez,
       edad: 22
    }
]

Luego podrás hacer tecnicos.length sin problema.
Sin embargo, en el modo que tú estás declarando el JSON está mal, porque al tener comillas los nombres de atributos, el objeto deja de tener claves, por lo tanto deja de ser un objeto porque no tiene el formato (key, value) que maneja todo objeto.
Prueba quitándole las comillas así:
 $scope.tecnicos = {
      id_usuario: 5,
      nombre: "Oscar Javier",
      puesto: "Personal de soporte técnico",
      perfil_id: 6,
      empresa_id: 1,
      nombre_usuario: "ovivas",
      correo: "ovivas@gmail.com",
      activo: 1,
      deleted_at: null,
      created_at: "2016-07-26 17:50:38",
      updated_at: "2016-10-05 22:12:51",
      carga_trabajo: 0
    }

En teoría, al corregir esto, deberías poder hacer sin problemas esto:
Object.keys($scope.tecnicos)

Y te retornaría un arreglo con todas las claves del objeto:
['id_usuario', 'nombre', 'puesto', 'perfil_id', 'empresa_id', 'nombre_usuario', 'correo', 'activo', 'deleted_at', 'created_at', 'updated_at', 'carga_trabajo']

Y si a eso le haces .length:
$scope.count = Object.keys($scope.tecnicos).length;
console.log($scope.count); // console: 12

El resultado es 12


text:
Q: Aviso de confirmação Estou em um projeto em ASP.NET e entrei em uma situação em que precisa de um aviso para um botão.
Este botão excluía o arquivo, mas sem nenhum tipo de confirmação e no caso de clicar sem querer teria o seu arquivo deletado.
E então queria saber como que posso colocar um aviso do tipo: 'Deseja realmente excluir?' e esperar a confirmação do OK para excluir ou então um modo de Cancelar a ação.
Em algumas pesquisas consegui a resposta que mandei abaixo que no meu caso serve, mas teria alguma outra forma sem usar javascript?

A: Como descrito na pergunta, em algumas pesquisas, consegui resolver apenas usando js dentro da minha aplicação mesmo sendo em asp.net.
Uma maneira bem simples foi colocar o OnClientClick no próprio botão e fazer toda essa validação e após isso ele faz o OnCommand.
<asp:LinkButton runat="server" ID="exclr" OnClientClick="return confirm('Deseja realmente excluir?');" Text="Excluir" OnCommand="exclr_Command"/>


text:
Q: Excel Spreadsheet - One to Many matching excercise Basically from the picture linked here, what I'm trying to do is to look for a formula that can compare the value of the second row, with the values of the first column. If it finds that, for example, the first cell has the letter "A" in it then that row cell for A would get a yes, otherwise it would remain blank
Is this possible in excel?

A: Use ISNUMBER() & SEARCH() within an IF()

• Formula used in cell B3
=IF(ISNUMBER(SEARCH(B$2,$A3)),"Yes","")

Fill Down & Fill Right!!!

You can also use the formula as shown below, and showing the cells as Yes using a custom formatting though it will be a façade, still.

• Formula used in cell B3
=--ISNUMBER(SEARCH(B$2,$A3))

And Fill down & fill right, next select all the cells, where you applied the formula, Press CTRL + 1 to open Format Cells Dialogue, Number Tab, Category will be Custom and type by removing the General,
[=1]"Yes";;

So the above Custom Formatting turns the cells which returns 1 to Yes while the 0's as blank.

A: XMATCH() also can be considered with wild card character matching mode..
=IFNA(XMATCH("*"&B$2&"*",$A3,2),"")


text:
Q: Eclipse folder Referenced Libraries disappears In Java projects in Eclipse version 3.4.1 sometimes the folder "Referenced Libraries" disappears from the "Project Explorer" view. All third party jars are shown directly in the root of the project folder. The project compiles and runs fine. It seems to be a GUI problem.
How can I get this folder back?

A: First, bring up the "Package Explorer" view (instead of the "Project Explorer" view).
Then, if the referenced .jar files still are visible in the root of the project, click on the little "down arrow" icon in the top-right corner of the Package Explorer view. In the context menu that appears, one of the items on the menu is "Show 'Referenced Libraries' Node."  Click on that menu item.

A: I've been struggling with this thing for a while in Eclipse Juno because it's a little bit different.

*

*click the little down arrow as before

*click Customize view

*check Libraries from external

A: For those hitting the issue today (Kepler): it is possible that you are in the "Java EE" perspective, which by default has the Project Explorer. Simply switch to the "Java" perspective and it will replace Project Explorer with Package Explorer, which will have the missing Referenced Libraries folder.

A: Make sure you're actually in Project Explorer and not in some other view like Navigator, like my friend was...

A: Use the Package Explorer view instead of the Project Explorer view.


text:
Q: rails sql does not store value in object for this habtm relation b/w listings and categories, listings has to be filtered through two select box populated from the same category model, displaying listings belonging to either or both of the categories.
sql is returning correct listings when checked in the dbconsole but not in the application.
category controller
def index
  @categories = Category.all
end

def show
  @category = Category.find_by_sql ["select place from listings l , categories c, categories_listings cl where c.id = cl.category_id and l.id = cl.listing_id and name in (?,?)" ,  params[:name][:id] , params[:name][:id]]
end

category index page
<%= form_for :categories, :url => {:action => :show}, :method => "get" do |f| %>

    <%= f.label :category %>

    <%= collection_select(:name, :id, Category.all, :id, :name) %>

    <%= f.label :category %>

    <%= collection_select(:name, :id, Category.all, :id, :name) %>

    <%= f.submit "Submit" %>

<% end %>

category show page

  <% @category.each do |c| %>

<%= c %>

  <% end %>

this only shows empty boxes - [ ]
what seems to be the issue.


text:
Q: How to style ProgressBar like in Google Fit? Can anyone help me to make such ProgressBar as in Google Fit application? Like on image below:

Thank you!

A: You can review this library Progressbar with number and can customize background of progress bar from its property. Use nine-patch image to make it awesome.


text:
Q: Convert JSON response to Google Sheet ( Google Apps Script) I have been trying to figure out to insert the JSON response into google Sheet in Google Apps Script with below code but for some reason I am getting error while trying to run.
please see screenshot and below code.
    function myFunction() {

  var key_67 = 'YYYYYYYYYYYYYYYYYY';
  var ss_67 = SpreadsheetApp.openById(key_67);
  var sheet_67 = ss_67.getActiveSheet();
  sheet_67.getRange('A1:AZ10000').clearContent();
 var url = 'https://creator.zoho.com/api/json/arfater/view/Leads_Report?authtoken=XXXXXXXXXXXXXXXXXXXX&scope=creatorapi&zc_ownername=ipekuet';
 var response = UrlFetchApp.fetch(url);
var json = response.getContentText();
var data = JSON.parse(json);
Logger.log(data);

  var stats=[]; //create empty array to hold data points

  //The following lines push the parsed json into empty stats array

    stats.push(data.Yearly_Sales); //temp
    stats.push(data.Email); //dewPoint
    stats.push(data.Phone); //visibility

  //append the stats array to the active sheet
  sheet_67.appendRow(stats)

}

A: So your JSON response based on postman app is
var zohoipekuetview65 = {"Leads":[{"Yearly_Sales":"$ 1,000.00","Email":"test@zoho.com","Phone":"123-032-03323","Potentially":50,"State":"NY","ZipCode":"10036","Street":"1515 Broadway","Country":"USA","ID":"2198633000000063029","City":"New York","Name":"Arfater Rahman"}]};
When I use that response as is:
function JsonResponse(){
 var json ='var zohoipekuetview65 = {"Leads":[{"Yearly_Sales":"$ 1,000.00","Email":"test@zoho.com","Phone":"123-032-03323","Potentially":50,"State":"NY","ZipCode":"10036","Street":"1515 Broadway","Country":"USA","ID":"2198633000000063029","City":"New York","Name":"Arfater Rahman"}]} '
 var data = JSON.parse(json);
Logger.log(data);
}

I get the same error as you:

SyntaxError: Unexpected token: v

Which leads me to believe your response from API has this term var zohoipekuetview65 (Not really sure as to why? a bug perhaps)
The below code splits the response string to give you the JSON response only
function trialParse(){
var json ='var zohoipekuetview65 = {"Leads":[{"Yearly_Sales":"$ 1,000.00","Email":"test@zoho.com","Phone":"123-032-03323","Potentially":50,"State":"NY","ZipCode":"10036","Street":"1515 Broadway","Country":"USA","ID":"2198633000000063029","City":"New York","Name":"Arfater Rahman"}]} '
Logger.log(JsonResponse(json))
}
function JsonResponse(response){
  Logger.log(response)
  var json = response.split("=")[1]
  var data = JSON.parse(json);
  Logger.log(data);
  return data
}

Just call the above function in your code using var data = JsonResponse(json)
Final Note: As mentioned by Jordan Rhea you can use Logger.log(json) to output the response to your logs. To view your logs goto Views>Logs, it will show you the response you receive from Api.


text:
Q: Curl request to Openstack API returns 403 forbidden error I am using openstack api as given below:
curl -i -X GET "https://cloud.lab.fiware.org:5000/v3/users?name=username" -H "X-Auth-token:token"
However, it doesn't return me any result. It gives 403 error code as Forbidden.
Please find the below response
HTTP/1.1 403 Forbidden
Server: nginx/1.4.6 (Ubuntu)
Date: Wed, 30 Jan 2019 10:55:04 GMT
Content-Type: application/json
Content-Length: 136
Connection: keep-alive
Vary: X-Auth-Token
X-Distribution: Ubuntu
X-Openstack-Request-Id: req-9948991c-83f2-452b-b942-2ff3d5a9c5eb
{"error": {"message": "You are not authorized to perform the requested action: identity:list_users", "code": 403, "title": "Forbidden"}}

A: Just admin privilege could get list of users: "As an administrator, you manage projects, users, and roles." ( from https://docs.openstack.org/keystone/pike/admin/cli-manage-projects-users-and-roles.html)

A: I asume that you provided a correct token. What I mean is that this operation has to be launched by an authorised user with enough privileges to get this information. Probably, you requested the API with a token of a normal user and then you cannot get the information for the requested user for security reasons.


text:
Q: How do we copy the file in S3 to a /usr/local/tomcat/webapps/ROOT/js directory? I am looking to copy the file in S3 to the container which is created in my AWS ECS, How do we copy the file in S3 to a /usr/local/tomcat/webapps/ROOT/js directory? I am passing in in the CMD in task definition but it is not working.
I tried it via command and it is throwing "executable file not found in $PATH:unknown.


text:
Q: Sqoop not working on Mac I have installed Apache sqoop on Mac using homebrew with all it's dependencies. But it seems sqoop is not doing anything at all.
Even if I just type 'sqoop help' it outputs -
Warning: /usr/local/Cellar/sqoop/1.4.6_1/libexec/bin/../../accumulo does not exist! Accumulo imports will fail.
Please set $ACCUMULO_HOME to the root of your Accumulo installation.

And no help is printed.
Other commands like snoop-import is there too but does not seem to be doing anything at all when executed.
Does sqoop not work on Mac or is there anything wrong on my setup?
Thanks.

A: After I installed it from this location -
http://ftp.jaist.ac.jp/pub/apache/sqoop/1.4.7/
its working fine. Though I had to set some environment variables properly. Thanks.

A: export HADOOP_PREFIX=/usr/local/Cellar/hadoop/2.7.7
export HADOOP_HOME=/usr/local/Cellar/hadoop/2.7.7
export HADOOP_HDFS_HOME=$HADOOP_PREFIX
export HADOOP_MAPRED_HOME=$HADOOP_HDFS_HOME
export HADOOP_YARN_HOME=/usr/local/Cellar/hadoop/2.7.7
export HCAT_HOME=/usr/local/opt/hive/libexec/hcatalog
export HADOOP_CONF_DIR=/usr/local/Cellar/hadoop/2.7.7/etc/hadoop
export ZOOKEEPER_HOME=/usr/local/Cellar/zookeeper/3.4.12
export HBASE_HOME=/usr/local/Cellar/hbase
export SQOOP_HOME=/usr/local/Cellar/sqoop
export HADOOP_CLASSPATH=`hadoop classpath`
export HIVE_HOME=/usr/local/Cellar/hive/2.1.0/

Also, not all version of Hadoop is compatible with all version of HIVE/HBASE/SQOOP. You need to install right versions.
Hope this helps.


text:
Q: Close backend with AccessControl I can trying simple code.
I have an AccessController which having behaviors():
class AccessController extends BackendController
{
  public function behaviors()
  {
    return [
      'access' => [
        'class' => AccessControl::className(),
        'rules' => [
          [
            'allow' => true,
            'roles' => ['@'],
          ],
        ]
      ],
    ];
  }
  /*public function init()
  {
    parent::init();

    if( Yii::$app->getUser()->getIsGuest() )
    {
      return $this->redirect('/auth');
    }

    return true;

  }*/

  public function actions()
  {
    return [
      'WysiwygUpload' => [
        'class' => WysiwygUpload::className(),
      ]
    ];
  }

}

AS I understand, if I didn't declare 'only' key, that is mean to all actions and controllers.
But nothing happen: no one error, nothing

A: Your  controller AccessController work only for yourApp/backend/access request  not for all controllerAction..
If you want deny the access to guest in AdminController you shuold apply the behavior of AdminController
class AdminController extends Controller
{
    public function behaviors()
    {
       return [
           'access' => [
           'class' => AccessControl::className(),
           'rules' => [
              [
                'allow' => true,
                'roles' => ['@'],
             ],
          ]
        ],
      ];
    }
    ........

Then when a guest try accessing to  yourApp/backend/admin  this is not permitted


text:
Q: How to Resolve Arguments are not valid for System.ComponentModel.PropertyChangingEventHandler I'm rewriting an ASP.NET MVC3 app in MVC5 which makes heavy use of Knockout and MVVM.  The model classes are heavily laden with INotifyPropertyChanged and INotifyPropertyChanging functions.
While bringing the following statements into the MVC5 app, I'm receiving the build error in the subject line above:
public event PropertyChangingEventHandler PropertyChanging;
    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void SendPropertyChanging()
    {
        if (this.PropertyChanging == null)
            return;
        this.PropertyChanging((object)this, AFCity.emptyChangingEventArgs);
    }

What must be done to resolve the above error?


text:
Q: Python Pandas DataFrame; Place to excel cells Hello, I want to put each "0" in excel cells. How can I do this?
This is my python code for convert json to Dataframe and to excel

with urllib.request.urlopen(myurl.json") as url:
        data = json.loads(url.read().decode())
        df = pd.DataFrame(data)
        df1 = df.stack().swaplevel()

And this is the output image.
Output image
This is how I want to do
Image, how ı want to do
And this is my json file

{"ADMİN":{"MUSTAFA SEMİH YAMAN":[null,0,0,0,0,1,0,0,1,0,0,1,1,1,1,0,0,1,0,1,0,0,1,0,1,1,1,1,1,1,0,0]}}

A: Assuming there will always be only one key/value pair, the following piece of code should work.
data = json.loads(url.read().decode())
role = list(data.keys())[0]
name = list(data[role].keys())[0]
listData = data[role][name]
columns = ['', '']+list(range(0, len(listData)))

df = pd.DataFrame([role, name]+listData).T #transform the dataframe
df.columns = columns
df.to_csv("result.csv",index=False)