text:
Q: implement my own java.nio for socket server Ive been reading for the past few days about the difference between io and nio when building a java socket server. for my use i need a server which can run lots of connections and ion supposed to do the trick.
My only fear is that it a bit slower and a bit harder to implement instead of running a thread for each connection. so i thought why dont i use the same easiness of threads and the logic of java.nio and build a server has a thread which checks all the open connection and when ever there is a new event, it will open a new thread for handing it.  i think in that way im enjoying both of the worlds... what do u suggest?

A: I suggest you don't understand the point of NIO, which is to only use one thread. It is certainly complex and it is arguable whether you have any need for it at all below 1000 clients, probably 10,000, possibly even 100,000. I would implement your server with java.net to get it running and save java.nio for phase 2 if you ever get there and prove to yourself that you really need it.
EDIT: I would certainly forget this concept of rolling your own. You're wildly underestimating the task (It took Sun 1.4.0, 1.4.1, 1.4.2 before it really worked properly), and you seem to be aiming to get the worst of both worlds. You won't be able to get any more out of it than Sun did with java.nio, as there isn't any more. Arguably a bit less ;-)

A: NIO almost entirely relies on JNI, so if you want to implement it again, you'll actually have to write loads of C/++ and OS API interface code.
I think the existing Java implementations are already quite good. For example, the Selector class wraps the system call for waiting on multiple file descriptors. There's hardly anything you can do to improve the efficiency of that.


text:
Q: Migration of Small Parse IDs to normal MongoDB's ObjectIDs I am using Parse Dashboard for User Management of my iOS Application.Also, I am using external APIs which are using MongoDB database.
The issue currently I am facing is the User created from Parse Dashboard is having small id instead of MongoDB's ObjectID, and other resources which are not over parse are generated by normal ObjectID.
eg. User Object:
{
_id:"qVnyrGynJE",
user_name:"Aditya Raval"
}

Document Object:
{
_id:"507f191e810c19729de860ea",
doc_name:"Marksheet",
user:"qVnyrGynJE"
}

Task Object:
{
_id:"507f191e810c19729de860ea",
task_name:"Marksheet",
user:"qVnyrGynJE"
}

I am also using Keystone.js as a Backend Admin Dashboard.So basically due to this mix kind of IDs relationships inside KeyStone.js is broken and Keystone.js gets crashed.
So I want to migrate all my existing small IDs to normal MongoDB ObjectIDs without breaking into relationships or any other walkthrough by fixing Keystone.js

A: You can run something like this:
var users = db.Users.find({});

for(var i = 0; i < users.length(); i++)
{
    var oldId = users[i]._id;
    delete users[i]._id;
    db.Users.insert(users[i], function(err, newUser) {
            db.Documents.updateMany({"user": oldId},{ $set: { "user": newUser._id }});
            //Do this for all collections that need to be update.
        });
    );
}

db.Users.deleteMany({_id: { $type: "string" }});

redpajama_set_name: RedPajamaStackExchange


text:
Q: Reinstalling OS X Lion vs restoring from Time Machine backup If the system doesn't boot up (it was due to this issue), is it better to reinstall OS X Lion, or restore from a Time Machine backup?
I do see a Time Machine backup from 3 AM last night, so if that is used to restore the machine, will it read all 600 GB from the external backup drive and copy it to the iMac's hard drive, or will it just do the selective restore, kind of like Windows 7's setting a restore point, and any rollback should be partial - i.e., it only needs to restore a few files to make the system work fine again, but is it the same as on OS X Lion's Time Machine restore?
Is restoring a better approach than reinstalling OS X?

A: A Time Machine restore will restore to the last point in time in the backup. A fresh install of Lion will bring your machine to new status.
However, if you do a fresh install and tell it to use the Time Machine backup to restore your data, it will also bring it back to the same point in time.
Some people [citation needed] prefer to use this opportunity to do a fresh install and then selectively drag the data they want from Time Machine back again.
However, keep in mind that if you set up a new backup, it could overwrite the old one.

A: They are basically the same in the end - one lets you play with the new OS and the other installs and starts the migration. Yes - if you make a new account, you'll have to delete that and the old account you migrate will no longer be the "first account" created, but for most people, this is a hidden detail that won't change how they work.
If you are looking to isolate why the Mac failed and see if it works again after the re-install, you should take the time to install a clean system and then test. If that works, you will have isolated your backup from the list of potential causes of the issue.
If you go for the restore and it's still broken, you won't know if it's a problem with the hardware or your current image. (and then have to re-do the erase and then test).
There is no clear winner - it's a guess and you might waste time you don't need if a restore fixes everything. That could be a waste if you still need to run a clean install to determine something has failed and then seek a repair.


text:
Q: How to Get Rust Member Function to Callback in Struct I've been trying to understand callback functions in Rust. After going through a few examples in stackoverflow, I still can't get it to run when the function I want to call is a member function of another struct.
My example is built upon this example post: How to pass a member function of a struct to another struct as callback
struct Person {
    name: String
}

impl Person {
    pub fn print_name(&self) {
        println!("Hello from {}", self.name);
    }
}

struct Operation {
    cb: fn(&Person),
}

impl Operation {
    pub fn caller(&self) {
        (self.cb)()
    }
}

fn main() {
    let person = Person {
        name: "Brad".to_string()
    };

    let op = Operation {
        cb: Person::print_name,
    };

    op.caller()
}

This example doesn't break the linter, but when I try to run it, I get errors about the type and arguments provided.
   Compiling playground v0.0.1 (/playground)
error[E0061]: this function takes 1 argument but 0 arguments were supplied
  --> src/main.rs:17:9
   |
17 |         (self.cb)()
   |         ^^^^^^^^^-- supplied 0 arguments
   |         |
   |         expected 1 argument

For more information about this error, try `rustc --explain E0061`.
error: could not compile `playground` due to previous error

It seems to me that it cant resolve the self variable so it makes me wonder why the example in the previous post was accepted if that structs function can't actually be called.

A: In your struct definition, you are saying that the function stored in cb takes a &Person argument, so you need to make sure that argument is passed along whenever you try to call the function. You should change the caller method to handle the argument like so:
struct Person {
    name: String
}

impl Person {
    pub fn print_name(&self) {
        println!("Hello from {}", self.name);
    }
}

struct Operation {
    cb: Box<dyn Fn()>,
}

impl Operation {
    pub fn caller(&self) {
        (self.cb)()
    }
}

fn main() {
    let person = Person {
        name: "Brad".to_string()
    };

    let op = Operation {
        cb: Box::new(move || person.print_name()),
    };

    // person is no longer available here because it has been moved into `op.cp`
    //dbg!(person.name); // this will fail

    op.caller();
}


text:
Q: Error every second in Apache error log I'm getting this error every second in my apache error log, what is causing this, how to fix?
[debug] mod_headers.c(743): headers: ap_headers_output_filter()

A: Looks like you are have debugging enabled. Check the log level.
http://httpd.apache.org/docs/current/logs.html#errorlog


text:
Q: Characteristic function problem first time poster so be nice!
Here's the problem:
Let $\phi(t)$ be a characteristic function, then $e^{\lambda(\phi(t)-1)}$ is a characteristic function.
Pretty stuck, any help appreciated!

A: Suppose that $\phi(t)$ is CF of $Y$. Suppose $X=Y_1+...+Y_P$, sum of $P$ i.i.d. $Y_i$'s, where $P$ follows Poisson distribution of parameter $\lambda$. Then we have:
$$
\mathbb E(e^{itX})=\sum_{k=0}^\infty \mathbb E(e^{itX};P=k)\frac{e^{-\lambda}\lambda^k}{k!}=\sum_{k=0}^\infty \phi(t)^k \frac{e^{-\lambda}\lambda^k}{k!}=e^{\lambda(\phi(t)-1)}.
$$


text:
Q: Matching a SQL command with database I am using webdb for client side and I want to match the server side database so the web app can be used offline. This here is the script for creating the server side table...
USE [TESTDB]
GO

