Q: Understanding std::move and unique_ptr I am new to c++11 and trying to understand to meaning of std::move and unique_ptr and wrote the following code, which I use std::move on a unique_ptr in two different ways:
void unique_ptr_plain_move() {
  unique_ptr<int> intptr(new int(10));
  unique_ptr<int> intptr2;

  printf("*intptr = %d\n", *intptr);
  intptr2 = std::move(intptr);
  printf("*intptr2 = %d\n", *intptr2);
  // as expected, crash here as we have already moved intptr's ownership.
  printf("*intptr = %d\n", *intptr);
}

/////////////////////////////////////////////

void function_call_move(unique_ptr<int>&& intptr) {
  printf("[func] *intptr = %d\n", *intptr);
}

void unique_ptr_function_call_move() {
  unique_ptr<int> intptr(new int(10));

  printf("*intptr = %d\n", *intptr);
  function_call_move(std::move(intptr));
  // this does not crash, intptr still has the ownership of its pointed instance ....
  printf("*intptr = %d\n", *intptr);
}

In unique_ptr_plain_move(), intptr2 takes the ownership of intptr after std::move and therefore we can no longer use intptr.  However, in unique_ptr_function_call_move(), when using std::move in a function call, intptr still have its ownership of its pointed instance.  Can I know what exactly happened when we pass a std::move(unique_ptr) to a function?  Thank you.

A: The key concept here is that std::move by itself won't do any moving.
You can think of it as marking the object as a object that can be moved from.
The signature for function_call_move is
void function_call_move( unique_ptr<int>&& ptr );

Which means it can only receive objects that could be moved from, formally known as rvalues, and bind that to a reference. The act of associating an rvalue to a rvalue reference don't invalidate the state of the original object either.
So, unless function_call_move actually moves ptr to another std::unique_ptrinside it, your call to function_call_move(std::move(intptr)); won't invalidate intptr and your usage will be perfectly fine.


Q: Sampling method for constructing multiple groups from a given pool There is a set A having $N$ elements. Based on set A,  I would like to construct $M$ groups, where each group has $P$ elements. Naturally, $M P <N$.   All of those elements in the $M$ groups are sampled from set A by following the two criteria, they are different with each other; the sampling probability for each of these MP elements are the same.
Which kind of sampling method should I use? How to do that in R?

A: A <- LETTERS[1:20]
M <- 4
P <- 3
matrix(sample(A,size=M*P),nrow=M, ncol=P)

Then each row of the matrix gives you one group of size $P$. Alternatively, you can sample with replacement:
matrix(sample(A,size=M*P,replace=TRUE),nrow=M, ncol=P)


Q: Duplicating Cell Text Formating using Offset/Indirect I am attempting to create a "GUI" for my sheet with variable inputs options depending on other inputs. This means I have to summon the text from elsewhere using Offset() or Indirect() or similar functions. However, whenever I use those functions, all text formatting like bolding or subscripts are removed.
Example:
A1: "V∞,final"
A2: =indirect(A1) → "V∞,final"
Are there any functions or options in Excel for those sorts of formatting options to be carried over?


Q: Springboot jersey with multiple source paths (servlets) I am starting to use Springboot in my application. My web.xml looks like this
    <servlet>
        <servlet-name>Internal Tools</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>jersey.config.server.provider.packages</param-name>
            <param-value>in.playment.internal.api;in.playment.auditor.api</param-value>
        </init-param>
        <init-param>
            <param-name>jersey.config.server.provider.classnames</param-name>
            <param-value>org.glassfish.jersey.filter.LoggingFilter;org.glassfish.jersey.media.multipart.MultiPartFeature;in.playment.gateway.RequestFilter;in.playment.gateway.ResponseFilter;in.playment.gateway.DebugExceptionMapper;in.playment.gateway.security.Binder</param-value>
        </init-param>

        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>Internal Tools</servlet-name>
        <url-pattern>/v0/internal/*</url-pattern>
    </servlet-mapping>

    <servlet>
        <servlet-name>External Apis</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>jersey.config.server.provider.packages</param-name>
            <param-value>in.playment.rutherford.api;in.playment.payment.api;in.playment.payment.resource</param-value>
        </init-param>
        <init-param>
            <param-name>jersey.config.server.provider.classnames</param-name>
            <param-value>org.glassfish.jersey.filter.LoggingFilter;org.glassfish.jersey.media.multipart.MultiPartFeature;in.playment.gateway.RequestFilter;in.playment.gateway.ResponseFilter;in.playment.gateway.DebugExceptionMapper;in.playment.gateway.security.Binder;in.playment.payment.exception.PaymentExceptionMapper</param-value>
        </init-param>

        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>External Apis</servlet-name>
        <url-pattern>/api/*</url-pattern>
    </servlet-mapping>

I want to use two different base paths for urls. I have different packages and different exception mappers. How can I achieve this in Springboot embedded tomcat. So far, I am able to achieve only one of these. If I try to do two registries, it throws me Exception saying org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'org.glassfish.jersey.server.ResourceConfig' available: expected single matching bean but found 2: jerseyConfig,getResourceConfig


Q: SVG Rect Ignores Height? Here is a working demo of a rectangle. I'd like to move the height property to css and well, it doesn't work and gives me a blank. It happens in firefox and chrome.
Is there a different name for it? I don't understand why I can't use a css file. The fill color works.
Working example.
css:
rect {
    fill:rgb(0, 0, 255);
    /*doesnt work height:100;*/
}

html:
<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
    <rect width="100" height="100" style="stroke-width:1;stroke:rgb(0,0,0)"/>
</svg>

A: The width of a <rect> element isn't a CSS property in SVG, it's only usable as an attribute. It's for example like the size of a <select> element in HTML. You can only set it as an attribute.

A: SVG doesn't have a straightforward support for CSS for setting shape dimensions.
However there's a workaround for rects, which can also be used to generate horizontal and vertical lines:

*

*Set width and height to 1, and use CSS transform: scale(width, height)

*Don't specify x,y location, and use transform: translate(x, y)

E.g.

.svg {
  width: 100px;
  height: 30px;
}
.rectangle {
  transform: scale(30, 10);
  fill: orange;
}
.horiz-line {
  transform: translate(15px,5px) scale(50, 1);
  fill: red;
}
.vert-line {
  transform: translate(10px, 5px) scale(1, 30);
  fill: blue;
}
<svg>
  <rect class="rectangle" width="1" height="1" />
  <rect class="horiz-line" width="1" height="1" />
  <rect class="vert-line" width="1" height="1" />
</svg>

A: In SVG the x, y, width and height of <rect> elements are attributes rather than CSS properties. Only CSS properties can be styled using CSS.

A: workaround for symmetric rectangles:

rect:hover {
  stroke-width: 20 !important;
}
<svg width="100" height="100">
  <rect
    stroke-width="0"
    fill="blue" stroke="blue"
    x="30" y="30" width="40" height="40"
  />
</svg>

(darkreader will use different colors for stroke and fill)


Q: Can I develop Windows 8 Apps without installing 2012 Express for Windows 8?
Microsoft provides two free tools, designed to work together, that help you develop, test, and deploy Windows Store apps: Microsoft Visual Studio Express 2012 for Windows 8 and Blend for Visual Studio. (These tools require Windows 8.)

I already have too many IDE's on my box. One of them is Visual Studio 2012 Pro. If I want to develop Windows 8 Apps, expecially the HTML5 variety, do I really need to install that huge SDK along with Visual Studio Express 2012 for Windows 8?? Or can I just install some templates and add some nuget packages?

A: you can install the Windows 8 SDK http://msdn.microsoft.com/en-us/windows/desktop/hh852363.aspx


Q: Construct json with multiple identical keys in Qt5 I want to generate a json that looks like this:
{
    "myRepeatedKey": "test_data_1",
    "myRepeatedKey": "test_data_2",
    "myRepeatedKey": "test_data_3",
    "myRepeatedKey": "test_data_4"
}

using Qt5. My naive approach looks like this:
QVariantMap map;
map_fill["myRepeatedKey"]="test_data_1";
map_fill["myRepeatedKey"]="test_data_2";
map_fill["myRepeatedKey"]="test_data_3";
map_fill["myRepeatedKey"]="test_data_4";
QJsonDocument doc=QJsonDocument::fromVariant(map);
qDebug()<<doc.toJson();

Since this replaces data for the entry, this outputs (not surprisingly) this:
}
    "myRepeatedKey": "test_data_4"
}

So how could I do this in Qt5?
PS: According to RFC4627 it is recommended but not required for names in name/value pairs in json data to be unique, so even though what I am asking for is not recommended practice, I would still know how to do it.
Thanks!

A: I think adding duplicate keys is a bad idea. You should use json array (QJsonArray) in this case.
QJsonArray array;
array.append("test_data_1");
array.append("test_data_2");
array.append("test_data_3");
array.append("test_data_4");

QJsonObject o;
o["myArray"] = array;

QJsonDocument doc(o);
qDebug() << doc.toJson();

Output will be
{
    "myArray": [
        "test_data_1",
        "test_data_2",
        "test_data_3",
        "test_data_4"
    ]
}


Q: Wake on Lan on Ubuntu? There is a computer in lab I need to turn it on wakeonlan, I followed these instructions. I used gWakeOnLan tool to wake up the system. The default UDP port number is 9 and i checked from the website that port is blocked in my network. so i thought any other will work which are open in my network but nothing worked for me I tried 80, 443, 22, 23,20, 14000
Help!

A: You have to forward the external port to your internal network. You are most likely under a firewall/router that blocks incoming external connections.


Q: .Net Xml Deserialization I have the following XElement
  <Issue Type="Duplicate" Distance="1">
    <Record>
      <ID>6832</ID>
      <Name_First>JAMES </Name_First>
      <Name_Last>SMITH</Name_Last>
      <Company>SMITH CO.</Company>
    </Record>
    <Record>
      <ID>6831</ID>
      <Name_First>JAMES</Name_First>
      <Name_Last>SMITH</Name_Last>
      <Company>SMITH CO.</Company>
    </Record>
  </Issue>

I'm trying to Deserialize it into this object
public class Issue
{
    [XmlAttribute]
    public string Type { get; set; }

    [XmlArrayItem(typeof(XElement), ElementName = "Record")]
    public List<XElement> Record { get; set; }
}

The type works no problem, but I can't get the two Record nodes into the Record list of the object.
Is it possible without overriding ISerializable and writing custom code?

A: Try this:
public class Issue
{
    [XmlAttribute]
    public string Type { get; set; }

