Q:

Dropping certain values in columns depending on contents of other column

I have a dataframe that looks like this:
   Deal      Year  Financial Data1  Financial Data2  Financial Data3  Quarter
0     1  1991/1/1              122              123              120        1
3     1  1991/1/1              122              123              120        2
6     1  1991/1/1              122              123              120        3
1     2  1992/1/1               85               90               80        4
4     2  1992/1/1               85               90               80        5
7     2  1992/1/1               85               90               80        6
2     3  1993/1/1               85               90              100        1
5     3  1993/1/1               85               90              100        2
8     3  1993/1/1               85               90              100        3

However I only want the Financial Data1 displayed for the first quarter in each deal and The whole thing combined into one column again.
The end result should look something like this:
       Deal    Year         Financial Data   Quarter
    0     1  1991/1/1              122          1
    3     1  1991/1/1              123          2
    6     1  1991/1/1              120          3
    1     2  1992/1/1               85          4
    4     2  1992/1/1               90          5
    7     2  1992/1/1               80          6
    2     3  1993/1/1               85          1
    5     3  1993/1/1               90          2
    8     3  1993/1/1              100          3

A:

Okie dokie, using np.where() I think this does what you're trying to do:
import pandas as pd
import numpy as np

df = pd.read_fwf(StringIO(
"""Deal      Year  Financial_Data1  Financial_Data2  Financial_Data3  Quarter
1     1991/1/1  122              123              120              1
1     1991/1/1  122              123              120              2
1     1991/1/1  122              123              120              3
2     1992/1/1  85               90               80               4
2     1992/1/1  85               90               80               5
2     1992/1/1  85               90               80               6
3     1993/1/1  85               90               100              1
3     1993/1/1  85               90               100              2
3     1993/1/1  85               90               100              3"""))

df['Financial_Data'] = np.where(
    # if 'Quarter'%3==1
    df['Quarter']%3==1,
    # Then return Financial_Data1
    df['Financial_Data1'],
    # Else
    np.where(
        # If 'Quarter'%3==2
        df['Quarter']%3==2,
        # Then return Financial_Data2
        df['Financial_Data2'],
        # Else return Financial_Data3
        df['Financial_Data3']
    )
)

# Drop Old Columns
df = df.drop(['Financial_Data1', 'Financial_Data2', 'Financial_Data3'], axis=1)

print(df)

Output:
   Deal      Year  Quarter  Financial_Data
0     1  1991/1/1        1             122
1     1  1991/1/1        2             123
2     1  1991/1/1        3             120
3     2  1992/1/1        4              85
4     2  1992/1/1        5              90
5     2  1992/1/1        6              80
6     3  1993/1/1        1              85
7     3  1993/1/1        2              90
8     3  1993/1/1        3             100

(PS: I wasn't 100% sure how you intended on dealing with Quarter 4-6, in this example I just treat them as 1-3)


Q:

How to add Font Awesome to Next.js project

I'm trying to add font-awesome to my Next.js project using webpack. I've tried following various instructions I've found on the web (using file-loader, url-loader), but nothing has worked for me. I gave up loading font-awesome with webpack for the moment, but I want to know how I can accomplish this. Currently, I have a .scss file that I use to load font-awesome.
It's contents:
$fa-font-path: "static/fonts";
@import "~font-awesome/scss/font-awesome.scss";

And I'm manually moving the fonts from node_modules/font-awesome/fonts to static/fonts. This works perfectly, But I wanted to know if there's a webpack 2 way to do it in 2017.

A:

There are a few ways to do this. The first would be to create a head component via next/head and import there - see here:
Another way is to create a HOC to wrap your pages with and import there with a simple import 'font-awesome/css/font-awesome.min.css'
Or, you could just import it into one of your page's with the same kind of import. (I believe this will scope it to that particular page however. Double check me on that)
Hope this helps.


Q:

Cannot use 'cd' command in Python console

I want to change directory using 'cd' command in PyCharm's python console. It works all the time until I bought a new PC.
Environment is Python 3.7; Pycharm 2019.1.1.
I google it and some guys told me to use os.chdir() but I want to use 'cd' because it is easy to use.
The error report is:
NameError: name 'cd' is not defined

Thanks :)

A:

cd is not a Python command. You can't use it unless you're running in a non-standard interpreter that provides access to it. Even if you could use it, running cd in a subshell (which is how most other interpreters expose shell commands) wouldn't change the working directory for the Python session you're in.
If you use an alternate interpreter/interpreter wrapper like ipython, yes, it has cd built-in the way you'd expect it to function.
But if you're on the bog standard Python interpreter, just use os.chdir. You can always alias it to something shorter if you like, e.g.
>>> from os import chdir as cd
>>> cd('foo/bar')


Q:

When using ExecutorService, are the classes within threadsafe?

I have an implementation of a Runnable class which contains a Vector of objects that items are removed from one by one and processed.
Using the ExecutorService and creating a newFixedThreadPool with n number of threads, are there n number of instances of the Runnable class? If so, are the classes and the Vector within threadsafe, or would this need to be implemented using synchronized?
Thanks

A:

As others have stated, if you are sharing your Vector across Runnables, then it is not threadsafe.  To be threadsafe, you should use either bound queue (like BlockingQueue) or unbound queue (like ConcurrentLinkedQueue) instead of Vector.


Q:

Controlling HDMI Switch via RS232/UART

Problem:
I have an HDMI switch that is controllable via RS232

Scenario 1:

Setup: PC connected to HDMI switch using USB -> serial adapter
Test: Opening PuTTY on COM port and sending command "sw i01" from my PC
Results: HDMI switch input changes to port 1 [Good]

Scenario 2:

Setup: Arduino UART port connected to TTL->RS232 adapter connected to serial->USB adapter connected to PC with PuTTY program open on COM port
Test: Sending command "sw i01" from Arduino to PC using code below
Results: "sw i01" prints repeatedly on the Putty terminal [Good]

Scenario 3:

Setup: Arduino UART port connected to TTL->RS232 adapter connected to HDMI switch serial port
Test: Sending "sw i01" from Arduino repeatedly to HDMI switch using code below
Results: HDMI port does not switch from port2 to port1 [Bad]

Hardware:

Intel Galileo Gen 2
SparkFunRS232/TTL Shifter connected to Galileo UART
HDMI switch is IOGear GHSW8141

Code:
[Note: Galileo Gen 2 requires Serial1 for UART communication]
void setup() {
    Serial1.begin(19200);
}

void loop() {
    Serial1.print("sw i01");
    Serial1.write(13);    // CR
    Serial1.write(10);    // LF
    delay(1000);
}

Question:
It seems like Scenario 1 and 2 confirm that the Arduino->HDMI switch communication should work, but it doesn't. Am I missing something regarding physical connectivity? Does manually typing "sw i01" in PuTTY send different commands than I have in the Arduino code?

A:

I found it is was related to the physical connection!
In Scenario 3, I originally had the Sparkfun TTL/RS232 adapter that had a female DB9 connector wired to the HDMI switch female DB9 connector using a male/male serial cable. The serial cable I bought was a straight through cable.
I swapped it out with a null modem cable and it worked right away.
Looking at the wiring diagram, I thought swapping the Tx/Rx pins on the Sparkfun adapter would have achieved the same result as the null modem cable, but apparently not.
If anybody can point out why the null modem cable made the difference, that would be something good to know for the future.


Q:

Length of tangents of incircle and excircle

Given a triangle $ABC$ , the incircle touches side $BC $ at $D $ and the excircle touches the side $BC$ at $F$ .
Prove that $BF=CD$ .
Can't think of a way to relate the tangents of the incircle and the excircle.
Any tips please?

A:

I will provide a sketch of the proof:

Let $a,b,c$ be the lengths of sides $BC,CA,AB$, respectively, and let $s=\frac{a+b+c}{2}$ be the semi-perimeter of the triangle.
Show that $CD=s-c$.
Show by similar logic that $BF=s-c$ as well.


Q:

How to plot a dashed line for some data predictions followed from a solid line from historical data

Problem
I have a set of data from a .dat file, which every value could be "historical" or "prediction".
year    emision   data_type
2008    9.24309   hist
2010    8.50724   hist
2012    8.06490   hist
2014    7.84779   hist
2016    7.22237   pred
2018    6.71319   pred
2020    6.26255   pred

I need to plot a solid a line with those data which are historical, and a dashed line with those which are predictions, in the same plot. Below is an example plot of what I want.
I have check this answer but I didn't understand how to apply this, with data from a file.

What I have:
Here is the code :
\documentclass{article}

\usepackage{pgfplots}
\pgfplotsset{compat=1.16}
\usepackage{lipsum}

%\pgfplotstableread{data/example_data.dat}\datatable

\pgfplotstableread{
year    emision data_type
2008    9.24309 hist
2010    8.50724 hist
2012    8.06490 hist
2014    7.84779 hist
2016    7.22237 pred
2018    6.71319 pred
2020    6.26255 pred
}\datatable

\begin{document}
\lipsum[1]

\begin{figure}[t]
\centering
\begin{tikzpicture}
    \pgfplotsset{every axis legend/.append style={
        at={(0.5,-0.1)},
        anchor=north}}
    \begin{axis}[
            width=\textwidth,
            height=\axisdefaultheight,
            legend columns=4,
            grid=major,
            cycle list name=exotic,
            ]
    \addplot table[y=emision] from \datatable;
\end{axis}
\end{tikzpicture}
\end{figure}
\end{document}

Thanks in advance!

A:

a rude solution:
\documentclass{article}

\usepackage{pgfplots}
\pgfplotsset{compat=1.16}
\usepackage{lipsum}

%\pgfplotstableread{data/example_data.dat}\datatable

\pgfplotstableread{
year    emission data_type
2008    9.24309  hist
2010    8.50724  hist
2012    8.06490  hist
2014    7.84779  hist
2016    7.22237  pred
2018    6.71319  pred
2020    6.26255  pred
}\datatable

\begin{document}
\lipsum[1]

\begin{figure}[t]
\centering
\begin{tikzpicture}
    \pgfplotsset{every axis legend/.append style={
        at={(0.5,-0.1)},
        anchor=north}}
    \begin{axis}[
            width=\textwidth,
            height=\axisdefaultheight,
            legend columns=4,
            grid=major,
            cycle list name=exotic,
            ]
    \addplot            table[y=emission, x=year, restrict x to domain=2008:2014] from \datatable;
    \addplot +[dashed]  table[y=emission, x=year, restrict x to domain=2014:2020] from \datatable;
\end{axis}
\end{tikzpicture}
\end{figure}
\end{document}


Q:

How to make jQuery animation smoother

Currently, the animation on my website looks a bit jittery. Ideally, I would like the page to load, wait a few seconds, then smoothly anchor to #howgreen and then open the accordion.
In this webpage (URL), it anchors to #howgreen and the jQuery below looks for #howgreen in the URL and if it exists it opens/triggers/clicks it to open the accordion (#howgreen-text).  How can I delay the animation or make the animation on my website work more smoothly?
$("#howgreen").click(function () {
    $(this)
        .parent()
        .children('#howgreen-text')
        .animate({
            height: 'toggle'
        }, 'slow', function () {
            if ($(this).parent().children('#howgreen-text').css('display') == 'block') {
                $(this)
                    .parent()
                    .children('#howgreen')
                    .addClass("work-main-bar-active");
            } else {
                $(this)
                    .parent()
                    .children('#howgreen')
                    .removeClass("work-main-bar-active");
            }
        });
});
/* Anchor Open Accordions */
$(document).ready(function () {
    $(function () {
        if (document.location.href.indexOf('#howgreen') > -1) {
            $('#howgreen')
                .trigger('click');
        }
    });
});