/****** Object:  Table [dbo].[tblInternalMobile_SalesCalls]    Script Date: 01/08/2013 11:30:31 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[tblInternalMobile_SalesCalls](
    [newcall_id] [int] IDENTITY(1,1) NOT NULL,
    [companyname] [varchar](30) NOT NULL,
    [comment] [varchar](300) NULL,
    [dateUTC] [datetime2](7) NOT NULL,
 CONSTRAINT [PK_tblInternalMobile_SalesCalls] PRIMARY KEY CLUSTERED
(
    [newcall_id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO

I am trying to match that on the client side but around identity I get an error Uncaught Error: [object SQLError], Error Code: 5, Error Message: could not prepare statement (1 near "IDENTITY": syntax error)
This is my client side code...
//Database helper
//I want to use a 'namespace' for this to minimize name conflicts
var DbHelper = {};
//use the webDb 'namespace' so we could use indexDb if need be in the future by making a new 'namespace'
DbHelper.webDb = {};
//To store the database object
DbHelper.webDb.db = null;
//Open the database
DbHelper.webDb.openDb = function() {
    var dbSize = 5 * 1024 * 1024 //5MB I believe is the max
    DbHelper.webDb.db = openDatabase("TestDB", "1.0", "Database manager", 5 * 1024 * 1024);
};
//If there is an error its going to throw an error, I havent added any handlers for this, so it should be added where the function is called
DbHelper.webDb.onError = function(tx, e) {
    throw "Error: " + e + ", Error Code: " + e.code + ", Error Message: " + e.message;
};
//This should be used if we are doing a non query, where we dont need to use the result
DbHelper.webDb.onSuccess = function(tx, r) {
    console.log("Database result: " + r)
};
//Create the tables we are going to use
DbHelper.webDb.createTables = function() {
    var db = DbHelper.webDb.db;
    db.transaction(function(tx) {
        //I am using the same tables as I am on the server, so we dont confuse things
        tx.executeSql("CREATE TABLE IF NOT EXISTS tblInternalMobile_SalesCalls(newcall_id INT PRIMARY KEY IDENTITY(1,1), companyname varchar(30), comment varchar(300), dateUTC DATETIME2)", [], DbHelper.webDb.onSuccess, DbHelper.webDb.onError);
    });
}
DbHelper.webDb.init = function() {
    DbHelper.webDb.openDb();
    DbHelper.webDb.createTables();
}

$(document).ready(function(e) {
    DbHelper.webDb.init();
});

Why the heck isn't it working? I believe I am using the right syntax, obviously not.
The problem is this statement CREATE TABLE IF NOT EXISTS tblInternalMobile_SalesCalls(newcall_id INT PRIMARY KEY IDENTITY(1,1), companyname varchar(30), comment varchar(300), dateUTC DATETIME2)

A: If you're actually using SQL Server or one of its variants on the client side as well as on the server side, you should probably use the same CREATE TABLE statement. But SQL Server doesn't support CREATE TABLE IF NOT EXISTS.
If you're using the deprecated HTML5 interface, your user agent is expected to conform to SQLite syntax.
CREATE TABLE tblInternalMobile_SalesCalls(
  newcall_id INTEGER PRIMARY KEY AUTOINCREMENT,
  companyname varchar(30),
  comment varchar(300),
  dateUTC DATETIME2
);

I believe w3.org's Indexed Database API is intended to supersede webdb.


text:
Q: Automating Manual Excel report to PowerBI I'm working on one customer's project in which they are using 20+ Excel reports. These Excel file fetching data from Database. There are multiple VBA macros are written in Excel files to do some manual calculations, filtering of data etc. Also each Excel workbook file contains multiple sheets. And after Excel report gets ready, they send it over an email.
Now customer wanted to do all this process in PowerBI. All Excel files with VBA macros should get converted to PowerBI reports. How we can achieve this? How we can add excel VBA macro codes to PowerBI reports ? Did anyone go through the similar tasks ?


text:
Q: Google Maps API V3 Add a button near to a polygon hovered I'm working with Google Maps API V3, and I'd like to display a clickable image near to a drawed polygon when the mouse hovers it.
Until now, I'm able to create this event, but I have no idea how to display this image near to my polygon. Ideally, I'd like this image appears where the mouse entered in the polygon.

Here is a piece of my code, but it's just a try and the image is not displayed, so it is very incomplete (and maybe wrong). You can suggest me to do otherwise, Javascript is not my preferred language...
google.maps.event.addListener(polygon, 'mouseover', function(e) {
    this.setOptions( {fillOpacity: 0.1} );

    polygon["btnMyButtonClickHandler"] = {};
    polygon["btnMyButtonImageUrl"] = MyImage;
    displayMyButton(polygon);
});

function displayMyButton(polygon) {
    var path = polygon.getPath();
    var myButton = getMyButton(path.btnMyButtonImageUrl);

    if(myButton.length === 0)
    {
        console.log("IN"); //Is displayed in the console
        var myImg= $("img[src$='http://linkToMyImage.png']");

        myImg.parent().css('height', '21px !important');
        myImg.parent().parent().append('

');

    // now get that button back again!
    myButton = getMyButton(path.btnMyButtonImageUrl);
    myButton.hover(function() {
        $(this).css('left', '-30px'); return false; },
        function() { $(this).css('left', '0px'); return false; });
    myButton.mousedown(function() { $(this).css('left', '-60px'); return false;});
    }

    // if we've already attached a handler, remove it
    if(path.btnDeleteClickHandler)
        myButton.unbind('click', path.btnMyButtonClickHandler);

    myButton.click(path.btnMyButtonClickHandler);
}

function getMyButton(imageUrl) {
    return  $("img[src$='" + imageUrl + "']");
}

Thanks for your suggestions !

EDIT
@MrUpsidown, unfortunately no, click event can't be a solution, I really need your Something here div appears at mouseover.
I modified your code like this :
google.maps.event.addListener(polygonPath, 'mouseover', function (event) {
    if( $("#map_overlay").css('display') == "none")
    {
        $("#map_overlay").css({
                               'position': 'absolute',
                               'display': 'block',
                               'left': event.Sa.pageX,
                               'top': event.Sa.pageY
                              });
     }
 });

The div appears when my mouse enter the polygon and don't move except if my mouse hovers the div (which hovers the polygon). On this case, the event seems called continuously. How can we avoid this and let the div at its inital position once the mouse enter the polygon ?
Here is your modified : fiddle

A: You need to create an element to hold your clickable image. Make it position:absolute; with a bigger z-index than your map container. To place it at a specific place, check the mouse position on your polygon mouseover event and set the element position accordingly. Hope this helps.
Edit: Yes, wrap it in a DIV is a good idea. Here is a simple fiddle to show the concepts. And sorry, of course it was mouseover and not mouseenter like I first wrote.
http://jsfiddle.net/upsidown/zrC2D/


text:
Q: How to add two waveforms in pgfplots In my example code given below, I have two plots. I wanted to add a third and fourth plot that is the sum and then product of the original two plots.  Is there a simple way to do this in pgfplots?
Here is my code
%\documentclass[varwidth]{standalone}
\documentclass[tikz]{standalone}
\usepackage{varwidth}
\usepackage{pgfplots,pgfplotstable, booktabs}
\usepackage{bm}

\usepgfplotslibrary{groupplots}
\usepackage{filecontents}
\usepackage{graphicx}
\usepackage{float}

\begin{filecontents*}{MAG.dat}
  Iter   Abs1   Abs2      x      y
     1, 0.9317521, 1.1849326, 1.6130556, 0.8022207
     2, 1.8946202, 1.1228282, 1.8964566, -0.5353802
     3, 1.5243302, 1.0372991, 1.4375012, 0.9719003
     4, 1.5797030, 1.1346832, 1.8717142, 0.3138737
     5, 1.8814457, 1.0529187, 2.0568468, -0.5509391
     6, 2.0435003, 1.0470546, 2.0621956, -0.3565483
     7, 2.0373926, 1.1215579, 2.1836100, 0.3360301
     8, 1.9797077, 1.1632352, 1.8299063, 0.3871091
     9, 1.9972528, 1.1952478, 1.8133509, -0.0867033
    10, 1.8320176, 1.0625633, 1.0727495, 1.7256738
\end{filecontents*}

\pgfplotsset{compat=1.12}
\pgfplotsset{minor grid style={dotted,gray!90}}
\pgfplotsset{major grid style={gray!70!black},
            every tick label/.append style={font=\scriptsize},
            every axis plot/.append style={line width=0.8pt},
            }

\newcommand{\bod}{MAG.dat}

\begin{document}
\begin{figure}[H]
\centering
\begin{tikzpicture}
\begin{semilogxaxis}[width=14cm,height=10.2cm,
                    grid = both,
                    log ticks with fixed point,
                    every major grid/.style={gray, opacity=0.9},
                    title = {},
                    xlabel={\emph{\bfseries{Iteration}}},
                    ylabel={\emph{\bfseries{Temp}}},
                    no markers,
                    every axis plot/.append style={very thick},
                    legend style={at={(0,0)},anchor=south west},
                    legend cell align=left,
                    ]

\addplot+ [red]table[x index=0,y index=1, col sep=comma] {\bod};
\addlegendentry{$\zeta = 0.3$};
\addplot+ [blue]table[x index=0,y index=3, col sep=comma] {\bod};
\addlegendentry{$\zeta = 0.5$};

\addlegendentry{\emph{Sum}}

\end{semilogxaxis}
\end{tikzpicture}
\end{figure}
\end{document}

A: You can use y expr and then mention the cols with \thisrow/\thisrowno
\documentclass[]{standalone}
\usepackage{pgfplots}

\pgfplotstableread[col sep=comma]{
Iter,Abs1,Abs2,x,y
     1, 0.9317521, 1.1849326, 1.6130556, 0.8022207
     2, 1.8946202, 1.1228282, 1.8964566, -0.5353802
     3, 1.5243302, 1.0372991, 1.4375012, 0.9719003
     4, 1.5797030, 1.1346832, 1.8717142, 0.3138737
     5, 1.8814457, 1.0529187, 2.0568468, -0.5509391
     6, 2.0435003, 1.0470546, 2.0621956, -0.3565483
     7, 2.0373926, 1.1215579, 2.1836100, 0.3360301
     8, 1.9797077, 1.1632352, 1.8299063, 0.3871091
     9, 1.9972528, 1.1952478, 1.8133509, -0.0867033
    10, 1.8320176, 1.0625633, 1.0727495, 1.7256738
}\bod

\pgfplotsset{compat=1.12}
\pgfplotsset{minor grid style={dotted,gray!90}}
\pgfplotsset{major grid style={gray!70!black},
            every tick label/.append style={font=\scriptsize},
            every axis plot/.append style={line width=0.8pt},
            }
\begin{document}
\begin{tikzpicture}
\begin{semilogxaxis}[width=14cm,height=10.2cm,
                    grid = both,
                    log ticks with fixed point,
                    every major grid/.style={gray, opacity=0.9},
                    title = {},
                    xlabel={\emph{\bfseries{Iteration}}},
                    ylabel={\emph{\bfseries{Temp}}},
                    no markers,
                    every axis plot/.append style={very thick},
                    legend style={at={(0,0)},anchor=south west},
                    legend cell align=left,
                    ]

\addplot+ [red]table[x index=0,y index=1 , col sep=comma] {\bod};
\addlegendentry{$\zeta = 0.3$};
\addplot+ [blue]table[x index=0,y index=3, col sep=comma] {\bod};
\addlegendentry{$\zeta = 0.5$};
\addplot+ [gray,ultra thick]table[x index=0,y expr=\thisrowno{1}+\thisrowno{3}, col sep=comma] {\bod};
\addlegendentry{\emph{Sum}}
\addplot+ [orange,ultra thick]table[x index=0,y expr=\thisrowno{1}*\thisrowno{3}, col sep=comma] {\bod};
\addlegendentry{\emph{Product}}

\end{semilogxaxis}
\end{tikzpicture}
\end{document}


text:
Q: Extract text between two text strings from webpage with BeautifulSoup and Python There's lots out there on BeautifulSoup, but I can't find anything that answers this... I want to extract the text between two bits of html by specifying the bit of text before and after in the code. I can do this with Outwit Python module but need to use BeautifulSoup this time...
The bit of the pages I want is the usernames below:

So, I want to specify beautifulsoup to scrape the username by telling it to look for

'a class="generic_class" href="/people/'

before the bit to scrape and stop after

'"'

I then want it to do this in a loop of urls from a csv (this already works) and then append the results line by line to a new csv (this bit probably doesn't work):
for row in url_reader:
    url = row[0]
    page = br.open(url).read()
    soup = BeautifulSoup(br.response().read())
    user = soup.findAll('<a class="generic_class" href="/people/') # this is the line where the code that works should go! Obviously this bit does nothing as it doesn't extract what comes after, stopping at the closing quotation mark for the end of the href.
    page.append.user(output_file) # not sure if this is right?!

Obviously, in an ideal world, I'd put this in an if/else to if (finds "page not found") and else (do the thing above) to deal with urls that don't work, but I'll work the error handling in once I can actually make the thing work! That's my priority now...
Any help much appreciated.

A: can't you just extract "href" attribute value and parse that?
usernames = []

for anchor in soup.findAll('a', {'class': 'generic_class'}):
    usernames.append(anchor['href'].split('/')[-1])

with open('usernames.csv', 'ab') as f:
    writer = csv.writer(f)
    for username in usernames:
        writer.writerow([username])

This is just a simple example, I recommend making some additional validation etc.

A: You can pass a function in the href attribute:
def start_with_people(href):
    return href and href.startswith('/people/')

a_tags = soup.find_all('a', class_='generic_class', href=start_with_people)

This will return all the  tags which have an href starting with /people/.
Once you have these anchor tags :

*

*you can loop over it

*get the href value

*split it and get the username


text:
Q: Appium Test Android Automating Test using Appium
I am Following This Two Tutorials
https://www.youtube.com/watch?v=n8QqYAXKWEU
https://www.youtube.com/watch?v=AlBrQ_-phsQ
org.gradle.execution.MultipleBuildFailures: Build completed with 1 failures.
    at org.gradle.initialization.DefaultGradleLauncher$ExecuteTasks.run(DefaultGradleLauncher.java:358)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:300)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:292)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:174)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:90)
    at org.gradle.internal.operations.DelegatingBuildOperationExecutor.run(DelegatingBuildOperationExecutor.java:31)
    at org.gradle.initialization.DefaultGradleLauncher.runTasks(DefaultGradleLauncher.java:219)
    at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:149)
    at org.gradle.initialization.DefaultGradleLauncher.executeTasks(DefaultGradleLauncher.java:124)
    at org.gradle.internal.invocation.GradleBuildController$1.call(GradleBuildController.java:77)
    at org.gradle.internal.invocation.GradleBuildController$1.call(GradleBuildController.java:74)
    at org.gradle.internal.work.DefaultWorkerLeaseService.withLocks(DefaultWorkerLeaseService.java:154)
    at org.gradle.internal.work.StopShieldingWorkerLeaseService.withLocks(StopShieldingWorkerLeaseService.java:38)
    at org.gradle.internal.invocation.GradleBuildController.doBuild(GradleBuildController.java:96)
    at org.gradle.internal.invocation.GradleBuildController.run(GradleBuildController.java:74)
    at org.gradle.tooling.internal.provider.runner.BuildModelActionRunner.run(BuildModelActionRunner.java:55)
    at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
    at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
    at org.gradle.tooling.internal.provider.ValidatingBuildActionRunner.run(ValidatingBuildActionRunner.java:32)
    at org.gradle.launcher.exec.RunAsBuildOperationBuildActionRunner$3.run(RunAsBuildOperationBuildActionRunner.java:50)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:300)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:292)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:174)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:90)
    at org.gradle.internal.operations.DelegatingBuildOperationExecutor.run(DelegatingBuildOperationExecutor.java:31)
    at org.gradle.launcher.exec.RunAsBuildOperationBuildActionRunner.run(RunAsBuildOperationBuildActionRunner.java:45)
    at org.gradle.tooling.internal.provider.SubscribableBuildActionRunner.run(SubscribableBuildActionRunner.java:51)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter$1.transform(InProcessBuildActionExecuter.java:47)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter$1.transform(InProcessBuildActionExecuter.java:44)
    at org.gradle.composite.internal.DefaultRootBuildState.run(DefaultRootBuildState.java:79)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:44)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:30)
    at org.gradle.launcher.exec.BuildTreeScopeBuildActionExecuter.execute(BuildTreeScopeBuildActionExecuter.java:39)
    at org.gradle.launcher.exec.BuildTreeScopeBuildActionExecuter.execute(BuildTreeScopeBuildActionExecuter.java:25)
    at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:80)
    at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:53)
    at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:62)
    at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:34)
    at org.gradle.tooling.internal.provider.GradleThreadBuildActionExecuter.execute(GradleThreadBuildActionExecuter.java:36)
    at org.gradle.tooling.internal.provider.GradleThreadBuildActionExecuter.execute(GradleThreadBuildActionExecuter.java:25)
    at org.gradle.tooling.internal.provider.ParallelismConfigurationBuildActionExecuter.execute(ParallelismConfigurationBuildActionExecuter.java:43)
    at org.gradle.tooling.internal.provider.ParallelismConfigurationBuildActionExecuter.execute(ParallelismConfigurationBuildActionExecuter.java:29)
    at org.gradle.tooling.internal.provider.StartParamsValidatingActionExecuter.execute(StartParamsValidatingActionExecuter.java:59)
    at org.gradle.tooling.internal.provider.StartParamsValidatingActionExecuter.execute(StartParamsValidatingActionExecuter.java:31)
    at org.gradle.tooling.internal.provider.SessionFailureReportingActionExecuter.execute(SessionFailureReportingActionExecuter.java:59)
    at org.gradle.tooling.internal.provider.SessionFailureReportingActionExecuter.execute(SessionFailureReportingActionExecuter.java:44)
    at org.gradle.tooling.internal.provider.SetupLoggingActionExecuter.execute(SetupLoggingActionExecuter.java:46)
    at org.gradle.tooling.internal.provider.SetupLoggingActionExecuter.execute(SetupLoggingActionExecuter.java:30)
    at org.gradle.launcher.daemon.server.exec.ExecuteBuild.doBuild(ExecuteBuild.java:67)
    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.WatchForDisconnection.execute(WatchForDisconnection.java:37)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.ResetDeprecationLogger.execute(ResetDeprecationLogger.java:26)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.RequestStopIfSingleUsedDaemon.execute(RequestStopIfSingleUsedDaemon.java:34)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:74)
    at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:72)
    at org.gradle.util.Swapper.swap(Swapper.java:38)
    at org.gradle.launcher.daemon.server.exec.ForwardClientInput.execute(ForwardClientInput.java:72)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.LogAndCheckHealth.execute(LogAndCheckHealth.java:55)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.LogToClient.doBuild(LogToClient.java:62)
    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.EstablishBuildEnvironment.doBuild(EstablishBuildEnvironment.java:81)
    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.StartBuildOrRespondWithBusy$1.run(StartBuildOrRespondWithBusy.java:50)
    at org.gradle.launcher.daemon.server.DaemonStateCoordinator$1.run(DaemonStateCoordinator.java:295)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
    at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
    at java.lang.Thread.run(Thread.java:748)
Caused by: org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:transformClassesWithDexBuilderForDebug'.
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:110)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:77)
    at org.gradle.api.internal.tasks.execution.OutputDirectoryCreatingTaskExecuter.execute(OutputDirectoryCreatingTaskExecuter.java:51)
    at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:59)
    at org.gradle.api.internal.tasks.execution.ResolveTaskOutputCachingStateExecuter.execute(ResolveTaskOutputCachingStateExecuter.java:54)
    at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:59)
    at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:101)
    at org.gradle.api.internal.tasks.execution.FinalizeInputFilePropertiesTaskExecuter.execute(FinalizeInputFilePropertiesTaskExecuter.java:44)
    at org.gradle.api.internal.tasks.execution.CleanupStaleOutputsExecuter.execute(CleanupStaleOutputsExecuter.java:91)
    at org.gradle.api.internal.tasks.execution.ResolveTaskArtifactStateTaskExecuter.execute(ResolveTaskArtifactStateTaskExecuter.java:62)
    at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:59)
    at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:54)
    at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
    at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:34)
    at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.run(EventFiringTaskExecuter.java:51)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:300)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:292)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:174)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:90)
    at org.gradle.internal.operations.DelegatingBuildOperationExecutor.run(DelegatingBuildOperationExecutor.java:31)
    at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter.execute(EventFiringTaskExecuter.java:46)
    .....
Caused by: java.lang.RuntimeException: com.android.build.api.transform.TransformException: com.android.builder.dexing.DexArchiveBuilderException: com.android.builder.dexing.DexArchiveBuilderException: Failed to process /home/android/Desktop/Android Studio Projects/MyApplication/app/libs/java-client-7.0.0.jar
    at com.android.builder.profile.Recorder$Block.handleException(Recorder.java:55)
    at com.android.builder.profile.ThreadRecorder.record(ThreadRecorder.java:104)
    at com.android.build.gradle.internal.pipeline.TransformTask.transform(TransformTask.java:230)
    at sun.reflect.GeneratedMethodAccessor1021.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:73)
    at org.gradle.api.internal.project.taskfactory.IncrementalTaskAction.doExecute(IncrementalTaskAction.java:50)
    at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:39)
    at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:26)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$1.run(ExecuteActionsTaskExecuter.java:131)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:300)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:292)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:174)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:90)
    at org.gradle.internal.operations.DelegatingBuildOperationExecutor.run(DelegatingBuildOperationExecutor.java:31)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:120)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:99)
    ... 34 more
Caused by: com.android.build.api.transform.TransformException: com.android.builder.dexing.DexArchiveBuilderException: com.android.builder.dexing.DexArchiveBuilderException: Failed to process /home/android/Desktop/Android Studio Projects/MyApplication/app/libs/java-client-7.0.0.jar
    at com.android.build.gradle.internal.transforms.DexArchiveBuilderTransform.transform(DexArchiveBuilderTransform.java:442)
    at com.android.build.gradle.internal.pipeline.TransformTask$2.call(TransformTask.java:239)
    at com.android.build.gradle.internal.pipeline.TransformTask$2.call(TransformTask.java:235)
    at com.android.builder.profile.ThreadRecorder.record(ThreadRecorder.java:102)
    ... 50 more
Caused by: com.android.builder.dexing.DexArchiveBuilderException: com.android.builder.dexing.DexArchiveBuilderException: Failed to process /home/android/Desktop/Android Studio Projects/MyApplication/app/libs/java-client-7.0.0.jar
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at java.util.concurrent.ForkJoinTask.getThrowableException(ForkJoinTask.java:593)
    at java.util.concurrent.ForkJoinTask.reportException(ForkJoinTask.java:677)
    at java.util.concurrent.ForkJoinTask.join(ForkJoinTask.java:720)
    at com.android.ide.common.internal.WaitableExecutor.waitForTasksWithQuickFail(WaitableExecutor.java:146)
    at com.android.build.gradle.internal.transforms.DexArchiveBuilderTransform.transform(DexArchiveBuilderTransform.java:420)
    ... 53 more
Caused by: com.android.builder.dexing.DexArchiveBuilderException: Failed to process /home/android/Desktop/Android Studio Projects/MyApplication/app/libs/java-client-7.0.0.jar
    at com.android.build.gradle.internal.transforms.DexArchiveBuilderTransform.launchProcessing(DexArchiveBuilderTransform.java:909)
    at com.android.build.gradle.internal.transforms.DexArchiveBuilderTransform.lambda$convertToDexArchive$6(DexArchiveBuilderTransform.java:834)
    at java.util.concurrent.ForkJoinTask$AdaptedCallable.exec(ForkJoinTask.java:1424)
    at java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:289)
    at java.util.concurrent.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1056)
    at java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1692)
    at java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:157)
Caused by: com.android.builder.dexing.DexArchiveBuilderException: Error while dexing.
    at com.android.builder.dexing.D8DexArchiveBuilder.getExceptionToRethrow(D8DexArchiveBuilder.java:124)
    at com.android.builder.dexing.D8DexArchiveBuilder.convert(D8DexArchiveBuilder.java:101)
    at com.android.build.gradle.internal.transforms.DexArchiveBuilderTransform.launchProcessing(DexArchiveBuilderTransform.java:904)
    ... 6 more
Caused by: com.android.tools.r8.CompilationFailedException: Compilation failed to complete
    at com.android.tools.r8.utils.ExceptionUtils.withCompilationHandler(ExceptionUtils.java:70)
    at com.android.tools.r8.utils.ExceptionUtils.withD8CompilationHandler(ExceptionUtils.java:43)
    at com.android.tools.r8.D8.run(D8.java:94)
    at com.android.builder.dexing.D8DexArchiveBuilder.convert(D8DexArchiveBuilder.java:99)
    ... 7 more
Caused by: com.android.tools.r8.utils.AbortException: Error: Default method desugaring of `io.appium.java_client.android.AndroidDriver` failed because it's hierarchy is incomplete. The class `org.openqa.selenium.remote.RemoteWebDriver` is missing and it is the declared super class of `io.appium.java_client.DefaultGenericMobileDriver(classpath class)`
    at com.android.tools.r8.utils.Reporter.failIfPendingErrors(Reporter.java:89)
    at com.android.tools.r8.utils.Reporter.fatalError(Reporter.java:60)
    at com.android.tools.r8.utils.ExceptionUtils.withCompilationHandler(ExceptionUtils.java:64)
    ... 10 more

Java Compiler :
Caused by: com.android.builder.dexing.DexArchiveBuilderException: Failed to process /home/android/Desktop/Android Studio Projects/MyApplication/app/libs/java-client-7.0.0.jar

Caused by: com.android.builder.dexing.DexArchiveBuilderException: Error while dexing.

Caused by: com.android.tools.r8.CompilationFailedException: Compilation failed to complete

Caused by: com.android.tools.r8.utils.AbortException: Error: Default method desugaring of `io.appium.java_client.android.AndroidDriver` failed because it's hierarchy is incomplete. The class `org.openqa.selenium.remote.RemoteWebDriver` is missing and it is the declared super class of `io.appium.java_client.DefaultGenericMobileDriver(classpath class)`

Android Errors:
AGPBI: {"kind":"error","text":"Default method desugaring of `io.appium.java_client.android.AndroidDriver` failed because it\u0027s hierarchy is incomplete. The class `org.openqa.selenium.remote.RemoteWebDriver` is missing and it is the declared super class of `io.appium.java_client.DefaultGenericMobileDriver(classpath class)`","sources":[{}],"tool":"D8"}
> Task :app:transformClassesWithDexBuilderForDebug FAILED
com.android.builder.dexing.DexArchiveBuilderException: com.android.builder.dexing.DexArchiveBuilderException: Failed to process /home/android/Desktop/Android Studio Projects/MyApplication/app/libs/java-client-7.0.0.jar
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    ......
    at com.android.tools.r8.utils.ExceptionUtils.withCompilationHandler(ExceptionUtils.java:64)
    ... 10 more
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':app:transformClassesWithDexBuilderForDebug'.
> com.android.build.api.transform.TransformException: com.android.builder.dexing.DexArchiveBuilderException: com.android.builder.dexing.DexArchiveBuilderException: Failed to process /home/android/Desktop/Android Studio Projects/MyApplication/app/libs/java-client-7.0.0.jar

Dependencies
dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support:design:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    implementation 'com.android.support:support-vector-drawable:28.0.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation 'com.github.armcha:SpaceNavigationView:1.6.0'

    implementation files('libs/byte-buddy-1.8.15.jar')
    implementation files('libs/commons-exec-1.3.jar')
    implementation files('libs/guava-25.0-jre.jar')
    implementation files('libs/java-client-7.0.0.jar')
    implementation files('libs/okhttp-3.11.0.jar')
    implementation files('libs/okio-1.14.0.jar')

   implementation 'com.android.support:multidex:1.0.3'
}

its not multidex problem
class App : MultiDexApplication
{
    constructor() : super()

    override fun onCreate() {
        super.onCreate()

        MultiDex.install(this)
    }
}

I am new with this type of application any one help me to solve this problem.

A: First Time I miss to add two library's in dependency
dependencies
{
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support:design:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'com.android.support:support-vector-drawable:28.0.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation 'com.github.armcha:SpaceNavigationView:1.6.0'

implementation files('libs/byte-buddy-1.8.15.jar')
implementation files('libs/commons-exec-1.3.jar')
implementation files('libs/guava-25.0-jre.jar')
implementation files('libs/java-client-7.0.0.jar')
implementation files('libs/okhttp-3.11.0.jar')
implementation files('libs/okio-1.14.0.jar')

implementation 'com.android.support:multidex:1.0.3'

//missed
implementation files('libs/client-combined-3.141.59.jar')
implementation files('libs/client-combined-3.141.59-sources.jar')

}

Then After Sync the Project and getting erro like
AGPBI: {"kind":"error","text":"Program type already present: org.openqa.selenium.WebDriver$Window","sources":[{}],"tool":"D8"}

Followed Answer  : Error: Program type already present: org.openqa.selenium.WebDriver$ImeHandler
When I add the "Appium Jar files for Java" plugin (java-client-7.0.0.jar) I checked that it already contains the classes contained in the "Latest Appium Client Library" (selenium-java-3.141.59) as described in some tutorials on the internet.
To solve the problem do:

*

*Delete the java-client-7.0.0.jar file from your project

*Open java-client-7.0.0.jar with 7zip and delete the "org /" folder and all subfolders.

*Include the updated java-client-7.0.0.jar in your project. Rebuild project


text:
Q: parse_url giving host name as stars when debugged (but can still get value) Using PHP 5.5.12
Using CakePHP 2.6.7
Running
debug($url); // output = "http://google.co.uk"

debug(parse_url($url));
/* output = array(
                'host' => '*****',
                'scheme' => 'http'
            )
*/