    [XmlAnyElement("Record")]
    public List<XElement> Record { get; set; }
}

I think that tells the serializer that multiple Record elements will go in the list.

A: Implement Record class which has ID, Name_First, Name_Last and Company fields


Q: Get Model name in a partial view Is there any way to get the name of current model in a partial view?
I want to do something like:
@if(Model.Name=="Something"){
....
}
else{
...
}

A: you can use try something like
@model.GetType().Name


Q: Make Selectable True for only given date range in React Big Calendar I am using React Big Calendar. By Default selectable true make the whole calendar selectable but I want to make only selectable true of given time and change the background color of that time range in the calendar. I am not willing to create event. Just make selectable true of given times.
Thanks

A: I found a solution that may help you to disable some dates , in my case , I needed to disable unavailability events, so I used  selectable="ignoreEvents"
         `<BigCalendar
            selectable="ignoreEvents"
            localizer={localizer}
            events={events}
            views={allViews}
            step={60}
            showMultiDayTimes
            defaultDate={new Date()}
            defaultView={BigCalendar.Views.WEEK}
            style={{height: "90vh" }}
            resources={resourceMap}
            resourceIdAccessor="resourceId"
            resourceTitleAccessor="resourceTitle"
            onSelectSlot={this.handleSelect}
            eventPropGetter={(this.eventStyleGetter)}
          />`

use eventPropGetter to style you events


Q: How to hook api calls in another application I am trying to hook the ExtTextOut and DrawTextExt GDI method calls of another application.
I know that I need to Use GetProcAddress to find the address of those methods in gdi32.dll, and overwrite the address in the process I want to hook with the address of my function.  Then in my function I do what I need, then call the original function.
I want to make this hook functionality available to .net applications, and apparently this is do-able by creating an 'intermediate' unmanaged dll that does the hooking, and is capable of firing a event on the .net side, so that the new function can bet written in the managed environment.  I'm just not sure how to implement this.  Does anyone have any code samples or links to information?

A: I would recommend Microsoft's Detours (C++ x86 only) or EasyHook (C++ & C#, x86/x64).
http://easyhook.codeplex.com/
I've used it before, works pretty well. You have to pass a function or address and where you want it redirected to, and you can have all calls (for all processes or a specific one) sent into your function. The tutorials cover most of the basics, but I can edit code into this answer if you'd like.
A bit of trivia is that it also works the other way. Pass a pointer to your function and you can redirect calls into external code. Makes for some interesting integration with old apps or closed-source ones.

A: You can use Deviare API Hook, use DeviareCSharpConsole that is a tool that is in the package that let you hook any API and see parameter values in a treeview-like control.
The only trick that it needs in Windows7 is to be load as admin, I reported.

A: How I Built a Working Poker Bot has samples of injecting code and hooking gdi events.


Q: Jasper Report graph in iReport repeating I have a line graph in iReport which is incrementally repeating in every page, that is, if the graph has 30 x/y pairs (this is dynamic), the report will have 30 pages, of which the first will have just one value, the 2nd two values, and so on. Only the last one will contain the complete graph.
Questions "chart repeat many time" and "Problem with charting using JasperReport" and "How to print the grand total only in the last page of a very long report?" did not solve my problem. I understand that putting the chart in the Detail section makes the chart repeat, but putting it in the Summary, Footer, lastPageFooter, Title, etc. sections makes it display only one value. Same when I put it in the Detail section and use <printWhenExpression>.
My code:
<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="nodes-allarmipersistenti" language="groovy" pageWidth="842" pageHeight="595" orientation="Landscape" columnWidth="802" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20">
    <property name="ireport.zoom" value="1.0"/>
    <property name="ireport.x" value="0"/>
    <property name="ireport.y" value="0"/>
    <field name="day" class="java.lang.Number"/>
    <field name="month" class="java.lang.String"/>
    <field name="year" class="java.lang.String"/>
    <field name="dsunita" class="java.lang.String"/>
    <field name="valueNumber" class="java.lang.Number"/>
    <field name="logo" class="java.lang.String"/>
    <field name="today" class="java.lang.String"/>
    <field name="option" class="java.lang.String"/>
    <title>
        <band height="89">
            <staticText>
                <reportElement mode="Opaque" x="0" y="67" width="424" height="22" backcolor="#CCFFFF"/>
                <textElement textAlignment="Right" verticalAlignment="Middle" markup="none">
                    <font size="10" isBold="true" pdfFontName="Helvetica-Bold" isPdfEmbedded="true"/>
                </textElement>
                <text><![CDATA[GRAFICO PARAMETRO]]></text>
            </staticText>
            <staticText>
                <reportElement x="600" y="0" width="100" height="38"/>
                <textElement verticalAlignment="Middle"/>
                <text><![CDATA[Stampato in data]]></text>
            </staticText>
            <textField>
                <reportElement x="700" y="0" width="102" height="38"/>
                <textElement textAlignment="Right" verticalAlignment="Middle"/>
                <textFieldExpression><![CDATA[$F{today}]]></textFieldExpression>
            </textField>
            <image>
                <reportElement x="0" y="0" width="100" height="67"/>
                <imageExpression><![CDATA[$F{logo}]]></imageExpression>
            </image>
            <staticText>
                <reportElement x="700" y="38" width="102" height="29"/>
                <textElement textAlignment="Right"/>
                <text><![CDATA[MaRe - Telecontrollo]]></text>
            </staticText>
            <textField>
                <reportElement mode="Opaque" x="424" y="67" width="378" height="22" backcolor="#CCFFFF"/>
                <textElement verticalAlignment="Middle"/>
                <textFieldExpression><![CDATA[' ' + $F{option}]]></textFieldExpression>
            </textField>
        </band>
    </title>
    <lastPageFooter>
        <band height="387" splitType="Stretch">
            <xyLineChart>
                <chart evaluationTime="Page">
                    <reportElement x="0" y="0" width="802" height="387"/>
                    <chartTitle/>
                    <chartSubtitle/>
                    <chartLegend/>
                </chart>
                <xyDataset>
                    <dataset incrementType="Report"/>
                    <xySeries>
                        <seriesExpression><![CDATA["Unità " + $F{dsunita}]]></seriesExpression>
                        <xValueExpression><![CDATA[$F{day}]]></xValueExpression>
                        <yValueExpression><![CDATA[$F{valueNumber}]]></yValueExpression>
                    </xySeries>
                </xyDataset>
                <linePlot>
                    <plot/>
                </linePlot>
            </xyLineChart>
        </band>
    </lastPageFooter>
</jasperReport>

Datasource here is a JRBeanCollectionDataSource.

A: Putting it in the Detail band is wrong (as you noticed). Putting it in the Title or Summary will work. Your choice of evaluationTime="Page" doesn't look right. Try changing this to evaluationTime="Report"


Q: How do I use two different custom UITableViewCell subclasses in a single table? How to I properly display to different UITableViewCell subclasses within the same UITableView?
I am using the storyboard for this question. I am trying to use two different subclasses of UITableView cell in a single table. The idea that TTTextFieldCells know how to show a text box and TTPickerCells know how to present a UIPicker to the user. There the protocol TTTableViewCell specifies a single selector: [setCellDetails (NSDictionary*) cellDetails] Each UITableViewCell subclass knows what to do with the cellDetails Dictionary to setup the cell.
-(NSArray *)tableData {
     if (!_tableData) {
          _tableData =
          @[ // Sections
             @{ // Section Details
                  kSectionName:@"Scout Information"
                  ,kRows:@[ // Rows
                             @{// Cell Details
                                  kBoundProperty:self.scoutName
                                  ,kReuseIdentifier:kTextFieldCell
                                  ,kLabel:@"Name"
                                  ,kPlaceholderValue:@"Scout's Name"
                                  }
                             ,@{
                                  kReuseIdentifier:@"TTPickerCell"
                                  ,kLabel:@"Type"
                                  ,kPlaceholderValue:@"Cadet, Junior, etc..."
                                  }
                             ,@{
                                  kBoundProperty:self.yearsScouting
                                  ,kReuseIdentifier:kTextFieldCell
                                  ,kLabel:@"Years"
                                  ,kPlaceholderValue:@"Years of Experience"
                                  ,kKeyboardStyle:@(UIKeyboardTypeNumberPad)
                                  }
                             ]
                  }
             ,@{ // Section Details
                  kSectionName:@"Parent Information"
                  ,kRows:@[
                             @{
                                  kBoundProperty:self.parentName
                                  ,kReuseIdentifier:kTextFieldCell
                                  ,kLabel:@"Name"
                                  ,kPlaceholderValue:@"Parents's Name"
                                  }
                             ]
                  }
             ];
     }
     return _tableData;
}

- (void)viewDidLoad
{
     [super viewDidLoad];
    // Do any additional setup after loading the view.
    // Line A
     [self.tableView registerClass:[TTTextFieldCell class] forCellReuseIdentifier:@"TTTextFieldCell"];
    // Line B
     [self.tableView registerClass:[TTPickerCell class] forCellReuseIdentifier:@"TTPickerCell"];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
     NSDictionary* cellDetails = self.tableData[indexPath.section][kRows][indexPath.row];

     NSString* reuseIdentifier = cellDetails[kReuseIdentifier];

     // Line C
     UITableViewCell<TTTableViewCell> *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];

     [cell setCellDetails:cellDetails];
     return cell;
}

Now, here is the question. If I comment out line A and B, then the TTTextFieldCells are displayed correctly. But Line C will fail because it is attempting to call the TTTextFieldCell init with a TTPickerCell object, and failing because the TTPickerCell object doesn't have the same properties. If I uncomment Line A and B then the cell styles default to UITableViewCellStyleDefault and they don't display the custom controls. Oddly, if I comment out Line A, and uncomment line B, then the TTTextFieldCells look great, but the TTPickerCells default to UITableViewCellStyleDefault.
It seems that if I do not register a class, dequeue will return an instance of the first prototype cell class. If I register the class then the cell defaults to UITableViewCellStyleDefault.
Also of note, the initWithStyle:reuseIdentifier: selectors only get called if the class is registered.
So, how to I properly display to different UITableViewCell subclasses within the same UITableView? Do I have to forgo using the storyboard to design the cell?
Thank you in advance.

A: You do not want to be calling tableView registerClass:... inside of cellForRowAtIndexPath. Instead, you should be registering your classes/nibs a single time. This is often done in the controller's viewDidLoad method. Your cellForRowAtIndexPath implementation can then look something like this:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary* cellDetails = self.tableData[indexPath.section][kRows][indexPath.row];

    NSString *reuseIdentifier = (/*some condition*/ ? @"TTTextFieldCell" : @"TTPickerCell");
    UITableViewCell<TTTableViewCell> *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    [cell setCellDetails:cellDetails];
    return cell;
}

