Q:

Using the decorator pattern on this composition

Well I have a composition pattern used, where one graphic object is extended in a group and in rectangles. A group can have many rectangles and a paint() method call for the groups, calls paint methods in rectangles and each rectangle draws itself.
Now I need to somehow use a decorator pattern on that, to align the rectangles to the left or right side. Now If I use the decorator on the group, it just aligns the groups coordinates I guess, but since all the rectangles draw themselves, it doesn't have effect on them.
So any ideas how I could use the decorator pattern in here?
I mean the only way I can think of using it is to use the decorator wrapper around every rectangle and every element in the group that needs to be aligned. But doesn't this go against the policies of the decorator pattern? I mean the group technically doesn't know what it has in it's list, to it the elemnts are just GraphicObject instances and the rectangles don't know they are wrapped around with a decorator that would modify their coordinates before calling the rectangles' paint() methods.
If that's the only way, then how do I use it to decorate those items? Do I have to use reflections here or is there any other/more correct way to do that?
Some code:
if (mainGroup == null) {
        mainGroup = new Group();

        // first line
        currentBounds = convertToBoundsForLine(x, y, width, lineHeight, 1);
        //System.out.format("current bounds: x1=%d, y1=%d, x2=%d, y2=%d%n", currentBounds.getX(), currentBounds.getY(), currentBounds.getX2(), currentBounds.getY2());
        GraphicObject rect1 = new Rectangle(currentBounds);
        mainGroup.addChild(rect1);

        // other lines...

        // fifth line
        currentBounds = convertToBoundsForLine(x, y, width, lineHeight, 5);
        //System.out.format("current bounds: x1=%d, y1=%d, x2=%d, y2=%d%n", currentBounds.getX1(), currentBounds.getY1(), currentBounds.getX2(), currentBounds.getY2());
        GraphicObject rect5 = new Rectangle(currentBounds);

        // this is with the decorator wrapper around - should I use reflection here?
        GraphicObject blabla = new DecoratorLeft(rect5);
        mainGroup.addChild(blabla);

Well at the fifth line, you can see where I'm putting the rectangle inside the decorator before adding it to the group, so should I use reflections and use them on every rectangle which is added to the group. Or is there a better way to do that?
Or is the way I'm using the decorator here totally wrong in general?
Thanks in advance.
EDIT:
Here's how my paint method is implemented in the group:
public void draw(Graphics g, AlignStrategy align) {
    for (GraphicObject graphic: children) {
        graphic.draw(g, align);
    }
}

The group just calls the childrens draw methods.
The thing is, the decorator should be Universal in my opinon, according to the suggestion you gave it seems like it would make it dependant? I mean the group is the basically dependant on the alignment? What if say I created a decorator that would rotate the object, or switch coordinates x with y? I mean it's not about aligning left, right or center, it's about the decorator working without having to adapt the code too much to the decorator?

A:

If you have full control over the code behind GraphicObject, Group, Rectangle, and the like (i.e., if it's all your code), then I think using the decorator pattern may be the hard way to go. It would be simpler to implement the drawing alignment using code similar to AWT's Layout approach, where the parent object (probably a Group in your case) is given a single Layout object that is responsible for managing the arrangement of the parent's children. The default layout doesn't affect the children. The "align left" and "align right" layouts would make the necessary position changes to the children during a layout phase that takes place some time before painting. So Group would have a default Layout object that could be replaced by the alignment-specific versions when you need them.
If you don't have control of the code behind the drawing objects, then I think a decorator around Group would work better than decorating all the children. Have the Group-level decorator's paint() method manage the alignment of the children when it's called. This way you have only one decorator per Group rather than one decorator per drawable object. This is essentially the layout code rolled into a decorator class, but you could always break out the layout code and have the decorator call it.
Edit: Here's an example of the second case. To keep it simple, I only list the necessary parts, not the details.
public class GroupDecorator extends GraphicObject { //or extends whatever is best
    public GroupDecorator(Group wrappedGroup) {
        myGroup = wrappedGroup;
    }

    public void paint() { //Assume this is your common paint() method
        //note I'm making up the names here, since I don't know them
        List groupsChildren = myGroup.getChildren();

        //The type of alignment is stored somewhere in this object
        //or is hard-coded. That's up to you. I'll assume it's stored somewhere...

        if (isAlignedLeft()) {
          //align all the children to the left here
        } else if (isAlignedRight()){
          //align all the children to the right here
        } else {
          //do nothing because no alignment is necessary
        }

        //call the wrapped Group's paint now. It will call its children's paint()s.
        myGroup.paint();

        //Unalign all the children here, if necessary, to put them back in
        //their original state. How you implement that is up to you.
    }

}
// Somewhere in your main code...

    mainGroup = new Group();

    //Decorate mainGroup now...
    GroupDecorator decoratedGroup = new GroupDecorator(mainGroup);
    //Configure decoratedGroup to align however you want.

    // first line
    GraphicObject rect1 = new Rectangle();
    mainGroup.addChild(rect1);

    // other lines...

    // fifth line
    GraphicObject rect5 = new Rectangle();

    //Now use decoratedGroup now in place of mainGroup.


Q:

How to supervise a process and schedule a periodic restart?

I run a process that sometime crash and sometime freeze.  I used supervise to have it automatically restart when it crash.  However, if it freeze, it stay frozen until I am back in front of the computer.  I would like a tool that would restart it when it crash, but can also be configure to do periodic kill and restart, so if it freeze, it won't stay frozen more that a given period of time.
Which tool would who suggest?
Thanks

A:

I tried using supervise from daemontools with a crontab :
First, I start with
supervise /fullpath

and I use this crontab :
0 23 * * * svc -d /fullpath
2 23 * * * svc -k /fullpath
5 23 * * * svc -u /fullpath

Where fullpath is the directory containing the file called run which start my process.  The tricky part is the file called should end with :
exec java ...

Normally, I start the application with a script, but if I put that script in the file called run, when svc is executed, it send the signal to the script and the java process continue to run.  I created a copy of the script and modified it to make it output the call to java with all parameter, and copied this in the file called run.


Q:

How to add or change an Xml namespace in SQL Server / Cannot use 'xmlns' in the name expression

I have a XML column that is not generated with a namespace, meaning no xmlns attribute. Unfortunately, I cannot fix the actual problem, meaning where the XML is created.
For example:
<root>Our Content</root>

I can modify the XML data before it's returned to a particular client that expects a namespace. What I want is pretty simple:
<root xmlns="http://OurNamespace">Our Content</root>

I tried something like:
.modify('insert attribute xmlns {"ournamespace"}...

But that errors with

Cannot use 'xmlns' in the name expression.

My questions are:

Is there a technique around this particular error?
Is there an alternative or better way to add/change a namespace on a SQL XML type?

This is in a SQL Server 2012 stored procedure.

A:

Maybe as simple as this?
DECLARE @xml XML='<root>Our Content</root>';

SELECT CAST( REPLACE(CAST(@xml AS NVARCHAR(MAX)),'<root>','<root xmlns="http://OurNamespace">') AS XML)


Q:

Why I can not use a variable for the :eq filter to append data to an unordered list?

Why I can not use a variable counter for the :eq filter to append data to an unordered list?
For example, the code is not working. It not being updated into the div of unordered list.
 $('#list li:eq("+ counter +")').append('
' + variable + '
');

A:

In addition to the string issue that Shadow Wizard mentions, if you're trying to add another li tag on the same level as #list li, then you're code isn't right.  Append, will add a child so:
$('#list li').eq(n).append('
' + variable + '
')

adds an LI tag inside the nth LI tag, not after the nth LI tag.  From the jQuery doc:

The .append() method inserts the specified content as the last child
  of each element in the jQuery collection

You may be interested in the .after() method if what you're trying to do is to insert a new LI tag after an existing LI tag, but at the same level:
$('#list li').eq(n).after('
' + variable + '
')

See here http://jsfiddle.net/jfriend00/PHkm4/ for a working example.


Q:

How to change the value of associated field

I have 2 classes with a LINQ association between them i.e.:
Table1:       Table2:
ID            ID
Name          Description
              ForiegnID

The association here is between Table1.ID -> Table2.ForiegnID
I need to be able to change the value of Table2.ForiegnID, however I can't and think it is because of the association (as when I remove it, it works).
Therefore, does anyone know how I can change the value of the associated field Table2.ForiegnID?

A:

Check out the designer.cs file.  This is the key's property
[Column(Storage="_ParentKey", DbType="Int")]
public System.Nullable<int> ParentKey
{
    get
    {
        return this._ParentKey;
    }
    set
    {
        if ((this._ParentKey != value))
        {
            //This code is added by the association
            if (this._Parent.HasLoadedOrAssignedValue)
            {
                throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();
            }
            //This code is present regardless of association
            this.OnParentKeyChanging(value);
            this.SendPropertyChanging();
            this._ParentKey = value;
            this.SendPropertyChanged("ParentKey");
            this.OnServiceAddrIDChanged();
        }
    }
}

And this is the associations property.
[Association(Name="Parent_Child", Storage="_Parent", ThisKey="ParentKey", IsForeignKey=true, DeleteRule="CASCADE")]
public Parent Parent
{
    get
    {
        return this._Parent.Entity;
    }
    set
    {
        Parent previousValue = this._Parent.Entity;
        if (((previousValue != value)
                    || (this._Parent.HasLoadedOrAssignedValue == false)))
        {
            this.SendPropertyChanging();
            if ((previousValue != null))
            {
                this._Parent.Entity = null;
                previousValue.Exemptions.Remove(this);
            }
            this._Parent.Entity = value;
            if ((value != null))
            {
                value.Exemptions.Add(this);
                this._ParentKey = value.ParentKey;
            }
            else
            {
                this._ParentKey = default(Nullable<int>);
            }
            this.SendPropertyChanged("Parent");
        }
    }
}

It's best to assign changes through the association instead of the key.  That way, you don't have to worry about whether the parent is loaded.


Q:

Java check platform supports sctp otherwise use tcp

Because netty uses different channel initialization for SCTP and TCP, so I would like to check if the platform supports SCTP, if it does, uses SCTP otherwise uses TCP. However, I could not find any method to check this in both JDK8 or netty4.

A:

It should be possible to call com.sun.nio.sctp.SctpServerChannel without an exception if sctp is available but I can't confirm that because I support sctp on all my devices.
Openjdk SCTP guide

To ensure that you have a correctly configured machine and JDK, try compiling and running the following application:

public class TestSCTP
{
    public static void main(String[] args) throws Exception {
        com.sun.nio.sctp.SctpChannel sc = com.sun.nio.sctp.SctpChannel.open();
    }
}

$ jdk1.7.0/bin/javac TestSCTP.java
$ jdk1.7.0/bin/java TestSCTP

If it compiles and runs without any errors, then congratulations you have a correctly configured machine and JDK. You can now start writing applications that use the SCTP API.


Q:

How to handle 401 errors in a Redux/React application

I am building a site with React and Redux and I have a query about how I should be handling 401 status responses.
Currently when the API reports a 401 HTTP Status it is usually caught in one of my actions and I dispatch:
return dispatch({
    type: 'FETCH_MONTHLY_DATA_FAILURE',
    error: response.data
});

And the related reducer checks the HTTP status code and I have some Redux middleware that checks for this HTTPStatus state value and reacts accordingly.
Is there a more elegant way I can handle these errors in a general manner? I am using Axios for my HTTP requests.

A:

Add global response interceptor which dispatches action when error occurs
import store from './store';

// Add a response interceptor
axios.interceptors.response.use(function (response) {
    // Do something with response data
    return response;
}, function (error) {
    // Do something with response error
    store.dispatch({
        type: 'API_ERROR',
        payload: error,
    })
    return Promise.reject(error);
});

// In you reducers...
reduce(state, action) {
    if (action.type === 'API_ERROR' && action.payload.statusCode === 401) {
        return { // whatever needed }
    }
    return state;
}

A:

You said :

And the related reducer checks the HTTP status code...

Using a middleware is great but the reducer should not check for the http status. It would be outside of its purpose.
From the documentation :

The reducer job is to specify how the application's state changes in
  response.

Your action-creators should be pure, all the async codes should live somewhere else.
Side effects do not belong in reducers
There are many ways to do it. It all comes down to preferences.
Here are 3 ways to handle HTTP requests in a more elegant way:
Option 1 (the most powerful one) : Generators, Sagas and complex chains of asynchronous operations
redux-saga allows you to do just that. I personally use this middleware to handle my api calls and responses.

The mental model is that a saga is like a separate thread in your
  application that's solely responsible for side effects. redux-saga is
  a redux middleware, which means this thread can be started, paused and
  cancelled from the main application with normal redux actions, it has
  access to the full redux application state and it can dispatch redux
  actions as well.

Here are the benefits I get from using this option :

isolate side-effect code to a single domain of the application(sagas)
composition of multiple sagas(complex with promises)
reduces promise boilerplate action
creators are pure so much easier to test!

Simplify implementation of use cases like:

In a large multi-user, multi-department blog, if a user had ever
clicked on a "subscribe to RSS Feed" button, then the next time the
user visits a section that has a dedicated RSS feed, show him/her a
suggestion to subscribe to this section's feed.
In an online IDE, if a user has never used a particular feature of an
application, but has arrived at a state that the aforementioned
feature might potentially be useful, show a help dialog introducing
this feature.
In stackoverflow, while the user was responding to a question, the
question has been changed by OP so you inform the user that the
question has been changed and the answer is potentially no longer
valid.
etc.

redux-observable is another option :
Compose and cancel async actions to create side effects and more.
Option 2 : put the intelligence that drives asynchronous operations in your application operations in actions creators
redux-promise or redux-thunk are good exemples.
So far so good. We removed the coupling, separated our the async logic somewhere else and have a clean architecture. However, redux-saga's more advanced feature will simplify complex use cases.
Here is the gist of redux thunk :

Asynchronous middleware like redux-thunk or redux-promise wraps the
  store's dispatch() method and allows you to dispatch something other
  than actions, for example, functions or Promises. Any middleware you
  use can then interpret anything you dispatch, and in turn, can pass
  actions to the next middleware in the chain. For example, a Promise
  middleware can intercept Promises and dispatch a pair of begin/end
  actions asynchronously in response to each Promise.

Option 3 : Managing side effects through Higher order components
Higher-Order Components (HOCs) are JavaScript functions which add functionality to existing component classes. Just as React components let you add functionality to an application, Higher-Order Components let you add functionality to components. You could say they’re components for components.
Not ideal for all use cases !
Exemple : axios, a promise based HTTP client for the browser and node.js
Option 4 : Generators and promises, sans Sagas
Last but not the least, you can still use generators to manage your async control flow, in frontend, without adding redux-thunk dependency, if you do not need some of its advanced features.


Q:

MySQL Inserting data from one table to another - error FULLTEXT index

Hey guys i'm trying to create a stored procedure where I enter in the Loan_ID from my loan_table and it moves it into another table called loan_history. I'm unsure on what I'm doing wrong. The error I'm getting is 'Can't Find FULLTEXT index matching the column list'
CREATE PROCEDURE `INSERT_INTO_lOAN_HISTORY`(in INSERT_LOAN_ID INT(11))
INSERT into loan_history
SELECT  *
FROM `loan_table`
Where MATCH (LOAN_ID) AGAINST (INSERT_LOAN_ID)

Schema
CREATE TABLE loan_table
( Loan_ID int(11) NOT NULL AUTO_INCREMENT,
Member_ID int(11) DEFAULT NULL,
Item_ID int(11) DEFAULT NULL,
Book_ID varchar(45) DEFAULT NULL,
Video_ID varchar(45) DEFAULT NULL,
Transaction_Date date DEFAULT NULL,
Due_date date DEFAULT NULL,
etc

A:

For other users and future reference, the solution was to remove the MATCH and change the WHERE conditional to where the ID equals the ID value from the IN parameter.
CREATE PROCEDURE `INSERT_INTO_lOAN_HISTORY`(in INSERT_LOAN_ID INT(11))
INSERT into loan_history
SELECT  *
FROM `loan_table`
WHERE Loan_ID = INSERT_LOAN_ID


Q:

POI 3.17 creating Cell Comments in a cloned sheet creates inconsistent xlsx

I used the cloneSheet method to copy a sheet within the same workbook which already contains comments.
Afterwards new comments where added to this new sheet and the excel saved.
When openening the file with Excel 365, it complained about /xl/comments1.xml and recovered the file.
The newly created comments are available. The comments from the clone are removed during the recovery.
Opening the zip file and looking at the /xl/comments1.xml, it shows a difference.

Is this an issue with the cloneSheet method or is Microsoft using new ways?

A:

As mature the apache poi project even is, it is long not finished yet. So one who needs using it must nevertheless know about the internals of the used file systems.
So how are comments stored in Excel's Office Open XML (*.xlsx) file system?
The whole file system is a ZIP archive. The sheet data of first sheet is in /xl/worksheets/sheet1.xml within that ZIP. The XML there has
...
<legacyDrawing r:id="rId2"/>
...

which points to a legacy VMLDrawing having rId2 in the relation parts XML of the first sheet.
The relation parts XML of the first sheet is /xl/worksheets/_rels/sheet1.xml.rels and looks like
<Relationships>
 <Relationship Id="rId3" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments" Target="../comments1.xml"/>
 <Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing" Target="../drawings/vmlDrawing1.vml"/>
...
</Relationships>

So rId2 points to /xl/drawings/vmlDrawing1.vml and rId3 points to /xl/comments1.xml.
So the vmlDrawing1.vml contains the anchors of the comments' shapes on the sheet while the 'comments1.xml` contains the comments' contents.
Now what is method public XSSFSheet cloneSheet(int sheetNum, String newName) of XSSFWorkbook doing?
At first, it copies all sheet's relations. So also the relations to the VMLDrawing and the Comments parts are copied. So if we are cloning first sheet, then after cloning /xl/worksheets/_rels/sheet2.xml.rels will have the same content as /xl/worksheets/_rels/sheet1.xml.rels has.
But then it states: "Cloning sheets with comments is not yet supported." and removes the <legacyDrawing r:id="rId2"/> from the sheet's  XML. But the previous copied relations are not removed.
So as the result we have a cloned sheet without comments linked in the sheet but having relations to the comments and their shapes set.
If we now creating new comments in that cloned sheet, then new /xl/drawings/vmlDrawing2.vml also is created inclusive its relation in /xl/worksheets/_rels/sheet2.xml.rels. So after that we have a /xl/worksheets/_rels/sheet2.xml.rels which points to /xl/drawings/vmlDrawing1.vml and to /xl/drawings/vmlDrawing2.vml as well. But that's not allowed and so Excel throws error while opening and suggests repairing.
Furthermore the new created comments are stored in /xl/comments1.xml which also is wrong because each sheet needs its own comments part. That happens because while cloning theXSSFSheet the field private CommentsTable sheetComments also is cloned and contains the old comments table of the source sheet now.
So for being able creating comments in the cloned sheet, we need get rid of the wrong relations and also get rid of the wrong CommentsTable in field sheetComments of the XSSFSheet.
Example:
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;

import org.apache.poi.POIXMLDocumentPart;
import org.apache.poi.POIXMLDocumentPart.RelationPart;

import java.io.FileInputStream;
import java.io.FileOutputStream;

import java.lang.reflect.Field;

class ExcelCloneSheetHavingComments {

 public static void main(String[] args) throws Exception {

  Workbook workbook = WorkbookFactory.create(new FileInputStream("ExcelHavingComments.xlsx"));

  Sheet sheetClone = workbook.cloneSheet(0);
  workbook.setSheetName(workbook.getSheetIndex(sheetClone), "Cloned first Sheet");

  if (sheetClone instanceof XSSFSheet) {
   XSSFSheet xssfSheet = (XSSFSheet)sheetClone;

   // get rid of the wrong relations
   for (POIXMLDocumentPart.RelationPart relationPart : xssfSheet.getRelationParts()) {
    if (relationPart.getDocumentPart() instanceof org.apache.poi.xssf.usermodel.XSSFVMLDrawing
     || relationPart.getDocumentPart() instanceof org.apache.poi.xssf.model.CommentsTable) {
     relationPart.getRelationship().getSource().removeRelationship(relationPart.getRelationship().getId());
    }
   }

   // get rid of the wrong org.apache.poi.xssf.model.CommentsTable
   Field sheetComments = XSSFSheet.class.getDeclaredField("sheetComments");
   sheetComments.setAccessible(true);
   sheetComments.set(xssfSheet, null);
  }

  Drawing drawing = sheetClone.createDrawingPatriarch();
  Comment comment = drawing.createCellComment(drawing.createAnchor(0, 0, 0, 0, 2, 1, 4, 4));
  comment.setString(new XSSFRichTextString("Comment in Cell C2 in cloned sheet"));

  workbook.write(new FileOutputStream("CopyOfExcelHavingComments.xlsx"));
  workbook.close();

 }
}

This does not copying the comments from source sheet. But of course this also wil be possible now using Sheet.getCellComments in source sheet and then Drawing.createCellComment in cloned sheet.


Q:

Laravel 5.2 What goes in facade getFacadeAccessor return

So I am trying to create my first ever Service provider and complimentary Facade in Laravel.
Service Provider:
<?php namespace Jbm\Providers;

use Illuminate\Contracts\Http\Kernel;
use Illuminate\Http\Request;
use Illuminate\Support\ServiceProvider as BaseServiceProvider;

use Jbm\Helpers\ReportGenerator;

class ReportGeneratorServiceProvider extends BaseServiceProvider
{
    /**
     * Indicates if loading of the provider is deferred.
     *
     * @var bool
     */
    protected $defer = true;

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app->bind('Jbm\Helpers\Contracts\ReportGeneratorContract', function($app){
            return new ReportGenerator();
        });
    }

    /**
     * Add the Cors middleware to the router.
     *
     * @param Kernel $kernel
     */
    public function boot(Request $request, Kernel $kernel)
    {
        //
    }

    /**
     * Get the services provided by the provider.
     *
     * @return array
     */
    public function provides()
    {
        return array('jbm.reportGenerator');
    }

}

Facade:
<?php

namespace Jbm\Facades;

use Illuminate\Support\Facades\Facade;

class ReportGenerator extends Facade
{
    protected static function getFacadeAccessor()
    {
        return 'jbm.reportGenerator';
    }
}

It seems that every package I look at handles things different ways. One thing I am confused about is what is supposed to go in the return of getFacadeAccessor() in the Facade. In my service provider I say it provides jbm.reportGenerator and then use that in the Facade but I don't know how that connects to what I've registered. Any help would be greatly appreciated.
Update:
I decided to add my service provider and my facade to my config/app.php and then tried to use it in a controller and it says "Report Generator not found". So it obviously isn't working...no idea why
Update 2:
After removing the dot in the name I am now getting Call to undefined method Jbm\Facades\ReportGenerator::parseConfig().

A:

getFacadeAccessor should return a string that your container "knows about". That means something that is registered via a Provider.
You add your facade and an alias to app.php to be able to access something your registered statically.
So when you call YourFacadeAlias::doSomething(); laravel detects YourFacaseAlias, sees what is returned from getFacadeAccessor and uses that result to return an object associated with it from container.
Since both your facade and helper are called "ReportGenerator" the problem might be with both of them. But I think you should first check your app.php to see if you set it right. And then make sure your getFacadeAccessor and binded values match.

A:

First, your service provider should be in the App\Providers namespace, and should extend ServiceProvider. So it will look like this:
<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Jbm\Helpers\ReportGenerator;

class ReportGeneratorServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->bind('Jbm\Helpers\Contracts\ReportGeneratorContract', function($app){
            return new ReportGenerator();
        });
    }
}

After that, the facade should be in the App\Facades namespace, and the getFacadeAccessor() method should return the class name of your service provider:
<?php

namespace App\Facades;

use Illuminate\Support\Facades\Facade;

class ReportGenerator extends Facade
{
    protected static function getFacadeAccessor()
    {
        return App\Providers\ReportGeneratorServiceProvider::class;
    }
}

Now, let's add the service provider and facade to the app:
// config/app.php

'providers' => [
    App\Providers\ReportGeneratorServiceProvider::class,
]

'aliases' => [
    'ReportGenerator' => App\Facades\ReportGenerator::class,
]


Q:

GCC not linking libraries. It compiles, but the resulting library is missing necessary references

Possible Duplicate:
GCC C++ Linker errors: Undefined reference to 'vtable for XXX', Undefined reference to 'ClassName::ClassName()'

Alright so I'm trying to compile a shared object library made up of 2 object files and a static library. I'm linking to libraries, but only Lua is actually used in MY objects the others are used in the .a file.
Here's the IDE generated linking step:
g++ -shared  obj/Debug/GL/Window/Window.o obj/Debug/main.o   -o bin/Debug/libLOOGL.so -lX11 -lXrandr -lGL -llua5.2  /home/matt/Desktop/Development/LOOGL/lib/bin/OOGL.a

Here's the output of ldd on the result:
ldd loogl.so
  linux-vdso.so.1 =>  (0x00007fff30b3e000)
  liblua5.2.so.0 => /usr/lib/x86_64-linux-gnu/liblua5.2.so.0 (0x00007f521b53e000)
  libstdc++.so.6 => /usr/lib/x86_64-linux-gnu/libstdc++.so.6 (0x00007f521b23e000)
  libgcc_s.so.1 => /lib/x86_64-linux-gnu/libgcc_s.so.1 (0x00007f521b027000)
  libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f521ac68000)
  libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 (0x00007f521a96e000)
  libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007f521a769000)
  /lib64/ld-linux-x86-64.so.2 (0x00007f521b991000)

The necessary libraries are not linked and the result will not run, it is missing references.

A:

The order of libraries on the link line is important:
Try:
g++ -shared  obj/Debug/GL/Window/Window.o obj/Debug/main.o   -o bin/Debug/libLOOGL.so /home/matt/Desktop/Development/LOOGL/lib/bin/OOGL.a -lX11 -lXrandr -lGL -llua5.2


Q:

How can I convert non-ASCII characters encoded in UTF8 to ASCII-equivalent in Perl?

I have a Perl script that is being called by third parties to send me names of people who have registered my software. One of these parties encodes the names in UTF-8, so I have adapted my script accordingly to decode UTF-8 to ASCII with Encode::decode_utf8(...).
This usually works fine, but every 6 months or so one of the names contains cyrillic, greek or romanian characters, so decoding the name results in garbage characters such as "ÐŸÐ¾Ð´Ñ€Ð°Ð¶Ð°Ð½ÑÐºÐ°Ñ". I have to follow-up with the customer and ask him for a "latin character version" of his name in order to issue a registration code.
So, is there any Perl module that can detect whether there are such characters and automatically translates them to their closest ASCII representation if necessary?
It seems that I can use Lingua::Cyrillic::Translit::ICAO plus Lingua::DetectCharset to handle Cyrillic, but I would prefer something that works with other character sets as well.

A:

I believe you could use Text::Unidecode for this, it is precisely what it tries to do.


Q:

Mobile @media query not making container cover whole screen

I have a survey page, with a background-color: red and a smaller container to hold survey contents, as in the example below from a desktop:

Now, I have used these @media queries to attempt to make the white container cover the whole page on a phone (so the whole page is the white container, no red background)
@media (max-width: 600px) {
  #survey-container {
    width: 100%;
    padding: 0px;
    }
  }
  @media (max-height: 800px) {
  #survey-container {
    height: 100%;
    padding: 0px;
    }
  }

Now, these queries have seemingly no effect on a mobile phone, giving me this page:

Why is my container still not covering the whole page?
Full HTML code here, giants-survey.html page: https://glitch.com/edit/#!/jdipasquale

A:

@import url(https://fonts.googleapis.com/css?family=Raleway:400,500) }

The bracket in the end of this font import caused the @media queries to not work, removing it and adding min-width: 100% made it work.


Q:

MySQL foreign key select matches

I have a database with articles. All articles have keywords. The keywords are in a separate table and keywords and articles are connected with a relational table, thusly:
articles
CREATE TABLE `articles` (
  `id` int(11) NOT NULL,
  `articleTitle` varchar(50) NOT NULL,
  `articleBody` text NOT NULL,
  `articlePermalink` varchar(50) NOT NULL,
  `articleAuthor` int(11) NOT NULL,
  `createdAt` datetime DEFAULT CURRENT_TIMESTAMP,
  `updatedAt` datetime DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

keywords
CREATE TABLE `keywords` (
  `id` int(11) NOT NULL,
  `keyword` varchar(64) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

articlekeywords
CREATE TABLE `articlekeywords` (
  `id` int(11) NOT NULL,
  `articleId` int(11) NOT NULL,
  `keywordId` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

I want to select all articles that have some or all keywords in common with any given article using articles.id as the identifier. Preferably with a single SQL call.
EDIT:
I ended up doing something very similar to what Gordon Linoff suggested below.
SELECT DISTINCT a.articleTitle, a.articlePermalink
FROM articles a
JOIN articlekeywords ak ON a.id = ak.articleId
JOIN articlekeywords ak2 ON ak.keywordId = ak2.keywordId AND ak2.articleId = $articleId AND not(a.id = $articleId)

A:

This is a self join.  You can get matching articles ordered by the number of keywords in common by doing:
select ak2.article2, count(*) as numKeywordsInCommon
from articlekeywords ak join
     articlekeywords ak2
     on ak.keywordid = ak2.keywordid and ak2.articleid = $arcticleid
group by ak2.articleid
order by numKeywordsInCommon desc;


Q:

Add a different title to leaflet multi layers control

I have two control layers on the top left and bottom left. I want to add a title only to the control layer on the top left. I use insertBefore() is work but the title appears on both control layers. is there any solution for this problem?
this my layer control
var layertopleft = new L.control.layers(baseMaps1, overlayMaps, optionL).addTo(map);
var layerbotleft = new L.control.layers(baseMaps, overlayMaps1, {collapsed: false, position: "bottomright"}).addTo(map);

this code of add a title
$('
Peta Bantuan Pemerintah
Dinas Ketahanan Pangan Provinsi Riau

').insertBefore('.leaflet-control-layers-base');

this a result
I want the title on the bottom left control layer do not exist:

A:

finally, I got the answer for my problem
by add + on selector and using children(), I don't know if this is the best way but it looks fine to me
$(".leaflet-top" + ".leaflet-right").children().prepend('
Peta Bantuan Pemerintah
Dinas Ketahanan Pangan Provinsi Riau

');


Q:

Does each assignment of values to an output NetCDF variable result in a rewrite of the entire dataset?

I am writing the results of a calculation to NetCDF variables at each iteration of a compute loop because I can't keep all the result data in memory before doing a single write to the variable.  My assumption was that each write to the NetCDF variable would only write the slice of data I'm writing and hence each write would be quick, however each write appears to be taking quite a while and my fear is that the entire NetCDF file is being rewritten at each variable assignment statement, rather than just the slice of data being assigned, resulting in quite an unnecessary I/O overhead.
The slices of result data are written into the output NetCDF variables like so:
outputSpi01MonthVariable[totalNumberOfOutputMonths, lat:lat + 1:1, len(lonDimension)] = spiScale01  # a numpy array with compatible shape assigned to the variable at specified indices

Is there a better way of assigning values to the output NetCDF variable which doesn't result in so much I/O overhead?  BTW I have set the fill to off for the output variables but this appears to have no effect.

A:

I use  NetCDF4-Python for reading/writing NetCDF, and no, the whole file is not written when you write a variable, or chunk of a variable.  Here's a full example:
http://nbviewer.ipython.org/5764942


Q:

How can I get the machine IP address only for several PCs using ForEach-Object in Powershell?

I am working on a script to get the IP address information from several computers using the ForEach statement. Problem is that the IP address string returns extra info, so in order to get rid of that info, I run this...
Get-WmiObject win32_networkadapterconfiguration |
    where { $_.ipaddress -like "1*" } |
    select -ExpandProperty ipaddress |
    select -First 1}

Which is fine for one computer but when I add it to the whole ForEach part of my script below, it returns the IP Address for my machine attached to all machine queried in the script.
Get-Content $MultiActivePing | foreach {
    Get-WmiObject win32_networkadapterconfiguration -ComputerName $_ |
    where { $_.ipaddress -ne $null} |
    select @{Expression={$_.__SErver};Label="Computer"}
      ,@{Expression={Get-WmiObject win32_networkadapterconfiguration | where { $_.ipaddress -like "1*" } | select -ExpandProperty ipaddress | select -First 1};Label="IPAddress"} `
      ,@{Expression={$_.DefaultIPGateway};Label="Gateway"}
                                        }

So I was wondering if there was a way to expand the property of the IP address without having to run another GWMI inside the SELECT IP address portion.

A:

Admitting I am a little confused since I don't know what you are expecting exactly however I can venture a guess. Mostly I'm not sure what you want the IP Address output to look like.
Get-Content $MultiActivePing | ForEach-Object {
    # Save the current computer name so we can use down the line.
    $computer = $_
    Get-WmiObject win32_networkadapterconfiguration -ComputerName $_ |
    where { $_.ipaddress -ne $null} |
    Select @{l="IPAddress";e={$_.ipaddress | Select -First 1}},@{l="Computer";e={$computer}},DHcpenabled,macaddress
}

The part about this that will vary depending on what you are trying to accomplish:
Select @{l="IPAddress";e={$_.ipaddress | Select -First 1}}

You already know the IP so there is no need to acquire it again. This takes the first IP in the array and outputs it alone. This is the part I think you are having issues with but I don't know how you choose what information to drop. The caveat obviously is that you could lose IP information that you actually want depending on the order it appears. I would suggest this then as well so nothing is lost:
Change the calculated property for IPAddress highlighted above to this:
@{l="IPAddresses";e={$_.ipaddress -Join ";"}}

That would take all IP's and convert them into a semicolon delimited string


Q:

mouseClicked event not working properly

 private JTable getTRent() {
    if (tRent == null) { ...

        tRent.addMouseListener(new MouseAdapter() {

            @Override
            public void mouseClicked(MouseEvent arg0) {
                tDescription.setText(house.getDescripcionMansion(tRent.getSelectedRow()));

                image.setIcon(new ImageIcon(BookWindow.class.getResource(
                        "/images/" + house.getCodeMansion(tRent.getSelectedRow()) + ".png")));

                String childrenAllowed = house.getChildrenAllowed(tRent.getSelectedRow());

                if (childrenAllowed == "N"){
                    txKids.setEditable(false);
                    cbBookHouse.setEnabled(true);
                }

           }
       });
    }
    return tRent;
}

The problem that I'm having with the previous code is that any condition, apart from the image, is accomplished, seems to be ignored.
I just checked if the value was read correctly and it is, with a println in console, I get a N or Y depending on the row, but if I check that value, nothing happens with the components I want its state to be changed.
Also tried to put those conditions inside the components and the same happens.
The code of the methods getChildrenAllowed() for example, is like this
      public String getChildrenAllowed(int index) {
      return houseRelation.get(index).getChildren();
  }

A:

Don't compare strings with ==, use equals() or equalsIgnoreCase()
if ("N".equalsIgnoreCase(childrenAllowed))

See How do I compare Strings in Java


Q:

How to use a group by in inner join

I have Two tables:
Table 1
ID   totalamount
---  -----------
100  1000
101  500

Table 2
ID   Individualamount
---  ----------------
100  500
100  300
100  100
101  200
101  300

I Need a result which shows
ID   TotalAmount  sum(Individualamount)  difference (TA-IA)  % of diff
---  -----------  ---------------------  ------------------  ---------
100  1000         900                    100                 10
101  500          500                    0                   0

A:

You can do this by putting the GROUP BY in a subquery. Here is a solution:
CREATE TABLE #1 (ID int, TotalAmount decimal(20,2));
CREATE TABLE #2 (ID int, Individualamount decimal(20,2));

INSERT #1 VALUES (100, 1000), (101, 500);
INSERT #2 VALUES (100, 500), (100, 300), (100, 100), (101, 200), (101, 300);

SELECT a.ID
, a.TotalAmount
, c.[Sum(IndividualAmount)]
, d.[Diffence(TA-IA)]
, e.[%of diff]
FROM #1 a
LEFT JOIN
(
    SELECT b.ID, [Sum(IndividualAmount)] = SUM(b.IndividualAmount)
    FROM #2 b
    GROUP BY b.ID
) c
    ON c.ID = a.ID
CROSS APPLY
(
    SELECT [Diffence(TA-IA)] = a.TotalAmount - c.[Sum(IndividualAmount)]
) d
CROSS APPLY
(
    SELECT [%of diff] = 100.0 * [Diffence(TA-IA)] / NULLIF(a.TotalAmount, 0)
) e;

Results:
ID   TotalAmount  Sum(IndividualAmount)  Diffence(TA-IA)    %of diff
100      1000.00                 900.00           100.00   10.000000
101       500.00                 500.00             0.00    0.000000


Q:

How do I remake my floor using hardwood such that it will not squeak at all?

I have carpet in my bedroom that when you walk on certain spots makes lots of noise. I am tossing the carpet and putting down hardwood flooring. I am using 3/4 in prefinished oak in widths of 3 1/4 inch.
I dont want my shiny new floor to be squeaky. What should I do to kill any noise in the current floor, sub floor, and new hardwood floor?
I have joists at 16" on center with 1/2 plywood layer on top and nailed down. This is my current floor after I got rid of the carpet that used to be there.
What do I do now, what steps do I take, what materials/ tools do I need?
EDIT: thanks all, i will 100% use screws and drive them in near each nail already in the plywood to hold things together well. then i will go around and knock each nail in good.
then add the paper and install hardwood on top.

A:

Use screws instead of nails to hold the plywood down.  If you can, screw it into the joists, not just the existing floor.  You can also put down some glue betwen the plywood & subfloor to prevent the plywood from moving at all.  Use tongue-and-groove plywood if possible.
If that doesn't help (and you should be able to do that & check to see if you still have squeaks before putting down the hardwood) you might need to beef up the joists, or add additional bracing, from underneath.  Not so hard if the ceiling below is open, a lot of work if it's finished.

A:

Squeaky floors are usually caused by loose floorboards. The boards rub against each other when you walk over them, which causes the squeak.
To remedy this situation, lift the carpet and locate the loose boards. Then just simply screw or nail the board down (being careful not to hit any pipes/wires that might be threaded through the joists).
For your new floor you need to make sure that there's no movement of boards against each other.

A:

We have talked about this topic several times. Definitely screw down the existing subfloor and any new underlayment or use coated treaded nails in your air nailer. Hit the joists and keep screws and nails at 10 to 12 inches apart throughout the field, with special attention to joints and corners. I don't recommended glue between subfloor layers as it can cause buckling of dislike materials. Instead of glue, simply add a layer of red rosin paper to keep the woods from rubbing against each other.  The same is true before you put down your new hardwood. The most common cause of squeaks are loose nails in old shrunken wood and loose fitting wood on wood. Good luck.


Q:

How to make Apache Nutch indexing while crawling

I started using Apache Nutch (v1.5.1) to index all the website under some certain domain.
There is huge number of websites (in the order of milions) in my domains and I need to index them step by step instead of waiting the end of the whole process.
I found this in nutch wiki (here http://wiki.apache.org/nutch/NutchTutorial/#A3.2_Using_Individual_Commands_for_Whole-Web_Crawling) something that should work. The idea is to make a script witch calls every single step of my process (crawl, fetch, parse, ...) on a certain amount of data (for example 1000 URL) cyclically.
bin/nutch inject crawl/crawldb crawl/seed.txt

bin/nutch generate crawl/crawldb crawl/segments -topN 25
s1=`ls -d crawl/segments/2* | tail -1`
echo $s1

bin/nutch fetch $s1
bin/nutch parse $s1
bin/nutch updatedb crawl/crawldb $s1

bin/nutch generate crawl/crawldb crawl/segments -topN 25
s2=`ls -d crawl/segments/2* | tail -1`
echo $s2

bin/nutch fetch $s2
bin/nutch parse $s2
bin/nutch updatedb crawl/crawldb $s2

...

bin/nutch invertlinks crawl/linkdb -dir crawl/segments
bin/nutch index crawl/indexes crawl/crawldb crawl/linkdb crawl/segments/*

My question is: is there any way to specify this setting directly into Nutch and make him do this stuff in a parallel and more trasparent way? For example on separated threds?
Thank for answering.
UPDATE
I tried to create the script (the code is above) but unfortunatlly I get an error on the invert link phases. This is the output:
LinkDb: starting at 2012-07-30 11:04:58
LinkDb: linkdb: crawl/linkdb
LinkDb: URL normalize: true
LinkDb: URL filter: true
LinkDb: internal links will be ignored.
LinkDb: adding segment: file:/home/apache-nutch-1.5-bin/crawl/segments/20120730102927
LinkDb: adding segment: file:/home/apache-nutch-1.5-bin/crawl/segments/20120704094625
...
LinkDb: adding segment: file:/home/apache-nutch-1.5-bin/crawl/segments/20120704095730

LinkDb: org.apache.hadoop.mapred.InvalidInputException: Input path does not exist:
file:/home/apache-nutch-1.5-bin/crawl/segments/20120730102927/parse_data

Input path does not exist:
file:/home/apache-nutch-1.5-bin/crawl/segments/20120704094625/parse_data
...

Thanks for your help.

A:

(If I had enough rep I would post this as a comment).
Remember that the -depth switch refers to EACH CRAWL, and not the overall depth of the site it will crawl. That means that the second run of depth=1 will descend one MORE level from the already indexed data and stop at topN documents.
So, If you aren't in a hurry to fully populate the data, I've had a lot of success in a similar situation by performing a large number of repeated shallow nutch crawl statements (using smallish -depth (3-5) and -topN (100-200) variables) from a large seed list. This will ensure that only (depth * topN) pages get indexed in each batch, and the index will start delivering URLs within a few minutes.
Then, I typically set up the crawl to fire off every (1.5*initial crawl time average) seconds and let it rip. Understandably, at only 1,000 documents per crawl, it can take a lot of time to get through a large infrastructure, and (after indexing, the paused time and other overhead) the method can multiply the time to crawl the whole stack.
First few times through the infrastructure, it's a pretty bad slog. As the adaptive crawling algo starts to kick in, however, and the recrawl times start to approach reasonable values : the package starts really delivering.
(This is somewhat similar to the "whole web crawling" method you mention in the nutch wiki, which advises you to break the data into 1,000 page segments, but much more terse and understandable for a beginner.)


Q:

How can i add sequence no using awk to any input file?

Suppose i am having following data in a file name Details.txt:
0154 Raghav Sharma 26 Indore
0159 rakh   patid  24 Pune
0159 rakh   patid  24 Pune
0018 sai    kanak  28 mumbai
0159 rakh   patid     Pune
0159 sarak  jatid     Pune

now i have applied following awk command for generating 4 digit sequence no:
awk 'BEGIN{a=1;OFS="    "}/^/{$1=sprintf("%04d",a);++a;print $0; next;}{print $0}' Details.txt

output:
0001 0154 Raghav Sharma 26 Indore
0002 0159 rakh   patid  24 Pune
0003 0159 rakh   patid  24 Pune
0004 0018 sai    kanak  28 mumbai
0005 0159 rakh   patid Pune
0006 0159 sarak  jatid Pune

the formatting of last two rows are disturbed.Please suggest a way,so that
proper formatting along with correct sequence no can be maintained.

A:

You want to avoid recomputing $0; if you do, multiple spaces will be condensed to a single space:
$ cat Details.txt
0154 Raghav Sharma 26 Indore
0159 rakh   patid  24 Pune
0159 rakh   patid  24 Pune
0018 sai    kanak  28 mumbai
0159 rakh   patid     Pune
0159 sarak  jatid     Pune

$ gawk '{printf "%04d %s\n", NR, $0}' Details.txt
0001 0154 Raghav Sharma 26 Indore
0002 0159 rakh   patid  24 Pune
0003 0159 rakh   patid  24 Pune
0004 0018 sai    kanak  28 mumbai
0005 0159 rakh   patid     Pune
0006 0159 sarak  jatid     Pune


Q:

How to use @EnvironmentObject to populate and update list automatically in SwiftUI?

Like the title says, I'm trying to use an @EnvironmentObject that holds data to populate and update a List automatically in SwiftUI.
For context, I'm building an app that is supposed to show a list of locations. The location data will be shown in multiple places of my app and will be changing during use, so I thought an @EnvironmentObject would be perfect for holding the data. But, I'm having trouble feeding an @EnvironmentObject to populate a List() and having the list update as the @EnvironmentObject changes.

Below is the struct I created for the location data I want to display:
struct ListVenue : Identifiable {
    var id = UUID()
    var name: String
    var formatted_address : String?
    var website : String?
}

Below is my SceneDelegate.swift file, where I create the @EnvironmentObject and the class it references:
import UIKit
import SwiftUI

class venDataArray: ObservableObject {
    var array : [ListVenue] = [ListVenue(name: "test_name")]
}

class SceneDelegate: UIResponder, UIWindowSceneDelegate {

    var window: UIWindow?
    @EnvironmentObject var VDArray: venDataArray

    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
        // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
        // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).

        // Create the SwiftUI view that provides the window contents.
        let contentView = ContentView().environmentObject(VDArray)

        // Use a UIHostingController as window root view controller.
        if let windowScene = scene as? UIWindowScene {
            let window = UIWindow(windowScene: windowScene)
            window.rootViewController = UIHostingController(rootView: contentView)
            self.window = window
            window.makeKeyAndVisible()
        }
    }

    func sceneDidDisconnect(_ scene: UIScene) {
        // Called as the scene is being released by the system.
        // This occurs shortly after the scene enters the background, or when its session is discarded.
        // Release any resources associated with this scene that can be re-created the next time the scene connects.
        // The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead).
    }

    func sceneDidBecomeActive(_ scene: UIScene) {
        // Called when the scene has moved from an inactive state to an active state.
        // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
    }

    func sceneWillResignActive(_ scene: UIScene) {
        // Called when the scene will move from an active state to an inactive state.
        // This may occur due to temporary interruptions (ex. an incoming phone call).
    }

    func sceneWillEnterForeground(_ scene: UIScene) {
        // Called as the scene transitions from the background to the foreground.
        // Use this method to undo the changes made on entering the background.
    }

    func sceneDidEnterBackground(_ scene: UIScene) {
        // Called as the scene transitions from the foreground to the background.
        // Use this method to save data, release shared resources, and store enough scene-specific state information
        // to restore the scene back to its current state.
    }

}

And, here is the my ContentView.swift file where I want to use the @EnvironmentObject above to populate and update a List() automatically:
import SwiftUI

struct ContentView: View {

    @EnvironmentObject var VDArray: venDataArray

    var body: some View {

    VStack(alignment: .leading) {

        Text("Location List")

    //  This is where im failing at having a list take in an @EnvironmentObject
        List(VDArray) { ListVenue in
        //  vvv  This is the view I want displayed for each item in the @EnvironmentObject  vvv
            VenueRowTest()
        }
    }
}

Can anyone show me how to alter my code so that I can display and update data in a list using an @EnvironmentObject??
Or is there a better way to implement a dynamic List?

A:

Have a look at the following tutorials:
How to use environmentobject to share data
Apple - handling user inputs
First You need a @Published property wrapper for your code to work.
class VenDataArray: ObservableObject {
@Published var array : [ListVenue] = [ListVenue(name: "test_name")]
}

Than adjust yout Scene delegate
var window: UIWindow?
var vDArray = VenDataArray()

let contentView = ContentView().environmentObject(vDArray)

Note: I have adjusted the variables with lowerCamelCase acc. to the API design guidelines


Q:

Adding double pages to a turnjs "book"

I have a created a website where visitors can skim through a book using turnjs. I have the pages as jpgs of double pages and I want them to be loaded dynamically.
Here's the code:

var flipbook = $('.flipbook');
flipbook.turn({
    elevation: 50,
    gradients: true,
    autoCenter: true,
    pages: 118,
    when: {
      missing: function (e, pages) {
        for (var i = 0; i < pages.length; i++) {
          var n = pages[i];
          if(!$(this).turn('hasPage',pages[i])) {
            var pagenum = Math.floor(pages[i] / 2) + 1,
                src="url(/pages/page_" + pagenum + ".jpg)",
                element = $('<div />',{'class': 'double', css:{backgroundImage:src}});
            flipbook.turn('addPage',element,n);
          }
        }
      }
    }
});
<div class="flipbook">
<!-- Insert content dynamically -->
</div>

Unfortunately this doesn't work like I want it to, here's what's happening:
The code as I posted it above inserts the pages, but every double page is just scaled to 50% of its width an put on one page. for example, on page 4 I have what should be page 4 & 5 and on the left page I have the same as on its right neighbor.
I changed the last line to flipbook.turn('addPage',element); hoping that it would automatically add two pages, but then the first page inserted is .p113 and not .p1
I also changed my code to
if(0 == n%2 && !$(this).turn('hasPage',pages[i])) {
  var pagenum = Math.floor(pages[i] / 2) + 1,
      src="url(/fileadmin/kollektion/2015/pages/page_" + pagenum + ".jpg)",
      element = $('<div />',{'class': 'double', css:{backgroundImage:src}});
      element.scissor();
      flipbook.turn('addPage',element,n);
  }
}

But that resulted in only getting the left pages inserted.
So, what's the best way to dynamically add double pages using addPage? I couldn't find anything about that in the documentation or the examples.

A:

Since the images that are my pages are put in the background of a <div>, the trick is to add some styles to scale the background images and position them accordingly:
.double{
    background-size:200% 100%;
}

.double.even {
    background-position: 0% 0%;
}

.double.odd {
    background-position: 100% 0%;
}


Q:

Cassandra effective ownership is less than 100%

I have been running Cassandra in two data centres with 6 nodes each. Recently, I had to upgrade the hardware and I just wanted to start it off by adding the new node and removing the existing node. I started off with increments of three as I have three three groups in each data center. Previously, effective ownership was split equally in two data centres - it was 50-50. Post adding three new nodes and removing the existing three nodes, I find the effective ownership to be 50--49.9. I would like to know if something is wrong with respect to my cluster. I don't understand how this gets unbalanced now.
Cassandra version used : 2.0.3

A:

This is most likely a rounding error and you shouldn't be too worried about it (Especially for a %.1 difference). The actual ownership should be keyspace dependent since you should be using NetworkTopologyStrategy.
Try calling nodetool status keyspaceName to see how your keyspaces are actually distributed amongst the cluster. This will also take into account the Replication Factor of the keyspace so you'll get an accurate picture of how a particular keyspace is replicated throughout your entire cluster.


Q:

Como remover pacotes não usados na pasta node_modules com o comando NPM?

Eu instalei alguns pacotes do NodeJS via npm install. Porém depois decidi remover alguns. Mesmo quando eu instalo novamente, as pastas dos pacotes que não estou usando permanecem lá.
No composer do PHP, quando não usamos mais um pacote (quer dizer, removemos ele da lista de dependências do arquivo de configuração json), o mesmo é removido.
Tem como fazer isso no Npm do NodeJS?

A:

Nos projetos onde o há o arquivo package.json, além do uninstall já mencionado na resposta anterior, você pode utilizar o comando:
node prune

Simplesmente edite o arquivo package.json para que ele contenha apenas as dependências que você utiliza e rode o comando que ele vai eliminar todos os pacotes que estão no node_modules e que você não referencia no package.json.
É recomendado também que no package.json você coloque no script de postinstall o comando npm prune para que após uma atualização de versão por exemplo, os pacotes não mais utilizados sejam removidos.
Exemplo de package.json com script de postinstall:
 {
   "name": "teste",
   "version": "1.0.0",
   "description": "Teste",
   "main": "index.js",
   "scripts": {
     "test": "echo \"Error: no test specified\" && exit 1",
     "postinstall": "npm prune"
   },
   "author": "bigous",
   "license": "ISC",
   "dependencies": {
     "luaparse": "^0.2.1"
   }
 }

Neste exemplo, qualquer pacote, exceto o luaparse@0.2.x, será removido do node_modules com o comando node prune ou após um npm install sem mais parâmetros.


Q:

Is there any way to connect directly to a SharePoint database?

A list inside our Intranet SharePoint has reached the 5000 items limit threshold. We followed the Microsoft recommendation on how to overcome this limit adding indexed columns combined with filters as described here. Now, the issue is solved and I'm wondering if there's any way to download all the items from the list without filters. Datasheet view allows to download all the data without filters but I'm not sure if this datasheet view is going to collapse some day. Does anyone know how to connect directly to the entire's list data?

A:

Instead of trying to do anything with the database, check out the daily time window, which is a setting that allows you to configure a time of day where list thresholds are ignored. No, don't set this for 24 hours a day, as the list threshold is an important aspect for keeping the farm healthy.


Q:

Input sends empty message

I'm making live chatter for my project, and I need this script to recognize this:

If clientmsg is empty, it will call out an error and won't post the
message.
If clientmsg has more than 3 or 4 chars (letters) - it will post the message.

The code:
$("#submitmsg").click(function(){
    var clientmsg = $("#usermsg").val();
    $.post("post3.php", {text: clientmsg});
    $("#usermsg").attr("value", "");
    return false;
});

I can't find out how this works.
Here you can see the whole code for it.
index.php
<?php
/*****************************
    File: index.php
    Written by: exZerry development crew
******************************/
session_start();

if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true) {
    echo "";
} else {
    header ("Location: login.php");
}
require('includes/config.php');
echo $sOutput;

if(isset($_POST['enter'])){
    if($_POST['username'] != ""){
        $_SESSION['username'] = stripslashes(htmlspecialchars($_POST['username']));
    }
    else{
        echo 'Please type in a name';
    }
}
?>

<?php
    if(file_exists("tmp/log.html") && filesize("tmp/log.html") > 0){
    $handle = fopen("tmp/log.html", "r");
    $contents = fread($handle, filesize("tmp/log.html"));
    fclose($handle);

    echo $contents;
    }
?>

<form name="message" action="" id="sender" class="sender">
    <input name="usermsg" id="usermsg" class="required" type="text" placeholder="Your message here" maxlength="60"/>
    <input name="submitmsg" type="submit" id="submitmsg" width="0" height="0"/>
</form>

chatbox.js file
// jQuery Document
$(document).ready(function(){
    //If user submits the form
    $("#submitmsg").click(function(){
        var clientmsg = $("#usermsg").val();
        $.post("post3.php", {text: clientmsg});
        $("#usermsg").attr("value", "");
        return false;
    });

    //Load the file containing the chat log
    function loadLog(){
        var oldscrollHeight = $("#chatbox").attr("scrollHeight") - 20;
        $.ajax({
            url: "tmp/log.html",
            cache: false,
            success: function(html){
                $("#chatbox").html(html); //Insert chat log into the #chatbox div
                var newscrollHeight = $("#chatbox").attr("scrollHeight") - 20;
                if(newscrollHeight > oldscrollHeight){
                    $("#chatbox").animate({ scrollTop: newscrollHeight }, 'normal'); //Autoscroll to bottom of div
                }
            },
        });
    }
    setInterval (loadLog, 2000);    //Reload file every 3 seconds

});

post3.php file
<?
session_start();

if(isset($_SESSION['username'])){
    $text = $_POST['text'];

    $fp = fopen("tmp/log.html", 'a');
    fwrite($fp, "
 ".$_SESSION['username'].": ".stripslashes(htmlspecialchars($text))."

");
    fclose($fp);
}
?>

This is full js + php chatter.

A:

Like this?
$("#submitmsg").click(function(){
    var clientmsg = $.trim($("#usermsg").val());
    if(clientmsg.length >= 3){
        $.post("post3.php", {text: clientmsg});
        $("#usermsg").val("");
    }else{
        alert('error');
    }
    return false;
});


Q:

How to trigger an action on specific date even if the app is closed?

I am trying to implement a scheduler function in my application using UIDatePicker and dateFormatter so that when a user select a date and time for the action to run on that specific date, the action should occur even if the app is closed, so how can I achieve same?

A:

It is not possible to (guaranteed) run specific code at a certain time if your app is not running.
It is possible to schedule a local NSNotification to inform the user. In case the user triggers your notification, your app is started / woken up by the OS and you can handle it. A nice notification guide can be found here


Q:

Adding a node to tree

[Bindable]
            private var company:XML =

              <list>
                <department title="Finance" code="200">
                    <employee name="John H"/>

                    <employee name="Sam K"/>
                </department>
                <department title="Operations" code="400">

                    <employee name="Bill C"/>
                    <employee name="Jill W"/>
                </department>
                <department title="Engineering" code="300">

                    <employee name="Erin M"/>
                    <employee name="Ann B"/>
                </department>
              </list>;

private function addEmployee():void

            {
                var newNode:XML = <employee/>;
                newNode.@name = empName.text;
                var dept:XMLList =company.department.(@title == "Operations");
                if( dept.length() > 0 ) {

                    dept[0].appendChild(newNode);
                    empName.text = "";
                }
            }

The Particular code adds a new node to the operations, but i want to add a node any item i select.

A:

Add a combo box (myCombobox) for the user to select where to add user (ie Operations, Finance, Engineering). Based on selected Department add to specific list:
 private function addEmployee():void
        {
            var newNode:XML = <employee/>;
            newNode.@name = empName.text;

            var dept:XMLList;

            switch(myCombobox.selectedLabel){
                 case 'Operations':
                     dept = company.department.(@title == "Operations");
                     break;

                 case 'Finance':
                     dept = company.department.(@title == "Finance");
                     break;

                 case 'Engineering':
                     dept = company.department.(@title == "Engineering");
                     break;
            }

            if( dept.length() > 0 ) {

                dept[0].appendChild(newNode);
                empName.text = "";
            }
        }


Q:

Как получить путь к изображению?

Как получить путь к изображению, когда блоки находятся на одном уровне, таких блоков несколько, просто обратится по классу не правильно, как можно это реализовать?
Мой код ищет путь у родителя, как можно исправить?

Комплект брелков для гаджетов

                558

                279

                Заказать

JS
$(".buyprod").click(function () {
        var img = $(this).parent().find("img").attr("src");
        var text = $(this).parent().find(".name").text();
        var price = $(this).parent().find(".price").text();
        if($('.item'+i).length) {
          document.getElementById('input'+i).value = parseInt(document.getElementById('input'+i).value,10)+1;
          $(".price"+i).html('' + (parseInt(document.getElementById('input' + i).value, 10) * pr));
        }
        else{
           $("#cartdiv").append(`

X

${text}

-

          <input type="test" id="input${i}" value="1" readonly="true"/>

+

${price}

          `);
          }
  });

A:

Решил это так, может кому-то будет полезно:
var img = $(this).prevAll(".item-img").find("img").attr("src");


Q:

Big O complexity , multiple for loops

I have written a simple algorithm to re-order the items in a list whenever the user drag and drop them. Also, if an item is deleted or a now one is added the list will be re-ordered. The algorithm contains three separated linear for loops (each one of them is O(n) ) and has two nested loops ( O(n^2) ). Is the total complexity O( n+ n +n + n^2) = O (3n+ n^2)?
How can I calculate the total big O ?
Thank you in advance

A:

O(3n + n^2) is the same thing as O(n^2).
Big O notation only describes limiting behavior, and both functions have the same limiting behavior -- doubling n quadruples them. (As n goes to infinity, the 3n component becomes smaller and smaller relative to the n^2 component. At the limit, it completely dominates it.)


Q:

Can Silverlight downloads be zipped to speed up the download?

When Silverlight downloads the assemblies in your app can it be made to download them as zipped files and then uncompress them before running? This would speed up the download time for a large application.

A:

afaik silverlight 2 xap files are already zip compressed. So unless I misunderstood you there should not be much optimization through compression. (Edit: See other posts and comments on how to optimize through re-compression. Thanks!)
More Info: Structure of the xap file
What you could do is dynamically load additional assemblies after a small "bootstrap" version of your program distracts the user long enough to load the rest. ;)
Dynamically Loading an Assembly

A:

The Silverlight 2 .xap file format is already compressed, if you rename it to .zip you'll be able to open it in Windows Explorer for example.
The default compression is not as optimal as it can be however and so there are a few free utilities you can use to reduce the filesize of the .xap often dramatically.
Here are the best links:
http://web-snippets.blogspot.com/2008/11/another-one-on-repacking-xaps-to-reduce.html
http://blogs.msdn.com/delay/archive/2008/11/04/smaller-is-still-better-a-simple-step-continues-to-shrink-the-download-size-of-silverlight-2-applications.aspx
http://blogs.telerik.com/ValeriHristov/Posts/08-05-13/Increasing_the_compression_ratio_of_the_XAP_files.aspx


Q:

unhandle promise rejection warning. even though i added catch statement after then

I got an unhandle promise rejection warning when I'm saving to mondodb (with mongoose), but i implemented the catch statement.
So I don't get why I have this warning.
Bellow my code,
cheers.
--declaring the function with promise :
module.exports = {

getGameResult : () => {
    var gameResult = new GameResultModel();
    return new Promise((resolve, reject) =>{

        GameResultModel.find({}, function (err, docs){

            if (err) reject(err);
            if (!err) resolve(docs);

        });
    })

}

}
--calling the function :
 router.get("/all", (req, res) => {

databaseFunction.getGameResult()
    .then((result) => {
        res.send(result);
        res.sendStatus(200);
    })
    .catch((err) => {
        res.send(err);
        res.sendStatus(500);
    });

});

A:

Try this:
GameResultModel.find({}, function (err, docs){
    if (err) reject(err);
    if (!err) resolve(docs);
}).catch(err => console.error("db.find has some error ", err));

I recently had a similar issue and if this solution helps I would need to find for you the source where I found a good description of the issue and the resolution.


Q:

How to make mysqli connect function?

I'm having a problem with a function that connects me to the database using mysqli. What I'm aiming to have is to just type getConnected(); where I need the connection.
This is the code:
function getConnected()
{
    $host = 'localhost';
    $user = 'logintest';
    $pass = 'logintest';
    $db = 'vibo';

    $mysqli = new mysqli($host, $user, $pass, $db);

    if ($mysqli->connect_error) {
        die('Connect Error (' . mysqli_connect_errno() . ') '
            . mysqli_connect_error());
    }
}

This is the error I get when I try to use $mysqli after calling getConnected():

Notice: Undefined variable: mysqli in C:\xampp\htdocs\xampp\loginsystem\index.php on line 19

A:

As some users have suggested (and is the best way), return the mysqli instance
function getConnected($host,$user,$pass,$db) {

   $mysqli = new mysqli($host, $user, $pass, $db);

   if($mysqli->connect_error)
     die('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());

   return $mysqli;
}

Example:
$mysqli = getConnected('localhost','user','password','database');


Q:

renaming the output column with the plyr package in R

Hadley turned me on to the plyr package and I find myself using it all the time to do 'group by' sort of stuff. But I find myself having to always rename the resulting columns since they default to V1, V2, etc.
Here's an example:
mydata<-data.frame(matrix(rnorm(144, mean=2, sd=2),72,2),c(rep("A",24),rep("B",24),rep("C",24)))
colnames(mydata) <- c("x_value", "acres",  "state")
groupAcres <- ddply(mydata, c("state"), function(df)c(sum(df$acres)))
colnames(groupAcres) <- c("state","stateAcres")

Is there a way to make ddply name the resulting column for me so I can omit that last line?

A:

Use summarise (or summarize):
  groupAcres <- ddply(mydata, "state", summarise,
     myName = sum(acres))

A:

This seems to work:
> groupAcres <- ddply(mydata, c("state"), function(df) c(myName=sum(df$acres)))
> groupAcres
  state   myName
1     A 56.87973
2     B 57.84451
3     C 52.82415


Q:

Oracle APEX - Display card image from the dynamic list

I am displaying a list on my page in the format of cards but the image is not showing up - only a grey circle. Here is my query for the dynamic list:
SELECT null as level_value,
   TITLE as label,
   null astarget,
   null as is_current,
   IMG_PATH as image,
   'width="40" height="40"' image_attribute,
   TITLE as image_alt_attribute,
   DECRIPTION as attribute1
FROM  TABLE1
ORDER BY TITLE

I also tried:
SELECT null as level_value,
   TITLE as label,
   null astarget,
   null as is_current,
   '' as image,
   'width="40" height="40"' image_attribute,
   TITLE as image_alt_attribute,
   DECRIPTION as attribute1
FROM  TABLE1
ORDER BY TITLE

I have noticed when inspecting the page that APEX adds my image tag to the class of a span:
<span class="t-Icon ">

instead of just adding an image to the card

A:

I found a solution. Actually two solutions.
1) Modify dynamic list to utilize CARD_INITIALS and attributes
SELECT null as level_value,
  TITLE as label,
  null astarget,
  null as is_current,
  IMG_PATH as CARD_INITIALS,
  'width="40" height="40"' image_attribute,
  TITLE as image_alt_attribute,
  DECRIPTION as attribute1,
  '' as attribute2,
  '' as attribute3
FROM  TABLE1
ORDER BY TITLE

Setting both CARD_INITIALS and attributes3 that way was necessary - other combinations did not work properly.
Then, in List region attributes, set List template to Cards, style to featured, and Icons to - Display Initials.
2) Classic report - setting its attributes to Cards template and using CARD_INITIALS, CARD_TITLE, and CARD_TEXT as aliases in the source query. Both methods produce desired results


Q:

javascript disable event listener after first hit

How do I disable this event listener so that it only fires once?
document.getElementById('element').ontouchmove = function (e)
{
  DISABLE HERE
  do something that should only happen once
};

A:

document.getElementById('element').ontouchmove = function (e) {
  this.ontouchmove = null;

  // Do something here.
};


Q:

SFML and running from Code::Blocks

UPDATE: All Issues Resolved Using Bart's suggestions for Issue 2 & 3 ( first response )
Issue 1
For my game, I was using SDL, and everything was mostly okay. But I decided by recommendation of a friend to switch to SFML. I finally got all the changes done, and now when I try to build and run in Code::Blocks, the console opens up and then I get the following issue.

The program can't start because libgcc_s_dw2-1.dll is missing from you computer.
  Try reinstalling the program to fix this problem.

Issue 2
Well, when I originally tried running the exe created in the bin/debug folder, I got a message saying

sfml-graphics.dll cannot be found.

Well, when I copy and paste the SFML DLLs in the bin/debug folder everything works fine. But note, only when running the application from the windows explorer ( running from Code::Blocks still shows the mentioned issue ).
Issue 3:
When I try to build and run in the Release build target, I get a compiler error mentioning a undefined reference. NOTE, I didn't get this error when using the Debug build target.
Can anyone point me in the direction of a solution.

A:

Normally you should give us a bit more info to work with, but let's have a go
For issue 1:
It can't find the DLL. Either make sure it's visible by including it in the same directory as your executable, or by having the path to the file as part of your PATH environment variable.
For issue 2:
Make sure that Code::Blocks does not have another directory set as the working directory for your executable. I'm not sure about C::B, but in Visual Studio you can explicitly set this.
For issue 3:
Going off the information you give us, I would say that you forget to link against a certain library (the particular undefined reference should give you a hint as to which one it is) in release mode, that you do correctly link against in debug.


Q:

How to view the data on a drive that was a part of a RAID 1 array?

I have removed RAID 1 hard drive from my old PC.
I connected it to my new PC as a normal SATA drive (not RAID) but I am unable to view the content.
Windows keep prompting to format it, but I dont want to format it as I want to copy the data to the new PC.
Is there any way to access this drive’s data?

A:

What you can do :
You can connect an additional hard drive with same/larger capacity of the volume
Download macrium reflect 7 free addition
Then clone this RAW partition into the new space.
this should give you your files back.


Q:

Passing user id in the url

I am trying to pass the userId in the url. This is what I have, but it giving me error.
<?php echo "
Edit
"?>

A:

try this:
<?php echo "
Edit
"?>


Q:

Check for a specific value in pandas dataframe column

I am trying to retrieve the value in A if the value of B is 1. But the below code throws the error "ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()"
    A   B
0   a1  18
1   b1  25229
2   c2  2
3   d3  12
4   e4  1

Code:
for a,b in df7.iteritems():
  if (df7['b'] == 1):
    print (df7['a'])

A:

You could use a simple comparison like
import pandas as pd

df = pd.DataFrame({'A': ['a1', 'b1', 'c2', 'd3', 'e4'], 'B': [18, 25229, 2, 12, 1]})
print(df[df['B'] == 1]['A'])

Which yields
4    e4
Name: A, dtype: object


Q:

Redux mock store only returning one action when multiple actions are dispatched

I'm trying to mock this axios call:
export const fetchCountry = (query) => {
  return dispatch => {
    dispatch(fetchCountryPending());
    return axios.get(`${process.env.REACT_APP_API_URL}/api/v1/countries/?search=${query}`)
      .then(response => {
        const country = response.data;
        dispatch(fetchCountryFulfilled(country));
      })
      .catch(err => {
        dispatch(fetchCountryRejected());
        dispatch({type: "ADD_ERROR", error: err});
      })
  }
}

Which on a successful call, should dispatch both action creators fetchCountryPending() and fetchCountryFullfilled(country). When I mock it like so:
const middlewares = [thunk];
const mockStore = configureMockStore(middlewares);

// Async action tests
describe('country async actions', () => {
  let store;
  let mock;

  beforeEach(function () {
    mock = new MockAdapter(axios)
    store = mockStore({ country: [], fetching: false, fetched: true })
  });

  afterEach(function () {
    mock.restore();
    store.clearActions();
  });

  it('dispatches FETCH_COUNTRY_FULFILLED after axios request', () => {
    const query = 'Aland Islands'
    mock.onGet(`${process.env.REACT_APP_API_URL}/api/v1/countries/?search=${query}`).replyOnce(200, country)
    store.dispatch(countryActions.fetchCountry(query))
    const actions = store.getActions()
    console.log(actions)
    expect(actions[0]).toEqual(countryActions.fetchCountryPending())
    expect(actions[1]).toEqual(countryActions.fetchCountryFulfilled(country))
  });
});

The second expect fails and console.log(actions) only shows an array with the one action, but it should contain both actions, fetchCountryPending and fetchCountrySuccess. When I log ('dispatched'), it shows the second action is getting dispatched in the terminal.

A:

I couldn't get a then(() => {}) block to work but I was able to await the function and make it async:
  it('dispatches FETCH_COUNTRY_FULFILLED after axios request', async () => {
    const query = 'Aland Islands'
    mock.onGet(`${process.env.REACT_APP_API_URL}/api/v1/countries/?search=${query}`).replyOnce(200, country)
    await store.dispatch(countryActions.fetchCountry(query))
    const actions = store.getActions()
    console.log(actions)
    expect(actions[0]).toEqual(countryActions.fetchCountryPending())
    expect(actions[1]).toEqual(countryActions.fetchCountryFulfilled(country))
  });
});


Q:

List 'MyList' does not exist at site with URL

I am trying to make a query on a SPList but I got an error saying that List doesn't exist.
How can I read the current context in the proper way ?
Is somehow a deployment issue ?
var clientContext = new SP.ClientContext.get_current();;
var oList = clientContext.get_web().get_lists().getByTitle("MyList");

var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml('<View><Query><Where><Eq><FieldRef Name="SearchUserName" /><Value Type="Text">' + loginName + '</Value></Eq></Where></Query></View>');
this.collListItem = oList.getItems(camlQuery);

clientContext.load(collListItem);

clientContext.executeQueryAsync(Function.createDelegate(this, function (sender, args) {
  //do something
}), Function.createDelegate(this, function (sender, args) {
  //log error
}));

I get the error: List 'MyList' does not exist at site with URL '.... site path'
What am I doing wrong? Is there another way of reading the current context?

A:

You could have run into a simple problem which tripped me up:
When you use getByTitle() you need to use the List's display name,
Is your list display name "MyList" or might it be "My List"?

The List 'Title' = List Display Name (Often has spaces)
The List 'Name' = List Internal Name (usually no spaces or special characters)

To find the display name look at what the list is called in the "Site Contents" page.
To find the internal name, look at the URL when you hover over (or click) the List name in "Site Contents".
Try get_web().get_lists().getByTitle("My List");


Q:

How does one build a new X11 3D driver?

I was wondering why there is no X11 driver for the mali 3D arm gfx chip.  I looked into building an X11 driver for the available kernel driver, but could not find any documentation on how to build an X11 3D driver.  There exists only the minimal amount of documentation about how to build projects like DRI and Mesa, but no documentation about how to contribute or exand those projects.
Is there any documentation about how to start developing a hardware accelerated 3D driver for Xorg?

A:

1) x.org, freedesktop.org
2) dri-devel@lists.freedesktop.org, xorg-devel@lists.freedesktop.org
3) irc.freenode.org #dri-devel #xorg-devel
Of course, we're going to say the same thing, which is "We don't have docs on Mali, and don't know anybody that does, so your task is going to be time-consuming and arduous." But you should talk to us anyway, since we love talking to new developers.
~ C.


Q:

Opencv video with artifacts and colour issues

I am writing an opencv code to fix this particular rgb image ...

Any inputs on how to fix this image ?
Thanks!

A:

I have fixed this issue . .. This was due to an incorrect attribute in the caps properties of in one of my gstreamer pipelines ... Hence, the issue is not related to the opencv side .
Apologies ...


Q:

Replace multiple Strings in a file using fileinput

I am trying to replace multiple strings in a file.
My file may have some contents like this:
file1:
#groovy
some test
some more test
REPLACE_1
REPLACE_OPTIONAL_1
REPLACE_2
end test

I am trying to use fileinput module to replace above text but its not working as expected. My method is something like this:
    import fileinput
    def replace_method():
        file_path = './file1.txt'
        try:
            with fileinput.FileInput(file_path, inplace=True, backup=".bak") as file:
                for line in file:
                    print (line.replace('REPLACE_1', 'replaced_value1'), end='')
                    print (line.replace('REPLACE_OPTIONAL_1', 'replaced_value2'), end='')
                    print (line.replace('REPLACE_OPTIONAL_2', 'replaced_value3'), end='')
                   print (line.replace('REPLACE_2', 'replaced_value4'), end='')

        except Exception as e:
            print (str(e))

Above code works but it prints everyline 4 times in the new modified file. I believe this is something to do with line.replace which Imight be using wrongly.
Can you please help me fixing this.
Please let me know if you need more information.

A:

Don't print 4 times
import fileinput
def replace_method():
    file_path = './file1.txt'
    try:
        with fileinput.FileInput(file_path, inplace=True, backup=".bak") as file:
            for line in file:
                line = line.replace('REPLACE_1', 'replaced_value1')
                line = line.replace('REPLACE_OPTIONAL_1', 'replaced_value2')
                line = line.replace('REPLACE_OPTIONAL_2', 'replaced_value3')
                line = line.replace('REPLACE_2', 'replaced_value4')
                print (line, end='')
    except Exception as e:
        print (str(e))


Q:

Why does WAIISHost lock certain files

I am deploying a web application to azure.  The application is built using Nancy, and there is no RoleEntryPoint defined (please note this isn't a problem, the website itself is running just fine).  When I deploy to azure, i have enabled the web deploy option.
When I attempt to run a webdeployment, am getting the following error:

Error 7   Web deployment task failed.((6/26/2012 12:28:45 PM) An error
  occurred when the request was processed on the remote computer.)
(6/26/2012 12:28:45 PM) An error occurred when the request was
  processed on the remote computer. An error was encountered when
  processing operation 'Create File' on 'Castle.Windsor.dll'. The error
  code was 0x80070020. The process cannot access
  'E:\approot\bin\Castle.Windsor.dll' because it is being used by
  another process.

I've RDP'd into the role instance and using process explorer I see that WAIISHost has a lock to a number of assemblies that my project references.
I haven't been able to determine what is causing those files to be locked.
thanks,
jason

A:

Web Deploy is not for use in a production environment. (described here)
WaIisHost.exe is the role hose process for full IIS web role so when your web role starts, your role DLL is loaded in this process. During the life of your webrole the role dll is loaded in the host process and can not be changed. As Castle.Windsor.dll is in E:\approot\bin* where role specific DLL are located, the host process has this binary loaded in it.
If you want to update your web role you would need to, you the Windows Azure Upgrade option either from portal or from powershell.


Q:

How to use cin.fail() in c++ properly

I'm writing a program where I get an integer input from the user with cin>>iUserSel;. If the user puts in a letter, the program goes to an infinite loop. I tried to prevent that with the code below, but the program goes to an infinite loop and prints out "Wrong! Enter a #!". How can I fix my program?
cin>>iUserSel;
while (iValid == 1)
{
        if (cin.fail())
        {
                cin.ignore();
                cout<<"Wrong! Enter a #!"<<endl;
                cin>>iUserSel;
        }//closes if
        else
                iValid = 0;
}//closes while

I found some information on this at Correct way to use cin.fail() and  C++ cin.fail() question
, but I didn't understand how to use them to fix my issue.

A:

When cin fails, you need to clear the error flag. Otherwise subsequent input operations will be a non op.
To clear the error flags, you need to call cin.clear().
Your code would then become:
cin >> iUserSel;
while (iValid == 1)
{
    if (cin.fail())
    {
        cin.clear(); // clears error flags
        cin.ignore();
        cout << "Wrong! Enter a #!" << endl;
        cin >> iUserSel;
    }//closes if
    else
        iValid = 0;
}//closes while

I would also suggest you change
cin.ignore();

to
cin.ignore(numeric_limits<streamsize>::max(), '\n');

In case the user enters more than one letter.

A:

The problem you are having is that you don't clear the failbit from the stream. This is done with the clear function.

On a somewhat related note, you don't really need to use the fail function at all, instead rely of the fact that the input operator function returns the stream, and that streams can be used in boolean conditions, then you could do something like the following (untested) code:
while (!(std::cin >> iUserSel))
{
    // Clear errors (like the failbit flag)
    std::cin.clear();

    // Throw away the rest of the line
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

    std::cout << "Wrong input, please enter a number: ";
}


Q:

Configure IIS 7.5 to let only special User Agents visit the site

I want to restrict all visitors (by user-agents) from visiting my site, except some special user-agents (say visitors using Firefox or so...)
Please show me a way to deny all, but allow those special visitors.

A:

You can use UrlRewrite plugin to check for user-agent strings and redirect to an access restricted page.


Q:

Return document in each group with max value using MongoDB

Given a dataset:
{_id: 0, type: 'banana', amount: 5}
{_id: 1, type: 'banana', amount: 3}
{_id: 2, type: 'apple', amount: 8}
{_id: 3, type: 'apple', amount: 2}

What is the most efficient way of getting only the records of the same type, that has the highest amount?
The expected result is:
{_id: 0, type: 'banana', amount: 5}
{_id: 2, type: 'apple', amount: 8}

Right now I'm doing it this way, but it seems kinda silly:
collection.aggregate([
  { $sort: { 'amount': -1 } },
  { $group: {
     _id: '$type',
     group: {
       $push: '$$ROOT'
     }
   }, {
     $replaceRoot: {
       newRoot: { $arrayElemAt: ["$group", 0] }
     }
   }
])

A:

You can use below aggregation with $sort amount descending followed by $first operator to project max amount document.
$replaceRoot to promote the max amount document to top level.
collection.aggregate([
 {$sort:{'amount':-1}},
 {$group:{ _id: '$type',group:{$first:'$$ROOT'}}},
 {$replaceRoot:{newRoot:"$group"}}
])


Q:

If my fingers were stung by fish spines, shall I describe it as "I got hurt" or "I got injured" or what?

Dr. Lee asked me in email why I wanted to further my study of health care.
I was in a hurry to set out for work so I just wrote this short sentence as a response to her question:
"I often got hurt and sick".
Misuse of words can lead to Misunderstanding between two parties.
I have to handle a lot of different seafood, fishes in particular on my job. Sometimes my fingers were stung by fish spines, and the wounds were not treated appropriately and infected. I ended up getting a fever and lying in the bed for the following few days.
That is what I intended to tell her in the email, but I just wrote "I often got hurt and sick".
Now, my question is that, the way she perceived the word "got hurt" might be different from the original idea in my mind.
If my fingers were stung and then infected by viruses, is it correct to say "I got hurt" or "I got injured" or something, perhaps some other good words for better description of my situation.

A:

Here's what my native ear tells me:

I got sick often

implies that you had bouts with recurrent sickness at one time in your life, but you don't any longer, while:

I get sick often

implies that you still get sick rather frequently.
The word sick usually implies illness, and covers symptoms such as congestion, fever, nausea, and vomiting.
The word injured implies you were hurt, and covers things like cuts and abrasions, muscle pulls, ligament strains, and bone fractures.

Sometimes my fingers were stung by fish spines, and the wounds were not treated appropriately and infected. I ended up getting a fever and laying in the bed for a few days.

I would characterize the stings as minor injuries, and the subsequent infections as illness or being sick. Moreover, since the illnesses were caused by the injuries, you could refer to those as complications. NOAD says:

complication (n.) Medicine a secondary disease or condition aggravating an already existing one : she developed complications after the surgery.

So, you could have told the person:

I've often been hurt with minor injuries, and have sometimes been sick from complications when these injuries were not properly treated.

You could also be more specific and use infections in place of complications; of the two, complications is the more general word.

A:

J.R.'s handling of get vs got is correct.  "Get" is present tense, implying the event is still happening.  "Got" implies that it happened in the past, and you believe it is no longer happening.
As for "hurt" vs. "injury," injury is a more sterile word.  "Injury" just says that you've sustained damage.  Hurt usually implies that something is affecting your physical or mental state.  If I was playing soccer and skinned my knee, I could say I was injured.  If I kept playing and was generally unaffected, I would not choose to say "I was hurt."  However, if that skinned knee affected how steady I was on my feet such that the coach had to remove me from the game, I would say "I was hurt."  This word also covers psychological injuries, so if the skinned knee wrecked my confidence such that I could not play well, I might say "It hurt me [psychologically]."
Likewise, if a player sustains an injury, they may be "hurt" initially.  The coach and medic may look at them, and decide the player needs to "walk it off."  If the player does so, and gets back in the game, we wouldn't say he is "hurt."  He was "injured and hurt," but he walked off, so now he's only "injured."
It is possible to be "hurt" without being injured.  If something causes you to believe you have been injured, you may being protecting that part of your body, even though nothing actually happened.  Quite often a "stuck muscle" is not injured, but merely reacting to a hurt.
In the other direction, war vets often talk about war "injuries."  These are physical events which they have gotten over.  They may still limp, or lack flexibility due to the injury, but they choose not to claim they are "hurt" because they wish to project the image that they are [mentally] over the injury, and are happy enough with their life working around it.  The vets who are still "hurt" don't let those injuries out so freely... they keep that hurt deep inside because it is considered socially unacceptable for a warrior or ex-warrior to show that they are hurt (this causes a lot of trouble for groups that want to help veterans; the stigma against seeking help is really dangerous).

In your case, I'd think that a few days in bed would qualify as "hurt," in the past tense, so you could use it if you want.  Or, if you want to demonstrate that you are over the memory of that event, you might chose "injured" instead.
In this very specific case of someone asking why you want to enter healthcare, "I often got hurt" has a slight implication that you're still holding those wounds deep inside your mind and you joined them as part of an effort to rise above those memories.  Dr. Lee would be lead to assume your reason for entering healthcare is to silence an unhappiness in your soul regarding being hurt.
"I often got injured" has an implication that you have accepted those memories.  If that is your "reason for entering healthcare," then Dr. Lee would likely have to assume that your reason for entering healthcare is to either try to help those who get injured/hurt in the same way, or to try to prevent people from getting injured/hurt in that way.
Usually English is not so demanding of exactness.  The issue is that Dr. Lee asked a very pointed question.  For most people, the answer to "why do you want to enter healthcare" is not an easy question to put in words.  Usually when a mentor asks a question like that, its because you're about to enter a very challenging environment.  People who have words to describe why they want to be there can often lean on those word when times get rough.  People who don't have the words often stray from the path when it gets difficult.  (and don't worry if you don't have a "good" wording: some of the strongest reasons don't have words... and some words snap like twigs when you lean on them.  It's just a test Dr. Lee is doing to gauge where you're at.)