I had been using this without trouble but now copy/pasting a section of my code to have it as method (to save repeating myself) has started giving me this output. But testing it back in the same place I had it originally gives me this output too.
Can anyone explain why the hostname is stars and why the rest of the array doesn't appear (I realise all other elements should be expected to be NULL)?
Edit
Just tried it again with a url that had a path to a page after the host. The path shows up fine but the host is still starred out.
Partial Answer
Just thought to try debug(parse_url($url)['host']) and it prints the host correctly. I realised that the other elements would only be set if they exist in the url.
However, can anyone explain why printing out the array prints several stars instead of the hostname even though it is definitely stored there?

A: The reason this happens is because of how debug() works. Many moons ago people were not pleased that they could accidentally have their database credentials dumped out in error pages (which use the same underlying code as debug()). Because of this, debug() and Debugger::export() blacklist a set of array keys that could have database credentials.  The following keys are replaced with ***'s:

*

*password

*login

*host

*database

*port

*prefix

*schema


text:
Q: Multiple count in ORM is not working I want to get count of tenancies based on differnet times
    $start_date = $end_date = $end_date1 = new \DateTime('first day of last month');

    $start_date = $start_date->format('Y-m-01 00:00:00');
    $end_date = $end_date->format('Y-m-t 23:59:59');
    $end_date1 = $end_date1->format('Y-m-'. date('d') .' 23:59:59');

    $start_date2 = $end_date2 = new \DateTime('now');
    $start_date2 = $start_date2->format('Y-m-01 00:00:00');
    $end_date2 = $end_date2->format('Y-m-d 23:59:59');

   $tenancyDetails = $this
        ->find()
        ->select([
            'total_last_month' => $this->find()->func()->count('Tenancy.id'),
            'count_last_month' => $this->find()->func()->count('Tenancy1.id'),
            'count_curr_month' => $this->find()->func()->count('Tenancy2.id'),
            'Tenancy.created', 'Tenancy1.created', 'Tenancy2.created',
        ])
        ->leftJoin(['Tenancy1' => 'tenancy'],[
            'Tenancy1.active' => 1,
            'Tenancy1.stage !=' => 1,
            'Tenancy1.company_id' => $id,
        ])
        ->leftJoin(['Tenancy2' => 'tenancy'],[
            'Tenancy2.active' => 1,
            'Tenancy2.stage !=' => 1,
            'Tenancy2.company_id' => $id,
        ])
        ->where([
            'Tenancy.active' => 1,
            'Tenancy.stage !=' => 1,
            'Tenancy.company_id' => $id,
        ])
       ->where(function ($exp, $q) use ($start_date, $end_date) {
            return $exp->between('Tenancy.created', $start_date, $end_date);
        })
       ->where(function ($exp, $q) use ($start_date, $end_date1) {
            return $exp->between('Tenancy1.created', $start_date, $end_date1);
        })
       ->where(function ($exp, $q) use ($start_date2, $end_date2) {
            return $exp->between('Tenancy2.created', $start_date2, $end_date2);
        })->toArray();