A:

You could listen for the page load event and then wrap the click trigger in a setTimeout like so
/* Anchor Open Accordions */
$(function() {
    $(window).load(function() {
        setTimeout(function() {
            if ( document.location.href.indexOf('#howgreen') > -1 ) {
                $('#howgreen').trigger('click');
            }
        }, 2000);
    });
});


Q:

How to implement "Refresh" and "Reload" Table (re-factoring of code)

I have the following situation:
1) 1 X PhotoTableViewController to display a list of photos (one photo per cell) like what Instagram does
2) A refresh button in the navbar of PhotoTableViewController to do a table reload (top right)
3) An option button in the navbar of PhotoTableViewController to select a list of options e.g. "Latest photos, most popular etc) (top left)

4) A "Load more" cell at the end of the list (limit to 20 photos) to append the next set of photos to the table view.

The photos are obtained from a server and comes in a form of a JSON file.
Query: I believe that all 3 buttons (point 2,3 and 4) essentially want to do the same thing, which is to refresh and reload the table. Also my understanding is that this is a common sort of practice in a few apps, so I would like some advise on  the following
1) How do I implement this sort of 'Refresh' and 'Reload' method in the most effective way without repeating code.
2) After I click each button, the intention is to sort of have a 'Blank page' with a spinner and show only the reloaded table after processing is completed. I am thinking of popping the current tableview controller at point of button click and push a new controller back once processing is completed. Does this make sense? Or is there a better way of doing it?

A:

You are correct that they all essentially have the same behavior.  I would say that you implement a cursor type of backend call so that you can pass in the next result number you want or the next page you want.  That is up to you, but here's a sample.
{
"cursor": {
    "currentPageIndex":0,
    "estimatedNumberOfHits":351,
    "pages":[{
        "label":"1",
        "offset":0
    },{
        "label":"2",
        "offset":10
    },{
        "label":"3",
        "offset":20
    }]
},
"details":"",
"data":[{
    "id":709,
    "modifiedOnTimestamp":1304009527000,
    "state":"California",

    "city":"Santa Monica",
}]

Create the network call in one place (on iOS side) that passes in the result number you want next.  Then, when you process the JSON, they call call reloadData on the table view.


Q:

How to access a WCF service in an ASP.Net MVC application?

I have question about the way to access the WCF. I built a secure WCF service that returns data from a data base and it works fine. Now I need to access this web service through MVC (I do not have enough knowledge about it).
I checked similar questions on Stack Overflow but I did not find what I need. I followed this link but as I said, WCF returns data from SQL, I connect my WCF with SQL and when I used this example I don't get the expected result.
the operation that i invoke in MVC and it return dataset type from SQL
[OperationContract]
DataSet GetAllbooks(string Title)

in Homecontrller in MVC i wrote
ServiceReference1.Service1Client obj = new ServiceReference1.Service1Client();
public ActionResult Index()
{
    DataSet ds = obj.GetAllbooks();
    ViewBag.AuthorList = ds.Tables[0];
    return View();
}

and in view i wrote
     @{
    ViewBag.Title = "AuthorList";
   }

ISBN	Author	Price

   <%foreach (System.Data.DataRow dr in ViewBag.AuthorList.Rows)
  {%>

   <%=dr["ISBN"].ToString()%>
     <%=dr["Author"].ToString() %>
   <%=dr["Price"].ToString() %>

  <% } %>

i don't get any result
Also some services that provide by WCF need to accept input from user how i can do it
Thank you.

A:

This is a pretty basic question but generally speaking you can add a web service reference and endpoint info in the main Web.Config file but I suspect you are having trouble with calling the WCF service URL, if so I posted an example of a generic class/wrapper for calling WCF web services in an MVC application.
Add the Web Reference to Visual Studio 2012:

Right click the project in the Solution Explorer
Choose Add–>  Service Reference –> Then click the Advanced Button... –>
Then click the "Add Web Reference…" button –> then type the address of your Web Service  into the URL box. Then click the green arrow and Visual Studio will discover your Web Services and display them.

You may have known the above already and might just need a generic wrapper class which makes calling the WCF Web Service easy in MVC. I've found that using the generic class works well. I can't take credit for it; found it on the internet and there was no attribution.  There is a complete example with downloadable source code at http://www.displacedguy.com/tech/powerbuilder-125-wcf-web-services-asp-net-p3 that calls a WCF Web service that was made using PowerBuilder 12.5.Net, but the process of calling the WCF Web service in MVC is the same no matter if it was created in Visual Studio or PowerBuilder.
Here is the code for a generic wrapper class for calling WCF Web Services in ASP.NET MVC
Of course don't model your error handling after my incomplete example...
using System;
using System.ServiceModel;
namespace LinkDBMvc.Controllers
{
   public class WebService<T>
   {
     public static void Use(Action<T> action)
     {
       ChannelFactory<T> factory = new ChannelFactory<T>("*");
       T client = factory.CreateChannel();
       bool success = false;
       try
       {
          action(client);
          ((IClientChannel)client).Close();
          factory.Close();
          success = true;
       }
       catch (EndpointNotFoundException e)
       {
          LinkDBMvc.AppViewPage.apperror.LogError("WebService", e, "Check that the Web Service is running");
       }
       catch (CommunicationException e)
       {
          LinkDBMvc.AppViewPage.apperror.LogError("WebService", e, "Check that the Web Service is running");
       }
       catch (TimeoutException e)
       {
          LinkDBMvc.AppViewPage.apperror.LogError("WebService", e, "Check that the Web Service is running");
       }
       catch (Exception e)
       {
          LinkDBMvc.AppViewPage.apperror.LogError("WebService", e, "Check that the Web Service is running");
       }
       finally
       {
         if (!success)
         {
           // abort the channel
           ((IClientChannel)client).Abort();
           factory.Abort();
         }
       }
     }
   }
 }


Q:

If an Excel criteria is met in one column, record the value of the column next to the matching criteria into a range

Perhaps I just haven't been looking in the right places, but I don't think this should be as difficult as I am finding it to be.
I have a spreadsheet, that CANNOT be sorted (it's in a production line, connected to individual sheets that bring other data in, filled out by many different people). The data that comes in is essentially random, and looks like this:
''    Type    Sieve #40
''
''    Truck       55%
''    Truck       55%
''    CoA         48%
''    Basement    55%
''    Bin2        55%
''    Bin1        55%
''    Hopper      57%
''    Basement    58%
''    Bin2        54%
''    Bin1        58%
''    Hopper      56%
''    Truck       56%
''    CoA         47%
''    Basement    55%
''    Bin2        57%
''    Bin1        61%
''    Hopper      50%

Now, I need a macro that can find the sample type (truck, bin1, etc.) and puts each value that corresponds to that sample type into a range. Then I can plot the ranges on a chart.
For example, the "Truck" range would have the numbers 55%, 55%, 56%.
So there are 6 different sample types which means 6 different ranges, which means 6 different series on my chart.
I have all the code written to plot the chart, and all the code written to gather the data into these two columns. I am just missing this piece.
Ideally, for example, there would be a way to set up a For loop that goes from row 1 to the last row of the sheet, and when it finds "truck", it assigns the number in the column next to "truck" to the first spot in a new array. Then the next instance of "truck" fills the next spot in the "Truck" array, and so on.
Adding sheets is very nearly impossible for me, because the operators must add a new sheet for each sample, which then gets some data pulled into this summary sheet.

A:

edited as per OP's last clarifications
try this
Option Explicit

Sub main()

Dim dataRng As Range, dbRng As Range, helperRng As Range, cell As Range, found As Range
Dim rangeArray() As Range
Dim iRng As Long

With Worksheets("MySheet") '<= change it to your actual worksheet name
    Set dbRng = .Range("A1:A" & .Cells(.Rows.Count, 1).End(xlUp).Row).Resize(, 2) '<= change "A1" to your actual data first up-left cell address
    Set dataRng = dbRng.Offset(1).Resize(dbRng.Rows.Count - 1) 'extrapolate data only (headers off)
    'Set helperRng = dbRng.Offset(.UsedRange.Rows.Count + 1, .UsedRange.Columns.Count + 1).Cells(1, 1) ' localize "helper" range out of sheet used range
    Set helperRng = .Range("AA1") ' localize "helper" range from cell "AA1"
End With
dataRng.Columns(1).SpecialCells(xlCellTypeConstants, xlTextValues).Copy Destination:=helperRng ' copy relevant data into "helper" rang

With helperRng
    If .CurrentRegion.Rows.Count > 1 Then .CurrentRegion.RemoveDuplicates Columns:=Array(1), Header:=xlNo ' take only samples unique values
    With .CurrentRegion
        ReDim rangeArray(1 To .Rows.Count) 'size the array to sample unique values number
        For iRng = 1 To .Rows.Count 'loop through sample unique values
            dbRng.AutoFilter field:=1, Criteria1:=helperRng(iRng, 1) ' filter data accordingly to current sample value
            Set rangeArray(iRng) = dataRng.Columns(2).SpecialCells(xlCellTypeVisible) 'store filtered rows columns 2 ranges
            .AutoFilter
        Next iRng
    End With
'    .ClearContents '<== remove the comment once you're done with the example
End With

' here follows an example of exploiting rangeArray array
' once you're done with it, remove this example and uncomment the ".ClearContents" statement by the end of preceeding "With ... End With" block
For iRng = 1 To UBound(rangeArray)
    rangeArray(iRng).Copy
    helperRng.Offset(iRng - 1, 1).Resize(1, rangeArray(iRng).Count).PasteSpecial xlPasteAll, Transpose:=True
Next iRng

End sub

it'll work with whatever samples different values


Q:

PHP in_array issue while checking zero value in array giving true

I am facing one strange situation while working with PHP's in_array(). Below is my code and its output
<?php
$process = array("as12"=>"deleted","as13"=>1,"as14"=>1);
if(!in_array(0, $process))
    echo "success";
else
    echo "not success";

//It's outputting "not success";

var_dump(in_array(0, $process));
//Output : null

var_dump(in_array(0, $this->tProcessActions) === true);
///Output : true

If we look at the $process array, there is no 0 value in it. Still it's giving me true if I check if(in_array(0, $process))
Can anybody has idea about it?

A:

Try like
if(!in_array('0', $process)) {

or you can use search(optional) like
if(array_search('0',$process)) {

A:

If you need strict checks, use the $strict option:
in_array(0, $process, true)

PHP's string ⟷ int comparison is well known to be complicated if you don't know the rules/expect the wrong thing.


Q:

tcolorbox theorem numbering

\documentclass{article}
\usepackage{amsmath,amsthm,amssymb,parskip}
\usepackage{graphicx,float,hyperref}
\usepackage[margin=1in]{geometry}
\usepackage{titling,multicol}
\usepackage{tcolorbox}
\tcbuselibrary{theorems}
\newtcbtheorem{mytheo*}{}%
{colback=purple!5,colframe=blue!100!,fonttitle=\bfseries}{th}

\begin{document}

\begin{mytheo*}{title...}{}
text...
\end{mytheo*}

\end{document}

I am trying to make the theorem unnumbered, but I have not managed to figure out how to remove the number 1 and the colon that appear at the beginning of the theorem title. Does anyone know how to do this?

A:

There is a misunderstanding by the OP what \newtcbtheorem does actually:
\newtcbtheorem{foo}{...}{...}{...} will actually define both the numbered theorem - like enviroment foo and foo*, so \newtcbtheorem{foo*} will actually define foo* and foo**, leaving foo* being numbered however and foo** is the unnumbered version.
See page 340 of current tcolorbox manual for a description of this.
In addition, hyperref should be loaded as last package as almost always in 98% of all cases.
As a reply to the comment below by Bryan-M-H:
The unstarred version of the theorem has an additional mandatory argument that is meant for the label, see the changed example where the label is given as {foo}, which is extended to th:foo since the definition of the theorem has th as label prefix.
Related (but not duplicate) Counter for tcolorbox
Also related (no duplicate too): Problem with tcolorbox package
\documentclass{article}
\usepackage{amsmath,amsthm,amssymb,parskip}
\usepackage[margin=1in]{geometry}
\usepackage{titling,multicol}
\usepackage[most]{tcolorbox}

\usepackage{graphicx,float}
\usepackage{hyperref}

\newtcbtheorem{mytheo}{My theorem}{colback=purple!5,colframe=blue!100!,fonttitle=\bfseries}{th}

\begin{document}

\begin{mytheo*}{}
  text...
\end{mytheo*}

See \ref{th:foo}

\begin{mytheo}{Foo}{foo}
  text...
\end{mytheo}

\end{document}


Q:

Assigning member in optional structure memeber

What is the best style for assigning an optional member of structure?
For example I have a struct:
struct B{
public:
    int x;
}

struct A{
public:
    boost::optional<B> b;
};

void foo(){
   A a;
   a.b.x = 10; //Runtime exception because a.b is not initialized.
}

One option is to define temporary B struct and assign it to A:
void foo(){
    A a;
    B tmp;
    a.b = tmp;
    a.b.x = 10; //OK.
}

or:
void foo(){
    A a;
    a.b = B();
    a.b.x = 10; //OK.
}

Is there a clearer way to do this?

A:

You have no choice but to initialize it before using it. If you don't, you'll have an assertion fail which will cause a termination.
But if you are asking about ways to initialize it, there are a lot of them:

a.b = B{10} as it is POD-type.
a.b = B() as you did already (works always and not only for POD-types).
Create a constructor and make it like a.b = B(10). But still, you always have to create an object and assign to it. So, you may do either implicit or explicit creation of the object, but you must do it.
In boost 1.56, as @n.m told, here is an emplace() method that does the same for you: a.b.emplace().


Q:

How to start a Windows GUI app from telnet

I have a GUI application running on a windows XP client machine.  I would like to telnet in, shut it down, pull some files over via ftp and then start it up again.
It's that last part that I'm having problems with as it seems like starting any GUI app from telnet "starts" it only in the sense that it is added to the process list.  It does not pop up forms or really start doing anything (like writing log files).
Try it yourself.  Telnet localhost => notepad.exe
Is there a simple way around this limitation? I also have RAdmin installed on all these machines, maybe there's a way to somehow use it?  I doubt it since this is for an automation script and my experience is that RAdmin has 0 support for this.
By the way, I started this discussion on stackoverflow and it was recommended to me that you guys might know a thing or two about this.

A:

It looks like this is not possible with the Windows telnet service.  I even tested running the service under the local system account with "interact with desktop" enabled, but that did not work (which is fine as it would have serious security implications).
As an alternative to using telnet, I would recommend PsExec.  PsExec is part of the SysInternal tools now managed by Microsoft.  Use the -i option to enable desktop interaction.
psexec \\machine -u user -p password -i -w "C:\application" myapp.exe

You can download PsExec here.

A:

See http://msdn.microsoft.com/en-us/library/ms687096(VS.85).aspx for a long and detailed though ultimately unhelpful description of what is happening when you launch apps from a telnet session. Many years ago I wrote a telnet server for Windows NT3.50 and I learned all this stuff the hard way :-)
I think you need to look again at what you're trying to do. From your description I'd guess that you have some GUI app being run by a logged in user and you want to kill it so you can do some maintenance then restart it. Killing it is easy as you can just kill the process. Restarting it in any useful way is harder. Could you set the PC to autologin and run the app from the Start Menu? Then you could just restart the PC when you've grabbed your files. I'm somewhat ashamed to admit this is what I did under similar circumstances.
JR


Q:

I'm trying to add a Box to a JLayeredPane

I declared the Box as: Box caja=Box.createHorizontalBox();
  However the first layer the one that says FondoMenu.png is the only one showing and the Box doesnt show unless I put that JOptionPane showing it first, please some help (The BuscaImagen is a method I made that creates JLabel with my specifications)

capas.add(new BuscaImagen("FondoMenu.png", 0, 0), new Integer(0));
        caja.add(new BuscaImagen("JUGAR", "FIz.png", 2, 40, 90));
        caja.add(Box.createHorizontalStrut(20));
        caja.add(new BuscaImagen("SALIR", "FDe.png", 2, 40, 240));
        caja.add(Box.createHorizontalStrut(20));
        caja.add(new BuscaImagen("INSTRUCCIONES", "FAb.png", 2, 40, 390));
        JOptionPane.showMessageDialog(null, caja);
        caja.setLocation(60, capas.getHeight() / 2 - 10);
        capas.add(caja, new Integer(1));

A:

There is a nice write up on oracle on how to use Layered Panes. I hope this helps with your issue
http://docs.oracle.com/javase/tutorial/uiswing/components/layeredpane.html


Q:

Parameterized queries in sqlite3 using question marks

I am using sqlite3 module with Python and have this code so far. In the database I have stored daily weather conditions, and now I need my code to replace some rows with updated data. The code is supposed to be looking for the row with datetime value equal to new_data[0].
The way I parameterized the query is wrong, but cannot figure out the correct and most elegant way of going about it!
new_data = ['12 Mar 2014', 'sunny', 20, 12]

conn = sqlite3.connect(database_file)
c = conn.cursor()
c.execute("UPDATE weather SET datetime = ?, condition = ?, high = ?, low = ? WHERE datetime = %s" new_data, %new_data[0])

A:

You are mixin up a parameterized query with string operations. First, that's highly insecure and second, you have created a problem with your syntax (you missed a comma after your query string). Try this instead:
new_data = ('12 Mar 2014', 'sunny', 20, 12, '12 Mar 2014',)

conn = sqlite3.connect(database_file)
c = conn.cursor()
c.execute("UPDATE weather SET datetime = ?, condition = ?, high = ?, low = ? WHERE datetime = ?", new_data)

More details can be found here:
https://docs.python.org/2/library/sqlite3.html


Q:

How do I cite an article with no page numbers and only a DOI number (APA format)?

I am writing an article that requires citations in APA format. As you may know, that format requires page numbers
I am pulling quite a few articles from the journal of Remote Sensing (MDPI), which publishes almost all content as open access articles online. The problem is that they publish the articles online, and do not indicate a page number. For example, an article entitled "Time-Series Multispectral Indices from Unmanned Aerial Vehicle Imagery Reveal Senescence Rate in Bread Wheat" has the following short citation:
Remote Sens. 2018, 10, 809; doi:10.3390/rs10060809
(https://www.mdpi.com/2072-4292/10/6/809)
From further investigating, I think the number 809 is the article in the volume, not the page number. Am I right on this? If so, how do you cite page numbers for a journal where they are not given?

A:

According to the 6th edition of APA:

When using the exact words or a close paraphrase or summary of a source, a page number must be provided as part of a complete in-text citation. However, some publications (such as websites) have no numbered pages. To help readers locate the words being cited, include one or both of these elements:

Paragraph number (counted by yourself or as indicated in the text)
Main heading or sub-heading within the text (if available and appropriate)

So, if you are using a direct citation the approach with manually counted paragraph number and sub-heading section is recommended. The link above provides the following example:

According to the 2012 Canadian Survey on Disability, “[o]ver 11% of Canadian adults experienced one of the three most prevalent disability types: pain, mobility or flexibility” (Statistics Canada, 2013, para. 2)

However, if you are referencing for a purpose other than direct quotation or a close paraphrase, you can simply use 1–N, where N is the number of pages in the cited paper:

Simon, S. L., Field, J., Miller, L. E., DiFrancesco, M., & Beebe, D. W. (2015). Sweet/dessert foods are more appealing to adolescents after sleep restriction. PLoS ONE, 10, 1–8. http://dx.doi.org/10.1371/journal.pone.0115434


Q:

Search characters in a String and replace it with a blank space T-SQL

I have a table with a list of invalid characters like:
InVCh
-----

!
"
$
%
&
'
(
)
*
+
,
.
/

Then, i have a lot of tables with different number of columns (all of those columns are string type), example:
Product          Store
-------          ------
Prod1            Store1
Pr$od!2          Sto$re!2
P:;()ro!!!"d3    S:;()to!!!"re3

I would like to create a procedure that finds all those invalid characters and replace them with a blank space, if there are too many blank space together then i have to replace them with a single one space. So my expected result should be:
Product          Store
-------          ------
Prod1            Store1
Pr od 2          Sto re 2
P ro d3          S to re3

This is possible?
Thanks!

A:

Since it's SQL Server 2016, using R is an option. This doesn't seem to be so far-fetched, as there's an MSSQLTips article from 2017 that describes this: SQL Server 2016 Regular Expressions with the R Language.
The article's code isn't that hard either :
create table dbo.tblRegEx (id int identity, a varchar(300), b  varchar(300) );

-- 3. Remove duplicate words
exec sp_execute_external_script @language=N'R'
, @script = N'
pattern <-"\\b(\\w+\\s*)(\\1\\s*)+";
inData$a <- gsub(pattern, "\\1", inData$a, perl = T );
outData <- inData;'
, @input_data_1 = N'select id, a, b from dbo.tblRegEx'
, @input_data_1_name = N'inData'
, @output_data_1_name=N'outData'
with result sets ( as object dbo.tblRegEx);

This question asks for something far easier, just replace some characters.
create table #products
(
    id int primary key identity,
    product varchar(300),
    store  varchar(300)
);
go

insert into #products (product,store)
values
('Prod1',            'Store1'),
('Pr$od!2',          'Sto$re!2'),
('P:;()ro!!!"d3',    'S:;()to!!!"re3')

exec sp_execute_external_script @language=N'R'
, @script = N'
pattern <-"[!\"$%&''()*+,./:;]+";
inData$product <- gsub(pattern, " ", inData$product, perl = T );
inData$store <- gsub(pattern, " ", inData$store, perl = T );
outData <- inData;'
, @input_data_1 = N'select id, product, store from #products'
, @input_data_1_name = N'inData'
, @output_data_1_name=N'outData'
with result sets ( as object #products);

Like all stored procedures, the results can only be returned to the client, or used as the source for an INSERT INTO. This could be to a stating or temporary table or a table variable that can be used to update the source table :
declare @outData table (id int primary key, product varchar(300), store  varchar(300) );

insert into @outData
exec sp_execute_external_script @language=N'R'
, @script = N'
pattern <-"[!\"$%&''()*+,./:;]+";
inData$product <- gsub(pattern, " ", inData$product, perl = T );
inData$store <- gsub(pattern, " ", inData$store, perl = T );
outData <- inData;'
, @input_data_1 = N'select id, product, store from #products'
, @input_data_1_name = N'inData'
, @output_data_1_name=N'outData'

update #products
set product = r.product,
    store   = r.store
from #products inner join @outdata r on r.id=#products.id

select * from #products

This returns :
id  product   store
--  -------   --------
1   Prod1     Store1
2   Pr od 2   Sto re 2
3   P ro d3   S to re3


Q:

How to use NSUserDefault with PickerView in Swift?

I made some Labels that change using PickerView. But when I change the Label and if I run my app again, it doesn't save to selected one. So I have to use NSUserDefault but I don't know how to use it in right way.
This is my code:
var selectedFood = 0

class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {

@IBOutlet var foodLabel: UILabel!
@IBOutlet var labelTwo: UILabel!
@IBOutlet var labelThree: UILabel!

@IBOutlet weak var foodPicker: UIPickerView!

var food = ["Bread", "Pizza", "Pasta", "Hot Dog", "Burger"]

@IBAction func submitLanguageButton(sender: AnyObject) {
    if (selectedFood == 0) {
       foodLabel.text = "Bread"
       labelTwo.text = "Bread is a staple food prepared from a dough of flour and water..."
       labelThree.text = "Bread is one of the oldest prepared foods..." // I used random information just as sample
    }
    else if (selectedFood == 1) {
       foodLabel.text = "Pizza"
       labelTwo.text = "Here will be more informations about Pizza"
       labelThree.text = "A fact about Pizza"   // I used random information just as sample
    }
    else if (selectedFood == 2) {
       foodLabel.text = "Pasta"
       labelTwo.text = "Here will be more informations about Pasta"
       labelThree.text = "A fact about Pasta"    // I used random information just as sample
    }
    else if (selectedFood == 3) {
       foodLabel.text = "Hot Dog"
       labelTwo.text = "Here will be more informations about Hot Dog"
       labelThree.text = "A fact about Hot Dog"  // I used random information just as sample
    }
    else if (selectedFood == 4) {
       foodLabel.text = "Burger"
       labelTwo.text = "Here will be more informations about Burger"
       labelThree.text = "A fact about Burger" // I used random information just as sample
    }
}

override func viewDidLoad() {
  super.viewDidLoad()
  // Do any additional setup after loading the view.

    foodPicker.delegate = self
    foodPicker.dataSource = self

    if (selectedFood == 0) {
       foodLabel.text = "Bread"
       labelTwo.text = "Bread is a staple food prepared from a dough of flour and water..."
       labelThree.text = "Bread is one of the oldest prepared foods..." // I used random information just as sample
    }
    else if (selectedFood == 1) {
       foodLabel.text = "Pizza"
       labelTwo.text = "Here will be more informations about Pizza"
       labelThree.text = "A fact about Pizza"   // I used random information just as sample
    }
    else if (selectedFood == 2) {
       foodLabel.text = "Pasta"
       labelTwo.text = "Here will be more informations about Pasta"
       labelThree.text = "A fact about Pasta"    // I used random information just as sample
    }
    else if (selectedFood == 3) {
       foodLabel.text = "Hot Dog"
       labelTwo.text = "Here will be more informations about Hot Dog"
       labelThree.text = "A fact about Hot Dog"  // I used random information just as sample
    }
    else if (selectedFood == 4) {
       foodLabel.text = "Burger"
       labelTwo.text = "Here will be more informations about Burger"
       labelThree.text = "A fact about Burger" // I used random information just as sample
    }
}

func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    return food[row]
}

func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return food.count
}

public func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
    return 1
}

func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

    selectedFood = row
}

}

So when I choose Pizza, whenever I run my app I want to be it Pizza, if I select another one for example Pasta, I want to be that one Pasta.
Can you please help me ?

A:

WBMDDrugManagerErrorCodeSave the selection like so:
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    NSUserDefaults.standardUserDefaults().setInteger(row, forKey: "choosenFood")
    NSUserDefaults.standardUserDefaults().synchronize()
    self.setLabelsForChoice(row)
}

Retrieve the chosen selection like so:
override func viewWillAppear() {
    super.viewWillAppear()
    if let previousSelection:Int = NSUserDefaults.standardUserDefaults().integerForKey("choosenFood") as? Int{
        self.setLabelsForChoice(previousSelection)
    }
}

Create a label update method similar to this:
func setLabelsForChoice(_choice:Int){
    switch _choice{
        case 0:
            foodLabel.text = "Bread"
            labelTwo.text = "Bread is a staple food prepared from a dough of flour and water..."
            labelThree.text = "Bread is one of the oldest prepared foods..."
            break
        case 1:
            foodLabel.text = "Pizza"
            labelTwo.text = "Here will be more informations about Pizza"
            labelThree.text = "A fact about Pizza"
            break
        default:

            break
    }

}


Q:

PHP: Using hidden GET variable as login?

I'm looking at doing a very basic authentication script as follows:
<?php
   // admin.php
   session_start();

   if($_GET['login'] == 'adminLoginWord')
   {
       $_SESSION['auth'] = true;
   }

   if($_SESSION['auth'])
   {
       // code to show Admin control panel
   }
   else
   {
       echo 'Please login.';
   }

Therefore, to login, someone would need to know to navigate to the URL
admin.php?login=adminLoginWord

Is this a safe way of authentication?

A:

It's not safe at all, you would leave the "password" in the computer's history, it would be very vulnerable to anyone sniffing... etc
This said, safe always depends on the application, but if you want a safer approach, use a POST variable and compare it like so:
if($_POST['pass'] == 'password123'){
    echo 'Login OK';
}

(Which still isn't the best approach, but it's better than a GET variable)

A:

In this case in particular, I was just being thick, and making it more complicated than needs be.
A .htaccess file was more than sufficient for this... woops!


Q:

Drupal 7 how to use item menu as MENU_LOCAL_TASK and MENU_NORMAL_ITEM simultaneous?

I have hook_menu with 3 pages they are defined by default as MENU_NORMAL_ITEMs and I see them from in main menu:

$items['accounting'] = [
    'title' => 'Accounting',
    'page callback' => 'accounting_extras_unprocessed_page',
    'access arguments' => ['access accounting extras'],
    'file' => 'accounting.pages.inc',
    'type' => MENU_NORMAL_ITEM,
    'menu_name' => 'main-menu',
    'weight' => 10,
  ];

  $items['accounting/extras'] = [
    'title'   => 'Extras',
    'page callback' => 'accounting_extras_unprocessed_page',
    'access arguments' => ['access accounting extras'],
    'file' => 'accounting.pages.inc',
    'weight'  => 0,
    'menu_name' => 'main-menu',
  ];

  $items['accounting/report'] = [
    'title'            => 'Report',
    'page callback'    => 'drupal_get_form',
    'page arguments'   => ['accounting_report_form', 'report'],
    'access arguments' => ['access accounting report'],
    'file'             => 'forms/accounting_report.inc',
    'weight'           => 1,
    'menu_name'        => 'main-menu',
  ];

  $items['accounting/transfer'] = [
    'title'            => 'Internal transactions',
    'page callback'    => 'drupal_get_form',
    'page arguments'   => ['accounting_report_form', 'transfer'],
    'access arguments' => ['access accounting report'],
    'file'             => 'forms/accounting_report.inc',
    'weight'           => 2,
    'menu_name'        => 'main-menu',
  ];

But I also need to see them as MENU_LOCAL_TASK and if I add type = MENU_LOCAL_TASK then they disappear from menu and appear as local tasks

What to do to see them in both places? Thank you.

A:

You can use a bitwise operator for that, e.g.
MENU_LOCAL_TASK | MENU_NORMAL_ITEM

There's a real-world example in the core comment module (comment_menu()):
$items['admin/content/comment'] = array(
  'title' => 'Comments',
  'description' => 'List and edit site comments and the comment approval queue.',
  'page callback' => 'comment_admin',
  'access arguments' => array('administer comments'),
  'type' => MENU_LOCAL_TASK | MENU_NORMAL_ITEM,
  'file' => 'comment.admin.inc',
);


Q:

How to fix "Could not initialize DirectSoundCapture" in Android Studio

I was just using Android Studio without issue and then one of the times I ran the project I got a list of errors saying "Emulator: dsound: Could not initialize DirectSoundCapture".
I have already looked up the issue and tried updating windows, updating android studio, updating drivers, un-ticking the "Enable instant run to hot swap code/resource changes on deploy" box in the settings, going to windows settings and enabling the microphone to be used by apps and I can't find any solution.
10:02 PM    Emulator: dsound: Could not initialize DirectSoundCapture

10:02 PM    Emulator: dsound: Reason: No sound driver is available for use, or the given GUID is not a valid DirectSound device ID

10:02 PM    Emulator: dsound: Attempt to initialize voice without DirectSoundCapture object

10:02 PM    Emulator: dsound: Attempt to initialize voice without DirectSoundCapture object

10:02 PM    Emulator: audio: Failed to create voice `goldfish_audio_in'

10:02 PM    Emulator: C:\Users\Joseph\AppData\Local\Android\Sdk\emulator\qemu\windows-x86_64\qemu-system-x86_64.exe: warning: opening audio input failed

10:02 PM    Emulator: dsound: At

10:02 PM    Emulator: tempt to initialize voice without DirectSoundCapture object

10:02 PM    Emulator: dsound: Attempt to initialize voice without DirectSoundCapture object

10:02 PM    Emulator: audio: Failed to create voice `adc'

10:02 PM    Emulator: dsound: Attempt to initialize voice without DirectSoundCapture object

10:02 PM    Emulator: dsound: Attempt to initialize voice without DirectSoundCapture object

10:02 PM    Emulator: audio: Failed to create voice `adc'

The emulator just has a black screen and won't do anything else, I don't care if the emulator makes sound or not I just want to see the visuals.

A:

Easy Fix....
i am running windows 10 but should be same for other versions.
Right click the audio icon at bottom right and click open sound settings then under the input section in the right window pane click manage sound devices and then enable stereo mix under input devices...
now the emulator will run without the audio error..

A:

I managed to fix the issue by plugging my microphone back into my computer. Not sure why that causes the issue but once plugged back in, the errors disappeared. The black screen still appeared but I made another virtual device in AVD manager and used that which worked fine.


Q:

Javascript Xpath and default namespaces

I have some JavaScript/Xpath which isn't working as I would expect. (available on jsfiddle) It would seem that I'm doing something wrong with an XML namespace, preventing me from querying for my elements by their node (tag) names.
If I try querying for all child nodes of the current node, I find the element myElement without problem:
    var xpathResult = xmlDoc.evaluate( "child::*", rootElement, nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);
    var queryEl;
    if(queryEl = xpathResult.iterateNext()) {
        alert("child::* found element " + queryEl.nodeName);
    }
    else {
        alert("child::* found nothing!");
    }

... but if I specifically target the nodes with myElement node (tag) names I get no results:
    /* Now try getting only those children with nodeName `myElement` */
   xpathResult = xmlDoc.evaluate( "child::myElement", rootElement, nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);
    var queryEl;
    if(queryEl = xpathResult.iterateNext()) {
        alert("child::myElement found element " + queryEl.nodeName);
    }
    else {
        alert("child::myElement found nothing!");
    }

What am I doing wrong?

A:

Try this as your resolver:
var nsResolver = (function (element) {
    var
      nsResolver = element.ownerDocument.createNSResolver(element),
      defaultNamespace = element.getAttribute('xmlns');

    return function (prefix) {
       return nsResolver.lookupNamespaceURI(prefix) || defaultNamespace;
    };
} (xmlDoc.documentElement));

You will also have to select the elements like this:
"child::default:myElement"
// where 'default' can be anything, as long as there is a namespace

Further reading:

https://developer.mozilla.org/en/DOM/document.createNSResolver
https://developer.mozilla.org/en/Introduction_to_using_XPath_in_JavaScript (=> Implementing a Default Namespace Resolver)
http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathNSResolver-lookupNamespaceURI

Your fiddle: http://jsfiddle.net/chKZc/5/  (updated)


Q:

Redondear con 2 decimales en C++

En el HUD de mi juego muestro el tiempo (tipo: float), pero necesito que sea mm:ss, es decir, 2 decimales después de la coma.
float timeReal = 12.342334;

float timeRedondeado = ...

Como puedo guardarlo con 2 decimales?

A:

¿Cómo puedo guardarlo con 2 decimales?

No puedes.

Los números con decimales no funcionan así.
Los números en coma flotante no guardan valores hasta cierto número de decimales si no que guardan un número expresado en índice y exponente guardado de forma binaria.
En C++ se sigue el estándar del IEEE para aritmética en coma flotante en que cada número está representado de la siguiente manera:

r = c × be

Siendo:

c El coeficiente del número.
b La base.
e El exponente entero, el cual eleva la base a una potencia.

Así pues, el número -12,345 (r) podría representarse como -12345 (b) × 10-3 (e).
Cambia de estrategia.

En el HUD de mi juego muestro el tiempo (tipo: float), pero necesito que sea mm:ss, es decir, 2 decimales después de la coma.

Tienes un problema de concepto: los segundos no son decimales de minutos (un minuto no es 1/10 de hora si no 1/60) así que deberías hacer conversiones de tiempo teniendo la diferente proporción:

0,75 minutos son 45 segundos.
0,5 minutos son 30 segundos.
0,33 minutos son 20 segundos.
0,2 minutos son 12 segundos.
0,1 minutos son 6 segundos.
...

Pero tranquilo, no necesitas hacer ninguna conversión, C++ dispone de la librería <chrono> que te permite trabajar con unidades de tiempo:
auto tiempo = std::chrono::system_clock::now();
auto formato = std::chrono::system_clock::to_time_t(now);

std::stringstream ss;
ss << std::put_time(std::localtime(&formato), "%M:%S");

El código anterior captura la hora actual (en la variable tiempo) y le aplica el formato mm:ss usando std::put_time, para obtener la cadena de caracteres llama a stringstream::str.


Q:

How Make Conditional Row Connector in Talend?

I have a Talend job where I have a Postgres input component running a row connector into a tFileOutputDelimited control so I can write the results of the database query to a CSV file with a header line. When there are no rows resulting from the query, it still writes the CSV file with just the header line. I'd prefer it did not write the file at all.
How can I put a condition on the row connector, or refactor this flow, so that it does not run the tFileOutputDelimited component when the Postgres query yields 0 rows?

A:

Check the option "do not generate empty file" on the tFileOutputDelimited' advanced settings. When there are no rows, the file won't be created.


Q:

Catch an exception in embedded mono

MonoObject * pException = NULL;
// this method will cause an exception in c#, something like null exception
MonoString * pResult = (MonoString*) mono_runtime_invoke(g_pGetMethod, NULL, monoargs, &pException);
/* debugging with gdb:
    (gdb) n
    Program received signal SIGPWR, Power fail/restart.
    then this program stopped.
*/
char * szResult = NULL;
if(pException == NULL)
{
    szResult = mono_string_to_utf8(pResult);
} else
{
    //MonoString * pMsg = mono_object_to_string_ex(pException, NULL);
    //szResult = mono_string_to_utf8(pMsg);
    szResult = "Mono throwed an Exception!";
}

i'm trying to catch MonoException like the above,
is there something i've mistaken?
g_pGetMethod is a static function btw, these code works correctly if no exception thrown

A:

You should instruct gdb to ignore SIGPWR (and a few more signals):
handle SIGXCPU SIG33 SIG35 SIGPWR nostop noprint

More information about debugging Mono with gdb can be found here: http://www.mono-project.com/docs/debug+profile/debug/


Q:

Notification error

Is there any way to launch custom errors in the admin site like that?:

Currently I throw the error with
raise forms.ValidationError('error')

but shows the debug error screen

A:

Where are you putting the raise forms.ValidationError('error')?
In your form clean() method is a good place to raise custom errors. You can even do def clean_fieldname() to preform specific validation for one field. From the django docs
from django import forms

    class ContactForm(forms.Form):
        # Everything as before.
        ...

        def clean_recipients(self):
            data = self.cleaned_data['recipients']
            if "fred@example.com" not in data:
                raise forms.ValidationError("You have forgotten about Fred!")

            # Always return the cleaned data, whether you have changed it or
            # not.
            return data

This link also could help


Q:

Kill another process/application programmatically

I don't want to get on the discussion of whether a process can be killed by the user, whether it should be done that way or not.
I just want to know how almost every Android player's phone got a 'advanced task killer' which kills a process or how is it that the force close (in settings) option works just fine. I have tried many ways to kill a process, but all without result. But when I see these 'advanced task killer' I can't figure out what's wrong on my side.

A:

You can use the killBackgroundProcesses() method of ActivityManager:
    ActivityManager am = (ActivityManager) getSystemService(Activity.ACTIVITY_SERVICE);
    am.killBackgroundProcesses(packageName);

Please, note that your app needs to own the KILL_BACKGROUND_PROCESSES permission. Thus, in the AndroidManifest.xml, you need to include:
<uses-permission android:name="android.permission.KILL_BACKGROUND_PROCESSES" />


Q:

Finding which service has run an executable in C#

I was wondering if it were possible to find out which windows service has run an executable?
I've got two different services running from the same exe, doing different things. The main method of the program detects a command line parameter and will either start the console app (if running in Environment.UserInteractive), or start one of the two possible services. I can't find a good way to discern which service is running so I can choose the correct service to start in the code. Passing in .exe parameters in the image path of the windows service doesn't seem to work. The services are running on a server and starting automatically, so doing it manually isn't really an option.
I'd really like to avoid having to have two different projects with different executables, so any way I can notify the program of which service to run would be great.

A:

You can pass arguments in the ImagePath.  I know I have done it at some point using a .net windows service, but as I recall, I had to install the service using something other than the standard .Net installer.
The .Net installer adds quotes around whatever you pass, which makes ImagePath go from C:\test\test.exe -arguments to "C:\test\test.exe -arguments" when it should be "C:\test\test.exe" -arguments.
Check out WiX, sc.exe or CreateService to get the correct registry value.
To test, install your service as usual and browse in regedit to HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\yourServiceName and edit ImagePath.  For an example of how it should look, check out HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\seclogon.


Q:

Как можно сделать табы

Скажите как можно сделать табы

A:

<!DOCTYPE html>

<meta name="viewport" content="width=device-width, initial-scale=1">

Tabs

Click on the buttons inside the tabbed menu:

  <button class="tablinks" onclick="openCity(event, 'London')">London</button>
  <button class="tablinks" onclick="openCity(event, 'Paris')">Paris</button>
  <button class="tablinks" onclick="openCity(event, 'Tokyo')">Tokyo</button>

London

London is the capital city of England.

Paris

Paris is the capital of France.

Tokyo

Tokyo is the capital of Japan.

How To Create Tabs


Q:

AVCaptureVideoPreviewLayer orientation - need landscape

My app is landscape only. I'm presenting the AVCaptureVideoPreviewLayer like this:
self.previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:session];
[self.previewLayer setBackgroundColor:[[UIColor blackColor] CGColor]];
[self.previewLayer setVideoGravity:AVLayerVideoGravityResizeAspect];
NSLog(@"previewView: %@", self.previewView);
CALayer *rootLayer = [self.previewView layer];
[rootLayer setMasksToBounds:YES];
[self.previewLayer setFrame:[rootLayer bounds]];
    NSLog(@"previewlayer: %f, %f, %f, %f", self.previewLayer.frame.origin.x, self.previewLayer.frame.origin.y, self.previewLayer.frame.size.width, self.previewLayer.frame.size.height);
[rootLayer addSublayer:self.previewLayer];
[session startRunning];

self.previewView has a frame of (0,0,568,320), which is correct. self.previewLayer logs a frame of (0,0,568,320), which is theoretically correct. However, the camera display appears as a portrait rectangle in the middle of the landscape screen, and the orientation of the camera preview image is wrong by 90 degrees. What am I doing wrong? I need the camera preview layer to appear in the full screen, in landscape mode, and the image should be orientated correctly.

A:

BEST ANSWER FOR SWIFT 3.0 AND XCODE 8.0

private func updatePreviewLayer(layer: AVCaptureConnection, orientation: AVCaptureVideoOrientation) {

    layer.videoOrientation = orientation

    previewLayer.frame = self.view.bounds

}

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    if let connection =  self.previewLayer?.connection  {

        let currentDevice: UIDevice = UIDevice.current

        let orientation: UIDeviceOrientation = currentDevice.orientation

        let previewLayerConnection : AVCaptureConnection = connection

        if previewLayerConnection.isVideoOrientationSupported {

            switch (orientation) {
            case .portrait: updatePreviewLayer(layer: previewLayerConnection, orientation: .portrait)

            case .landscapeRight: updatePreviewLayer(layer: previewLayerConnection, orientation: .landscapeLeft)

            case .landscapeLeft: updatePreviewLayer(layer: previewLayerConnection, orientation: .landscapeRight)

            case .portraitUpsideDown: updatePreviewLayer(layer: previewLayerConnection, orientation: .portraitUpsideDown)

            default: updatePreviewLayer(layer: previewLayerConnection, orientation: .portrait)

            }
        }
    }
}

BEST ANSWER FOR SWIFT 2.2 AND XCODE 7.3
private func updatePreviewLayer(layer: AVCaptureConnection, orientation: AVCaptureVideoOrientation) {

    layer.videoOrientation = orientation

    previewLayer.frame = self.view.bounds

}

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    if let connection =  self.previewLayer?.connection  {

        let currentDevice: UIDevice = UIDevice.currentDevice()

        let orientation: UIDeviceOrientation = currentDevice.orientation

        let previewLayerConnection : AVCaptureConnection = connection

        if (previewLayerConnection.supportsVideoOrientation) {

            switch (orientation) {
            case .Portrait: updatePreviewLayer(previewLayerConnection, orientation: .Portrait)

            case .LandscapeRight: updatePreviewLayer(previewLayerConnection, orientation: .LandscapeLeft)

            case .LandscapeLeft: updatePreviewLayer(previewLayerConnection, orientation: .LandscapeRight)

            case .PortraitUpsideDown: updatePreviewLayer(previewLayerConnection, orientation: .PortraitUpsideDown)

            default: updatePreviewLayer(previewLayerConnection, orientation: .Portrait)

            }
        }
    }
}

A:

The default camera orientation is Landscape Left (home button one the left). You need to do two things here:
1- Change the previewLayer frame to:
self.previewLayer.frame=self.view.bounds;

You need to set the preview layer frame to the bounds of the screen so that the frame of the preview layer changes when the screen rotates (you cannot use frame of the root view because that does not change with rotation but the bounds of the root view do). In your example, you are setting the previewlayer frame to a previewView property which I do not see.
2- You need to rotate the preview layer connection with the rotation of the device. Add this code in viewDidAppear:
-(void) viewDidAppear:(BOOL)animated
{
  [super viewDidAppear:YES];

  //Get Preview Layer connection
  AVCaptureConnection *previewLayerConnection=self.previewLayer.connection;

  if ([previewLayerConnection isVideoOrientationSupported])
    [previewLayerConnection setVideoOrientation:[[UIApplication sharedApplication] statusBarOrientation]];
}

Hope this solves it.
Full Disclosure: This is a simplified version since you do not care if Landscape right or Landscape left.

A:

override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
    super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)
    if let connection = self.previewLayer?.connection {
        var currentDevice: UIDevice = UIDevice.currentDevice()
        var orientation: UIDeviceOrientation = currentDevice.orientation
        var previewLayerConnection : AVCaptureConnection = connection

        if (previewLayerConnection.supportsVideoOrientation) {
            switch (orientation) {
            case .portrait:
                previewLayerConnection.videoOrientation = AVCaptureVideoOrientation.portrait
            case .landscapeRight:
                previewLayerConnection.videoOrientation = AVCaptureVideoOrientation.landscapeRight
            case .landscapeLeft:
                previewLayerConnection.videoOrientation = AVCaptureVideoOrientation.landscapeLeft
            case .portraitUpsideDown:
                previewLayerConnection.videoOrientation = AVCaptureVideoOrientation.portraitUpsideDown

            default:
                previewLayerConnection.videoOrientation = AVCaptureVideoOrientation.portrait
            }
        }
    }
}


Q:

Objective C - Singleton not persisting data after App restart

I make a singleton like this:
+ (CurrentUser *)sharedInstance {
    static id sharedInstance = nil;

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc] init];
    });

    return sharedInstance;
}

It has a property called:
@property (nonatomic, strong) NSData *profilePicData;

I save an image like this:
[[CurrentUser sharedInstance] setProfilePicData:profilePictureData];

I load the image like this:
if ([[CurrentUser sharedInstance]profilePicData]) {

    self.profileImageView.image = [UIImage imageWithData:[[CurrentUser sharedInstance]profilePicData]];
}

The image shows up and everything is good, but when I restart the app and go to the same view controllers that contain this same code, the image no longer appears in the UIImageView. This leads me to believe the singleton is not persisting.
How do I persist the data across app restarts with a singleton object?

A:

The singleton instance is only alive while the app is running. You need to save profilePictureData to a file when it is set and then load it when the singleton gets created, once the app is run again.
For writing you can use [profilePicData writeToURL:atomically:]
Then in your singleton's initializer you should load this file into profilePicData again with  [NSData dataWithContentsOfURL:]
The URL used for writing must be the same you use for loading, and must be within your app's sandbox.
See NSData's documentation.


Q:

c++ type could not be resolved

I am working on a c++ program in Eclipse CDT.  I am using the gcc compiler on Ubuntu 13.  The program has two classes, Function, and Trial.  In one line of the Trial class, I am trying to allocate an array of Functions using new.  However, Eclipse is telling me that "type 'function' could not be resolved".  What's weird, is that in the same method, creating an instance of Function with  new does work.  I've included all of the files in case they will be useful, though probably just the Trial.cpp will.  The error is marked in the Trial::run method
Trial.cpp
#include "Trial.h"
#include "Function.h"
#include <string>
using namespace std;

Trial::Trial(long double* xs, long double* ys, int length, int popSize, double mutRate, int seed){
    this->xs=xs;
    this->ys=ys;
    this->length=length;
    this->popSize=popSize;
    this->mutRate=mutRate;
    this->seed=seed;
}
void Trial::run()
{
    Function* newArray =
            new Function[popSize]; //error here
    Function* f=new Function('x',0,0); //no error here
}

Trial::~Trial() {
    // TODO Auto-generated destructor stub
}

Trial.h
#ifndef TRIAL_H_
#define TRIAL_H_

#include "Function.h"

class Trial {
public:
    Trial(long double* xs, long double* ys, int length, int popSize, double mutRate, int seed);
    void run();
    virtual ~Trial();
private:
    long double* xs;
    long double* ys;
    int length;
    int popSize;
    double mutRate;
    int seed;
};

#endif /* TRIAL_H_ */

Function.h
#include <string>
#include <sstream>
using namespace std;

#ifndef FUNCTION_H_
#define FUNCTION_H_

class Function {
public:
    Function(char op, Function* l, Function* r);
    long double getValue(long double x);
    virtual ~Function();
    virtual string toString();
    static Function* makeFunction(int maxDepth);
    Function* clone();
    Function* breed(Function* other);
    void setNode(int i, Function* node);
    static double mutateChance;
    long double getFitness(long double* xs,long double* ys, int length);
private:
    Function* left;
    Function* right;
    char op;
    long double fitness;
    int getNumNodes();
    Function* getNode(int i);
    void mutate();
};

#endif /* FUNCTION_H_ */

Function.cpp  //This is a long one, and probably not important
#include "Function.h"
#include <sstream>
#include <iostream>
#include <cmath>
#include <cstdlib>
#define NUMBER_WEIGHT 1
#define OP_WEIGHT 5
#define X_WEIGHT 5
#define NUM_SWAPS 3
#define TOTAL 39
//Total is 5*OP_WEIGHT+X_WEIGHT+9*NUM_WEIGHT
using namespace std;

double Function::mutateChance=.01;

bool isOp(char c)
{
    return c=='+'||c=='-'||c=='*'||c=='/'||c=='^';
}
Function::Function(char op, Function* l, Function* r) {
    this->left=l;
    this->right=r;
    this->op=op;
}

Function::~Function() {
    // TODO Auto-generated destructor stub
    delete left;
    delete right;
}

string Function::toString()
{
    stringstream stream;
    if(isOp(op))
    {
        stream<<'('<<left->toString()<<op<<right->toString()<<')';
    }
    else
    {
        stream<<op;
    }
    return stream.str();
}
long double Function::getValue(long double x)
{
    switch(op)
    {
    /*case '0'://Zeroes are stupid.  adding/subtracting does nothing.  Dividing makes an error or zero.  Multiplying makes 0.  exponentiation makes 1, 0 or an error.
        return 0;*/
    case '1':
        return 1;
    case '2':
        return 2;
    case '3':
        return 3;
    case '4':
        return 4;
    case '5':
        return 5;
    case '6':
        return 6;
    case '7':
        return 7;
    case '8':
        return 8;
    case '9':
        return 9;
    case 'x':
        return x;
    case '+':
        return left->getValue(x)+right->getValue(x);
    case '-':
        return left->getValue(x)-right->getValue(x);
    case '*':
        return left->getValue(x)*right->getValue(x);
    case '/':
        return left->getValue(x)/right->getValue(x);
    case '^':
        return pow(left->getValue(x),right->getValue(x));
    }
    return 0.0;
}
char toOp(int i)
{
    char c=(char)i;
    bool found=false;
    for(int i=1;i<=9;i++)
        if(c<i*NUMBER_WEIGHT)
        {
            c=i+48;
            found=true;
            break;
        }
    if(!found)
    {
        c-=9*NUMBER_WEIGHT;
        if(c<X_WEIGHT)
        {
            c='x';
            found=true;
        }
    }
    if(!found)
    {
        c-=X_WEIGHT;
        for(int i=1;i<=5;i++)
            if(c<i*OP_WEIGHT)
            {
                switch(i)
                {
                case 1:
                    c='+';
                    break;
                case 2:
                    c='-';
                    break;
                case 3:
                    c='*';
                    break;
                case 4:
                    c='/';
                    break;
                case 5:
                    c='^';
                    break;
                }
                break;
            }
    }
    return c;
}
Function* Function::makeFunction(int maxDepth)
{
    char c;//first are numbers, then x, then the operators, +-*/^
    if(maxDepth==0)
        c=rand()%(10*NUMBER_WEIGHT);
    else
        c=rand()%(10*NUMBER_WEIGHT+5*OP_WEIGHT);
    c=toOp(c);
    if(isOp(c))
        return new Function(c,makeFunction(maxDepth-1),makeFunction(maxDepth-1));
    else
        return new Function(c,0,0);
}
Function* Function::clone()
{
    if(isOp(op))
        return new Function(op,left->clone(),right->clone());
    else
        return new Function(op,0,0);
}
Function* Function::getNode(int i)
{
    if(i==0)
        return this;
    int l=left->getNumNodes();
    if(i<=l)
        return left->getNode(i-1);
    else
        return right->getNode(i-l-i);
}
void Function::setNode(int i, Function* node)
{
    node=node->clone();
    int l=left->getNumNodes();
    if(i==1)
        right=node;
    else if(i==l+1)
        left=node;
    else if(i<=l)
        left->setNode(i-1,node);
    else
        right->setNode(i-l-1,node);
}
int Function::getNumNodes()
{
    if(isOp(op))
        return 1+left->getNumNodes()+right->getNumNodes();
    else
        return 1;
}
double randDouble()
{
    return 1.*rand()/RAND_MAX;
}
void Function::mutate()
{
    if(isOp(op))
        do
            op=toOp(rand()%TOTAL);
        while(!isOp(op));
    else
        do
            op=toOp(rand()%TOTAL);
        while(isOp(op));
}
Function* Function::breed(Function* other)
{
    Function* child;//The mom is copied, then functions form the dad are switched in
    Function* dad;
    if(rand()%2)
    {
        child=this->clone();
        dad=other;
    }
    else
    {
        child=other->clone();
        dad=this;
    }
    int num=dad->getNumNodes();
    for(int i=0;i<NUM_SWAPS;i++)
        child->setNode(1+rand()%(child->getNumNodes()-1),dad->getNode(rand()%num));
    num=child->getNumNodes();
    for(int i=0;i<num;i++)
        if(randDouble()<mutateChance)
            child->getNode(i)->mutate();
    return child;
}

long double Function::getFitness(long double* xs, long double* ys, int length)
{
    long double total=0;
    for(int i=0;i<length;i++)
        total+=abs(ys[i]-this->getValue(xs[i]));
    total/=length;
    this->fitness=total;
    return total;
}

A:

The new[] operator requires a public default constructor. Class Function doesn't provide one (since Function has a user-defined constructor, the compiler doesn't autogenerate a default constructor). Change that and it shall work.
Btw, you don't need to #include "Function.h" in Trial.h: it's not needed.


Q:

Get list related objects

I have model like (it is many to many relation):
class User(models.Model):
    name = moddels.CharField(max_length=255)

class MyModel(models.Model):
    user1 = models.ForeignKey(User, related_name='user_set')
    user2 = models.ForeignKey(User)

I want get for some user list objects which related to user2 field. How i can do it?
I can't use ManyToMany field.

A:

You might not be able to get the whole user objects in one query, but you could get the ids of the related user2:
user2_ids = request.user.user_set.all().values_list('user2', flat=True).distinct()

If you really need whole objects, you could do one more step:
user2s = User.objects.filter(id__in=user2_ids)


Q:

Having trouble proving relation is not necessary for RMS real-time scheduling to be true.

I can see how to solve the right side of the equation but when not knowing what C and T are how can I prove it is not necessary and confirm it is sufficient?
I thought about changing the C/T to a variable such as x and starting from N = 1 and solving for x at each step until the RHS is not >= to the LHS.  Is this a correct way to go about this?

A:

As the questions stated the bound you provided n(2^(1/n)-1) is sufficient in the sense that if it is true then the set of tasks is schedulable but it is not complete, it will reject task sets that are still schedulable under RMS.  A simple example is a harmonic task set.  A harmonic task set is one where each period is is an exact multiple of all the tasks with small periods.  A trivial example is the task set of two tasks each with a capacity of 1 and a period of 2.  It has 100% utilization and is schedulable under RMS but its utilization is greater than the percentage 0.828 listed in the chart for N=2.
In general, to determine if a task set is schedulable under RMS the follow recurrence relationship is solved for each task i:

If this value is less than T_i for each task assuming implicit deadlines) than the task set is schedulable.


Q:

After upgrade of Virtual Box, kernel sources are missing

I did upgrade VirtualBox from 4.1 to 4.2
wheneverver I want to load my Win XP VDI, it gives me the following error:

Kernel driver not installed (rc=-1908)

The VirtualBox Linux kernel driver (vboxdrv) is either not loaded or there is a permission problem with /dev/vboxdrv. Please reinstall the kernel module by executing
/etc/init.d/vboxdrv setup

as root. If it is available in your distribution, you should install the DKMS package first. This package keeps track of Linux kernel changes and recompiles the vboxdrv kernel module if necessary.
I ran the suggested step to reinstall the kernel module, and the log file is as follow:
Makefile:181: *** Error: unable to find the sources of your current Linux kernel. Specify KERN_DIR=<directory> and run Make again.  Stop.
Makefile:181: *** Error: unable to find the sources of your current Linux kernel. Specify KERN_DIR=<directory> and run Make again.  Stop.
Makefile:181: *** Error: unable to find the sources of your current Linux kernel. Specify KERN_DIR=<directory> and run Make again.  Stop.

I still unable to re-run my win virtual XP vdi file.
Anyone have any clue?

A:

Looks like you don't have the kernel headers installed, dkms needs then to install the Virtual Box kernel drive, to install then run:
sudo apt-get install linux-headers-`uname -r`

Afterwards,
/etc/init.d/vboxdrv setup

should work.


Q:

Perl looping through hash of arrays for single elements

I have a hash of arrays, as shown:
my %hash = (
  234 => ["aa", "bb", "aa", "ab", "aa"],
  235 => ["aa", "ab", "aa", "bb", "aa"],
  236 => ["bb", "aa", "aa", "aa", "bb"],
  ...
)

I am trying to go through each values's first element and count the number of occurrences of bb.
For example, in the hash above, I have one occurrence bb for all the first elements shown. I need to push that number (the number of "bb"s in the 0th element of all arrays) into a new array and then move to the next set of elements.
For the example above, I would loop through all 4 elements of the arrays and get a final array with (1, 1, 0, 1, 1).
I'm having a lot of trouble getting the code right and haven't yet found a similar question. Any help would be much appreciated.

A:

A simple solution: iterate over the hash values. For each value, iterate over the members of the array and add 1 to a resulting array if needed:
#!/usr/bin/perl
use warnings;
use strict;

my %hash = (234 => [qw/aa bb aa ab aa/],
            235 => [qw/aa ab aa bb aa/],
            236 => [qw/bb aa aa aa bb/],
           );

my @result;

for my $value (values %hash) {
    my $i = 0;
    for (@$value) {
        $result[$i++] += 'bb' eq $_;
    }
}

print "@result\n";


Q:

What is User Data Access_14d4fe service and how can I get rid of it?

I see a strange service in my windows 10 system called "User Data Access_14d4fe", with internal service name UserDataSvc_14d4fe.
The path to executable is C:\WINDOWS\system32\svchost.exe -k UnistackSvcGroup
I believe it has something to do with Windows Store applications. Can I stop it? Unregister it? What does it do?  Its description says "Provides apps access to structured user data, including contact info, calendars, messages, and other content. If you stop or disable this service, apps that use this data might not work correctly.".
I have stopped it and do not see anything not working, I assume it must be affecting something to do with Windows store?
I am unable to change the start up type from manual.  I can not disable, or delete it, even using the command line. Is there any way to get rid of this service completely in Windows 10?

A:

This is the User Data Access (UserDataSvc)Service which allows apps access user data, including contact info, calendars, messages, and other content. Apps need such a service because apps run in a sandbox and can't access the data the way like desktop applications would do it.
Leave it running and ignore it, sooner or later you'll run into issues when you stop the service.


Q:

How do I search for a string in a cell substring containing a string from another cell in SQL

I am looking to compare the results of 2 cells in the same row. the way the data is structured is essentially this:
Col_A: table,row,cell
Col_B: row

What I want to do is compare when Col_A 'row' is the same as Col_B 'row'
SELECT COUNT(*) FROM MyTable WHERE Col_A CONTAINS Col_B;

sample data:
Col_A: a=befd-47a8021a6522,b=7750195008,c=prof
Col_B: b=7750195008

Col_A: a=bokl-e5ac10085202,b=4478542348,c=pedf
Col_B: b=7750195008

I am looking to return the number of times the comparison between Col_A 'b' and Col_B 'b' is true.

A:

This does what I was looking for:
SELECT COUNT(*) FROM MyTable WHERE Col_A LIKE CONCAT('%',Col_B,'%');


Q:

It won't override class

If user didn't enter the fields properly, it will show the error message with class="ErrorInput" and class="TextError".
I am having a problem with ErrorInput class, when it has been defined in the html tag - it will not override the default input class.
HTML:

  First Name
   <input type="text" value="" class="ErrorInput" name="firstname">

Please enter First Name

   Second Name
   <input type="text" value="Gates" name="secondname">

CSS:
.FormStyle .ErrorInput {
    border: #AD2930;
}

.FormStyle input[type=text], .FormStyle textarea {
    padding: 3px;
    display: inline-block;
    width: 290px;
    border: 1px solid #BDC7D8;
    margin: 0;
    font-size: 12px;
}

A:

You are defining border-colour for the input in both .FormStyle .ErrorInput and .FormStyle input[type=text]
As .FormStyle input[type=text] is more specific than .FormStyle .ErrorInput, the #BDC7D8 colour is applied.
You will need to make the first CSS selector more specific for it to override the second colour:
.FormStyle input[type=text].ErrorInput {
    border-color: #AD2930;
}

Learn more about specificity here: http://coding.smashingmagazine.com/2007/07/27/css-specificity-things-you-should-know/


Q:

Counting whitespaces -argc/argv in C

I would like to count whitespaces, like ' ' (ASCII SP or 32). I have to pass the arguments using the command line. So for example, I enter Hello  World and would like to receive the amount of whitespaces, in this case the result should be 2.
I already tried following:
Text = Hello  World
#include <stdio.h>
#include <string.h>

int main(int argc, char* argv[]){
    int spaces = 0;
    char* mystring = argv[1];
    int size = strlen(argv[1]) + strlen(argv[2]);
     for(int i = 0; i < size; i++){
         if((*(mystring + i)) == ' '){
             spaces++;
             printf("%d\n", spaces);
         }
     }
}

I know that *(argv + 1) is Hello ( or ASCII number) and *(argv + 2) = World and thats the problem I do have. How can I count the spaces between the argv[n]? The amount of whitespaces can be different, so therefore I don't want to code like If(argc > 1){ spaces++;}.
Can someone help?
Best regards,
Keita

A:

If you execute:
$ a.out Hello      world # There are 5 spaces between both args here.

the shell is going to extract the arguments to the command by splitting the input command into arguments at the positions of a sequence os spaces (a contiguous sequence of spaces, tabs and/or newlines), and comments (like the above one) are eliminated from imput, so if you issue the command above, you'll get an argv like this:
int argc = 3;
char *argv[] = { "a.out", "Hello", "world", NULL, };

in case you use quotes to delimit arguments, you can issue
$ a.out "Hello     world"  # there are also 5 spaces between the words.

and it that case you will get something like:
int argc = 2;
char *argv[] = { "a.out", "Hello     world", NULL, };

In that case you'll get the spaces into the arguments.
Important
You don't check the number of arguments passed to a.out so in the case you post, you can be trying to pass NULL pointer to strlen() which will result in Undefined Behaviour.  This is an error, for your program to work correctly you might do the following (i have corrected some other errors and commented them in comments in your code):
#include <stdio.h>
#include <string.h>

int main(int argc, char* argv[])
{
    int spaces = 0;
    int arg_ix;  /* index of the argument to consider */
    for (arg_ix = 1; arg_ix < argc; arg_ix++) { /* so we don't check more arguments than available */
        char *mystring = argv[arg_ix];
        int size = strlen(mystring);
        for(int i = 0; i < size; i++) {
            if(mystring[i] == ' '){  /* why use such hell notation? */
                spaces++;
            }
        }
    }
    printf("%d\n", spaces); /* print the value collected at the end, not before */
}

and this code could be simplified (taking advantage of mystring being a pointer, by moving the pointer until we reach the end of string (pointing to a \0 char) with this approach (it also avoids to compute the string length, which makes another pass on the string ---unnecessary)
#include <stdio.h>
/* string.h is not needed anymore, as we don't use strlen() */

int main(int argc, char* argv[]){
    int spaces = 0;
    int arg_ix;
    for (arg_ix = 1; arg_ix < argc; arg_ix++) {
        char* mystring = argv[arg_ix];
        for( /* empty */; *mystring != '\0'; mystring++) {
            if(*mystring == ' '){
                spaces++;
            }
        }
     }
     printf("%d\n", spaces);
}

and finally, you have a <ctype.h> header with functions like isspace(c) to check if a character is a space (in this case, it checks for space and tab characters.
#include <stdio.h>
#include <ctype.h>

int main(int argc, char* argv[]){
    int spaces = 0;
    int arg_ix;
    for (arg_ix = 1; arg_ix < argc; arg_ix++) {
        char* mystring = argv[arg_ix];
        for(; *mystring != '\0'; mystring++) {
            if(isspace(*mystring)){
                spaces++;
            }
        }
     }
     printf("%d\n", spaces);
}


Q:

Python Decrement Dictionary

can I decrement a value in a dictionary ? I have a dict with string key and int value, how to decrement all value's key ?
d={'A': 0, 'B' : 1, 'C' : 2, 'D' : 3}
d.pop('B')
##How to decrement values after 'B' ?

A:

Assuming that 'after B' means the keys lexicographically following 'B' in this case, this snippet should work:
d={'A': 0, 'B' : 1, 'C' : 2, 'D' : 3}
d.pop('B')
for k in d.keys():
    if k > 'B':
        d[k] -= 1


Q:

Does RefCell::borrow move the contents?

I have a linked-list sort of struct, using Option, Rc, and RefCell.
I'd like to implement fmt::Debug for it, but have run into the lovely "cannot move out of borrowed content" error.
use std::fmt;
use std::rc::{Rc, Weak};
use std::cell::RefCell;

#[derive(Clone, Debug, Ord, Eq, PartialOrd, PartialEq)]
struct NodeId {id: String}

impl NodeId {
    pub fn new(s: &str) -> NodeId { NodeId{id: s.to_string()}}
}

struct NodeInfo {
    nodeid: NodeId,
    prev: Option<Rc<RefCell<NodeInfo>>>,
    next: Option<Rc<RefCell<NodeInfo>>>,
}

impl fmt::Debug for NodeInfo {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "NodeInfo( {} {} {} )", self.nodeid.id,
        match self.prev { None => "none".to_string(), Some(ref n) => n.borrow().nodeid.id},
        match self.next { None => "none".to_string(), Some(ref n) => "some".to_string()},
        )
    }
}

fn main() {}

Ideally the debug output would be able to show me the ids of the .next and .previous nodes. But Rust is not allowing access to them. The attempt to .borrow() the content of the RefCell causes the error, but I cannot understand why.
Play with it here: http://is.gd/Sah7sT

A:

Does RefCell::borrow() move the contents?

No. Calling it borrow and having it move would be pretty underhanded! ^_^
The problem is that you are trying to move the id out of your borrowed struct. This is a move because String isn't Copy:
n.borrow().nodeid.id

Instead, use clone to leave the current string where it is, and return a brand-new one:
n.borrow().nodeid.id.clone()

A:

To expand on @Shepmaster's answer (which is absolutely correct), you can avoid having to copy the string in this case, by writing the id of the child nodes directly to the formatter.
I've chosen to use a newtype to avoid repetition:
impl fmt::Debug for NodeInfo {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "NodeInfo( {} {:?} {:?} )", self.nodeid.id, ChildNode(&self.prev), ChildNode(&self.next))
    }
}

struct ChildNode<'a>(&'a Option<Rc<RefCell<NodeInfo>>>);

impl<'a> fmt::Debug for ChildNode<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self.0 {
            Some(ref n) => write!(f, "{}", n.borrow().nodeid.id),
            None        => write!(f, "None"),
        }
    }
}


Q:

how to check for duplicate values when creating a random string in Coldfusion?

I'm running Coldfusion8/MySQL 5.0.88 and have table with ids, which are random strings a-z 0-9
I want to avoid duplicate entries when creating new records in the table, but I'm not sure how to set it up correctly.
Here is what I have:
<cfset variables.listOfAppIds = "">

<!--- get all ids --->
<cfquery datasource="db" name="app_ids">
    SELECT app_id FROM apps
</cfquery>

<!--- create comma-separated list --->
<cfloop query="app_ids">
    <cfset variables.listOfAppIds = variables.listOfAppIds & "," & app_ids.app_id>
</cfloop>

<!--- create random string and test if it is in listOfAppIds --->
<cfloop condition="#ListFindNoCase(variables.listOfAppIds, variables.rndString, ',')#">
    <cfset variables.stringLength = 10>
    <cfset variables.stringList = "0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z">
    <cfset variables.rndString = "">
    <cfloop from="1" to="#variables.stringLength#" index="i">
        <cfset variables.rndNum = RandRange(1, listlen(variables.stringList))>
        <cfset variables.rndString = variables.rndString & listGetAt(variables.stringlist, variables.rndNum)>
    </cfloop>
    <cfset variables.current_appId = variables.rndString>
</cfloop>

Question:
I'm not sure I'm using the while-loop correctly. Will this make sure no duplicates are found?
Thanks for help!

A:

I would re-consider the approach. You could use a GUID and then not check at all (which a lot of apps do).
Or create the new random ID then query the DB to see if you have a collision. That way the database is handling the same logic for you. Your logic would then be:
collision=true;
while (collision=true) {
    newID=RandomIdFunction();
    SELECT app_id FROM apps where app_id = newID;
    if query had no rows, set collision=false;
}

That will become slower as the database fills up the the chance of collisions gets higher, that's why I'd probably use the GUID approach if you can.


Q:

Why are recursives methods useful for FIR filter design?

As I understand it, FIR filtering is a linear process. That mean for me that the whole filtering process will have a fully predictable behavior.
So, could someone explain why a universal deterministic and optimal filter design method  to obtain the desired response doesn't exist and why recursive approach seems to be of great interest in practice ?
EDIT: just to clarify, my question is about an "optimal" method, that is one which compute the shortest filter response while staying the closest to the design criteria.

A:

Sure, FIR filters are "simple" linear objects. But a typical FIR filter design task looks like this:

Find a set of numbers (the filter coefficients) such that the
  magnitude of their Discrete Fourier Transform is as close as possible to a
  target response. "As close as possible" being defined as "by
  minimizing the $L_\infty$ norm of the difference between ideal and actual
  response over some frequency ranges".

This is a non-linear, sometimes non-convex optimization problem and there is no universal, trivial procedure to solve those.
We have to use procedures like the Parks-McClellan algorithm because the real-world engineering constraints we want to impose when designing FIR filters do not translate into simple linear or quadratic constraints. For example, a least-square error criterion (L2 norm often leads to more tractable procedures than other norms...) would not be an acceptable choice for engineering applications, because it could allow solutions that are close to the required response on average, but with an outlier value.


Q:

Reset Android Studio settings to default setting on linux

everyone. I used to develop android application on Mac. Recently I installed android development environment on my Thinkpad which running Xubuntu.
I imported the Android studio settings on Mac to the  Android studio on Xubuntu via File-> import settings.
But after I have done this, everything goes wrong. The hotkey, the java path ecc.
I tried to delete android studio, and download it again, but the settings are still there.
On the internet I can find almost nothing about this, does anyone know how to reset Android Studio settings to default setting? Thanks!

A:

It's very simple. Depending on your AndroidStudio version, the settings are stored in ~/.AndroidStudio, ~/.AndroidStudio1.1 or ~/.AndroidStudio1.2.
Open a terminal and run the following code:
ls -a | grep Android # See which of those three folders above you have. Then rename each of the settings folders you have with the appropriate mv command:
mv .AndroidStudio .AndroidStudio.bak
mv .AndroidStudio1.1 .AndroidStudio1.1.bak
mv .AndroidStudio1.2 .AndroidStudio1.2.bak


Q:

Freeing subordinates?

typedef struct A
{
    int* whatever;
} A;

int main(void)
{
    A* foo = (A)malloc(sizeof(A));
    foo->whatever = (int)malloc(sizeof(int));
    free(A); // leak? (foo->whatever)
    return 0;
}

Do I have to free each component of a struct / composite data type, or can I just free the struct?

A:

Anything that is malloc'd needs to be freed


Q:

Connecting PHP5 to a Frontbase Database

Is there a way to connect PHP5 to a Frontbase database?
There seems to be an included connector, but it looks like that is not available anymore in PHP5:
http://php.net/manual/en/book.fbsql.php

A:

What OS are you using? What kind of PHP package are you using, i.e. if you are on *nix, are you perhaps using a prebuilt version of PHP?
If you can build your own version of PHP, you could perform the steps outlined here:
http://www.php.net/manual/en/fbsql.installation.php
(i.e. you need to build PHP with the --with-fbsql parameter)
If you're on Windows, you can find prebuilt binaries for Frontbase from the frontbase.com website itself, but they seem pretty outdated (the latest one is for PHP 4):
http://www.frontbase.com/cgi-bin/WebObjects/FBWebSite.woa/wa/mainFrame?currentMenu=downloadMenu&currentPage=Download&currentModule=Download&action=downloadArea


Q:

Max item quantity added to cart based on product category in Woocommerce

I am trying to customize the shop such that Category named Quantity4 allows only 4 items to be added in the cart and category named Quantity6 allows only items to be added in the cart.
As far as I can get, this can be achieved using nested if statements, but somehow this doesn't work.
add_filter( 'woocommerce_add_to_cart_validation', 'only_four_items_allowed_add_to_cart', 10, 3 );

function only_four_items_allowed_add_to_cart( $passed, $product_id, $quantity ) {

$cart_items_count = WC()->cart->get_cart_contents_count();
$total_count = $cart_items_count + $quantity;

if(has_term('quantity4','product_cat',$product_id )){
if($cart_items_count >= 4 || $total_count > 4){
        // Set to false
        $passed = false;
        // Display a message
        wc_add_notice( __( "You Chose a Box of 4 Items, Can't Add More", "woocommerce" ), "error" );
    }
  }

  else if (has_term('quantity6','product_cat',$product_id )){
    if($cart_items_count >= 6 || $total_count > 6){
        // Set to false
        $passed = false;
        // Display a message
        wc_add_notice( __( "You Chose a Box of 6 Items, Can't Add More", "woocommerce" ), "error" );
    }
}

return $passed;
}

Can someone pls point out what am I doing wrong here and how to get the desired results.

A:

I have revisited your code a bit and it's working. Please try this:
add_filter( 'woocommerce_add_to_cart_validation', 'only_four_items_allowed_add_to_cart', 10, 3 );
function only_four_items_allowed_add_to_cart( $passed, $product_id, $quantity ) {
    $cart_count = WC()->cart->get_cart_contents_count();
    $total_count = $cart_count + $quantity;

    if ( has_term( 'quantity4','product_cat',$product_id ) && ( $cart_count >= 4 || $total_count > 4 ) ) {
        $passed = false; // Set to false
        $notice = __( "You Chose a Box of 4 Items, Can't Add More", "woocommerce" ); // Notice to display
    }
    elseif ( has_term( 'quantity6','product_cat',$product_id ) && ( $cart_count >= 6 || $total_count > 6 ) ) {
        $passed = false; // Set to false
        $notice = __( "You Chose a Box of 6 Items, Can't Add More", "woocommerce" ); // Notice to display
    }
    if( ! $passed )
        wc_add_notice( $notice, 'error' );

    return $passed;
}

Code goes in function.php file of your active child theme (or active theme).
Tested and works.


Q:

Should a web service return an exception or an empty result when data is not found?

Should a web service return an exception or an empty result when data is not found?

A:

If no data is a normal and acceptable result (as it normally is), it should return an empty result set. You should only return an exception if an error/exception has occurred.

A:

A regular .net exception is a platform specific construct that should not be returned outside the webservice since the client calling upon the service might not implement such a thing, instead use a SoapException for exceptional circumstances
Is the empty result set something the client calling the webservice can recover from? If so I wouldn’t return the SoapException. If it’s something that’s so exceptional that it warrants a special handling logic then by all means do use the SoapException.
There resources might help you along

http://msdn.microsoft.com/en-us/library/ds492xtk(VS.71).aspx
http://www.developer.com/net/csharp/article.php/10918_3088231_1