EDIT: I should mention dequeueReusableCellWithIdentifier always returns a cell from iOS 6 on. If you are targeting an earlier version of iOS you need to account for creating cells in the even this method returns nil.

A: Ok, this is what I found to be the answer.

*

*Do not register the class for the reuse identifier. Comment out lines A and B.

*Do not copy and paste prototype cells, unless you take great care to review the IBOutlets. The pasted prototype cell doesn't care what UITableViewCell subclass you assign it too, it doesn't validate the IBOutlets are present.

Fixed up #2 and all was well.
Doh!

A: I used 2 types of cells loaded from NIB and NSMutable array with my objects, objects have texts, titles and imagens that i want to use in cells. In method cellForRowAtIndexPath... u put content from objects to cell. U can init without nib.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        if (your condition){
        NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"CellClass1" owner:self options:nil];
        CellClass1  *cell =  (CellClass1 *)[topLevelObjects objectAtIndex:0];
        }else{
        NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"CellClass2" owner:self options:nil];
        CellClass2  *cell =  (CellClass2 *)[topLevelObjects objectAtIndex:0];}

        //get your content for cell at array or your own estructure
        Content *content = [contents objectAtIndex:indexPath.row];

        cell.description.text = content.description;

        return cell;
    }


Q: Hardware accelerated Flash Player?
Possible Duplicate:
How do I fix Flash issues?