Here is what I get. The number of counts are the same. Eventhough the datesare different
[
(int) 0 => object(App\Model\Entity\Tenancy) {

    'total_last_month' => (int) 4590,
    'count_last_month' => (int) 4590,
    'count_curr_month' => (int) 4590,
    'created' => object(Cake\I18n\FrozenTime) {

        'time' => '2016-03-01T10:57:21+00:00',
        'timezone' => 'UTC',
        'fixedNowTime' => false

    },
    'Tenancy1' => [
        'created' => '2016-03-01 10:57:21'
    ],
    'Tenancy2' => [
        'created' => '2016-04-04 10:59:42'
    ],
    '[new]' => false,
    '[accessible]' => [
        '*' => true
    ],
    '[dirty]' => [],
    '[original]' => [],
    '[virtual]' => [],
    '[errors]' => [],
    '[invalid]' => [],
    '[repository]' => 'Tenancy'

}
]

Even though I have written the query this way but still the same problem.
    $query = $tenancies->find();
    $query->select([
        'total_last_month' => $query->func()->count('Tenancy.id'),
    ])
    ->where([
        'Tenancy.active' => 1,
        'Tenancy.stage !=' => 1,
        'Tenancy.company_id' => $id,
    ])
    ->where(function ($exp) use ($start_date, $end_date) {
        return $exp->between('Tenancy.created', $start_date, $end_date);
    });

    $query->select([
        'count_last_month' => $query->func()->count('Tenancy1.id'),
    ])
    ->leftJoin(['Tenancy1' => 'tenancy'],[
        'Tenancy1.company_id' => $id,
    ])
    ->where([
        'Tenancy1.active' => 1,
        'Tenancy1.stage !=' => 1,
    ])
    ->where(function ($exp) use ($start_date, $end_date1) {
        return $exp->between('Tenancy1.created', $start_date, $end_date1);
    });

I can see the printed query which is correct.

A: After looking at all the examples in the documentation it looks like you need to instantiate the ORM query builder instance before using the func() helpers.

http://book.cakephp.org/3.0/en/orm/query-builder.html#using-sql-functions

In theory $this->func() should work the same if the return is simply a string. but maybe using $this->func() results in a disconnect between the query instance you are trying to build and an unbound new instance?
try:
$tenancyDetails = $this>find();
$tenancyDetails->select([
            'total_last_month' => $tenancyDetails->find()->func()->count('Tenancy.id'),
            'count_last_month' => $tenancyDetails->find()->func()->count('Tenancy1.id'),
            'count_curr_month' => $tenancyDetails->find()->func()->count('Tenancy2.id'),
            'Tenancy.created',
            'Tenancy1.created',
            'Tenancy2.created',
        ])......

Edit
I checked the code for the count function in /ORM/query.php file.
If no values are set cake will perform the count() query on the call $this->func->count(). The PHP compiler must be reading and therefore executing the count query before the query has been built, meaning before your conditions have been set. That's why you you need to instantiate the class first to stop the count query executing prematurely.


text:
Q: Npm install is failing with docker buildx linux/arm64 I'm building a docker image from a x86_64 machine for the deployment server which is arm64. For testing I'm using the docker file below.
FROM node:14.16.0-buster

RUN npm install pm2@latest -g

For some reason the npm install is failing I've tried npm -v also but it failed.
Please check my console logs below for more clarity.
$~ docker buildx create --platform linux/arm64 --use --name arm64
arm64

$~ docker buildx ls
NAME/NODE DRIVER/ENDPOINT             STATUS   PLATFORMS
arm64 *   docker-container
  arm640  unix:///var/run/docker.sock inactive linux/arm64*
default   docker
  default default                     running  linux/amd64, linux/386

$~ docker buildx build --platform linux/arm64 -t fos-node --load .
[+] Building 146.3s (7/7) FINISHED
 => [internal] booting buildkit                                                                                29.7s
 => => pulling image moby/buildkit:buildx-stable-1                                                                                28.6s
 => => creating container buildx_buildkit_arm640                                                                                1.1s
 => [internal] load build definition from Dockerfile                                                                                0.1s
 => => transferring dockerfile: 770B                                                                                0.0s
 => [internal] load .dockerignore                                                                                0.1s
 => => transferring context: 380B                                                                                0.0s
 => [internal] load metadata for docker.io/library/node:14.16.0-buster                                                                                13.6s
 => [auth] library/node:pull token for registry-1.docker.io                                                                                0.0s
 => [1/2] FROM docker.io/library/node:14.16.0-buster@sha256:e09a63130ce4ec4b20af5bd07e2029a0ef26f64f1f496f0854f5b1ff1aa69575                                                         102.0s
 => => resolve docker.io/library/node:14.16.0-buster@sha256:e09a63130ce4ec4b20af5bd07e2029a0ef26f64f1f496f0854f5b1ff1aa69575                                                           0.0s
 => => sha256:4d7f255f49584b155894f79821624b3502337e5825df64c3be03a07f04fb1691 282B / 282B                                                                                0.4s
 => => sha256:ec755c817ff697a94525832b7ac0c6e41048d90ac0da7e9454a5fe5c1a04caf9 2.31MB / 2.31MB                                                                                2.2s
 => => sha256:238768c628173281bc3162a29cef7923808d66159e7249d80620b4221632200b 34.64MB / 34.64MB                                                                                33.4s
 => => sha256:754863281868391e5f6c82b8b29b874f9e1830f1919ac097ca6560a6ef747976 4.20kB / 4.20kB                                                                                1.7s
 => => sha256:ccc089388c7ca4407aec7247a44601b896e57e96d53a858fb0e8c6f2f94ab8da 183.90MB / 183.90MB                                                                                96.0s
 => => sha256:ba70c372ae296f23e908bf1e1ed9f4c0c81a8a6d7fc48c0e2db16035bb9b7a54 52.17MB / 52.17MB                                                                                58.0s
 => => sha256:299f3631f6b52be065a7342da0a46978d55cbd0d15c57fae22f4ca24efcc295a 9.98MB / 9.98MB                                                                                13.6s
 => => sha256:344d2d9a9cf41c137b0dbb41df255f95fb812a23771a10ee2ab5a8a5047c62c4 7.69MB / 7.69MB                                                                                18.6s
 => => sha256:ef28e7e77ecbd3b3b426832bc12e8f5e629959683767466e9bac149c3286e126 49.23MB / 49.23MB                                                                                59.1s
 => => extracting sha256:ef28e7e77ecbd3b3b426832bc12e8f5e629959683767466e9bac149c3286e126                                                                                1.5s
 => => extracting sha256:344d2d9a9cf41c137b0dbb41df255f95fb812a23771a10ee2ab5a8a5047c62c4                                                                                0.2s
 => => extracting sha256:299f3631f6b52be065a7342da0a46978d55cbd0d15c57fae22f4ca24efcc295a                                                                                0.2s
 => => extracting sha256:ba70c372ae296f23e908bf1e1ed9f4c0c81a8a6d7fc48c0e2db16035bb9b7a54                                                                                1.6s
 => => extracting sha256:ccc089388c7ca4407aec7247a44601b896e57e96d53a858fb0e8c6f2f94ab8da                                                                                4.5s
 => => extracting sha256:754863281868391e5f6c82b8b29b874f9e1830f1919ac097ca6560a6ef747976                                                                                0.0s
 => => extracting sha256:238768c628173281bc3162a29cef7923808d66159e7249d80620b4221632200b                                                                                1.4s
 => => extracting sha256:ec755c817ff697a94525832b7ac0c6e41048d90ac0da7e9454a5fe5c1a04caf9                                                                                0.1s
 => => extracting sha256:4d7f255f49584b155894f79821624b3502337e5825df64c3be03a07f04fb1691                                                                                0.0s
 => ERROR [2/2] RUN npm install pm2@latest -g                                                                                0.3s
------
 > [2/2] RUN npm install pm2@latest -g:
------
Dockerfile:3
--------------------
   1 |     FROM node:14.16.0-buster
   2 |
   3 | >>> RUN npm install pm2@latest -g
   4 |
   5 |     # RUN mkdir -p /home/ubuntu
--------------------
error: failed to solve: rpc error: code = Unknown desc = executor failed running [/dev/.buildkit_qemu_emulator /bin/sh -c npm install pm2@latest -g]: exit code: 1

I think a segmentation fault is happening after the npm install because host shell where the docker build is running is x86_64, this is just an assumption. Any help is appreciated.

A: I have been facing this issue lately and managed to bypass it.
First, I installed qemu and other dependencies:
apt-get install qemu qemu-user-static binfmt-support debootstrap -y

Then, I created a dedicated builder:
docker buildx create --name armBuilder

And used it:
docker buildx use armBuilder

After doing this, I faced connectivity errors in some projects, especially when talking about bigger dependencies, e.g. @material-ui/icon. In order to avoid this, I changed the build instructions by extending the timeout settings.
If you are using npm either change the instruction to:
npm install -timeout=600000

Or create a file called .npmrc:
fetch-retry-maxtimeout=60000

You can also set it like this:
npm config set fetch-retry-maxtimeout 60000

The options are described here https://docs.npmjs.com/cli/v6/using-npm/config#fetch-retry-mintimeout
Anyway, I recommend using yarn, which is faster. For yarn:
yarn install --network-timeout 600000

Or create a .yarnrc file:
network-timeout 600000

A: A bit late, but for all others that have the same error. Check if you have installed multi platform support for buildx:
docker run --privileged --rm tonistiigi/binfmt --install all

The full documentation is on the Docker page here


text:
Q: How include SVG picture in a table latex? I have a problem to insert multiple SVG pictures in a table. I try many ways with tabular but I don't have any succes.
I manage to implement a single picture in the document with this piece of code, using the inkscape method:
\begin{figure}[h!]
    \centering
    \def\svgwidth{5cm}
    \input{SupplyChain.pdf_tex}
\end{figure}

I would like a table with 3 rows and 2 columns. The first column contains the picture and the second its description.

A: You can use the same code in a tabular:
\documentclass{article}
\usepackage{graphicx}

\begin{document}