According to Adobe statements they gave up support for hardware acceleration in newest flash player for linux :( Is there any other dev/alpha/beta version of flash player which enables hardware acceleration in Ubuntu 11.10?

A: If you have nvidia card, install drivers and vdpau files and you will have h/w with flash.


Q: static interfaces in c# Sorry it's possibly a duplicate but in the other static interface they mention generics which I am not using.
I wanted a quick and simple logger for my app I though I could avoid a singleton using a static element.
I would have like to keep the interface so that later I could change to another logging package. The interface being for me (I may be wrong here) a way to implement a "facade" feature.
I have the feeling I am overlooking something.
A gentle push in the right direction would be greatly appreciated. (Hope it's a bit clearer)
public interface Ilogger
{
    void Log(string data, out DateTime datetime, out string uid);
}

public class Logger : Ilogger
{
    private static TraceSource AppTrace = new TraceSource("RD", SourceLevels.All);

    static Logger ()
    {
       AppTrace.Listeners.Clear();
       AppTrace.Listeners.Add(new DelimitedListTraceListener("RD.log"));
    }

    static void Log(string data, out DateTime datetime, out string uid)
    {
        datetime = DateTime.Now;
        uid = Guid.NewGuid().ToString();

        AppTrace.TraceInformation(datetime + ";" + uid + ";" + data);
    }
}

A: You want to combine a singleton with a facade. Sort of a service locator. i.e. create a singleton that got the same methods as your interface and then assign the interface to the facade as the singleton.
I've blogged about it.

A: C# does not support static inheritance or static interface implementation. static variables are just a form of a Singleton either way you look at it - just go with a Singleton or better use a DI container to inject the logger dependency.


Q: Eigen SparseLU factorize too slow In my code, SparseLU.factorize() takes 1'20" to execute. How to speed it up? Or, are there any inappropriate steps slowing it down in my code?
Here is the code:
Eigen::SparseMatrix<double> F(verticesNum, verticesNum);  // verticesNum is about 34918
// reserve space for non-zero elements in sparse matrix
F.reserve(Eigen::VectorXi::Constant(verticesNum, 20));
// build matrix operator
for (int i = 0; i < vertices->size(); i++)
{
    // ... some algorithm
}

// build solver for matrix
Eigen::SparseLU<Eigen::SparseMatrix<double>, Eigen::COLAMDOrdering<int>> solver;

// tailor solver to matrix
solver.analyzePattern(F);
solver.factorize(F);

Thank you!!


Q: Most easyest way of giving remote access with one account to several fodlers, under linux We have a new employee, who is not an expert in ssh, but he is a sitebuilder, so we need a proper and secure way to give him REMOTE access to several directories. Is there a secure, easy and convenient way to do so, without creating separate ftp accounts for each directory? Webdav excluded!
System is Debian squeeze
FTP: pure-ftpd

A: Pure-ftpd allows you to authenticate via the users in your system, so create a new user for the sitebuilder and then modify file permissions accordingly (either put him in a suitable group, or make him the owner of the particular directories and files), he will be able to connect via FTP (which will probably suit what he is familiar with, rather than SSH), and only modify the files he has permissions to edit.
Regards,
Phil,


Q: Alias one set of Subdomains to another I have to domains that I want to effectively mirror one another on select subdomains. Let's say they are pirates.com and ninjas.com and i want ninjas to mirror the content on pirates.
When I visit foo.ninjas.com I want to see the content on foo.pirates.com. Due to app restrictions I need to do this in DNS for an undefined number of subdomains. I was under the impression i could do this with a CNAME, but it appears that setting a CNAME for * subdomain of the ninjas.com domain to point to pirates.com will make any subdomain of ninjas.com point at pirates.com instead of the associated subdomain. I.e. foo.ninjas.com would reference pirates.com instead of foo.pirates.com.
Is there a way to do this using DNS? Am I missing something basic?

A: DNS is only one part of the story. The web server must be aware of the domain names that you intend to use. So you will have to set up the names in the web server as well (e.g. using Apache's ServerAlias directive.

A: If you control the DNS server, and if it uses zonefiles, you can make both domains use the same zonefile.
An example for bind:
zone "ninjas.com" IN {
    type master;
    file "master/ninjas.com.zone";
};

zone "pirates.com" IN {
    type master;
    file "master/ninjas.com.zone";
};

I use this technique to make ~2500 domainnames look exactly the same :)


Q: How to proxy requests in docker swagger ui I'm using Swagger UI using its docker version. The Try it out button is not working as expected from the Web UI because there's a problem with cors. I'm running the UI from localhost and doing requests to another domain. I have read this other question How to avoid CORS errors ("Failed to fetch" or "Server not found or an error occurred") when making requests from Swagger Editor? but I cannot do any of the solutions it says.
I'm not sure if it's posible to setup a proxy on the docker container as SwaggerHub does, like, instead of the Try it out request be resolved on the browser, resolve it on the docker container.
Do you know if that is posible?


Q: Can we put a comma before another punctuation? There's a show called "What Would You Do?" and I was wondering if you can put a comma after the interrogation mark.
For example:

What Would You Do?, the popular hidden camera show, was canceled by
  NBC.

A: This is a question of style not grammar. Different style guides recommend different approaches. The question should not be "Is this possible?", but "Is this necessary?"
It looks a little strange, but in this particular case, where the question mark is part of the title, it is probably necessary. You can make it look less strange by emphasising the title. You should put titles in an italic font, and you could use quotation marks

The show Who do you think you are?, which was broadcast on the BBC, features celebrities researching their family history.

In many cases it would be possible to rephrase to avoid the awkward punctuation.

NBC cancelled its popular hidden camera show What Would You Do?.


Q: Actionscript show button after amount of time Hi i'm loading a FLV into a blank video holder and would like to display a button when the video reaches a certain point. Is this at all possible?

A: You didn't specify the version of actionscript in use, so I'll assume you're using as3.
You could

*

*use cue points embedded in the flv (added when creating the flv)

*if you're using the FLVPlayer component, use cue points created with actionscript

*use a regular Timer
If you don't have access to the creating-the-flv-part, the simplest (and the most inaccurate, but I would assume that displaying a button doesn't need to be millisecond-level-accurate) solution would be number three. If the user has no control over the playback (i.e. pause, rewind) and the video isn't being streamed over network, just start/stop a timer with the playback. If the user can pause and rewind the video, you'll have to also stop and adjust the timer every time the user does so. If the video is being streamed over network, you'll have to take any buffering pauses into account, too.

A: You can add cuepoint and listen for them with:
_Player.AddEventListener(MetadataEvent.CUE_POINT, PlayerCuePoint);

function PlayerCuePoint(e:MetadataEvent):void
{
    _Button.visible = true;
}

Or you could check the progress like this:
const BUTTON_TIME:Number = 10; //Time in seconds

_Player.AddEventListener(VideoEvent.PLAYHEAD_UPDATE, PlayerPlayheadUpdate);

function PlayerPlayheadUpdate(e:VideoEvent):void
{
    if(_Player.playheadTime >= BUTTON_TIME)
        _Button.visible = true;
}


Q: Acesso a webservice com SOAP Headers e Node.js Estou tentando acessar um webservice usando Node.js (com módulo node-soap) e  que primeiro preciso efetuar login e depois nas chamadas de outros métodos é necessário enviar o Header recebido no login. Consigo efetuar o Login e abaixo segue o xml com o Header e o token recebidos:
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
 <soap:Header>
   <sessaoIdHeader xmlns="http://www.cvm.gov.br/webservices/">
    <Guid>8710-f7ad-4e20-ac28-0a5a9587bc2b</Guid>
    <IdSessao>270440</IdSessao>
   </sessaoIdHeader>
 </soap:Header>
<soap:Body><LoginResponse xmlns="http://www.cvm.gov.br/webservices/"/>
</soap:Body>
</soap:Envelope>

Quando tento chamar outro método do webservice não estou conseguindo enviar o Header recebido junto. Estou usando o método addSoapHeader do noad-soap e o código fica assim:
soap.createClient(url, function(err, client) {
  client.Login(args, function(err, result, headers) {
    let data = {
      tpDoc: 9,
      entregDoc: '2017-03-31'
    };
    client.addSoapHeader(headers);
    client.retornaListaComptcDocs(data, function(err, result) {
      console.log(client.lastRequest);
      console.log(result);
    });
  });
});

A propriedade lastRequest mostra que o XML tem elemento duplicado. Vejam que ao inserir o Header o XML fica assim:
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:tm="http://microsoft.com/wsdl/mime/textMatching/"
  xmlns:tns="http://www.cvm.gov.br/webservices/">
  <soap:Header>
   <?xml version="1.0" encoding="utf-8"?>
   <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:xsd="http://www.w3.org/2001/XMLSchema">
     <soap:Header>
       <sessaoIdHeader xmlns="http://www.cvm.gov.br/webservices/">
         <Guid>8710-f7ad-4e20-ac28-0a5a9587bc2b</Guid>
         <IdSessao>270440</IdSessao>
       </sessaoIdHeader>
     </soap:Header>
     <soap:Body><LoginResponse xmlns="http://www.cvm.gov.br/webservices/"/>
     </soap:Body>
   </soap:Envelope>
 </soap:Header>
 <soap:Body>
   <solicAutorizDownloadArqEntregaPorData
     xmlns="http://www.cvm.gov.br/webservices/">
     <iCdTpDoc>305</iCdTpDoc>
     <strDtEntregaDoc>2017-07-17</strDtEntregaDoc>
   </solicAutorizDownloadArqEntregaPorData>
 </soap:Body>
 </soap:Envelope>

Como posso adicionar o Header recebido em Login na Request dos outros métodos?


Q: Meaning of command ls -lt | wc -l My friend just passed me this command to count the number of files in a directory:
$ ls -lt | wc -l

Can someone please help me flush out the meaning of this command? I know that ls is to list all the files. But what does -lt mean?
Also, I get a different count if I use ls | wc -l with no -lt option. Why is that the case?

A: You'll want to get familiar with the "man (manual) pages":
$ man ls

In this case you'll see:
 -l      (The lowercase letter ``ell''.)  List in long format.  (See below.)  If
         the output is to a terminal, a total sum for all the file sizes is
         output on a line before the long listing.
 -t      Sort by time modified (most recently modified first) before sorting the
         operands by lexicographical order.

Another way you can see the effect of the options is to run ls without piping to the wc command. Compare
$ ls

with
$ ls -l

and
$ ls -lt


Q: building android project produces make error 2 I have recently purchased a book to assist in my development of C++ for Android which contained some code samples.  However, when I come to build some of the sample code, I receive the following error:
C:\ndk\android-ndk-r9\ndk-build.cmd all
"Compile++  : Chapter10 <= Chapter10.cpp
process_begin: CreateProcess(NULL, C:/ndk/android-ndk-r9/toolchains/arm-linux-androideabi-4.7/prebuilt/windows/bin/arm-linux-androideabi-g++ -MMD -MP -MF ./obj/local/armeabi/objs/Chapter10/Chapter10.o.d -fno-exceptions -fno-rtti -Ijni -IC:/ndk/android-ndk-r9/sources/android/native_app_glue -IC:/ndk/android-ndk-r9/sources/cxx-stl/stlport/stlport -IC:/ndk/android-ndk-r9/sources/cxx-stl//gabi++/include -Ijni -DANDROID -Wa,--noexecstack -Wformat -Werror=format-security -frtti -c jni/Chapter10.cpp -o ./obj/local/armeabi/objs/Chapter10/Chapter10.o, ...) failed.

make (e=2): The system cannot find the file specified.

make: *** [obj/local/armeabi/objs/Chapter10/Chapter10.o] Error 2

The make file is as shown below:
LOCAL_PATH:= $(call my-dir)

include $(CLEAR_VARS)

LOCAL_ARM_MODE          := arm
LOCAL_C_INCLUDES        := $(LOCAL_PATH)
LOCAL_MODULE            := Chapter10
LOCAL_SRC_FILES         := Chapter10.cpp \
                           (Other cpp Files . . . )
LOCAL_LDLIBS            := -llog -landroid -lEGL -lGLESv2 -lOpenSLES
LOCAL_STATIC_LIBRARIES  := android_native_app_glue

include $(BUILD_SHARED_LIBRARY)

$(call import-module,android/native_app_glue)

The Application.mk file is as below:
APP_PLATFORM    := android-9
APP_STL         := stlport_static
NDK_TOOLCHAIN_VERSION   := 4.7

This was compiled using ADT v22.2.1 and Android NDK r9 on a Windows 7 Machine.
The NDK was installed to 'C:\ndk\android-ndk-r9\'.

A: Android NDK r9 contains the following toolchains:

*

*arm-linux-androideabi-4.6

*arm-linux-androideabi-4.8

*arm-linux-androideabi-clang3.2

*arm-linux-androideabi-clang3.3

*llvm-3.2

*llvm-3.3

*mipsel-linux-android-4.6

*mipsel-linux-android-4.8

*mipsel-linux-android-clang3.2

*mipsel-linux-android-clang3.3

*x86-4.6

*x86-4.8

*x86-clang3.2

*x86-clang3.3

There is no toolchain for gcc 4.7. However, your Application.mk contains the line:
NDK_TOOLCHAIN_VERSION   := 4.7

Which tells the NDK to look for the 4.7 toolchain. And it fails.
So, the solution to your problem is changing the NDK_TOOLCHAIN_VERSION variable to 4.6, 4.8, clang3.2, clang3.3, or just clang (which will use the most recent version of Clang available in the NDK).

A: Check your project path if is contain spaces and non-english characters.
I moved my project into somewhere without spaces, re-build it and works.


Q: Error message converting pandas dataframe integers to datetime I was trying to convert dates into datetime since they were given to me in YYYYMMDD format on my HW. The date was already indexed for a previous problem so I wrote out:
df.reset_index()
df['DATE'] = pd.to_datetime(df['DATE'], format='%Y%m%d')

This is the error message I ended up getting:
   KeyError                                  Traceback (most recent call last)
    ~\anaconda3\lib\site-packages\pandas\core\indexes\base.py in
    get_loc(self, key, method, tolerance)
       3079             try:
    -> 3080                 return self._engine.get_loc(casted_key)
       3081             except KeyError as err:

    pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

    pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

    pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

    pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

    KeyError: 'DATE'

    The above exception was the direct cause of the following exception:

    KeyError                                  Traceback (most recent call last)
    <ipython-input-291-e5a2ae2efa46> in <module>
          1 df.reset_index()
    ----> 2 df['DATE'] = pd.to_datetime(df['DATE'], format='%Y%m%d')
          3 #df.set_index('DATE',inplace=True)
          4 #df.resample('A').apply(lambda x: x[x<0].count())

    ~\anaconda3\lib\site-packages\pandas\core\frame.py in __getitem__(self, key)
       3022             if self.columns.nlevels > 1:
       3023                 return self._getitem_multilevel(key)
    -> 3024             indexer = self.columns.get_loc(key)
       3025             if is_integer(indexer):
       3026                 indexer = [indexer]

    ~\anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
       3080                 return self._engine.get_loc(casted_key)
       3081             except KeyError as err:
    -> 3082                 raise KeyError(key) from err
       3083
       3084         if tolerance is not None:

    KeyError: 'DATE'

Very confused since I pretty much literally used this datetime line for a different problem without any issue. Is there anything I can do to fix this? thanks!


Q: Simplest way of integrating Angular-created elements with D3 I'm playing around with different ways of integrating D3 and Angular, in the context of learning both of these frameworks, and am hoping for some input:
My client application receives a JSON array of nodes and an array of edges from my server.
The central component of the client is a graph visualization implemented as a D3 force-directed layout: For each node in the nodes array, a (SVG) circle element is added to this visualization, and lines between these circles are added for each edge in the edges array.
Of course, D3's selection.data( ) makes it trivial to add these elements and bind each to the data it represents, but the graph visualization is only part of a much larger application: I need to create different types of elements representing these same nodes and edges in different parts of the application (which D3 has nothing to do with), and I'd like to keep all of these elements bound to a single dataset.
My primary goal is minimizing code complexity, and - although I've fallen in love with the simplicity and elegance of D3's data-binding functionality - I've arrived at the tentative conclusion that using it in one part of the application while using Angular to do the same in other parts is creating unnecessary complexity, and that the simplest approach would be to use Angular to handle the data-binding/element-creation
In other words, instead of using selection.data( ).enter( ).append( ) to create SVG elements, I'm thinking I should do so using a ng-repeat="node in nodes", perhaps creating each as a custom directive to allow for custom functionality. Having done so, I would then need to get these elements "into" D3, i.e. managed by its force-directed layout.
Is my reasoning here sound? In particular, I'm worried that I'm overlooking complications this will create with regard to object constancy, which is an important requirement as nodes will be entering, exiting and moving about the screen constantly and I need these transitions to be smooth. How would you recommend I go about integrating my angular-created elements into D3 (more precisely, getting them into my force.nodes{ } and force.links( ) arrays) to avoid any such complications?
Finally, I'm also considering a strategy that I'm hoping might give me the best of both worlds: I could use D3 to create my SVG elements and bind them to their respective datum, but rather than executing that code in the link function of visualization directive (as I've been doing, and as all the Angular/D3 tutorials I've found do), I could run it in the compile function, and do something like this:
d3.select('SVG')
  .selectAll('.node')
  .data('nodeDataArray')
  .enter( )
  .append('circle')
  .attr("class", "node-icon"); //...other attributes/styles etc

where node-icon is the normalized name of a directive with a restrict property that includes C. If this runs in the compile method, angular should then compile all of these directives as normal, adding any additional functionality / interfaces with other directives (etc.), the same way it does with any other type of element. Right?
This is the option I'm most attracted to intuitively - are there any pitfalls of it I might be overlooking, which might make the former strategy preferable?

A: I have been pondering pretty much the same problem for a while and come to the following conclusion.
The simplest way to integrate Angular created elements with d3 is to add the directives with .attr and then .call the compile service on the d3 generated elements. Like this:
mySvg.selectAll("circle")
                .data(scope.nodes)
                .enter()
                .append("circle")
                .attr("tooltip-append-to-body", true)
                .attr("tooltip", function(d){
                    return d.name;
                })
                .call(function(){
                    $compile(this[0].parentNode)(scope);
                });

Here is a Plunker.
I think the idea of generating elements with Angular ngRepeat rather than d3 is working against the frameworks. D3 does not expect to be handed a bunch of elements. It wants to be handed data - almost always an array. It then has a stack of excellent functions to convert that data into various SVG or HTML elements. Let it do that.
It seems from this quote...

D3 makes it trivial to add elements and bind each to the data it represents,  but the graph visualization is only part of a much larger application: I need to create different types of elements representing these same nodes and edges in different parts of the application (which D3 has nothing to do with), and I'd like to keep all of these elements bound to a single dataset.

... you are implying that generating elements with d3 somehow prevents you from binding the same data to different parts of the application. I can't see why. Just have d3 generate elements from a scope array (as is done in the linked Plunker). Then use the same dataset wherever you want in the usual Angular way. Other parts of the application can update the dataset and a $watch callback can re-render the d3 graphic.


Q: Cannot make child element the same height as parent element IE I am trying to make a child element of a table cell take on the table cell's height and width using CSS.  Here is the html:

Here is the CSS I'm using:

    table tbody tr td:nth-child(1){
        position: relative;
    }

    table tbody tr td div.yellowDiv{
        position: absolute;
        top: 0;
        bottom: 0;
        width: 100%;
        background: yellow;
    }

The above code renders properly in Chrome, but not in IE (only concerned with IE 9 and 10).  I have also tried setting display: table-cell; for the div element but to no avail.  I have also tried setting the height of the div element to be 100% but that has not worked either.

A: Absolutey-positioned elements are no longer part of the layout. They have their own layout context. Therefore they cannot know how big their parent element is.
You need to use JavaScript to solve this or consider why you need absolute positioning at all.
You can use:
.yellowDiv {
    background-color:#ffff00;
    height:100%;
}


Q: Регулярные выражения, фунция string.ascii_letters Как сделать так, чтобы функция string.ascii_letters не трогала пробелы
import string
s = '321eqweds***! .1dewq'
result = ''.join(c for c in s if c in string.ascii_letters)
print(result)

Выведет на экран: eqwedsdewq
А нужно что бы : eqweds dewq

A: Регулярка:

*

*[^a-z ] поиск символов, что не относятся к диапазону от a до z и к пробелу ()

Пример:
import re

text = '321eqweds***! .1dewq'

new_text = re.sub('[^a-z ]', '', text)
print(new_text)
# eqweds dewq


Q: Post php y javascript Buenas tardes.
El caso actualmente es el siguiente. Mi aplicación javascript con angular recibirá un post de una aplicación php, para esto se me solicita una url. Esa url tiene un formato parecido: http://localhost:9000/#!/unaPagina/vista.html, sin embargo, al recibir el post, aparece un error que dice 'cannot post 404 (not found)', por lo que he intentado con la url de un webservice en vez de la url de la vista.
He pensado en recibir el post que se hace desde una aplicación php (me enviará algunos datos) en una función javascript (tengo que proporcionar una url). ¿Es posible hacer un post de php y que una función javascript lo reciba?, ¿podría proporcionarme un ejemplo?
¿De no ser posible, qué podría hacer?
Gracias

A: Despues de los comentarios, el error es porque el PHP esta en un servidor externo por lo tanto no puede acceder a tu localhost. Debes publicar tu codigo javascript y apuntar desde el php a esa url.


Q: Android imageview over another imageview I want an icon (ImageView) over another ImageView. When I tried, the icon is hiding behind the white image. In my code below, first image view is for the white box and another image view is for the icon.
<RelativeLayout
            android:layout_width="54dp"
            android:layout_height="54dp"
            android:layout_alignParentTop="true"
            android:layout_alignParentStart="true"
            android:layout_marginStart="20dp"
            android:layout_marginTop="20dp">

            <ImageView
                android:id="@+id/button_menu"
                android:layout_width="44dp"
                android:layout_height="44dp"
                android:layout_alignParentTop="true"
                android:layout_alignParentStart="true"
                android:padding="5dp"
                android:src="@drawable/ic_menu"
                android:background="@drawable/button_white_rounded"
                android:elevation="4dp"
                android:scaleType="fitXY"
                android:adjustViewBounds="true"
                android:tint="@color/colorText"/>

            <ImageView
                android:id="@+id/warning_circle"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:layout_alignParentRight="true"
                android:src="@drawable/ic_warning_circle"/>
        </RelativeLayout>

I want the orange icon in screenshot over the white box. How can I bring it on the white box image?

A: <RelativeLayout
            android:layout_width="54dp"
            android:layout_height="54dp"
            android:layout_alignParentTop="true"
            android:layout_alignParentStart="true"
            android:layout_marginStart="20dp"
            android:layout_marginTop="20dp">

             <ImageView
                android:id="@+id/warning_circle"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:layout_alignParentRight="true"
                android:src="@drawable/ic_warning_circle"/>

            <ImageView
                android:id="@+id/button_menu"
                android:layout_width="44dp"
                android:layout_height="44dp"
                android:layout_alignParentTop="true"
                android:layout_alignParentStart="true"
                android:padding="5dp"
                android:src="@drawable/ic_menu"
                android:background="@drawable/button_white_rounded"
                android:elevation="4dp"
                android:scaleType="fitXY"
                android:adjustViewBounds="true"
                android:tint="@color/colorText"/>

        </RelativeLayout>

A: The layout_align [Top|Bottom|Left|Right] attribute in RelativeLayout is used to align views based on their respective x and y values within the margin. The second ImageView will now be aligned to the top, bottom, left, and right of the first ImageView based on the margins. Padding is ignored in the alignment.
<RelativeLayout
      xmlns:android="http://schemas.android.com/apk/res/android"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent"
      android:background="@color/white" >

    <ImageView
        android:id="@+id/inside_imageview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="5dip"
        android:layout_marginTop="5dip"
        android:src="@drawable/frame" />

      <ImageView
         android:id="@+id/outside_imageview"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_alignTop="@id/inside_imageview"
         android:layout_alignBottom="@id/inside_imageview"
         android:layout_alignLeft="@id/inside_imageview"
         android:layout_alignRight="@id/inside_imageview"
         android:scaleType="fitXY" />
  </RelativeLayout>

A: Your code is perfect but either you have to remove android:elevation from button_menu or you have to add android:elevation in warning_circle.
I have updated my answer based on @MikeM. suggestion for use RelativeLayout instead of ConstraintLayout
Solution 1:
<RelativeLayout
    android:layout_width="54dp"
    android:layout_height="54dp"
    android:layout_alignParentStart="true"
    android:layout_alignParentTop="true"
    android:layout_marginStart="20dp"
    android:layout_marginTop="20dp">

    <ImageView
        android:id="@+id/button_menu"
        android:layout_width="44dp"
        android:layout_height="44dp"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:adjustViewBounds="true"
        android:background="@drawable/button_white_rounded"
        android:padding="5dp"
        android:scaleType="fitXY"
        android:src="@drawable/ic_menu"
        android:tint="@color/colorText"
        tools:src="@tools:sample/avatars" />

    <ImageView
        android:id="@+id/warning_circle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentBottom="true"
        android:src="@drawable/ic_warning_circle"
        tools:src="@tools:sample/avatars" />
</RelativeLayout>

Solution 2:
<RelativeLayout
    android:layout_width="54dp"
    android:layout_height="54dp"
    android:layout_alignParentStart="true"
    android:layout_alignParentTop="true"
    android:layout_marginStart="20dp"
    android:layout_marginTop="20dp">

    <ImageView
        android:id="@+id/button_menu"
        android:layout_width="44dp"
        android:layout_height="44dp"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:adjustViewBounds="true"
        android:background="@drawable/button_white_rounded"
        android:elevation="4dp"
        android:padding="5dp"
        android:scaleType="fitXY"
        android:src="@drawable/ic_menu"
        android:tint="@color/colorText"
        tools:src="@tools:sample/avatars" />

    <ImageView
        android:id="@+id/warning_circle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentBottom="true"
        android:elevation="4dp"
        android:src="@drawable/ic_warning_circle"
        tools:src="@tools:sample/avatars" />
</RelativeLayout>

A: You can use FrameLayout to achieve this.. here is an example, you can modify this according to your need. In warning icon image view add gravity as bottom|end and in menu icon image view add margin of 10dp when using FrameLayout.
<FrameLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="20dp"
    android:layout_marginTop="20dp">

    <ImageView
        android:id="@+id/button_menu"
        android:layout_width="44dp"
        android:layout_height="44dp"
        android:layout_margin="10dp"
        android:padding="5dp"
        android:src="@drawable/ic_menu"
        android:background="@drawable/button_white_rounded"
        android:elevation="4dp"
        android:scaleType="fitXY"
        android:adjustViewBounds="true"
        android:tint="@color/colorText"/>

    <ImageView
        android:id="@+id/warning_circle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:src="@drawable/ic_warning_circle"/>

</FrameLayout>

A: <RelativeLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_marginTop="20dp">

    <ImageView
        android:layout_centerInParent="true"
        android:id="@+id/warning_circle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="20dp"
        android:src="@drawable/ic_launcher_background"/>

    <ImageView
        android:id="@+id/button_menu"
        android:layout_width="44dp"
        android:layout_height="44dp"
        android:padding="5dp"
        android:layout_marginRight="-20dp"
        android:layout_marginBottom="-20dp"
        android:layout_alignRight="@+id/warning_circle"
        android:layout_alignBottom="@+id/warning_circle"
        android:src="@drawable/ic_menu_gallery"
        android:background="@color/colorAccent"
        android:elevation="4dp"
        android:scaleType="fitXY"
        android:adjustViewBounds="true"/>

</RelativeLayout>

Use this way!!
We have a concept of layers in relative layout!
Vertically down views are on the top most layer.

A: <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="fitXY"
        android:src="@drawable/download" />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_centerInParent="true">

        <ImageView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:src="@drawable/download_img" />
    </RelativeLayout>

</RelativeLayout>

A: You could try to search any ready-to-use solutions for badges like ImageBadgeView.
Or try to play with BadgeDrawable from material lib.
I'd prefer to use ViewOverlay for such purposes and just add few rows of code:
button_menu.post {
    val drawable = ContextCompat.getDrawable(context, R.drawable.ic_warning_circle)
    drawable.setBounds(
        button_menu.width - drawable.intrinsicWidth,
        button_menu.height - drawable.intrinsicHeight,
        button_menu.width,
        button_menu.height
    )
    button_menu.overlay.add(drawable)
}

In this way you would reduce amount of containers in your xml layout and make it more readable.


Q: Sharepoint 2007 File Upload , Page cannot be Displayed Having a bit of strange Sharepoint 2007 issue , especially for a Monday.
Here's the scenario: Users within organisation cannot upload files to ANY doc Lib.
User is able to click upload, browse, select the file without any problems. As soon as he/she clicks OK, they immediately get a standard IE error : Page cannot be displayed.
The MOSS Server is setup in a DMZ where it is Internet accessible. When accessing it from the Internet (which I'm doing), the uploading works fine. It's only when users who are in the organisation try to upload anything, they get the error. Users within the organistaion also access the site using the Internet IP as no direct route exists between Internal Network and DMZ.
We have a LINUX Firewall involved (Yuck, I know), and clients also have Norton AV.
I suspect some kind of networking issue, or maybe the AV. Any ideas?

A: Ok. The issue was related to intermittant connectivity loss. All fixed now


Q: Issue constructing a has_many relation with scope using multiple join tables I have a tag system on multiple models that are linked together.
The system works like this:

*

*A Top has many Middles

*A Middle has many Lows

*Tops, Middles and Lows have many Tags

*A tag associated to Top level is supposed to qualify every Middle and Low associated to it.

*Same goes for a tag that would be associated to a Middle, every Low associated to it would 'inherit' from the tags.

This mechanic is not on a database level, in the end in what concerns the database, Tops, Middles and Lows all have their own tag collection, and i initially implemented instance methods on each model so that when you call, for example, low_instance.all_tags, it concatenates the tag collections of it's parent Middles, and the one of its Top.
Here is what the models look like:
#          ______________________________
#         /                              \
#      (1)                                (*)
#    [Top] (1) __ (*) [Middle] (*) __ (*) [Low]
#      (*)               (*)              (*)
#        \_______________ | ______________/
#                         |
#                         *
#                       [Tags]

class Low < ApplicationRecord
  has_many :low_tags, dependent: :destroy
  has_many :tags, through: :low_tags
  has_many :middle_foos, dependent: :destroy
  has_many :middles, through: :middle_foos
end

class Middle < ApplicationRecord
  belongs_to :top
  has_many :middle_tags, dependent: :destroy
  has_many :tags, through: :middle_tags

  has_many :middle_lows, dependent: :destroy
  has_many :lows, through: :middle_lows
end

class Top < ApplicationRecord
  has_many :middles, dependent: :destroy
  has_many :lows, dependent: :destroy
  has_many :top_tags, dependent: :destroy
  has_many :tags, through: :top_tags
end

### Join tables
class MiddleLow < ApplicationRecord
  belongs_to :middle
  belongs_to :low
end

class LowTag < ApplicationRecord
  belongs_to :low
  belongs_to :tag
end

class MiddleTag < ApplicationRecord
  belongs_to :middle
  belongs_to :tag
end

class TopTag < ApplicationRecord
  belongs_to :top
  belongs_to :tag
end

That actually works like a charm. The issue is that i want to be able to search my Lows with the awesome Ransack gem and using the full tag collection of a Low (its self tags, plus the ones inherited from the parent Middles and Top)
Problem: Ransack only works with ActiveRecord::Relations. So from Ransack's point of view, i can only search my Lows using their self-tags and not the full inherited collection as this does not exist on the database level.
The initial solution to this problem i wanted to implement is to add a "copy" full tag collection on the database level that updates with the rest and that i could use to search with Ransack.
But I'm sure i don't have to add anything to the database as all the info is already here in the join tables and i kind of don't want to duplicate that info which is not super cool i think and would make the code base less understandable.
I have seen potential solutions using has many with scopes like so:
has_many :all_tags, ->(low) {
  unscope(.........).
  left_joins(..........).
  where(.........)
  # Returs self tags (Low) + tags from associated Middles + tags from the Top
}

I'm pretty sure this would be the best solution, but I'm really not good when it comes to database querying especially with so much models and join tables. I get confused and can't seem to find what to put in that scope so that i get this full collection of tags.
So if anybody has a clue about that, any help would be greatly appreciated!
By the way, using Rails 6.1 and Ruby 2.7

A: So found the solution to the query I wanted to construct in the end.
The scope looks like following:
    has_many :full_tags, lambda { |low|
        where_clause = 'top_tags.top_id = ? or low_tags.low_id = ?'
        where_args = [low.top_id, low.id]
        if low.middles.any?
          where_clause += ' or middle_tags.zone_id IN ?'
          where_args << low.middle_ids
        end
        unscope(where: :low_id)
          .left_joins(:middle_tags, :top_tags, :low_tags)
          .where(where_clause, *where_args).distinct
      }, class_name: 'Tag'

Calling xxx.full_tags on any instance of low returns the whole collection of tags from every middle it belongs to , plus those from the top it belongs to, plus its own tags, and the distinct makes it a unique collection.
That being said, that didn't fully fixed my problem because the whole purpose was to pass this scoped has_many relation as an attribute used by the Ransack gem to filter out my Low models, out of their full inherited collection of tags.
Big disappointment it was when i discovered that Ransack performs eager loading when it comes to search on associations:
Rails does not support Eager Loading on scoped associations
So i ended up implementing a whole other solution for my tagging system. But hey, i learned a lot.


Q: EnterpriseLibrary Error I'm receiving reports of a rare and intermittent error in our live environment. I have been unsuccessful in my attempts to reproduce it, and the error itself is a slight mystery. Add to that, it seems to be something involving Enterprise Library tracing (we're using version 5.0) - all in all, a bit of a pain. This is happening on Windows Sever 2008, application is on .Net Framework 4.0 (WPF).
The error message and the stack trace follow:
ArgumentNullException: Value cannot be null. Parameter name: category

<StackTrace>
  Server stack trace:
  at Microsoft.Practices.EnterpriseLibrary.Logging.LogEntry.BuildCategoriesCollection(String category)
  at Microsoft.Practices.EnterpriseLibrary.Logging.Tracer.WriteTraceMessage(String message, String entryTitle, TraceEventType eventType)
  at Microsoft.Practices.EnterpriseLibrary.Logging.Tracer.WriteTraceEndMessage(String entryTitle)
  at Microsoft.Practices.EnterpriseLibrary.Logging.Tracer.Dispose()
  at TestApplication.ViewModelTest.<UpdateUsers>d__1a.MoveNext()

  Exception rethrown at [0]:
  at System.Runtime.CompilerServices.AsyncVoidMethodBuilder.<SetException>b__1(Object state)
  at System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(Object state)
  at System.Threading.ExecutionContext.runTryCode(Object userData)
  at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
  at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
  at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
  at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
  at System.Threading.ThreadPoolWorkQueue.Dispatch()
  at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()
</StackTrace>

Can anyone shed any light on what might be causing this?
EDIT:
I'm not modifying LogEntry.BuildCategoriesCollection. The input to the method BuildCategoriesCollection(String category) is null.
The UpdateUsers method is as follows:
async void UpdateUsers()
{
    Processing = true;

    using (traceMgr.StartTrace("Trace"))
        using (var engine = new EngineClient())
        {
            Users = new List<UserMasterDataModel> { _blankUser };
            var users = await engine.GetPossibleTagsTask(SelectedOutcomeId, _queue.SystemCd, _queue.QueueCd);
            Users.AddRange(users);
        }

    if (SelectedUser != _blankUser)
    {
        // If null user selected then initialize to the case's tag, otherwise try to find the previously selected UserName
        var userNameToFind = SelectedUser == null ? _details.TagTo : SelectedUser.UserName;
        SelectedUser = Users.FirstOrDefault(user => user.UserName == userNameToFind) ?? _blankUser;

        OnPropertyChanged("SelectedUser");
    }
}

A: This problem seem to be a known bug for E-Lib in previous versions too.
Known as: Unhandled exception when using the logging AB from multiple threads.
"The underlying issue is that in .NET 2.0 RTM a parent thread's operation stack was shared with its children if such a stack existed by the time the children were created."
Read more here:
http://entlib.codeplex.com/workitem/9592
Hard to suggest a generic solution to this as it is very depends on the architecture of your app.


Q: android jni from static to non static methods I am trying to refactor some android jni code. It was initially setup to use static variables in JNI and static calls on the android side. I would like to change that to improve compatibility with other code.
current method signatures
static jclass main_activity;

static jmethodID on_init;
static jmethodID on_update;
static jmethodID on_render;
static jmethodID on_exit;
static jmethodID on_get_input;

these bindings were setup in the beginning of the code like this:
main_activity = (jclass)((*mEnv)->NewGlobalRef(mEnv, cls));

on_init = (*mEnv)->GetStaticMethodID(mEnv, main_activity,
                            "on_native_init","()V");
on_update = (*mEnv)->GetStaticMethodID(mEnv, main_activity,
                            "on_native_update","()V");
on_render = (*mEnv)->GetStaticMethodID(mEnv, main_activity,
                            "on_native_render","()V");
on_exit = (*mEnv)->GetStaticMethodID(mEnv, main_activity,
                            "on_native_exit", "()V");

Then later in the code they would be used like this:
void Android_JNI_SwapEGLwindow(void)
{
    JNIEnv *a_env = get_android_jni_env();
    (*mEnv)->CallStaticVoidMethod(a_env, main_activity, on_update);
}

Since this project is currently setup to store the main activity and the function addresses as a static reference with only the call to get_android_jni_env(); allowing me access to get the current android jni environment.
How can I restructure this code to be able to get an instance instead of holding on to a static reference?

A: Just add one static method as "getInstance()" to retreive the object of class main_activity, then you can use the object to call non-static methods.
jmethodID midGetInstance = (*env)->GetStaticMethodID(env, main_activity_class, "getInstance", "()Lcom/package/yourapp/MainActivity;");
jobject main_activity_obj = (*env)->CallStaticObjectMethod(env, main_activity_class, midGetInstance);
...NewGlobalRef(main_activity_obj);

where main_activity_class is the same of your original jclass main_activity.
On Java side, you need
onCreate(...) {mInstance = this;...}
public static MainActivity getInstance() {return mInstance;}

Then you can use main_acitivty_obj to access the non-static methods.


Q: Send form data to Firebase The problem is that when I run this my real-time database is not updating and there are no errors coming or showing.

function writeData() {
    firebase.database().ref("user").set( {
            Email: document.getElementById("help").value,
            Price: document.getElementById("price1").value,
            Desc: document.getElementById("Pdesc").value,
        }

    );
}
<form>

        Enter Product name
        <input type="text" class="form-control" id="help" aria-describedby="emailHelp">

        Product Price
        <input type="number" class="form-control" id="price1">

        Product description
        <input type="text" class="form-control" id="Pdesc">

    <button type="submit" onclick="writeData()" class="btn btn-lg btn-success">Upload</button>
</form>

A: First, check your realtime firebase, sometimes if you use free, your realtime firebase has expired (for 1 month).
You can print it by inputting a simple value, for example:
If nothing happens, then check your project's API, library, or expiration date.
Solution:
Create a new project.


Q: $uibModal not loading correct content on first click I'm working in ServiceNow and am trying to use $uibModal to open up a modal window that holds an embedded widget.  The modal opens fine on the first click, but every click after that requires two clicks for the modal to load the correct content.  I've read on a few sites that it's because of the template cache doesn't clear and some people suggested not using the script tags, but I'm not sure how to get uibModal to work without the script tags in ServiceNow.  Has anyone run into this?  Would love to get some suggestions on how to fix this.
Here's my client script:
c.onWidget2 = function(template, task) {
    c.taskName = task.short_description;
    c.modalInstance = $uibModal.open({
        templateUrl: template,
        scope: $scope,
        size: 'lg'
    });
    spUtil.get('hrj_task_activity_scoped', {
        sys_id: task.sys_id,
        table: 'sn_hr_core_task',
        recordInfo: task.taskInfo
    }).then(function(response) {
        c.newTask2 = response;
    });
};

//closeModal for the "x"
c.closeModal = function() {
    c.modalInstance.close();
};

And here's my HTML:

A: problem here is "directive in modal", like in this thread:
Integrating directive in Angular UI Modal
The solution would be to load the directive after the modal is rendered:
c.onWidget2 = function(template, task) {
    c.taskName = task.short_description;

    var initWidget =  spUtil.get('hrj_task_activity_scoped', {
        sys_id: task.sys_id,
        table: 'sn_hr_core_task',
        recordInfo: task.taskInfo
    }).then(function(response) {
        c.newTask2 = response;
    });

    c.modalInstance = $uibModal.open({
        templateUrl: template,
        scope: $scope,
        size: 'lg'
    }).rendered.then(initWidget);
};

//closeModal for the "x"
c.closeModal = function() {
    c.modalInstance.close();
};


Q: Fatal error: Class ‘mysqli’ not found in C:\xampp\htdocs\code\query.php I’m in the middle of E10-4 from 'Learning PHP, MySQL & JavaScript' by Robin Nixon.  I have enjoyed the book until two days ago when I got to exercise 10-4 where I was asked to run the following php program:
<?php
require_once 'login.php';
  $conn = new mysqli($hn, $un, $pw, $db);
  if ($conn->connect_error) die($conn->connect_error);

  $query  = "SELECT * FROM classics";
  $result = $conn->query($query);
  if (!$result) die($conn->error);

  $rows = $result->num_rows;

  for ($j = 0 ; $j < $rows ; ++$j)
  {
    $result->data_seek($j);
    echo 'Author: '   . $result->fetch_assoc()['author']   . '
';
    $result->data_seek($j);
    echo 'Title: '    . $result->fetch_assoc()['title']    . '
';
    $result->data_seek($j);
    echo 'Category: ' . $result->fetch_assoc()['category'] . '
';
    $result->data_seek($j);
    echo 'Year: '     . $result->fetch_assoc()['year']     . '
';
    $result->data_seek($j);
    echo 'ISBN: '     . $result->fetch_assoc()['isbn']     . '

';
  }

  $result->close();
  $conn->close();
?>

I get the two following error messages:

*

*Fatal error: Class ‘mysqli’ not found in
C:\xampp\htdocs\code\query.php

*PHP Fatal error: Class ‘mysqli’ not found in C:\xampp\htdocs\code\query.php

I’m running the following systems:

*

*Windows 7 Home Premium

*PHP 5.6.8

*XAMPP Control Panel v3.2.1

*Apache 2.4.12

*Database client version: libmysql - mysqlnd 5.0.11-dev -

*PHP extension: mysqli

I have searched stackoverflow and found a few posts about similar problems but could not pull any information out to solve the problem.  I’m new to programming but the responses where over my head.  I really have enjoyed this book but this Fatal error is keeping me from doing some great stuff with php and I'm not sure what I can do if I don't get past this issue.  I'm sure it is simple to fix.  Thanks for your help.


Q: Why is this labeled javaScript continue not working? I am using this code to weather some circles are overlapping:
iCantThinkOfAGoodLabelName:
x = genX(radius);
y = genY(radius);
for(i in circles) {
  var thisCircle = circles[i];
  if(Math.abs(x-thisCircle["x"])+Math.abs(y-thisCircle["y"])>radius*2) { //No overlap
    continue;
  } else { //Overlap
    continue iCantThinkOfAGoodLabelName; //<- Line 256
  }
  thisCircle = [];
}

But when the continue statement is reached, chrome's developer console gives me this: client.html:256 Uncaught SyntaxError: Undefined label 'iCantThinkOfAGoodLabelName'

A: Because iCantThinkOfAGoodLabelName: needs to be right before the loop.
iCantThinkOfAGoodLabelName:
for (blah; blah; blah)
    ..

I think what you want is a function..
function iCantThinkOfAGoodFunctionName() {
    var x = genX(radius),
        y = genY(radius);

    for (i in circles) {
        var thisCircle = circles[i];
        if(Math.abs(x-thisCircle["x"])+Math.abs(y-thisCircle["y"])>radius*2) { //No overlap
            continue;
        } else { //Overlap
            iCantThinkOfAGoodFunctionName();
        }
        thisCircle = [];
    }
}

A: There should not be any statement between a label name and associated loop.
x = genX(radius);
y = genY(radius);
iCantThinkOfAGoodLabelName:
    for(i in circles) {

fixes it.

A: The label should come immediately before the loop
x = genX(radius);
y = genY(radius);

iCantThinkOfAGoodLabelName:
for(i in circles) {

A: I recently had this issue and I resolved it by using all lowercase in the loop's label in version v0.8.x of Node.js.
Using labelname: vs. iCantThinkOfAGoodLabelName: might help you.
Others have correctly corrected you on the location of the label. It should be immediately before the for loop.
The Mozilla Developer Network on labels advises to avoid using labels, and instead prefer calling functions or throwing an error. You might rethink your strategy on using them, if possible.
Example of calling a function depending on result:
var i, j;

for (i = 0; i < 3; i++) {
   for (j = 0; j < 3; j++) {
      if (i == 1 && j == 1) {
         // we want to ignore and continue
      } else {
         // do work with these variables from inside the doWork function
         // (scoped to whatever scope `this` for loop is in)
         doWork.call(this, i, j);
      }
   }
}


Q: error using result returned from angular service (undefined) So I have two variables in my Typescript class:
private myServiceSubscription: Subscription;
myVar: myDto[] = [];

In the ctor:
this.myServiceSubscription = this.deliveryPointService
        .getPostalAddresses()
        .subscribe(result => console.log(result));

I can see the expected result returned from the service in the console log (a list with two items)
However, if I use another subscribe instead:
.subscribe(result => this.myVar);

and (outside the subscribe):
    console.log(this.myVar[0]);
then I notice this.myVar is undefined.
Why does console.log(result) show the right result, but this.myVar does not?
This is in angular 4.

A: Right now, you don't do anything with the result of your service method. You have to assign the returned item to your variable:
.subscribe(result => {
   this.myVar = result;
   console.log(this.myVar);
});


Q: How to prompt message box in remote computer where application is running as service? I have an C++ MFC application running in master machine that installs update from a server in remote computers through an agent service. This service takes care of authorization in remote machines before update. Now, I need to prompt the currently active user in remote machines for confirmation. AfxMessagebox or MessageBox in the service context doesn't show up any window in remote machines. Is there a way to achieve this?

A: Look at WTSSendMessage():

Displays a message box on the client desktop of a specified Remote Desktop Services session.


Q: The row couldn't be updated because a foreign key constraint failed. Verify the constraint and try again    {
 "entity":{
  "base_currency_code":"AUD",
  "base_discount_amount":0,
  "base_grand_total":296.95,
  "base_shipping_amount":0.0,
  "base_shipping_incl_tax":5,
  "base_shipping_tax_amount":0,
  "base_shipping_discount_amount":0,
  "base_subtotal":33,
  "base_subtotal_incl_tax":33,
  "base_total_due":0,
  "base_total_paid":296.95,
  "base_to_global_rate":1,
  "base_to_order_rate":1,
  "discount_tax_compensation_amount":0,
  "base_discount_tax_compensation_amount":0,
  "shipping_discount_tax_compensation_amount":0,
  "customer_is_guest":0,
  "customer_email":"working@user.com",
  "customer_firstname":"Working",
  "customer_group_id":1,
  "customer_id":4,
  "customer_lastname":"User",
  "customer_note_notify":1,
  "discount_amount":0,
  "email_sent":1,
  "global_currency_code":"AUD",
  "grand_total":296.95,
  "order_currency_code":"AUD",
  "shipping_amount":0.0,
  "shipping_tax_amount":0,
  "shipping_description":"For this item only:",
  "shipping_discount_amount":0,
  "shipping_incl_tax":5,
  "state":"pending",
  "status":"processing",
  "store_currency_code":"AUD",
  "store_to_base_rate":0,
  "store_to_order_rate":0,
  "store_id":1,
  "subtotal":33,
  "subtotal_incl_tax":33,
  "total_due":0,
  "total_paid":296.95,
  "total_item_count":1,
  "total_qty_ordered":1,
  "tax_amount":27.0,
  "weight":1,
  "items":[
     {
        "base_original_price":99.95,
        "base_price":99.95,
        "base_price_incl_tax":109.95,
        "base_row_total":99.95,
        "name":"S00002 - [ IP1WW16ESIUPR2GRA] NEC Aspire IP1WW-16ESIU-PR2 16 Port Digital Station Card 0891014",
        "original_price":99.95,
        "price":99.95,
        "price_incl_tax":109.95,
        "product_id":11,
        "product_type":"simple",
        "qty_ordered":1.0,
        "row_total":109.95,
        "row_total_incl_tax":109.95,
        "sku":"002",
        "store_id":1,
        "weight":1
     },
     {
        "base_original_price":170.0,
        "base_price":170.0,
        "base_price_incl_tax":187.0,
        "base_row_total":170.0,
        "name":"S00002 - [ IP2WWEXIFUA1GRA] NEC IP2WW-EXIFU-A1 Programming Interface Card ",
        "original_price":170.0,
        "price":170.0,
        "price_incl_tax":187.0,
        "product_id":11,
        "product_type":"simple",
        "qty_ordered":1.0,
        "row_total":187.0,
        "row_total_incl_tax":187.0,
        "sku":"002",
        "store_id":1,
        "weight":1
     },
     {
        "base_original_price":0.0,
        "base_price":0.0,
        "base_price_incl_tax":0.0,
        "base_row_total":0.0,
        "name":"S00002 - Free delivery charges",
        "original_price":0.0,
        "price":0.0,
        "price_incl_tax":0.0,
        "product_id":11,
        "product_type":"simple",
        "qty_ordered":1.0,
        "row_total":0.0,
        "row_total_incl_tax":0.0,
        "sku":"002",
        "store_id":1,
        "weight":1
     }
  ],
  "billing_address":{
     "address_type":"billing",
     "city":"Karachi",
     "company":false,
     "country_id":"PK",
     "customer_address_id":4,
     "email":"working@user.com",
     "firstname":"Working",
     "lastname":"User",
     "postcode":"74600",
     "region":"SIN3",
     "street":[
        "abc"
     ],
     "telephone":"333333"
  },
  "payment":{
     "amount_ordered":38,
     "amount_paid":38,
     "base_amount_ordered":38,
     "base_amount_paid":38,
     "base_shipping_amount":0.0,
     "method":"banktransfer",
     "shipping_amount":0.0
  },
  "status_histories":[
     {
        "comment":"new order",
        "status":"processing"
     }
  ],
  "extension_attributes":{
     "shipping_assignments":[
        {
           "shipping":{
              "address":{
                 "address_type":"shipping",
                 "city":"Karachi",
                 "company":false,
                 "country_id":"PK",
                 "customer_address_id":4,
                 "email":"working@user.com",
                 "firstname":"Working",
                 "lastname":"User",
                 "postcode":"74600",
                 "region":"SIN3",
                 "street":[
                    "Sample Street Address"
                 ],
                 "telephone":"332543403"
              },
              "method":"freeshipping_freeshipping",
              "total":{
                 "base_shipping_amount":0.0,
                 "base_shipping_incl_tax":0.0,
                 "shipping_amount":0.0,
                 "shipping_incl_tax":0.0
              },
              "extension_attributes":[
              ]
           },
           "items":[
           ],
           "extension_attributes":[
           ]
        }
     ],
     "applied_taxes":[
     ],
     "item_applied_taxes":[
     ],
     "converting_from_quote":false
  }

i am hitting this end point with above parameter /V1/orders/
{
"message": "The row couldn't be updated because a foreign key constraint failed. Verify the constraint and try again."
}

A: check your order payload may be customer id issue or try developer mode then you can see error in details


Q: Push Data from a WCF Service to Website I have the following scenario, and I would like to know if there is a solution to achieve such thing:
I have a WCF service that is running in a backend server, and it does bulk data processing, like inserting records into DB, and I would like to have this service send a message or notification once a record has done processing to a webpage (ASP.NET Page), where this page should be listening to these messages and display a progress with the finished tasks at real-time.
Note: The WCF service is separate from the webpage; This means that the WCF service process starts when another WCF service calls it in the backend server, so the web-page should only 'listen' to the updates that comes from WCF service.
Through my research, I have come up with SignalR, can this technology help me build a solution for such a scenario, or maybe there is some other way to achieve it?


Q: How to collect activity information from network-attached storage (NAS) devices? My goal is to be able to generate a report about the users that have accessed a particular folder on any file share. This includes Windows file servers, Unix/Linux file servers, and NAS devices (CIFS/SMB/NFS).

*

*For Windows, this isn't too complicated because it has built-in functionality that supports this (see: http://blogs.splunk.com/2013/07/08/audit-file-access-and-change-in-windows).

*I'm assuming that there is similar built-in functionality for unix/linux shares.

*So this leaves the question of whether something like this is possible for NAS devices (CIFS/SMB/NFS).

I'm thinking that something like this is possible because of some tools that I see are available, such as what is available at http://www.imperva.com/products/fsc_file-activity-monitoring.html.
So my question is the following: Is it possible to collect file share activity information from NAS devices? If so, how do I collect this information? For example, if there were APIs to support this, it would be most useful.

A: Is your NAS running SAMBA?  If so will the Samba log files or smbstatus command solve your need?  See https://askubuntu.com/questions/89288/how-can-i-monitor-my-samba-traffic


Q: Нужны хорошие эмуляторы iPhone, iPad Подскажите, пожалуйста, хорошие эмуляторы iPhone, iPad для просмотра сайтов. ОС Windows 7.

A: Очень сложно ответить на этот вопрос, поскольку не озвучены критерии "хорошести".
Для большинства типичных задач лично мне вполне хватает Google Chrome в режиме эмуляции мобильного устройства...

A: Как вариант эмуляторы iPhone, iPad
http://iphone-emulator.org/


Q: Wordpress - How to extract the first video embed from post content and place it in different area? I am trying to build a wordpress theme which extracts the first embedded video out of the content of the post and features it on top of the page.
So for example, I am trying to go from this:

Post content

Post content

To this:

Post content

Post content

So the important things I am trying to accomplish are:
1) Finding the first embedded video within the post content.
2) Placing that first video in the above featured area.
3) Filtering that first video out of the content (so that it doesn't appear twice on the page).
So far I am simply using the get_post_custom() function to get the first embed code within the post and copy it into the featured area. I am having problems with number 3 though (filtering out the first video from the post content). I could just hide the first embedded video with CSS, but it doesn't feel right to me. I feel like I need to filter the video out of the content completely. Am I right or wrong about this?
I have also had ideas about using the oembed filters in wordpress but I can't seem to get my head round how to implement them.
Let me know what you think is the best way of doing this is.


Q: using JSON to get data from MYSQL to Java i'm trying for days to get this working.. but i still fail.
<?php
$province = $_POST['test'];
$dbhost = 'localhost';
$dbname = 'news';
$dblogin = 'root';
$dbpass = '';

function dbConnect() {
   global $dbhost;
   global $dbname;
   global $dblogin;
   global $dbpw;

   $db = mysql_connect($dbhost, $dblogin, $dbpw) or die("could not
connect to database: ".mysql_error());
   mysql_select_db($dbname) or die("could not select database");
   return $db;
}
function dbClose($db) {
   mysql_close($db);
}

// basis code ^^

$db = dbConnect();

$query = "SELECT title FROM news_google_us";

$result = mysql_query($query) or die(mysql_error());

while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{

echo json_encode($row);

 ;}

?>

i get this as response:
{"title":"Obama and GOP in Deal on Tax Cuts - New York Times"}{"title":"WikiLeaks Founder Warns About More Dispatches - New York Times"}{"title":"S. Korea to make islands near N. Korea fortresses - Jerusalem Post"}{"title":"9th Circuit judges explore narrow routes to reinstate gay marriage - Los Angeles Times"}{"title":"Killing of Iranian Scientist Overshadows 6-Nation Nuclear Talks - BusinessWeek"}{"title":"Schwarzenegger proposal rebuffed - San Jose Mercury News"}{"title":"WikiLeaks list of 'critical' sites: Is it a 'menu for terrorists'? - Christian Science Monitor"}{"title":"Big moments in the Concorde's history - BusinessWeek"}{"title":"Citigroup Stake Is Sold for About $10.5 Billion as US Unwinds Investment - Bloomberg"}{"title":"Jets Vs. Patriots: New England In Full-On Kobra Kai Mode...No Mercy - SB Nation"}{"title":"Obama, GOP cut deal to extend tax cuts - USA Today"}

I use Jquery to get the data:
 $.ajaxSetup({"error":function(XMLHttpRequest,textStatus, errorThrown) {
      alert(textStatus);
      alert(errorThrown);
      alert(XMLHttpRequest.responseText);
  }});

 $.getJSON('mysql-query.php', function(data) {
    alert(data);
 });

I've tried a stripped version
<?

$dsn = "mysql:host=localhost;dbname=news";
$username = "root";
$password = "";

$pdo = new PDO($dsn, $username, $password);

$rows = array();
if(isset($_GET['descrtiption'])) {
 $stmt = $pdo->prepare("SELECT description FROM news_BBC_sport WHERE name = ? ORDER BY description");
 //   $stmt = $pdo->prepare("SELECT variety FROM fruit WHERE name = ? ORDER BY variety");
    $stmt->execute(array($_GET['descrtiption']));
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    echo "
";
print_r(phpinfo());
echo "
";
}

echo json_encode($rows);
?>

tried this one
I've tried a stripped version
<?

$dsn = "mysql:host=localhost;dbname=news";
$username = "root";
$password = "";

$pdo = new PDO($dsn, $username, $password);

$rows = array();
if(isset($_GET['descrtiption'])) {
 $stmt = $pdo->prepare("SELECT description FROM news_BBC_sport WHERE name = ? ORDER BY description");
 //   $stmt = $pdo->prepare("SELECT variety FROM fruit WHERE name = ? ORDER BY variety");
    $stmt->execute(array($_GET['descrtiption']));
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    echo "
";
print_r(phpinfo());
echo "
";
}

echo json_encode($rows);
?>

tried this one
http://www.phpclasses.org/package/4369-PHP-Generate-JSON-representation-from-MySQL-queries.html
I'm using firebug to check what's wrong. I get this:
parse error

syntax error JSON parse

(shows json data)

I've tried like everything, but i still get this error. I'm using a XAMPP server on OSX.

A: You first attempt is almost right, just don't echo each row, collect the result then echo:
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
    $rows[] = $row;
}
echo json_encode($rows);


Q: While installing yolov3 using conda on window10 getting error Solving environment: failed When I am trying to install yolov3 on windows10 using Conda, getting following error:
(base) D:\aaa\yolo>conda env create -f yolo.yml
Collecting package metadata (repodata.json): done
Solving environment: failed  ResolvePackageNotFound:
vc==14.1=h0510ff6_3
vs2015_runtime==15.5.2=3

How do I solve this issue?


Q: Create a Spring bean that cannot be autowired I have a class A that extends B, which implements C. Currently, A takes B has an input argument and is the only defined bean that is an implementation of C, so it gets autowired whenever C is needed.
Without changing the ALL of the places where C is needed or the class structure of A/B/C, I need make B a defined bean so the same instance can be re-used. The problem is then I have 2 implementations of C (A and B). Is there a way to mark B so that it cannot be autowired?
Current:
  <bean id="A" class="A">
    <constructor-arg>
      <bean class="B">
    </constructor-arg>
  </bean>

Wanted (so same instance of B can be used elsewhere):
  <!-- TODO: Somehow mark B so it cannot be autowired -->
  <bean id="B" class="B"/>

  <bean id="A" class="A">
    <constructor-arg ref="B">
  </bean>

  <bean id="Foo" class="Foo">
    <constructor-arg ref="B">
  </bean>

A: If you want to eliminate a bean from autowiring, then you can set autowire-candidate attribute of that bean tag to false.
For example consider your case(Here I am setting B bean's autowire-candidate attribute to false)
 <bean id="B" class="B" autowire-candidate="false"/>

  <bean id="A" class="A">
    <constructor-arg ref="B">
  </bean>

  <bean id="Foo" class="Foo">
    <constructor-arg ref="B">
  </bean>

A: You could use qualifiers attached to @Autowired.
E.g., if you want to wire the bean with id B, you can do the following:
@Autowired
@Qualifier("B")
private C c;