{
\begin{tabular}{cc}
\def\svgwidth{5cm}
\input{test.pdf_tex}
&
text\\
\def\svgwidth{5cm}
\input{test.pdf_tex}
&
text\\
\def\svgwidth{5cm}
\input{test.pdf_tex}
&
text\\
\end{tabular}

\end{document}


text:
Q: Unable to delete records as the transaction log file is full My disk is running out of space and as a result I decided to free some space by deleting old data. I tried to delete 100,000 by 100,000 as there are 240 million records to be deleted. But I am unable to delete them at once and shrinking the database doesn't free much space. This is the error im getting at times.
The transaction log for database 'TEST_ARCHIVE' is full. To find out why space in the log cannot be reused, see the log_reuse_wait_desc column in sys.databases
How can I overcome this situation and delete all the old records? Please advice.

A: Shrink Log File
Your disk where your log file is located is full, try freeing up some space on the log drive.
Use [DatabaseName]
GO

CHECKPOINT;
GO

CHECKPOINT;  --<-- executed twice
GO

DBCC SHRINKFILE('LogFileName' , 1024)
GO

Delete Records in small Chunks
Delete Records in small chunks something like ...
DECLARE @Deleted_Rows INT;
SET @Deleted_Rows = 1;

WHILE (@Deleted_Rows > 0)
  BEGIN
   -- Delete some small number of rows at a time
    DELETE TOP (10000) FROM [TableName]

  SET @Deleted_Rows = @@ROWCOUNT;
END

A: You need to need to backup the transaction log more frequently during a large delete operation.  A log backup will remove records from the transaction log that are no longer needed for rollback or crash recovery.  If that doesn't help, run the query suggested in the error message:
SELECT log_reuse_wait_desc
FROM sys.databases
WHERE name = N'TEST_ARCHIVE';


text:
Q: Can I listen to when the Navigation drawer is opened or closed (e.g: listener like button onclick)? I want to call some methods when Navigation Drawer is opened & closed. How can I listen to it (like button's onclick listener) ?
I know we can check (mDrawer.isDrawerOpen(Gravity.LEFT)) or ((mDrawer.isDrawerClose(Gravity.LEFT))).
Thanks in Advance.

A: I know this is a very old question, but I had the same question.
for newer android versions you can do the following :
 DrawerLayout drawer = findViewById(R.id.drawer_layout);

 drawer.addDrawerListener(new DrawerLayout.DrawerListener() {
        @Override
        public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {

        }

        @Override
        public void onDrawerOpened(@NonNull View drawerView) {
        }

        @Override
        public void onDrawerClosed(@NonNull View drawerView) {

        }

        @Override
        public void onDrawerStateChanged(int newState) {
            Toast.makeText(SideMenuActivity.this, "state: " + newState, Toast.LENGTH_SHORT).show();

        }
    });

A: You can know it by using this piece of code by using ActionBarDrawerToggle as:
     ActionBarDrawerToggle  drawerToggle = new  android.support.v7.app.ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) {

        @Override
        public void onDrawerClosed(View drawerView) {
            super.onDrawerClosed(drawerView);

        }

        @Override
        public void onDrawerOpened(View drawerView) {
            super.onDrawerOpened(drawerView);

        }
    };
    mDrawer.setDrawerListener(drawerToggle);

A: There are 4 abstract methods provided in the abstract inner class 'DrawerListener' of 'DrawerLayout' Class
public abstract void onDrawerClosed (View drawerView)
public abstract void onDrawerOpened (View drawerView)
public abstract void onDrawerSlide (View drawerView, float slideOffset)
public abstract void onDrawerStateChanged (int newState)

Useful Example :
((DrawerLayout) findViewById(R.id.drawer_layout)).addDrawerListener(new DrawerLayout.DrawerListener() {
        @Override
        public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
            // Whatever you want
        }

        @Override
        public void onDrawerOpened(@NonNull View drawerView) {
            // Whatever you want
        }

        @Override
        public void onDrawerClosed(@NonNull View drawerView) {
            // Whatever you want
        }

        @Override
        public void onDrawerStateChanged(int newState) {
            // Whatever you want
        }
    });

You can check this for more informations HERE

A: Yeah there are four abstract methods that you can use as listeners
public abstract void onDrawerClosed (View drawerView)
public abstract void onDrawerOpened (View drawerView)
public abstract void onDrawerSlide (View drawerView, float slideOffset)
public abstract void onDrawerStateChanged (int newState)

can be used like this
ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
        R.drawable.ic_drawer, R.string.drawer_open, R.string.drawer_close) {
    public void onDrawerClosed(View view) {
        super.onDrawerClosed(view);
        // Do whatever you want here
    }
    public void onDrawerOpened(View drawerView) {
        super.onDrawerOpened(drawerView);
        // Do whatever you want here
    }
};
mDrawerLayout.addDrawerListener(mDrawerToggle);

copied from http://developer.android.com/reference/android/support/v4/widget/DrawerLayout.DrawerListener.html
UPDATE
setDrawerListener method was deprecated in API level 24.1.0. so use addDrawerListener()

A: KOTLIN
Initialize the DrawerLayout View
`val drawerLayout: DrawerLayout = findViewById(R.id.drawer_layout)`

If you want to take actions automatically when the drawer is opened or closed, you can do the following.

*

*In your main activity, create an inner class that is a subclass of DrawerLayout.DrawerListener. The DrawerLayout class implements the DrawerListener interface. As mentioned in this post, the onDrawerSlide function can be used to take an action when the drawer starts to open.
inner class CustomDrawer : DrawerLayout.DrawerListener{
  override fun onDrawerStateChanged(newState: Int) {
  }

  override fun onDrawerSlide(drawerView: View, slideOffset: Float) {
    imm.hideSoftInputFromWindow(drawerView?.getWindowToken(), 0)
  }

  override fun onDrawerClosed(drawerView: View) {
    imm.hideSoftInputFromWindow(drawerView?.getWindowToken(), 0)
  }

  override fun onDrawerOpened(drawerView: View) {
    imm.hideSoftInputFromWindow(drawerView?.getWindowToken(), 0)
  }
}

*Put your action in the function you want to use. In my example, I'm closing the soft keyboard if the user interacts with the navigation drawer. Declare the InputMethodManager like this in your main activity:
var imm: InputMethodManager = this.getSystemService(Activity.INPUT_METHOD_SERVICE)

*Add your custom DrawerListener to the drawerLayout (I put it in the onCreate method)
var drawerListener = CustomDrawer()
drawerLayout.addDrawerListener(drawerListener)

A: same issue here and this is what worked for me in Kotlin:
        drawerLayout.addDrawerListener(object : DrawerLayout.DrawerListener {
            override fun onDrawerSlide(drawerView: View, slideOffset: Float) {
                println("Drawer is sliding")
            }

            override fun onDrawerOpened(drawerView: View) {
                println("Drawer is open")
            }

            override fun onDrawerClosed(drawerView: View) {
                println("Drawer is closed")
            }

            override fun onDrawerStateChanged(newState: Int) {
                println("Drawer state changed")
            }
        })


text:
Q: How to obfuscate String in Android? I want to obfuscate my api url.Can i use Proguard for this?If yes how do i do that?And how to add classes in Proguard configuration file to obfuscate the methods and variables present in the classes?

A: You can now use a new gradle plugin + library to effectively obfuscate Strings in a class, Please check it here
https://github.com/MichaelRocks/paranoid
Also now there is a new plugin which can obfuscate resources also, please check it below
https://github.com/shwenzhang/AndResGuard
And help share and upvote this great information, so more developers can use it and thus more and more developers will contribute for further development of these plugins, and thus we can collectively improve these plugins and will give a nightmare for crackers.


text:
Q: TypeScript / prettier: Fluent interfaces and union types with prettier (using "//") When I am using fluent interfaces in TypeScript I normally want different method calls on different lines while by default prettier tries to format it in one single line (if not too long). A similar behavior for union types.
It seems that prettier supports a workaround by adding an empty comment (//), see the examples below.
The question: Is this //-workaround an official feature of prettier and if yes then where do I find the documentation for that?
const x = a().b().c();

/* prettier output:
const x = a().b().c();
*/

const y = a()
  .b()
  .c();

/* prettier output:
const y = a().b().c();
*/

const z = a() //
  .b()
  .c();

/* prettier output:
const z = a() //
  .b()
  .c();
*/

type A =
  | "x"
  | "y"
  | "z";

/* prettier output:
type A = "x" | "y" | "z";
*/

type B  =
  | "x" //
  | "y"
  | "z";

/* prettier output:
type B =
  | "x" //
  | "y"
  | "z";
*/


text:
Q: Pushing a local object onto a global array I'm grabbing JSON from reddit's API, and placing the JSON objects into a global array.
var stories = [];

var request = new XMLHttpRequest();
request.open('GET', 'http://www.reddit.com/r/news/top.json?limit=5', true);

request.onload = function() {
    var rawStories = JSON.parse(request.response);
    for (var i in rawStories.data.children) {
        var story = {};
        story.title = rawStories.data.children[i].data.title;
        stories.push(story);
    }
};

alert(stories); //Here I am accessing stories in global scope.

The above global alert(stories) shows the empty initialized stories array. Moving the alert inside the function displays a properly filled array of objects.
How can I have a globally accessible stories array? My misunderstanding is either in the asynchronous nature of the request.onload function or I'm having scope trouble (or both).


text:
Q: consecutive rest API http calls angular 4 i looked for answers here but found none so i will go ahead and try to explain my situation as clearly as i can in hope that i get one.
Here is the situation : I am building an angular 4 SPA that consumes a rest API backend.
In one of my component i have to fetch several sets of data from the backend (from different methods), and i need to have all these different sets of data to display a chart in my component.
If i  just make consecutive http calls in my Init method and then call my process_data method, angular does not wait for all http responses before it calls the processing method. Thus the method is called when all needed data is not necessarily there yet, which can cause errors.
The solution i have right now : The fix i implemented for the time being is the following :

*

*I make a first http request, to which i subscribe.

*In this subscription i make the second http request, to which i also subscribe

*And so on for each subsequent http request

*In the last .subscribe() i call my processing method.

The result being a big Init method that is quite hard to read/debug because of all the nested http requests.
So the fix works but it is ugly and will be hard to reuse, which is a serious issue since i am developing this for a company. Which brings me to the...
Question : Is there a better (cleaner/standard/good practice) way of achieving the same result ?
TL;DR : Is there a good way of making several consecutive http requests and wait for all to be completed (and wait for the response) before proceeding ?
notes : Though i am developing this SPA for a company, i am only an intern (thus, still at school, still learning the ropes). In addition to not being a real engineer yet i am also new to angular and web development  in general.Of course, i apologize if the answer to my question is obvious.
Secondly, english is not my native language so i also apologize for any english-related mistakes in my post.
I thank you all in advance for your answers.

A: I believe you will find what you are looking for in Flatmaps or the other solutions found in this great tutorial.
Flatmaps will help you make your multiple HTTP requests linear.
To quote the official documentation:

transform the items emitted by an Observable into Observables, then flatten the emissions from those into a single Observable


text:
Q: How to retrieve struct pointer from Go list I have a struct
type clientData struct {
    msg    Message
    connId int
}

I'm trying to add this to a Go List as such
l := list.New()
l.PushBack(&clientData {
    msg: Message {
       some fields
    },
    connId: 1
});

Now, how do I get back the data as a *clientData data type back from the List ? I tried l.Front().Value but that returns an interface... I'm pretty sure I don't understand the marshalling/marshalling logic for Go here...

A: Collection in go contains a raw types (Element.Value  empty interface{}). You have to assign the type every time, when get value from the list:
l := list.New()
l.PushBack(&clientData {
    msg: Message {
       some fields
    },
    connId: 1,
})

cd, ok := l.Front().Value.(*clientData)
if !ok {
    panic(errors.New("not a client type"))
}
fmt.Println(cd.connId)


text:
Q: User not updating in mongo after save? I have an app for todos. I'm trying to update a specific todo within an array of todos stored in the User I'm currently logged into. This is the code that does that:
User.findById(req.user._id)
        .then(user => {
            user.todos.forEach(function(todo) {
                if (todo._id == req.params.todoId) {
                    todo.completed = !todo.completed;
                    console.log(todo.completed);
                }
            })
            return user.save();
        })
        .then(result => {
            console.log(result);
            res.json(result);
        })
        .catch(function(err) {
            res.send(err);
        })

When I console.log the result, everything comes out fine. When I console log the updated Todo in the ajax call I'm making in my javascript file, everything appears fine. The todo is updated. However, when I stop my server and find the user in Mongo, the todo still isn't updated.
Any help is much appreciated.

A: When you modify a nested property on a document, mongoose may not be aware that anything changed, so it won't know to persist the changes in the DB (otherwise it would have to pass everything, which could become expensive if you have a large document but only a tiny part of it changed).
This can be done via the markModified method:
 user.todos.forEach(function(todo) {
   if (todo._id == req.params.todoId) {
     todo.completed = !todo.completed;
     console.log(todo.completed);
   }
 })
 user.markModified('todos');
 return user.save();

A: Instead of doing it in JavaScript code I will suggest you can do it in query only which will more effective.
db.getCollection('User').update({"_id":<req.user._id>,"todo._id":<req.params.todoId>},
 {$set:
     {'todo.$.completed': true}
 }, {
   new : true
 }
)

In this query you need to pass completed status as well.


text:
Q: Cross domain jQuery ajax call with credentials I've followed the following steps:

*

*Get the server to allow cross domain calls (with all the headers and stuff) This works

*Test the server with some cross domain calls This works

*Get the server to force a certificate  This works

*Go to a file on the server with a browser, choose the right certificate and see the file Still works
Now we get to the nice part

*Combine the cross domain calls with the certificate <-- this does not work
Problem
I am getting the certificate request from the browser, but when I select the same certificate as I do when using the browser, the call is made but I get a 403 Forbidden.
Code
$.ajax({
     type: "POST",
     xhrFields: {withCredentials: true},
     dataType: "xml",
     contentType: "text/xml; charset=\"utf-8\"",
     url: "https://www.myOtherServer.com/testfile.asp",
});

Any ideas?
Edit
The Access-Control-Allow-Credentials: true and the Access-Control-Allow-Origin are properly configured.
Additional information
I'm starting to think that it has something to do with the content type. When I change it to "text/html" I get a 415 error, but I do really need to send xml because it is a SOAP server.
Response headers
Access-Control-Allow-Cred...    true
Access-Control-Allow-Head...    Content-Type, Origin, Man, Messagetype, Soapaction, X-Test-Header
Access-Control-Allow-Meth...    GET,POST,HEAD,DELETE,PUT,OPTIONS
Access-Control-Allow-Orig...    https://www.mywebsite.com
Access-Control-Max-Age  1800
Cache-Control   private
Content-Length  5561
Content-Type    text/html; charset=utf-8
Date    Wed, 19 Dec 2012 15:06:46 GMT
Server  Microsoft-IIS/7.5
X-Powered-By    ASP.NET

Request headers
Accept  text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding gzip, deflate
Accept-Language nl,en-us;q=0.7,en;q=0.3
Access-Control-Request-He...    content-type
Access-Control-Request-Me...    POST
Cache-Control   no-cache
Connection  keep-alive
Host    myhoast.com
Origin  https://www.mywebsite.com
Pragma  no-cache
User-Agent  Mozilla/5.0 (Windows NT 6.1; WOW64; rv:17.0) Gecko/20100101 Firefox/17.0

A: My best guess is that this is a problem not with your Javascript but with your CORS configuration. Did you set up your server with the Access-Control-Allow-Credentials: true header? http://www.w3.org/TR/cors/#access-control-allow-credentials-response-header
Also note that, even when the allow-credentials header is set, the browser will not allow responses to credentialed requests if Access-Control-Allow-Origin is *, according to these docs: https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS?redirectlocale=en-US&redirectslug=HTTP_access_control#Requests_with_credentials.
Edit: Since the OP has the CORS headers set up properly, the problem seems to be that the server is rejecting OPTIONS requests with a 403 status code. OPTIONS requests (known as the "preflight request") are sent before certain cross-domain requests (such as POSTs with application/xml content types), to allow the server to notify the browser of what types of requests are allowed. Since the browser doesn't see the 200 response that it expects from the OPTIONS request, it doesn't fire the actual POST request.

A: basicly we just have to write on htaccess
Header set Access-Control-Allow-Origin "*"

but when we need cookie etc, we had to add script on your ajax code and htaccess
i write about cross domain XHR on my blog, blog.imammubin.com/cross-domain-xhr/2014/05/28/ (Edit: site no longer exists)
hope this help..


text:
Q: Sumar Filas por valor de una columna conservando el resto- Rstudio Escribo porque estoy con la siguiente duda.
Tengo un dataframe que tiene 6 columnas y 10 filas.  Tengo 4 variables (ID, PAIS, SUCURSAL, VENDEDOR) que son categoricas  y 2 que son numericas ( VENTAS Y VENTAS MES ANTERIOR). Adjunto el ejemplo:

Lo que necesitaria es sumar las filas de las columnas 5 y 6 (VENTAS Y VENTAS ANTERIORES) para los cuales el ID es el mismo, luego el mismo PAIS, SUCURSAL Y NOMBRE. De esta manera me quedarian menos filas que en el caso anterior, y las que se repiten aparecen tan solo una vez.  El resultado seria algo asi:

Intente hacerlo con la función agregate(xx, by=list) pero no me devuelve el total de columnas, sino solo las que elijo sumar y la variable especifica por la que elijo sumar. Esto es, si no elijo agrupar por todas las columnas del data frame, solo me devuelve aquellas columnas que elegi para que sume y la columna de criterio.
Tambien intente utilizar Group_by complementado con mutate, pero me agrega mas columnas al dataframe, lo que no me hace consistente los datos.
Que podria hacer? Desde ya agradezco por adelantado!!

A: Con un group_by por todas esas variables, bastaría:
library(dplyr)

df %>%
  group_by(ID, Pais, Sucursal, Vendedor) %>%
  summarise(
    Suma_de_ventas = sum(Ventas),
    Suma_de_ventas_mes_anterior = sum(`ventas mes anterior`)
  )


text:
Q: How to make an aggregation of another aggregation I have a table that contains several projects and another table with several housing and a table with several quotes. I try to have a line per project and list all the housing of my project then all the quotes of my housing
I have a line by housing because it forces me to group by housing.
this is the code :
select
projet.id,
(struct(
( logement.id) as identifiant_logement , (logement.living_area) as superficie, array_agg(struct (
coalesce(devisdetail.id,0) as identifiant_devis,
  coalesce(devisdetail.price_incl_tax,0) as price_incl_tax

)) as logements
)) as projets
from
EXTERNAL_QUERY("app-oslo-prod.eu.oslo-prod-conn", "SELECT * FROM CORE.mission;")mission
left join EXTERNAL_QUERY("app-oslo-prod.eu.oslo-prod-conn", "SELECT * FROM CORE.PROJECT;")projet on projet.mission_id = mission.id left join
EXTERNAL_QUERY("app-oslo-prod.eu.oslo-prod-conn", "SELECT * FROM CORE.ACCOMMODATION;")logement on logement.project_id = projet.id
left join
EXTERNAL_QUERY("app-oslo-prod.eu.oslo-prod-conn",    "SELECT * FROM CORE.QUOTE_ACCOMMODATION") devisdetail
ON  logement.id = devisdetail.accommodation_id
where projet.id = 1194 or projet.id = 1195
group by projet.id , logement.id, logement.living_area


text:
Q: Uncaught TypeError: Object # has no method 'tags' I've tried to fix this but i must be missing something simple. This is a javascript menu and it works fine in IE but in chrome, the first level click to open the menu fails with the error
Uncaught TypeError: Object #<HTMLCollection> has no method 'tags'

Something tells me one of the elements isn't correctly defined but I dont see it.
Here is a simple working example
http://code.fraser.id.au/menu.html
NOTE: Pull down (Windows Sytle) menu top left.

A: the right way to get child nodes by tag name is getElementsByTagName: http://developer.mozilla.org/en/docs/DOM:element.getElementsByTagName


text:
Q: Reactjs: how to get item value into a variable from axios data received I am confused as how to get a value of an item from a data returned by axios function.  I've looked at many examples, but only avail are returning value using map, such as below.
render() {
  var student = this.state.student;
  return (
    student.map( d => (
      ..
      <td>{d.grade}
      ..
  );
)

But what I'm trying to do is store the value in a variable for manipulation. For example below, I want to extract the student grade:
class Student extends Component {
  state = { student: [], };

  componentDidMount() {
    axio.get(window.$API_URL).then(res=>this.setState({stduent: res.data}));
    var student = this.state.student;
    var grade = student.grade;                       //** doesn't work
    var grade = this.getGrade(student);              //** doesn't work
    var grade = getPropertyValue(student, "grade");  //** doesn't work
    ....
  }

  getGrade(student) {
    student.map(d=>{return(d.grade)});
  }

  getPropertyValue(obj, dataToRetrieve) {
    return dataToRetrieve
      .split('.')
      .reduce(function(o, k) {
        return o && o[k];
      }, obj)
  }

  render() { ....  }
}


text:
Q: Representation of objects Sometimes we have to represent our objects of classes with it's attributes. Mostly we use
def __str__

for string representation which generally return characters.
But I have a class with no attribute that has characters. I wanted to represent that with the only attribute which is a DecimalField. Please help me to get the right syntax to represent my objects.

A: The __str__ should always return a string. What you could do is following:
def __str__(self):
    return 'Average: {}'.format(self.average)

A: You can convert the value of the DecimalField to string:
def __str__(self):
    return str(self.average)

or alternatively, if you have more complex values, you could use the method to_eng_string:
def __str__(self):
    return self.average.to_eng_string

The documentation says:

Convert to a string, using engineering notation if an exponent is
  needed.
Engineering notation has an exponent which is a multiple of 3. This
  can leave up to 3 digits to the left of the decimal place and may
  require the addition of either one or two trailing zeros.
For example, this converts Decimal('123E+1') to Decimal('1.23E+3').


text:
Q: How can I get optimistic concurrency with JPA annotation I am using JPA 3, with annotation (no mapping file) and with provider org.hibernate.ejb.HibernatePersistence
I need to have optimistic concurrency.
1)I tried to rely on the tag called , it did not work.
2)
So I decided to do it with java code. I have a mergeServiceRequest method and an object with type Request as follows: I start a transaction, lock the request object,
then try to get a Request object newRequest from database, compare its timestamp with the current one request. If they do not match, I throw an exception; if they match, then I update the current request enter code herewith current time and save it to database.
I need to lock the object manually, because by starting a transaction from session, it does not put a lock on the row in database. I wrote some java code which shows that a transaction does not lock the record in database automatically.
Problem with this approach is the query
Request newRequest=entityManager.createQuery("select r  from Request r where serviceRequestId =  " + request.getServiceRequestId());

always return same object as request. "request" is in the session entityManger, and the query always return what is cached in the session. I tried all the five query.setHint lines and I still get same result: no database query is performed, the result is from session cache directly.
@Transactional
    public void mergeServiceRequest(Request request) {
        System.out.println("ServiceRequestDao.java line 209");
        EntityTransaction transaction = entityManager.getTransaction();
        transaction.begin();
        entityManager.lock(request, LockModeType.WRITE); // use to lock the database row

        Query query = entityManager.createQuery("select r  from Request r where serviceRequestId =  " + request.getServiceRequestId());
        //query.setHint("javax.persistence.cache.retrieveMode", "BYPASS");
        //query.setHint("org.hibernate.cacheMode", CacheMode.REFRESH);
        //query.setHint("javax.persistence.cache.retrieveMode", CacheMode.REFRESH);
        //query.setHint("javax.persistence.retrieveMode", CacheMode.REFRESH);
        //query.setHint(QueryHints.CACHE_USAGE, CacheUsage.DoNotCheckCache);

        Request newRequest=(Request)query.getSingleResult();

        if (! newRequest.getLastUpdatedOn().equals(request.getLastUpdatedOn())) {
            throw new StaleObjectStateException(request.getClass().toString(), request.getServiceRequestId());
        }

        request.setLastUpdatedOn(new Date(System.currentTimeMillis()));
        entityManager.persist(request);
        entityManager.flush();
        transaction.commit();
    }

3)So I also tried to use another session get query the newRequest, if I do that, the newRequest will be different from request. But for some reason, if I do that, then the lock on request object is never released, even after the transaction commit. Code looks like below
@Transactional
    public void mergeServiceRequest(Request request) {
        System.out.println("ServiceRequestDao.java line 209");
        EntityTransaction transaction = entityManager.getTransaction();
        transaction.begin();
        entityManager.lock(request, LockModeType.WRITE); // use to lock the database row

        Request newRequest=findRequest(request.getServiceRequestId()); // get it from another session

        if (! newRequest.getLastUpdatedOn().equals(request.getLastUpdatedOn())) {
            throw new StaleObjectStateException(request.getClass().toString(), request.getServiceRequestId());
        }

        request.setLastUpdatedOn(new Date(System.currentTimeMillis()));
        entityManager.persist(request);
        entityManager.flush();
        transaction.commit();
//lock on the database record is not released after this, and even after entityManager is closed
    }

Could anyone help me on this?
Thanks.
Daniel


text:
Q: uniq by only a part of the line I am trying to consolidate an email list, but I want to uniq (or uniq -i -u) by the email address, not the entire line so that we don't have duplicates.
list 1:
Company A <companya@companya.com>
Company B <companyb@companyb.com>
Company C <companyc@companyc.com>

list 2:
firstname lastname <firstname@gmail.com>
Fake Person <companyb@companyb.com>
Joe lastnanme <joe@gmail.com>

the current output is
Company A <companya@companya.com>
Company B <companyb@companyb.com>
Company C <companyc@companyc.com>
firstname lastname <firstname@gmail.com>
Fake Person <companyb@companyb.com>
Joe lastnanme <joe@gmail.com>

the desired output would be
Company A <companya@companya.com>
Company B <companyb@companyb.com>
Company C <companyc@companyc.com>
firstname lastname <firstname@gmail.com>
Joe lastnanme <joe@gmail.com>

(as companyb@companyb.com is listed in both)
How can I do that?

A: given your file format
$ awk -F'[<>]' '!a[$2]++' files

will print the first instance of duplicate content in angled brackets.  Or if there is no content after the email, you don't need to un-wrap the angled brackets
$ awk '!a[$NF]++' files

Same can be done with sort as well
$ sort -t'<' -k2,2 -u files

side-effect is output will be sorted which can be desired (or not).
N.B. For both alternatives the assumption is angled brackets don't appear anywhere else than the email wrappers.

A: Here is one in awk:
$ awk '
match($0,/[a-z0-9.]+@[a-z.]+/) {      # look for emailish string *
    a[substr($0,RSTART,RLENGTH)]=$0   # and hash the record using the address as key
}
END {                                 # after all are processed
    for(i in a)                       # output them in no particular order
        print a[i]
}' file2 file1                        # switch order to see how it affects output

Output
Company A <companya@companya.com>
Company B <companyb@companyb.com>
Company C <companyc@companyc.com>
Joe lastnanme <joe@gmail.com>
firstname lastname <firstname@gmail.com>

Script looks for very simple emailish string (* see the regex in the script and tune it to your liking) which it uses to hash the whole records,last instance wins as the earlier onse are overwritten.

A: uniq has an -f option to ignore a number of blank-delimited fields, so we can sort on the third field and then ignore the first two:
$ sort -k 3,3 infile | uniq -f 2
Company A <companya@companya.com>
Company B <companyb@companyb.com>
Company C <companyc@companyc.com>
firstname lastname <firstname@gmail.com>
Joe lastnanme <joe@gmail.com>

However, this isn't very robust: it breaks as soon as there aren't exactly two fields before the email address as the sorting will be on the wrong field and uniq will compare the wrong fields.
Check karakfa's answer to see how uniq isn't even required here.
Alternatively, just checking for uniqueness of the last field:
awk '!e[$NF] {print; ++e[$NF]}' infile

or even shorter, stealing from karakfa, awk '!e[$NF]++' infile

A: Could you please try following.
awk '
{
   match($0,/<.*>/)
   val=substr($0,RSTART,RLENGTH)
}
FNR==NR{
   a[val]=$0
   print
   next
}
!(val in a)
' list1 list2

Explanation: Adding explanation of above code.
awk '                                    ##Starting awk program here.
{                                        ##Starting BLOCK which will be executed for both of the Input_files.
   match($0,/<.*>/)                      ##Using match function of awk where giving regex to match everything from < to till >
   val=substr($0,RSTART,RLENGTH)         ##Creating variable named val whose value is substring of current line starting from RSTART to value of RLENGTH, basically matched string.
}                                        ##Closing above BLOCK here.
FNR==NR{                                 ##Checking condition FNR==NR which will be TRUE when 1st Input_file named list1 will be read.
   a[val]=$0                             ##Creating an array named a whose index is val and value is current line.
   print $0                              ##Printing current line here.
   next                                  ##next will skip all further statements from here.
}
!(val in a)                              ##Checking condition if variable val is NOT present in array a if it is NOT present then do printing of current line.
' list1 list2                            ##Mentioning Input_file names here.

Output will be as follows.
Company A <companya@companya.com>
Company B <companyb@companyb.com>
Company C <companyc@companyc.com>
firstname lastname <firstname@gmail.com>
Joe lastnanme <joe@gmail.com>

A: Perhaps I don't understand the question !
but you can try this awk :
awk 'NR!=FNR && $3 in a{next}{a[$3]}1' list1 list2


text:
Q: Django Paginate_by not displaying proper pagination Hello i have a page using paginate_by 10, and instead i'm getting only 9 elements per page, even tho in the element inspector i see 10 grid spaces my for cicle is just being able to fill 9 out of 10 then it goes into the next page.
Views.py
    class VideoListView(generic.ListView):
    model = Video
    template_name = 'index.html'
    context_object_name = 'video_list'
    paginate_by = 10

    def get_queryset(self):
        return Video.objects.order_by('-date')

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['category_list'] = Category.objects.all()
        return context

EDIT AFTER A QUESTION. here's the template logic

    {% for video in video_list %}
    {% if video.home ==True %}

    {% endif %} {% endfor %}

As possible causes i did find that when i do "paginate by 1" the page starts displaying empty pages for the pages that aren't considered in the IF. which makes me think that the if statement is taking into consideration the empty videos even tho they aren't listed.
How can i fix this?
i do want to filter the videos that aren't meant for the home_page
Thanks a lot in advance for the reply

A: The reason this happens is because you filter in the template, so after the queryset is paginated. Filtering in the template is not a good idea, for example because it will render the pagination incorrect, but it is also inefficent.
You should filter in the view, with:
class VideoListView(generic.ListView):
    model = Video
    queryset = Video.objects.filter(home=True).order_by('-date')
    template_name = 'index.html'
    context_object_name = 'video_list'
    paginate_by = 10

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['category_list'] = Category.objects.all()
        return context
and thus remove the {% if video.home == True %} … {% endif %} part.


text:
Q: What does a DependencyReplicator.xml file look like? I am trying to get started using Dependency Replicator http://www.codeplex.com/tfsdepreplicator. There is no documentation in place and therefore no example of a DependencyReplicator.xml file which I need in order to take my experiment further. Can anyone using Dependency Replicator supply a demo .xml file?

A: In the buildtype create a DependencyReplication.xml file and use something like the following:
<?xml version="1.0" encoding="utf-16"?>
<DependencyReplication  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://schemas.readify.net/tfsintegrator/dependencyreplication/20060725">
  <TeamProject TeamProject="AcmeAnvils" RootFolder="$/AcmeAnvils">
    <Dependency TeamProject="AcmeAnvils" BuildType="AcmeAnvilsContinuousBuild" >
      <File Source="Release/AcmeAnvils.Common.dll" Destination="$/AcmeAnvils/AcmeAnvil_Services/AcmeAnvils.Common.dll" />
      <File Source="Release/AcmeAnvils.Common.dll" Destination="$/AcmeAnvils/Dogfood/Dependencies/AcmeAnvils.Common.dll" />
    </Dependency>
  </TeamProject>
</DependencyReplication>