text:
Q: Spring MVC annotation relative path error I am trying to convert my app written in Spring MVC 2.5 to use the annotated style of controller.
Apparently, I am unable to get things going.
I have a mapping as below:

Equipment Qual Report

I created my controller like below:
@Controller
@RequestMapping("/eqr")
public class EQRMainController {
 private SimpleEQRTransManager eqrManager;
 protected final Log logger = LogFactory.getLog(getClass());

 @RequestMapping(value = "/eqrItemList.htm")
 public String setupForm(
   @RequestParam(value = "plant", required = false) String plant,
  return "eqrmain";
 }
}

I wanted to use the relative path so I set my request mapping at the class type level. But apparently, I am getting a 404 not found and a Handler mapping not found error at the tomcat console.
It says:

No mapping found for HTTP request with URI [/myapp/eqr/eqrItemList.htm]

I look at the Firebug console and it is requesting below path:
http://localhost:8080/myapp/eqr/eqrItemList.htm

I don't know why it can't find the mapping.

A: Are you sure you've configured the context correctly for annotations?
In the MVC context configuration (typically called dispatcher-servlet.xml, depending on the name if your servlet) you can configure MVC annotation support quite simply using this element:
<mvc:annotation-driven />
This is the easiest way to tell Spring that you're going to use MVC annotations. Here's a snippet from one of my projects to put it into context:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<import resource="application-context.xml" />

<mvc:annotation-driven />
<context:component-scan base-package="my.controllers.package.here" />

Careful; this is Spring 3 so it may not fully apply for 2.5. Check the reference documentation (it explains this quite thoroughly).

A: Check your servlet-mapping in web.xml:
     <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>*.do</url-pattern>
     </servlet-mapping>

If url-pattern fixes only some special extensions (like *.do in this example) then your servlet will never get this request.


text:
Q: ASP.NET UserControl not being updated after event I have a asp.net control that represents a table and a control that represents a row in the table. Each row contains a text field for a date and a button to submit the date entered.
<asp:TextBox ID="TextBox" runat="server"/>
<asp:ImageButton ID="SubmitButton" onclick="SubmitButton_Click" runat="server" />

The button fires an event which triggers an update in the database.
protected void SubmitButton_Click(object sender, EventArgs e)
{
    //Validate information in TextBox
    //Submit to database
}

This should cause a new set of rows to be shown based on the information entered in the text box.  However, the updated information is not being shown unless I force a page refresh. I suspect this is because of where event handling falls in the asp.net page/control lifecycle.  As near as I can tell the values are loaded into the rows before the event is actually triggered, which causes them to get the old values and not the new values that they should have.
My question is what is the best way to get around this?  I'm assuming it will be something like checking to see if it's a postback in the page load event and not loading the user control rows but instead causing them to load or to refresh from the event somehow but I'm not sure what that should look like.
Edit:  I think I need to call the same function that is being called in the Page_Load but I'm not sure how to get to it from the custom control I guess.

A: I think you need to re-bind your grid after your event has fired.

A: As Locksfree said, a rebind is what you are probably looking for.
Postback does not automatically show new data unless you specifically request the new data by calling DataBind() of your asp.net object.
If you are dynamically creating the table then you will have to rerun the code to rebuild your table again to get the new data. Depending on how it is built you may be able to get away with a partial reload of just the new data.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unable to edit/replace string value with plus symbol "+" in text file via PowerShell I'm trying to update a group of XML based .config files.  There is a string in the file that contains a plus sign that I cannot replace with my script:
< SharedPassKey=123456789abcdefghi/JKLM+nopqrst= />

If I include the plus sign, the script does nothing.  Since all the configs vary I need to replace the text - cannot just go with new files.
The desired result is that the matching value in the file be replaced with the specified value, but the + symbol is not allowing this. Here is my PS script:
$DIRs = Get-ChildItem -Path "C:\TEST" -Directory
Get-ChildItem $DIRs -File -Recurse -Filter *.config |
    ForEach { (Get-Content $_.FullName) |
    ForEach { $_ -replace '< SharedPassKey=123456789abcdefghi/JKLM+nopqrst= />','< SharedPassKey=123456789abcdefghi/JKLM.nopqrst= />' } |
    Set-Content $_.FullName }

As a test I replaced all the text up to the plus sign and it worked fine, but the plus sign and following were present at the end of the new text as I had left the "+nopqrst" out of the script.
Running on PSv3, FYI.

A: The -replace operator uses a regular expression for the first postfix argument to define the search pattern.  In a regular expression, certain characters have a special meaning.  + in particular is a so-called "quantifier" with the meaning "one or more times the preceding (sub)expression".  In order to replace literal special characters, you need to escape them.
Fortunately, there's a built-in method for escaping strings:
$_ -replace [RegEx]::Escape('< SharedPassKey=123456789abcdefghi/JKLM+nopqrst= />'),'< SharedPassKey=123456789abcdefghi/JKLM.nopqrst= />'

A: If you have valid XML data and you want to modify the value of a node attribute in an XML file you may want to consider using a proper XML parser, like this:
$xmlfile = 'C:\path\to\your.config'

[xml]$xml = Get-Content $xmlfile
$attr = $xml.SelectSingleNode('//somenode/@SharedPassKey')
$attr.'#text' = $attr.'#text'.Replace('+', '.')

$xml.Save($xmlfile)

Make the XPath expression for selecting the attribute as specific as it needs to be. That will allow you to replace a + with a . in just that attribute.


text:
Q: nginx mail module always passing PLAIN method AUTH command to backend I have implemented a nginx with mail module, and proxy to backend Hmail server. I realized no matter how I disable the auth-methods PLAIN. The nginx is just ignoring it.
How can I force to using smtp_auth login instead? As Hmail server does not support AUTH_PLAIN mechanism.

auth_http  localhost:8080/auth.pl;

 server {
        # not working as always AUTH_PLAIN
        listen    25;
        protocol  smtp;
        smtp_auth login;
#       starttls on;
        timeout 5s;
        proxy on;
        xclient off;
        proxy_smtp_auth on;
    }

A: In fact, i solved it in a other way, as i would like to use all features with my NGIX and my MAILCOW, i used this way
NGINX.conf
stream {
include /etc/nginx/streams/*;
}
/etc/nginx/streams/mailcow_proxy.conf
server {
listen [::]:25 ipv6only=off;
listen [::]:143 ipv6only=off;
listen [::]:587 ipv6only=off;
listen [::]:993 ipv6only=off;
proxy_pass 10.11.12.13:$server_port;
proxy_protocol on;
}

Conclusions
Instead of interferencing nginx to do the auth, you just pass anything directly to your Mailserver as it should and usually as you would if it would be connected directly.
You may also use the directly insertion into nginx.conf but i dislike this way.


text:
Q: Looking for a movie where there is a Powerful Board Game played by two brothers? I can't remember the title. It's a board game where two brothers played it. When they played the board, it sent them to space? It's a board where I think it has different levels,each levels has a card, and each levels has different obstacles in space? One level in there, they even put their house being pulled by the sun? And there is also a part there where there is an astronaut.

A: Sounds very much like John Favreau's  Zathura  (2005)

Danny and Walter are two brothers who barely get along even while driving their parents to distraction as their older sister tries to ignore them. Despite their squabbling, the brothers manage cooperate enough to play an old mechanical board game named Zathura. However, after their first move, they find that the game has apparently flung them, their sister and their entire house into outer space. Furthermore, the brothers surmise the only way to return home is to finish the game. However with almost every move, new dangers arise as the siblings find themselves learning to cooperate in ways they never expected as they realize what they mean to each other.


text:
Q: Prevent a Race Condition using dispatch_sync I am having a race condition with a NSManagedObjectContext. I was trying out various ways to prevent this using lock on NSManagedObjectContext. Using dispatch_sync seems to be a better approach as suggested by apple. But I am unable to figure out whether an object(being used under a block which is executed using dispatch_sync) can be saved from being accessed by two different threads.
Here is a more clear picture of what I am trying to ask:
    [[*Some Singleton class* instance].managedObjectContext executeFetchRequest:request error:&err];

    // After fetching results do something in DB

Let's say the above code is passed in a block executed using dispatch_sync like this:
    dispatch_sync(someConcurrentQueue, ^{
    [[*Some Singleton class* instance].managedObjectContext executeFetchRequest:request error:&err];
    // After fetching results do something in DB
});

Can any other thread access [Some Singleton class instance].managedObjectContext before this block is completely executed.
AFAIK it can be accessed. If this is true then, is applying lock on NSManagedObjectContext the only way to prevent this race condition?

A: As always: It depends
dispatch_sync (and it's even safer cousin dispatch_barrier_sync) cause the queue it's called from to synchronously execute the block.  In doing so, they block the thread.  This makes one case potentially safe: access from the same thread.  What you have to worry about in this scenario is that any reads you do may take place before the block is executed on the queue.  Plan accordingly.
But this is ignoring a huge flaw in your code.  Managed object contexts should never be shared across threads, or even dispatched off to a different thread from the one they were created on.  You can fix your concurrent access problems by simply spawning child contexts.


text:
Q: twitter search Api RestSharp not working and giving error unauthorize I am trying to develop twitter client. i am using RestSharp for api. its work fine with authentication and gettimeline but its give error when i try to search twitter with # hashtag . its gives error like bad request and unauthorized.
Working code
    public string GetTimeLine(string key,string secret,string userToken,string userSecret)
    {
        var request = new RestRequest("/1.1/statuses/user_timeline.json", Method.GET);

        Client.Authenticator = OAuth1Authenticator.ForProtectedResource(key, secret, userToken, userSecret);

        var response = Client.Execute(request);
        return response.Content;

    }

Respond with unauthorized error:
    public string GetHashtag(string key, string secret, string userToken, string userSecret)
    {
        var request = new RestRequest("/1.1/search/tweets.json?q=%23freebandnames", Method.GET);

        Client.Authenticator = OAuth1Authenticator.ForProtectedResource(key, secret, userToken, userSecret);

        var response = Client.Execute(request);
        return response.Content;

    }

A: Try this:
var request = new RestRequest("/1.1/search/tweets.json?q={query}", Method.GET);
request.AddUrlSegment("query", "#freebandnames");


text:
Q: Regex - ignoring text between quotes / HTML(5) attribute filtering So I have this Regular expression, which basically has to filter the given string to a HTML(5) format list of attributes. It currently isn't doing my fulfilling, but that's about to change! (I hope so)
I'm trying to achieve that whenever an occurrence is found, it selects the text until the next occurrence OR the end of the string, as the second match. So if you'd take a look at the current regular expression:
/([a-zA-Z]+|[a-zA-Z]+-[a-zA-Z0-9]+)=["']/g

A string like this: hey="hey world" hey-heyhhhhh3123="Hello world" data-goed="hey"
Would be filtered / matched out like this:
MATCH 1. [0-3]   `hey`
MATCH 2. [16-32] `hey-heyhhhhh3123`
MATCH 3. [47-56] `data-goed`

This has to be seen as the attribute-name(s), and now.. we just have to fetch the attribute's value(s). So the mentioned string has to have an outcome like this:
MATCH 1.
         1 [0-3]     `hey`
         2 [6-14]    `hey world`
MATCH 2.
         1 [16-32]   `hey-heyhhhhh3123`
         2 [35-45]   `Hello world`
MATCH 3.
         1 [47-56]   `data-goed`
         2 [59-61]   `hey`

Could anyone try and help me to get my fulfilling? It would be appericiated a lot!

A: You can use
/([^\s=]+)=(?:"([^"\\]*(?:\\.[^"\\]*)*)"|(\S+))/g

See regex demo
Pattern details:

*

*([^\s=]+)  - Group 1 capturing 1 or more characters other than whitespace and = symbol

*= - an equal sign

*(?:"([^"\\]*(?:\\.[^"\\]*)*)"|(\S+)) - a non-capturing group of 2 alternatives (one more '([^'\\]*(?:\\.[^'\\]*)*)' alternative can be added to account for single quoted string literals)

*

*"([^"\\]*(?:\\.[^"\\]*)*)" - a double quoted string literal pattern:

*

*" - a double quote

*([^"\\]*(?:\\.[^"\\]*)*) - Group 2 capturing 0+ characters other than \ and ", followed with 0+ sequences of any escaped symbol followed with 0+ characters other than \ and "

*" - a closing dlouble quote

*|  - or

*(\S+) - Group 3 capturing one or more non-whitespace characters

JS demo (no single quoted support):

var re = /([^\s=]+)=(?:"([^"\\]*(?:\\.[^"\\]*)*)"|(\S+))/g;
var str = 'hey="hey world" hey-heyhhhhh3123="Hello \\"world\\"" data-goed="hey" more=here';
var res = [];
while ((m = re.exec(str)) !== null) {
    if (m[3]) {
      res.push([m[1], m[3]]);
    } else {
      res.push([m[1], m[2]]);
    }
}
console.log(res);

JS demo (with single quoted literal support)

var re = /([^\s=]+)=(?:"([^"\\]*(?:\\.[^"\\]*)*)"|'([^'\\]*(?:\\.[^'\\]*)*)'|(\S+))/g;
var str = 'pseudoprefix-before=\'hey1"\' data-hey="hey\'hey" more=data and="more \\"here\\""';
var res = [];
while ((m = re.exec(str)) !== null) {
  if (m[2]) {
    res.push([m[1], m[2]])
  } else if (m[3]) {
    res.push([m[1], m[3]])
  } else if (m[4]) {
    res.push([m[1], m[4]])
  }
}
console.log(res);


text:
Q: Microchip device support - MPLAB Snap supported or unsupported devices list Need to program and debug PIC and AVR MCU's so MPLAB Snap looks to be a very attractive option however:

"it supports many of Microchip's newer MCU offerings but not some legacy products" - Microchip

Maintaining a list of all supported products is too hard maybe, at least devices are not supported is known, I guess?
How can I determine if a device is not supported?
Is there like a list?

A: Under MPLABX IDE Release Notes is a complete list in Readme for MPLAB Snap.htm.


text:
Q: How to write a program for multiplying list of numbers in shortest line? I come to this point when I was making a simple calculator. I did a simple program to sum  the list of numbers as follows, But the program for multiplication is a little bit long.
So can anybody have any idea how to make short program to multiple list of numbers in python. Here is my code what looks like.
def calculate(oper,*nm):
    return oper(nm)

add=lambda x:sum(x)

def mult(lst):
    tmp=1
    for i in lst:
        tmp*=i
    return tmp

calculate(add,2,34,2)
calculate(mult,8,5,7)

A: Really, you do not need to define calculate because Python already has a name for it: reduce.
def calculate(oper, *nm):
    return reduce(oper, nm)

In [6]: import operator

In [7]: calculate(operator.add, 2, 34, 2)
Out[7]: 38

In [8]: calculate(operator.mul, 8, 5, 7)
Out[9]: 280

Note: In Python3, reduce has been moved to the functools module. (Thanks to @ErikRoper for pointing this out.)

A: You can use the in-built reduce function, which takes a callable, a list and an optional starting element. It calls callable with a tuple (elem, result) where element is the ith element from the list and result is the result so far.
reduce(lambda item,prod: item * prod, range(1, 5), 1)
Out[2]: 24

So the above would call the lambda function first with (1,1), then with (2,1*1) then (3,2*1) and finally (4,3*2)
So you'd define add and mult and replace your calculate with the built-in reduce
add = lambda item,cumul_sum: item + cumul_sum
mult = lambda item,product: item * product
reduce(add, range(1,5), 0)
Out[5]: 10
reduce(mult, range(1,5), 1)
Out[6]: 24

http://docs.python.org/2.7/library/functions.html?highlight=reduce#reduce


text:
Q: Can be defined as string column to process in tbl_summary in r I'm trying to use tbl_summary in R.
I need to pass as input variable the list of columns to use in "add_p (include = ... )"
Is there a way for do it ???
thanks in advance
A
tmp=c(-age, -stage, -grade)

  trial %>%
    select(trt, stage, age, grade, response) %>%
    tbl_summary(by = trt) %>%
    add_p( include = tmp )

A: Using a vector of characters and any_of or all_of you could do:
library(gtsummary)

tmp <- c("age", "stage", "grade")

trial %>%
  select(trt, stage, age, grade, response) %>%
  tbl_summary(by = trt) %>%
  add_p( include = !any_of(tmp) )


text:
Q: Different behavior about c++ Friendship and inheritance from VC12 and VC14 class Base
{
protected:
    void func1();
};

class Derived : public Base
{
friend class Third;
};

class Third
{
     void foo()
     {
        Derive d;
        d.func1();
     }
};

I can compile the code in VC14 (Visual Studio 2015) withour error
but get error from VC12 (Visual Studio 2013)
cannot access protected member declared in class 'Base'

who is right?
what is the correctness of such freindship with inheritence?
from MSDN https://msdn.microsoft.com/en-us/library/465sdshe.aspx or http://en.cppreference.com/w/cpp/language/friend It looks like that friendship is not transitive and cannot be inherited. However I think it is not really the case of this code example.
But why VC14 won't get me an error?
If VC14 is right, how can I "modify" the code so that VC12 is also ok with that?
to define protected func1() again in the class Derived?

A: after fixing the typos, comments inline:
class Base
{
protected:
    void func1();   // protected access
};

class Derived : public Base
{
  // implicit protected func1, derived from Base

  // this means 'make all my protected and private names available to Third'
  friend class Third;
};

class Third
{
     void foo()
     {
        Derived d;
        // func1 is a protected name of Derived, but we are Derived's friend
        // we can therefore access every member of Derived
        d.func1();
     }
};

VC14 is correct.
Possible workaround for VC12:
class Base
{
protected:
    void func1();
};

class Derived : public Base
{
  protected:
    using Base::func1;

  private:
    friend class Third;
};

class Third
{
     void foo()
     {
        Derived d;
        d.func1();
     }
};

Another possible workaround (using key-based access)
class Third;
class Func1Key
{
  private:
    Func1Key() = default;
    friend Third;
};

class Base
{
protected:
    void func1();
};

class Derived : public Base
{
public:
  void func1(Func1Key)
  {
    Base::func1();
  }
};

class Third
{
     void foo()
     {
        Derived d;
        d.func1(Func1Key());
     }
};


text:
Q: Discrepancy in hard drive space; can I delete these files? While trying to clear space from my MacBook Pro hard drive, I noticed a 12.4 GB discrepancy between the amount of free space shown in Storage Bar in About This Mac and the total sum inside my Macintosh HD using OmniDiskSweeper (or du -sh * in Terminal). I've managed to account for 9.1 GB of that by running ODS as the root user.
Where could the remaining 3.3 GB be?
Can any of the major offenders be deleted to free up space? They are:

*

*/System/Library/Caches/com.apple.coresymbolicationd/data (4.3 vs. 0 GB)

*/.DocumentRevisions/.cs/ChunkStorage/0/0/ (1.5 vs. 0 GB)

*/private/var/folders/zz/ (1.3 GB vs. 9.5 MB, mostly in the file CFNetworkDownload_L4uNTH.tmp)

*/.MobileBackups/Computer/ (1.1 vs. 0 GB)

*/.Spotlight-V100/Store-V2/ (0.6 vs 0 GB)

A: You can certainly delete the two temporary items in your list:

*

*/System/Library/Caches/com.apple.coresymbolicationd/data/

*/private/var/folders/zz/CFNetworkDownload_L4uNTH.tmp
Avoid deleting the folder structures but large files in these locations can be safely removed.
To be extra safe, restart your Mac first and then remove any files. The restart will ensure the files are not in use.

A: Getting rid of these files is a great move, but keep in mind many of these caches will regenerate. For instance, spotlight files will regenerate at a cost of high processor usage and noisy fans (in a MacBook) immediately (look out for mds in Activity Monitor). MobileBackups is backup data from your iPhone which you might want on hand if you lose your phone and which will probably replicate the next time you plug it in.
Don't forget that if you sleep your computer, you'll often end up with a sleep image the same size as your physical drive. As we are almost all using flash drives now, don't forget flash drives need about 20% free disk space for self-cleaning and maintenance (I'm thinking of the SSD's which do their own garbage collection like Samsung and most of the Intel SSD). Spinning disks can go down to 10% but anything saved after about 50% usage is 1/3 or more slower than peak performance.
Clean out the files but think about upgrading the disk or moving some files or applications off to external storage. Time to go and follow my own useful advice. We humans generally procrastinate on important but not urgent tasks.

A: The /.MobileBackups folder is created by Time Machine, which saves snapshots to your local disk when your Time Machine volume is not available. To delete those snapshots and free up the space, the recommended way is to turn off local Time Machine backups altogether, by issuing the command:
sudo tmutil disablelocal
You can always turn them back on again later if your requirements change.


text:
Q: Express server add ssl I followed the angular server-side rendering tutorial and created an express server.
How can I add SSL support?
I found how to add SSL in server.js but I don't know how to add it in Typescript.
server.ts
import 'zone.js/dist/zone-node';
import 'reflect-metadata';

import { renderModuleFactory } from '@angular/platform-server';
import { enableProdMode } from '@angular/core';

import * as express from 'express';
import { join } from 'path';
import { readFileSync } from 'fs';

enableProdMode();

const app = express();

const PORT = process.env.PORT || 4000;
const DIST_FOLDER = join(process.cwd(), 'dist');

const template = readFileSync(join(DIST_FOLDER, 'browser', 'index.html')).toString();

const { AppServerModuleNgFactory, LAZY_MODULE_MAP } = require('./dist/server/main.bundle');

const { provideModuleMap } = require('@nguniversal/module-map-ngfactory-loader');

app.engine('html', (_, options, callback) => {
  renderModuleFactory(AppServerModuleNgFactory, {

    document: template,
    url: options.req.url,

    extraProviders: [
      provideModuleMap(LAZY_MODULE_MAP)
    ]
  }).then(html => {
    callback(null, html);
  });
});

app.set('view engine', 'html');
app.set('views', join(DIST_FOLDER, 'browser'));

app.get('*.*', express.static(join(DIST_FOLDER, 'browser')));

app.get('*', (req, res) => {
  res.render(join(DIST_FOLDER, 'browser', 'index.html'), { req });
});

app.listen(PORT, () => {
  console.log(`Node server listening on http://localhost:${PORT}`);
});

——————
I used a Reverse Proxy instead

A: import the fs and https module
import { readFileSync } from 'fs';
import * as https from 'https';

Now create an object to set the key and certificate paths.
const options = {
    key: readFileSync('./ssl/privatekey.pem'),
    cert: readFileSync('./ssl/certificate.pem'),
};

https.createServer(options, app).listen(PORT , function(){
  console.log("Express server listening on port " + PORT);
});


text:
Q: Can I configure things to open new windows on the left screen? When I attach an external (D-SUB) display and set it up (with xrandr) to be on the right to the main (built-in) display, the most of new windows opened appear on the external display and some even farther to the right of it (leaving the most of their area outside the visible area).
Can I configure things the way that new windows would appear in the centre of the main (the very left) display (the same way as they do when there is no external display attached)?
PS: I use XUbuntu 11.10 with XFCE 4.8 on Dell Latitude E5500 with Intel GMA X4500HD card. My built-in display has 1440x900 resolution, my external display resolution is 1024x768 (this is another problem of mine actually, I can't configure any external display for more than 1024x768, but this is a separate question).

A: wmctrl can do that. Check devilspie too (maybe). It's WM agnostic.

A: Generally, no. X11 doesn't work that way.
There may be ways to configure your WM to move certain windows to other desktops/screens/tags etc. If and how depends on the WM. And there are a few agents that may be able to do it for you as well (see sputnick's answer). It'll be a hack and how well it works depends on some details.
I've set up awesome to open mammoth browser (related) windows with tag 2, for example, so they don't pop up all over the place.


text:
Q: docker compose up showing that server is running but browser showing site can not be reached after running docker-compose up command
Starting tutorial_product-service_1 ...
Starting tutorial_product-service_1 ... done
Attaching to tutorial_product-service_1
product-service_1  |  * Running on http://0.0.0.0:80/ (Press CTRL+C to quit)
product-service_1  |  * Restarting with stat
product-service_1  |  * Debugger is active!
product-service_1  |  * Debugger PIN: 176-459-861

docker-compose.yml
version: '3'

services:
 product-service:
  container_name: tutorial_product-service_1
  build: ./product
  volumes:
   - ./product:/usr/src/app
  networks:
   testing_net:
    ipv4_address: 193.167.10.1
  ports:
   - 5001:80

networks:
 testing_net:
  ipam:
   config:
    - subnet: 193.167.10.0/16

This is the URL
http://193.167.10.1:5001/

but it is showing site can not be reached.
Anyone can help me?


text:
Q: ASP Template Column Sorting Alphanumbical and Dates I have a snippet of code that I need to sort multiple columns. The column headers are:

*

*Trade Reference

*Settlement Date

*Currency

*Commission

*Payment Status

I am using AllowSorting="True" in the asp:datagrid header. Then in each of the asp:TemplateColumn I am using SortExpression="tra_settlement_date"
I can't get the columns to sort either by A-Z / 1-10etc for the columns either from newest to oldest / Z-A. The page thinks, but it doesn't resort the items.
Here are the first two columns of the table.
<asp:datagrid
  ID="dgrStatement"
  runat="server"
  runat="server"
  CellPadding="4"
  AllowSorting="True"
  AutoGenerateColumns="False"
  Font-Bold="False"
  Font-Italic="False"
  Font-Names="Calibri"
  Font-Overline="False"
  Font-Strikeout="False"
  Font-Underline="False"
  GridLines="None"
  ForeColor="#333333"
  cssclass="figures statements-tbody statements-tbody-y"
>
  <HeaderStyle Font-Bold="True" HorizontalAlign="Center" />
  <Columns>
    <asp:BoundColumn
      Visible="False"
      DataField="tra_id"
      HeaderText="ID"
    ></asp:BoundColumn>
    <asp:TemplateColumn
      SortExpression="[trade reference]"
      HeaderText="Trade Reference"
    >
      <ItemTemplate>
        <asp:Label
          id="lblRef"
          runat="server"
          Text='<%# DataBinder.Eval(Container, "DataItem.[trade reference]") %>'
        >
        </asp:Label>
      </ItemTemplate>
      <EditItemTemplate>
        <asp:TextBox
          id="Textbox13"
          runat="server"
          Text='<%# DataBinder.Eval(Container, "DataItem.[trade reference]") %>'
        >
        </asp:TextBox>
      </EditItemTemplate>
      <ItemStyle
        Font-Bold="False"
        Font-Italic="False"
        Font-Overline="False"
        Font-Strikeout="False"
        Font-Underline="False"
      />
    </asp:TemplateColumn>
    <asp:TemplateColumn
      SortExpression="tra_settlement_date"
      HeaderText="Settlement Date"
    >
      <ItemTemplate>
        <asp:Label
          id="lblSettlDate"
          runat="server"
          Text='<%# Date.ParseExact(DataBinder.Eval(Container, "DataItem.tra_settlement_date"),"yyyyMMdd", System.Globalization.DateTimeFormatInfo.InvariantInfo).tostring("dd/MM/yyyy") %>'
        >
        </asp:Label>
      </ItemTemplate>
      <EditItemTemplate>
        <asp:TextBox
          id="Textbox1"
          runat="server"
          Text='<%# DataBinder.Eval(Container, "DataItem.tra_settlement_date") %>'
        >
        </asp:TextBox>
      </EditItemTemplate>
    </asp:TemplateColumn>
  </Columns>
</asp:datagrid>

Am i missing something?
Thanks,
Andrew


text:
Q: iOS 6 OpenGL ES 2.0 video memory leak in a render buffer object Below is an example code that behaves like one leaking a video memory on iPad 2 IOS 6.1 (basically it creates a render buffer object, allocates a memory for it and destroys it after drawing):
if I put it into a draw loop I see lots of memory warnings and finally the application is killed by OS. Instruments give no hints and I even cannot see any memory size growth, only memory warnings.
I understand that creating buffers in a draw loop is a bad idea, but the buffer needs to be recreated anyway in case if user rotates a device and resolution changes so the leak will remain but need more time to kill the app (also looks like springboard restarts sometimes when the application is killed).
So the example below is just a way to reproduce a problem that is usually hidden, I think.
I would be glad to here any ideas on what's wrong here and how this leak can be fixed.
There are several things I tried (see commented code) but nothing really helped. The only thing that helps is commenting of a glClear and glDrawArrays calls.
Looks like GPU doesn't touch the render buffer in this case and the problem disappears, but I need to clear that buffer and draw something to it (the reason why I need that buffer is next:
I try to implement a multi-sampled rendering into a texture, which works in fact, but leaks memory).
I check for glGetError() after every GL call and no errors appear.
GLuint rbo;
glGenRenderbuffers(1, &rbo);
glBindRenderbuffer(GL_RENDERBUFFER, rbo);
//glRenderbufferStorageMultisampleAPPLE(GL_RENDERBUFFER, 4, GL_RGBA4, 2000 , 2000);
glRenderbufferStorage(GL_RENDERBUFFER, GL_RGBA4, 2000 , 2000);

/*GLuint fbo_faa;
glGenFramebuffers(1, &fbo_faa);*/
glBindFramebuffer(GL_FRAMEBUFFER, defaultFramebuffer/*fbo_faa*/);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, rbo);

glClearColor(0, 0, 0, 0);
glClear(GL_COLOR_BUFFER_BIT);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, 0);
glDeleteRenderbuffers(1, &rbo);

A: I see now what you are doing and I have no idea why your code works in one of my projects. Anyway, it would seem you keep attaching render buffers to your frame buffer. The best guess would be they are not deleted as you did not signal the GL that those render buffers are no longer in use. So you do need to discard attachments and reattach the main render buffer.. Try pasting this code and tell me how it turns out..
    GLuint rbo;
    glGenRenderbuffers(1, &rbo);
    glBindRenderbuffer(GL_RENDERBUFFER, rbo);
    //glRenderbufferStorageMultisampleAPPLE(GL_RENDERBUFFER, 4, GL_RGBA4, 2000 , 2000);
    glRenderbufferStorage(GL_RENDERBUFFER, GL_RGBA4, 2000 , 2000);

    /*GLuint fbo_faa;
     glGenFramebuffers(1, &fbo_faa);*/
    glBindFramebuffer(GL_FRAMEBUFFER, defaultFramebuffer/*fbo_faa*/);
    glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, rbo);

    glClearColor(0, 0, 0, 0);
    glClear(GL_COLOR_BUFFER_BIT);
    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

    const GLenum discards[]  = {GL_COLOR_ATTACHMENT0};
    glDiscardFramebufferEXT(GL_FRAMEBUFFER, 1, discards);

    glDeleteRenderbuffers(1, &rbo);

    glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, colorRenderbuffer);
    glBindRenderbuffer(GL_RENDERBUFFER, colorRenderbuffer);


text:
Q: Sql server convert datetime to ''YYYY-MM-DD'T'HH:mm:ss.SSS'Z" In SQL Server, I have a column start_date in Table1 (2 values shown below)
'2006-08-15 00:00:00.000',
'2010-07-13 18:53:59.000'

I want to convert these dates to format "yyyy-mm-dd'T'hh:mm:ss.SSS'Z'".
I have tried both of the following things:

*

*Select Convert(varchar, start_date, 126) + 'Z' as required_date from Table1

*Select Convert(varchar, start_date, 127) + 'Z' as required_date from Table1
I get these results:
'2006-08-15T00:00:00Z'
'2010-07-13 18:53:59Z'

Last 000 is getting trimmed out (that should not happen).
I want result like this:
'2006-08-15T00:00:00.000Z'
'2010-07-13 18:53:59.000Z'

How can I achieve this? Any help would be appreciated.
Thanks.

A: I'm new to sql but I assume that the removal of .000 is because of sql itself not showing milliseconds or whatever that is. Try adding '.000Z' where you add 'Z' and you should have it?
Should look like this
Select Convert(varchar,start_date,126)+'.000Z' as required_date from Table1

Select Convert(varchar,start_date,127)+'.000Z' as required_date from Table1

A: You can use below
Select Convert(varchar(25),start_date,121)+'Z' as required_date from Table1

Some good explanation here SQL Convert Date functions and formats

A: As of now I can see only one way to get the desired answer:
Select
CONVERT(varchar(20),start_date,126)+
substring(CONVERT(varchar(35),start_date,121),20,23)+'Z'
AS required_date from Table1
Please comment if any optimized way.


text:
Q: Is $Bw_0B$ a dense open subset of $G$? Let $G=GL_n(\mathbb{C})$ and $B$ the Borel subgroup of $G$ containing all upper triangular matrices in $G$. Let $w_0$ be the longest word in the Weyl group $W$ of $G$. We have the Bruhat decomposition $G = \cup_{w \in W} BwB$. Is $Bw_0B$ a dense open subset of $G$?
I think that $Bw_0B$ is open because $Bw_0B = \{g \in G: \Delta_{\{n-i+1, \ldots, n\}, \{1,\ldots,i\}}(g) \ne 0, i=1,2,\ldots,n \}$.
How to show that $Bw_0B$ is dense in $G$? Thank you very much.

A: It is Zariski-open in the irreducible variety $\mathrm{GL}_n(\mathbf{C})$. Every Zariski-open subset of an irreducible variety is dense.
This particular variety is irreducible because its coordinate ring is the localization of the ring of polynomial functions on all matrices by the determinant, and is therefore an integral domain.

A: If you consider $G/B$ which is a flag variety and we have Bruhat decomposition and $BwB/B$ is an affine set which is isomorphic to $\mathbb{C}^{l(w)}$ where the dimension is the length of the Weyl group element. Also the $B$ orbits form a stratification by which I mean the closure of a B-orbit is union of other B orbit. If we consider the projection from $G$ to $G/B$ then the set $Bw_0B$ is the preimage of of an open dense set so it is also open and dense.


text:
Q: Magento1 Mage::getStoreConfig non cached value Is there a way to get a non-cached config value from Magento using Mage::getStoreConfig without having to first flush the entire config cache?

A: I do not believe this is possible.
You could look into querying the database directly for the value in core_config_data but you should really let Magento handle the full configuration and merging as the configuration is built on top of the xml files, and split into varying groups then cached.
If you want to handle this in a programmatic way you could call Mage::getConfig()->reinit() which should reinitialise the configuration object and re-cache it, while ignoring the current values in the cache.
https://github.com/OpenMage/magento-mirror/blob/1.9.3.9/app/code/core/Mage/Core/Model/Config.php#L363-L374
/**
 * Reinitialize configuration
 *
 * @param   array $options
 * @return  Mage_Core_Model_Config
 */
public function reinit($options = array())
{
    $this->_allowCacheForInit = false;
    $this->_useCache = false;
    return $this->init($options);
}


text:
Q: Parameters unexpected marked as Redacted in logs Since a couple of days, all the intent parameters in Dialogflow CX projects are incorrectly marked as Redacted in the Google stackdriver logging. However, in Dialogflow I haven't marked the 'Redact in log' option anywhere.
was: transcript: "example text here"
now is: transcript: "$parameter_redacted"
happens to all parameters I use in all my projects. Are more people having this issue or am I missing something?
Thanks in advance.


text:
Q: Oracle select with subquery Could you please help me with next oracle sql query.
SELECT "NEWS"."NEWSID" as ID,
       "NEWS"."SLUG",
       "NEWS_TRANSLATION".*,
       (SELECT FILENAME FROM NEWS_MEDIA WHERE NEWSID = ID AND rownum <= 1 ORDER BY POSITION ASC) as FILENAME
FROM "NEWS"
INNER JOIN "NEWS_TRANSLATION" ON NEWS.NEWSID = NEWS_TRANSLATION.NEWSID
WHERE (NEWS.PUBLISH = 1) AND (NEWS_TRANSLATION.LANG = :lang)
ORDER BY "NEWS"."NEWSID" DESC;

When I execute this query I have error
ORA-00907: missing right parenthesis
00907. 00000 -  "missing right parenthesis"
*Cause:
*Action:
Error at Line: 4 Column: 74

A: Here is the working code:
SELECT "NEWS"."NEWSID" as ID,
   "NEWS"."SLUG",
   "NEWS_TRANSLATION".*,
   (SELECT FILENAME FROM NEWS_MEDIA WHERE NEWSID = ID AND rownum <= 1 ) as FILENAME
FROM "NEWS"
INNER JOIN "NEWS_TRANSLATION" ON NEWS.NEWSID = NEWS_TRANSLATION.NEWSID
WHERE (NEWS.PUBLISH = 1) AND (NEWS_TRANSLATION.LANG = :lang)
ORDER BY "NEWS"."NEWSID" DESC

A: Try this:
SELECT "NEWS"."NEWSID" as ID,
   "NEWS"."SLUG",
   "NEWS_TRANSLATION".*,
   (SELECT * FROM (SELECT FILENAME FROM NEWS_MEDIA WHERE NEWSID = ID ORDER BY POSITION ASC) WHERE rownum = 1) as FILENAME
FROM "NEWS"
INNER JOIN "NEWS_TRANSLATION" ON NEWS.NEWSID = NEWS_TRANSLATION.NEWSID
WHERE (NEWS.PUBLISH = 1) AND (NEWS_TRANSLATION.LANG = :lang)
ORDER BY "NEWS"."NEWSID" DESC;

When are you are using "order by" and "rownum" together, you need to first order them and look for the first record.

A: Please try by removing the order by clause in the sub-query.

A: Try This:
SELECT "NEWS"."NEWSID" AS ID, "NEWS"."SLUG", "NEWS_TRANSLATION".*,
       (SELECT FILENAME
          FROM NEWS_MEDIA
         WHERE NEWSID = "NEWS"."NEWSID" AND ROWNUM <= 1)
           AS FILENAME
  FROM     "NEWS"
       INNER JOIN
           "NEWS_TRANSLATION"
       ON NEWS.NEWSID = NEWS_TRANSLATION.NEWSID
 WHERE (NEWS.PUBLISH = 1) AND (NEWS_TRANSLATION.LANG = :LANG)
ORDER BY "NEWS"."NEWSID" DESC

A: SELECT STUDENT_NAME, STUDENT_ALIAS_NAME
FROM school
WHERE STUDENT_NAME IN (
        SELECT STUDENT_NAME
        FROM school
        WHERE STUDENT_DEPARMENT= 0
        );


text:
Q: Need clarification as to why code is correct const isString = (a, b, c) => {
  if (((typeof a) == "string") && ((typeof b) == "string") && ((typeof c) == "string")) {
    return "strings";
  }
  return "not strings";
}

Why is the => after the argument required in order for this to work? I got this test question correct via trial and error, but I don't understand why it doesn't work without =>.
Here are the instructions.

Create a function called "isString" that takes 3 arguments (x1, x2, x3)

*

*Check if each argument is a string using typeof.

*If each argument is a string, return "strings".

*If each argument is NOT a string, return "not strings".

A: The => is the syntax for an arrow function

A: The => operator is required because that is how javascript's syntax for anonymous functions works. This is creating a function equivilent to isString(a,b,c) {...}.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

A: Assuming that this is javascript, the => is indicating that it is part of an Arrow Function. The following two codes are equivalent as for the understanding of the two.
// function declaration
function isString (a, b, c) {
  if (((typeof a) == "string") && ((typeof b) == "string") && ((typeof c) == "string")) {
    return "strings";
  }
  return "not strings";
}

// arrow function declaration; can also use `var` instead of `const`
const isString = (a, b, c) => {
  if (((typeof a) == "string") && ((typeof b) == "string") && ((typeof c) == "string")) {
    return "strings";
  }
  return "not strings";
};

A: This looks like Javascript. There are a few ways to declare a function in Javascript. One, is as you have done it
const myFunc = (params) => {
    // code
}

This is treating myFunc like any other name in Javascript needing to be assigned a value. Another more traditional way is:
function myFunc(params) {
    // code
}

Note that because you have the = after isString, the Javascript engine is expecting you to define it as in the first example.


text:
Q: how can i extract one field from json file and print it into differnet file in python i am trying to load JSON file and want to extract a field(only want frametime less that 4 sec) called frame time from that file and want to print it in different file in python, how can i do it?
piece of json file
[
  {
    "_index": "packets-2019-03-14",
    "_type": "pcap_file",
    "_score": null,
    "_source": {
      "layers": {
        "frame": {
          "frame.encap_type": "1",
          "frame.time": "Mar  5, 2019 17:51:00.270140000 India Standard Time",
          "frame.offset_shift": "0.000000000",
          "frame.time_epoch": "1551788460.270140000",
          "frame.time_delta": "0.000000000",
          "frame.time_delta_displayed": "0.000000000",
          "frame.time_relative": "0.000000000",
          "frame.number": "1",
          "frame.len": "99",
          "frame.cap_len": "99",
          "frame.marked": "0",
          "frame.ignored": "0",
          "frame.protocols": "eth:ethertype:ip:tcp",
          "frame.coloring_rule.name": "TCP",
          "frame.coloring_rule.string": "tcp"
        },
        "eth": {
          "eth.dst": "00:1a:11:00:00:02",
          "eth.dst_tree": {
            "eth.dst_resolved": "Google_00:00:02",
            "eth.addr": "00:1a:11:00:00:02",
            "eth.addr_resolved": "Google_00:00:02",
            "eth.lg": "0",
            "eth.ig": "0"
          },
          "eth.src": "00:1a:11:00:00:01",
          "eth.src_tree": {
            "eth.src_resolved": "Google_00:00:01",
            "eth.addr": "00:1a:11:00:00:01",
            "eth.addr_resolved": "Google_00:00:01",
            "eth.lg": "0",
            "eth.ig": "0"
          },
          "eth.type": "0x00000800"


text:
Q: Modify XML Configuration if Condition is Met - Ansible Hi I am new to ansible and I have to write a script for deployment where an artifact will be dropped in a folder and it's package is referenced from an XML config file. I am able to do the first part and it works just fine but the second part is challenging me where I have to edit the conf file and add a child element there. It is written like this:
- name: Configure Artifact Properties
- xml:
    path: '{{ server_home }}/conf.xml'
    xpath: /Server/SupportedArtifactTypes
    add_children:
      - NewArtifact
          ArtifactName: HelloWorld
          ArtifactPackage: org.HelloWorld

Now this will work fine the first time but when I am going to rerun it in the next deployment cycle, its going to add the child element again which should not be happening. Does anybody have a clue how can we modify the task so that the configuration is added only if it does not exist?

A: According to the Ansible XML documentation, you can perform a count against xpath matches. Try doing a count of the xpath first and register the result. Make your task execute when the count is less than 1.
- name: Check for existing artifacts in SupportedArtifactTypes
- xml:
    path: '{{ server_home }}/conf.xml'
    xpath: /Server/SupportedArtifactTypes
    count: yes
  register: hits

- name: Configure Artifact Properties
- xml:
    path: '{{ server_home }}/conf.xml'
    xpath: /Server/SupportedArtifactTypes
    add_children:
      - NewArtifact
          ArtifactName: HelloWorld
          ArtifactPackage: org.HelloWorld
  when: hits.count < 1

Give this a try and see if it helps!


text:
Q: joomla mutiple backgrounds at the same time I want to have multiple backgrounds at the same time, they will overlap each other.
I know it has to work but somehow it doesn't work for me.
code I have:
body{
height:100%;
width:100%;
background:
url("../images/background/top-img-bg.jpg") no-repeat center top,
url("../images/background/bottom-img-bg.jpg") no-repeat center bottom,
url("../images/background/overlay-pattern.png") repeat-x left top;
}

I want to have an image stick to the top, an image stick to the bottom and a image that overlay the whole background.
http://jsfiddle.net/8LtEk/

A: Try breaking your css into separate statements like below.  Using comma's to separate the individual background images and maintaining the same ordering for any other background properties:
background-image: url("../images/background/top-img-bg.jpg"), url("../images/background/bottom-img-bg.jpg"), url("../images/background/overlay-pattern.png");
background-position: center top, center bottom, left top;
background-repeat: no-repeat, no-repeat, repeat-x;

Also, this is one of those CSS3 features where browser support could be the culprit.


text:
Q: How To View All Child Properties in Power Shell When querying for the properties of a Power Shell object, I want to know if the properties listed have child properties that might provide me useful info, but neither the Get-Member command nor the Select-Object -ExpandProperty parameter offer me a way to get that information for all the properties up front.
For instance, if I execute a "Get-Member -MemberType Property" command against an instance of an X509 certificate object, I get a list of 18 properties including "Archived", "Extensions", "FriendlyName", etc.
Most of those properties do not have child properties, but at least one - the "Extensions" property - does.
In turn, some of those child properties have their own child properties.
I need to get all that info up front on one query, not experiment with each one to see if I discover something interesting.
Is there a way to get this info or has someone written a query that will display all the child properties of top-level properties?
I've looked around quite a bit and not found anything.
I tried scripting out a query, but thus far it has not produced good results.
Thank you.

A: I usually accomplish what you seek simply by converting to json.
By default, ConvertTo-Json have a depth of 4 elements.
Since you only want the top properties and their child, you can reduce the -depth to 2.
#Selecting the first certificate just for demonstration purposes.
$YourObject = (get-childitem -Path 'Cert:\CurrentUser\CA\')[0]

# This will work with any objects.
$YourObject | ConvertTo-Json -Depth 2

Here's a partial look at the resulting query:
{
    "Archived":  false,
    "Extensions":  [
                       {
                           "Critical":  false,
                           "Oid":  "System.Security.Cryptography.Oid",
                           "RawData":  "48 33 48 31 6 8 43 6 1 5 5 7 48 1 134 19 104 116 116 112 58 47 47 115 50 46 115 121 109 99 98 46 99
111 109"
                       },
                       {
                           "CertificateAuthority":  true,
                           "HasPathLengthConstraint":  true,
                           "PathLengthConstraint":  0,
                           "Critical":  true,
                           "Oid":  "System.Security.Cryptography.Oid",
                           "RawData":  "48 6 1 1 255 2 1 0"
                       },

(I only pasted a small snippet)
You can easily  see the properties such as Extensions, their child properties and the associated values.
Additional note
If you omit the -depth parameter for ConvertTo-Json, it will recurse to a depth of 4.
The depth is configurable up to 100 levels.
That being said, some object will have properties that recurse upon the object, so unless needed, you should not unnecessarily put the maximum value there.

A: Something like this is the "nuclear option" for me.  Usually I don't find what I want anyway:
get-process cmd | fc * | findstr /i whatever

See also How to list all properties of a PowerShell object

A: I typically use Format-Custom with a -Depth on the properties you want to expand.  Here's an example of displaying only the Extensions property.
Changing the default $FormatEnumerationLimit value to -1 will also allow you to display all enumerable property values:
# Remove limit from enumeration limit which is 4 by default
$FormatEnumerationLimit=-1

# Use Format-Custom with the depth required:
Get-ChildItem -Path 'Cert:\CurrentUser\CA\' | Select-Object -First 1 -Property Extensions | Format-Custom -Depth 1

Output:
class X509Certificate2
{
  Extensions =
    [
      System.Security.Cryptography.X509Certificates.X509BasicConstraintsExtension
      System.Security.Cryptography.X509Certificates.X509Extension
      System.Security.Cryptography.X509Certificates.X509KeyUsageExtension
      System.Security.Cryptography.X509Certificates.X509Extension
      System.Security.Cryptography.X509Certificates.X509Extension
      System.Security.Cryptography.X509Certificates.X509Extension
      System.Security.Cryptography.X509Certificates.X509SubjectKeyIdentifierExtension
      System.Security.Cryptography.X509Certificates.X509Extension
    ]

}


text:
Q: How to add Paho MQTT client to a C application in Eclipse toolchain I'm trying to figure out how to add functionality to a vendor's provided sample C application that is built with Eclipse, and I'd like to check if I'm on the right path. I can build their sample C application in a VM. It creates an executable for the target device, and I can make a .deb package from that executable to run on their device. That works fine.
Now I'd like to include Paho's MQTT client in this project so I can publish MQTT messages in the sample C application. This is the part that I'd not sure if I'm going down the right path. The sample project auto generates a make file in the debug folder. From the Eclipse project config, I can see it uses GNU Make to generate that Make file.
For the MQTT part, Paho MQTT C Client repo  provides a Debian cmake file. How do I go about marrying the cmake from Paho with the GNU Make toochain in the current Eclipse setup? Or is that even the right approach?
The Eclipse toolchain has all the necessary configurations to build for the specific target device, so I'd need to integrate the Paho MQTT library into this build system, right?
Here's some screen shots to help ensure I'm communicating correctly.

I'm currently stuck on if this is the right approach.


text:
Q: HTML Canvas drawing an image is not working I have this angularJS application and I am generating an image from the canvas. I have everything else working, I can even draw images from SVGs that are in the html, but trying to pull an image from a relative URL is failing to display.
I know that the image is being loaded and that it has actually found the right image because of some console logging.
Here is my options object:
// Define our options
self.options = {
    team: null,
    itemsPerRow: 3,
    targets: {
        containerId: 'totals',
        svgContainerClassName: 'total-item',
        svgClassName: 'svg-document',
        svgTitleClassName: 'total-title'
    },
    itemPadding: {
        top: 50,
        right: 50,
        bottom: 100,
        left: 50
    },
    canvasPadding: {
        top: 300,
        right: 100,
        bottom: 200,
        left: 100
    },
    sizes: {
        first: 1100,
        all: 300
    },
    footer: {
        logo: '/assets/images/k-logo-orange-black.png'
    }
};

You can see the footer logo.
The function for displaying that is this:
// Private function to draw the footer
var drawFooter = function (canvas, ctx) {

    var y = canvas.height - 50;

    // Draw our image
    var img = new Image();
    img.onload = function () {

        console.log(img.width);
        console.log(img.height);
        console.log(canvas.width - self.options.canvasPadding.right - img.width);
        console.log(y - img.height);

        ctx.drawImage(img, canvas.width - self.options.canvasPadding.right - img.width, y - img.height);
    };
    img.src = self.options.footer.logo;
};

So, the console logs are outputting the dimensions of the image and the canvas locations are well within the bounds of my canvas, but the image just isn't showing.
Does anyone know why?

A: I think you have two things going on here. first, if you are placing this image inside an SVG element, in Javascript SVG elements are created using a different namespace, using commands such as (with a few exceptions):
var svg = document.createElementNS('http://www.w3.org/2000/svg','svg');
svg.setAttributeNS('http://www.w3.org/2000/svg','xlink','http://www.w3.org/1999/xlink');

see w3 docs here
Second, I do not see where you have given the x attribute its variable, which is necessary, found on MDN here, (which also reference w3 docs here)

A: This question could never have been answered. I was using promises to draw other images and then doing a $q.all() once they had been resolved. I didn't return anything with the drawFooter so the image has not drawn, so I just changed the function to this:
// Private function to draw the footer
var drawFooter = function (canvas, ctx) {

    // Create a deferred promise
    var deferred = $q.defer();

    // Get our y location
    var y = canvas.height - 50;

    // Draw the copyright
    ctx.font = '20px lato-regular';
    ctx.fillStyle = 'black';
    ctx.textAlign = 'left';
    ctx.fillText(self.options.footer.copyright, self.options.canvasPadding.left, y);

    // Draw main text
    ctx.font = '60px lato-regular';
    ctx.fillStyle = 'black';
    ctx.textAlign = 'center';
    ctx.fillText(self.options.footer.mainText, canvas.width / 2, y);

    // Create a new image
    var img = new Image();

    // When the image loads
    img.onload = function () {

        // Get our coordinates
        var imageWidth = img.width / 2,
            imageHeight = img.height / 2,
            imageX = canvas.width - self.options.canvasPadding.right - imageWidth,
            imageY = y - imageHeight;

        // Draw the image
        ctx.drawImage(img, imageX, imageY, imageWidth, imageHeight);

        // Resolve our promise
        deferred.resolve();
    };

    // Set the SRC to the logo
    img.src = self.options.footer.logo;

    // Return our promise
    return deferred.promise;
};

and then I made sure it was being added to my pormises array:
// Finally add our footer to our promises array
promises.push(drawFooter(canvas, ctx));

When I did that, it all worked fine.


text:
Q: C++ equivalent for C# Action passing can somebody help me find a solution? I want to know whether there is a C++ equivalent for the following C# code:
// C# Code here

private void Execute(Action action)
{
    action();
}

Which can be called like this:
this.Execute( () => { this.DoA(); this.DoB(); } );

Now what I have come up with is to wrap the calls to this.DoA(); and this.DoB(); in another method and pass that as a function pointer:
// C++ Code here

void Execute(void (*f))
{
    (*f);
}

and
void DoBoth()
{
    DoA();
    DoB();
}

so then it can be called like this, which also works:
Execute(DoBoth);

But I am looking for a way without having to declare a method DoBoth. I know I could just use multiple parameters, but I dont want to restrict the number of the parameters and therefore I was hoping for a way like in C#.
Any help is gladly appreciated.

A: The term you're looking for is "lambda expression". Basically, it's a anonymous function.
I'll be honest, I have zero experience with C++ lambda.
They've been introduced in C++ 11 it would seem, and take the following form:
[]() {}

Instead of making plagiarism, I'll redirect you to this stackoverflow question, which seems to have excellent answers.


text:
Q: How to serialize a protobuf object to Ehcache? I have millions of objects, and I need to save them into cache. To reduce the size of these objects and the time of serialization/deserialization, I use protobuf object instead of POJO, then save them into Ehcache as byte array. But Ehcache will put protobuf byte array into an Ehcache's object, and then serialize the object into memory, so the advantage of using protobuf has gone.
Can I just save protobuf object's byte presentation directly into the Ehcache?

A: When you say "Ehcache will put protobuf byte array into an Ehcache's object", I guess you are referring to net.sf.ehcache.Element, right ? But "and then serialize the object into memory", what do you mean here ?
Just to clarify, Ehcache does not serialize anything to be stored on heap. If you talk about offHeap storage, then yes stuff gets serialized. But if you store byte arrays, serializing these values is... straightforward. Also, you shouldn't worry about internal datastructure serialization, these are handled very specifically and even if you'd be able to use protobuf there, you wouldn't gain anything.
But all the benefits you get on using protobuf for your domain instances vs. plain Java serialization, you wouldn't loose.


text:
Q: Any good javascript range highlighter I have been struggling for a long time looking for a range highlighter. If the user selects a particular text, that should be highlighted and in the same way if the use selects a range of text and click on remove highlight it should remove only the highlight from that selection. Please help me , i am stuck with this for a long time . Thanks.

A: You don't exactly need a plugin to do this, instead, you can get the element for where you the selected/highlighted text is, and then stored its content in a variable. Then you can set the elements .innerHTML back to the stored value. In the example below I have applied this to the entire body so it removed any selections made on the entire webpage.
See working example below:

const btn = _ => {
  const elem = document.querySelector('body');
  const txt = elem.innerHTML;
  elem.textContent = '';
  elem.innerHTML = txt;
}

This is some text. This is some more text, this is even mooooore text, this is even mooooore text, this is even mooooore text, this is even mooooore text, this is even mooooore text! this is even mooooore text! this is even mooooore text!

  <button onclick="btn()">Deselect</button>


text:
Q: Two columns don't stay in row (bootstrap)

Vardenis Pavardenis

Kebulo meistras

Petro servisas

Kaunas

Reitingas:

                    (123)

ratingsInfo should stay in the same row as userinfo but no it break into new row why?
I tried changing col-sizes col-xl and ... still doesnt do anything where is the problem?

A: Take the article tag out and add the below css to your page.
.userInfo {float:left;}
.ratingsInfo {margin-left : 20px;float:left;}

https://jsfiddle.net/javafiddleman/d19chtr6/7/

A: I don't use Bootstrap, but the element div has the display: block; by default, that is what is making the break row, to change it you can add the style: "display: inline-block;" to both divs.

Vardenis Pavardenis

Kebulo meistras

Petro servisas

Kaunas

Reitingas:

                (123)


text:
Q: How to implement a full text search with spring-data-jpa with more than one search term I have an Entity with a text that I want to search with spring-data-jpa.
With one search-string this is easy:
@Repository
public interface PostRepository extends CrudRepository<Post, Long> {
    public List<Post> findByTextContainingIgnoreCase(String searchString);
}

But what happens when a user is searching for more than one term?
like 'book harry potter'
The only working solution I have so far is:
public List<Post> findByTextContainingIgnoreCaseAndTextContainingIgnoreCase(String term1, String term2);

That gets very annoying when you want to allow to search for a couple of terms.
I already tried to have an Array<String> or a Collection<String> as parameter but that is not working.
Anyone an idea how to solve that?
I am using spring-data-jpa with version 1.9.4.RELEASE


text:
Q: How to get results from python unit tests in Django using custom settings I am trying to generate a report from the unit tests in Django.
For running the tests and retrieving the results I am using a custom TestResult class, which works fine:
results = TestResult()
loader = unittest.TestLoader()
suites = loader.discover('test_folder')
for suite in suites:
    suite(results)

My only issue is that I can't override the settings file to use in memory database. I decorated my test cases with override_settings from django.test, which works for me only in the command line. When I run it using the loader it uses the my_app.settings file, however, it looks like it is overridden:
>>> from django.conf import settings
>>> settings.DATABASES
{'default': {'TEST_CHARSET': 'UTF8', 'NAME': ':memory:', 'ENGINE': 'django.db.backends.sqlite3', 'TEST_NAME': ':memory:'}}

I also created my own override_settings file to override any function in my project and the result is the same. I tried to override the DJANGO_SETTINGS_MODULE in os.environ, but still having the same issue. Maybe I am missing some django.setup() function to load the settings file again.
I want to be able to:

*

*get results from the unit tests

*use custom settings

*load specific test module (just like with the loader.discover(start_dir))

TestCase example:
from rest_framework import status
from rest_framework.test import APITestCase

class TestCase(APITestCase):
    fixtures = ('dump',)
    url = '/api/post'

    def test_post(self):
         # returns post from existing database not from fixture
         post = Post.objects.get(pk=3)
         data = {
            'name': 'test',
            'post': post.content
        }
        response = self.client.post(self.url + '/1', data=data)
        self.assertEquals(response.status_code, status.HTTP_201_CREATED)

Using:

*

*Python 3.4

*Django 1.9

Thanks for your help.

A: Well, if you are using command ./manage.py test, then you could just parse the commandline argument and see if it's a test, then have an if statement in your settings.py:
if 'test' in sys.argv:
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3'
        }
    }


text: Q: What is the rationale behind being able to change the git commit author to anything? I noticed today that you can you can change the author of a commit to absolutely anything, just by changing the config. It doesn't need to be your username, or even a valid username. Is this not open to some kind of abuse?


text:
Q: angularjs ui-select scroll show causing jerk I've spent a while trying to formulate this question online without success. My problem is that when I click ui-select-choices rendered by angularjs ui-select-choices, the list opens fine down, but when I have devtools up (and when the browser is less than certain width), the options open upward and temporarily trigger the showing of vertical scroll bar. It is present for milliseconds but is causing a jerk on page.
Tried setting max-height to ul and li without success. I can put an overflow: y but I don't like seeing the scrollbar.

A: My solution is a workaround: add "limitTo:" in the repeat to limit the amount of results displayed. Doing this keeps the display beneath the dropdown rather than above (limiting amount to a certain quantity gives me the ability to match how much room I have left on page)
<ui-select-choices repeat="item in $ctrl.data | filter: $select.search | limitTo: 6">

</ui-select-choices>


text:
Q: How did Harry know that the "magic word" was "please"? In one of the early books (IIRC it was the first one; sorcerers stone, philosophers stone) Harry uses the term "magic word" to refer to the word "please" when talking to Dudley.
The Dursleys reaction shows that this term was considered taboo there (due to the word "magic"). If this was the case, how did Harry ever come to learn this phrase?

A: Harry had a life, albeit a somewhat limited one, outside of the Dursley home. He went to school and interacted with teachers, I'm sure we have all heard our parents or elders refer to please as a "magic word" when we were younger.
Of course there is no completely canon answer for this, but we know he interacted with muggles daily and it's a common phrase so it's safe to assume he picked it up from them.

A: "The magic word" meaning please or thank you is a common English idiom. E.g. see here.
It was perfectly natural for one child to say this to another; it was only Dudley's parents who might have thought to attach any significance to the phrase at that time. Even though they may not have used the phrase at home, due to the taboo on the word magic, Harry could easily have picked it up e.g. at primary school.


text:
Q: post request to rest api with json body in javascript Am trying to add comment to issue in my jira application through jira rest api's, am doing it in html/javascript code with json body but while am making the request am getting the following errors
"errorMessages":["Unexpected character ('Ã' (code 195)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')\n at "
{"errorMessages":["Unexpected end-of-input in VALUE_STRING\n at [Source: org.apache.catalina.connector.CoyoteInputStream@7b422cb8; line: 1, column: 159]"]}
Here is my code, please consider my URL and credentials are correct.I have tried with the same url,credentials and json body in REST Client and am able to add comment to issues in my JIRA, Can any one please tell where am doing wrong?

<meta charset="ISO-8859-1">
<title>Add Comment JIRA REST API</title>

Adding Comment

<button type="button" onclick="addComment()">Add Comment</button>

A: Seems like you transferring some data that is not in valid format. This mean you need to use JSON.Stringify() or encode the json data in UTF-8. Probably JSON.Stringify() would solve this.

A: This line:
 var commentJson = '{"body" : "adding comment to the task from client side javascript code"}';

...has the wrong kind of double quote marks around the second internal string. Make sure all of the double quote marks are straight, not left or right double quotes, like this:
var commentJson = '{"body" : "adding comment to the task from client side javascript code"}';

In addition, you might have to make sure your character encoding matches, as whiterabbitj suggested, but first you have to deal with using the wrong quote marks. It looks like you're sending in UTF-8, but the server is treating your data as ISO-8859-1.


text:
Q: In this properties(ng-repeat) variable is over lapping when i scroll the page ends? I want to send the limit and offset values from client side(angularjs) to nodejs.so
i tried with static values.
my html code :

In this properties(ng-repeat) variable is over lapping when i scroll the page ends . This loadMoreRecords() functions when the page scrolls to end.
my directive is scroll-trigger
sidemenu.directive('scrollTrigger', function() {
    return {
        restrict: "A",
        link: function(scope, element, attrs) {
             angular.element(document).bind('scroll', function() {
                if (jQuery(document).height() <= jQuery(window).scrollTop() +jQuery(window).height()) {
                    scope.$apply(attrs.scrollTrigger);
                }

            });
        }
    };
});

my controller code:
  sidemenu.controller('buildersCtrl', ['$scope', '$rootScope', '$location', '$http', 'allServices','$document','PropertyDetails','$routeParams','$window','typeServices', function (a, b, c, d, e,f,h,r,w,t) {

     var paging={start:0,rows:15}
    e.projectListing(r,paging).then(function (result) {
        a.properties = result.data.items;
        b.closeid = r.id;

    }, function (error) {

    });

    a.loadMoreRecords = function() {
alert("sss");
        var offset=paging.start+paging.rows;
       paging={start:offset,rows:15};
        e.projectListing(r,paging).then(function (result) {
            console.log(JSON.stringify(result));
            a.properties = result.data.items;
            b.closeid = r.id;
         }, function (error) {

        });
}
    }})


text:
Q: compare date to column header value in sql server I was creating the vehicle and driver availability chart.
I had a table looks like
driver_id    M1_1   M1_2  .... M1_31  M2_1 M2_2 M2_3 ..... M2_31 M3_1 M3_2 ... M3_31

it has up to 92 columns.
User will select up to 3 months.
Now if a driver was booked on 25-04-2014,if user searches for availability, the column M1_4 has to have some value say "Booked". Rest of all can be empty.with driver id in driver_id column.
similarly if the date is 25-05-2014 column M2_4 will get value "booked"
and if date is 25-06-2014 column  M3_4 will get value "booked".
When I export this data to excel header with dates and first column with driver and the dates booked will have "booked".rest will be empty.
Can be done by the way I was doing?
Is there Any other was to approach??
Please help me out.


text:
Q: Viewing/Recovering pending code reviews in Github When I start a code review, I can add multiple comments with a 'pending' status review and then submit them all at once instead of one-by-one.
If I close the review and come back to it, those pending comments are saved, but it requires me going back to that same pull request. Is there a way to search specifically for those PRs where I have started a review, but have not submitted yet? I tried using a search for commenter:me is:open and is:pending but this only returns PRs where I have fully published comments.


text:
Q: Spider-Man and his Amazing Friends comic from the early 80s I had a comic when I was younger that I believe came with the Sunday paper in the US, specifically Colorado. It was branded as 'Spider-Man and His Amazing Friends', the same as the cartoon of the time featuring Spider-Man, Iceman, and Firestar. In the comic, they battled the Abomination not the Green Goblin as in the official comic (Spider-Man and His Amazing Friends #1). I believe this comic was put out regionally and was associated with one of the large department stores in my town (I believe May D&F). I cannot find any mention of this comic anywhere. Would a comic like this in any way be considered canon? I would assume it had the blessing from Marvel when it was put out.

A: This is Spider-Man, Firestar and Iceman: Danger in Denver Vol.1 #1.

This was a special for the Denver Post in 1983 in which our heroes fight the Abomination at the NORAD complex in Colorado.

A: The comic you're referring to is listed on the Marvel Database website as Spider-Man Firestar Iceman Danger in Denver #1 (1983).
The site also has a page for the other comic you mentioned, Spider-Man and His Amazing Friends #1 (1981).
It's pretty safe to say that neither of these issues are canon to the mainstream comics for a number of reasons.
For one thing, the Official Handbook of the Marvel Universe lists the first appearance of the mainstream comics (Earth-616) Firestar as Uncanny X-Men #193 (1985), and specifies that her prior appearance in Spider-Man and His Amazing Friends #1 was set on Earth-8107.

Official Handbook of the Marvel Universe A to Z #4 (September, 2008)

Spider-Man Firestar Iceman Danger in Denver #1 isn't mentioned in the OHOTMU, however, given that it was published approximately two years prior to Uncanny X-Men #193 (the issue that's listed as Earth-616 Firestar's first appearance), that's an indirect indication that it isn't canon.
This is backed up by an advertisement for Firestar's 1986 miniseries, which only acknowledged her prior appearance in X-Men.

She's been a staple on Saturday morning television for a number of years now, but so far she has appeared in only one regular Marvel comic. That's about to change. Get ready to meet the latest addition to Marvel's mutant line-up in a four issue Limited Series, FIRESTAR.
Written by Tom DeFalco and illustrated by Mary Wilshire and Steve Leialoha, FIRESTAR will reintroduce us to the character who made one brief appearance in the X-MEN. We'll learn a lot about this mysterious young girl, her powers, and why she became a member of the Hellfire Club-controlled Hellions!

Marvel Age #35 (February, 1986)

Also, in Spider-Man Firestar Iceman Danger in Denver #1, the three title characters are depicted as being good friends and familiar with one another's secret identities, much as they were in the Spider-Man and His Amazing Friends animated series.

Spider-Man Firestar Iceman Danger in Denver #1 (1983)

By contrast, when Firestar introduced herself to Spider-Man in Web of Spider-Man Vol. 1 #75 (published eight years later), they each spoke as if they'd never met before.

FIRESTAR: Hi, I'm Firestar.
SPIDER-MAN: From the New Warriors, right? I've heard of you kids.

Web of Spider-Man Vol. 1 #75 (April, 1991)

They were later revealed to have had at least one prior meeting in Spider-Man Family Featuring Amazing Friends #1 (2006), but that story wouldn't have been set much earlier, since Firestar was acknowledged as being a member of the New Warriors, a team she didn't join until 1989. And again, she wasn't portrayed as being very familiar with either Spider-Man or Iceman in that issue. They'd both clearly heard of her, but this may be the first time they'd actually met her in canon.

SPIDER-MAN: Heya, Firestar.
ICEMAN: Oh-- Firestar. You're one of those New Kids, right?
FIRESTAR: New Warriors.
ICEMAN: Same thing.
FIRESTAR: So, hey, are you guys out on patrol or what? All my teammates are being boring tonight. Maybe you could use an extra hand?
ICEMAN: Heh! Listen, we're seasoned super heroes. I mean, it's not that we don't appreciate it-- you just wouldn't be able to keep up.
FIRESTAR: Uh... excuse me? I think the problem is you're too old to keep up with me.
ICEMAN: Too-- ah-hah! Is she for real? You hear that, Spidey? Too old!
SPIDER-MAN: Better watch it, Iceball. Firestar's no slouch.

Spider-Man Family Featuring Amazing Friends #1 (October, 2006)

Spider-Man and Iceman had met several times prior to this, and Spider-Man did know that Iceman was Bobby Drake. However, back in the '80s, Spider-Man was extremely protective of his secret identity, and didn't reveal it to any other hero, except his girlfriend, the Black Cat. Daredevil and Wolverine discovered his secret identity with their superhuman senses, but Iceman and Firestar almost certainly wouldn't have learned of it until he revealed it to the general public during the "Civil War" storyline in 2006.
Spider-Man later enlisted the help of Dr. Strange, Mr. Fantastic, and Iron Man to erase all knowledge of his secret identity from everyone except Mary Jane Watson, and while he subsequently re-revealed it to select heroes, such as the Fantastic Four and several Avengers, he's never been especially tight with either Iceman or Firestar in canon, and they're not currently among the heroes who know who he really is.
One other thing to note is that Iceman is described as a "teenager" in Spider-Man Firestar Iceman Danger in Denver #1...

Bobby Drake, an outgoing, fun-loving teenager, was born with the mutant power to turn himself and any moisture around him into ice. He fights evil and is known as Iceman!

Spider-Man Firestar Iceman Danger in Denver #1 (1983)

... whereas the Earth-616 versions of he and Spider-Man were college graduates in their early twenties by 1983, the year that comic was published. Spider-Man completed his first year of grad school that same year, as shown in Amazing Spider-Man Vol. 1 #243. Firestar was still a teenager when she made her first canon appearance in 1985, and according to her OHOTMU entry, she was only 19 years old during her time as an Avenger in Avengers Vol. 3 (1998–2004).


text:
Q: Scala Intellij suggests replacing size check with non empty, but why? if (cubeNames.size > 0) {
  //Do something
}

Intellij suggest this should be replaced by:
if (cubeNames.nonEmpty) {
  //Do something
}

Now function nonEmpty is defined as:
 def nonEmpty: Boolean = !isEmpty

Which is call to another function!
Is all this really necessary and in practicality, efficient?

A: .size needs to go through the whole collection to determine its size, while .isEmpty simply needs to find one element to return false.
It probably won't matter too much for small collections (but you should still do it). However, for huge collections there will be a significant difference.
Even worse, if the collection is infinite (eg val s:Stream[Int] = 0 #:: s), then .size will never terminate, while .isEmpty will.

A: I suppose that read code is much easier than evaluate code. That's why code list.nonEmpty may have only one meaning unlike list.size > 0.


text:
Q: Angular $q returning promise multiple $http calls I'm working on an $http call that loops over each of multiple api's and returns all of the data in one object. I usually have the promise ready to resolve when the $http call has been made. Similar to this:
function getAllData(api) {
    return $http({
        method: 'GET',
        url: '/api/' + api
    })
    .then(sendResponseData)
    .catch (sendGetVolunteerError);
}

The current function I have loops over each api and pushes each object in the api into an array and then pushes it into an overall array. I had this functioning, returning an multi-dimensional array, which needed to be flattened out.
I'd like to return this in a promise, but am returning undefined. Here is what I have so far? Is there a better way to approach this?
dataService:
function getSearchData() {
    return {
        loadDataFromUrls: function () {
            var apiList = ["abo", "ser", "vol", "con", "giv", "blo", "par"];
            var deferred = $q.defer();
            var log = [];
            angular.forEach(apiList, function (item, key) {
                var logNew = [];
                $http({
                    method: 'GET',
                    url: '/api/' + item
                }).then(function (response) {
                    angular.forEach(response.data, function (item, key) {
                        this.push(item);
                    }, logNew);
                    return logNew;
                });
                this.push(logNew);
            }, log);
            $q.all(log).then(

            function (results) {
                deferred.resolve(
                JSON.stringify(results))
            },

            function (errors) {
                deferred.reject(errors);
            },

            function (updates) {
                deferred.update(updates);
            });
            return deferred.promise;
        }
    };
};

Controller:
function getSearchData(){
  return dataService.getSearchData.loadDataFromUrls;
}

$scope.searchData = getSearchData();

A: If you have an arbitrary set of api calls I would do something like this:
function getSearchData(){
    var deferred = $q.defer();
    var noOfCalls = apiList.length;
    var results = [];
    var called = 0;

    angular.forEach(apiList, function(item, key) {
        $http.get(url).then(function(result){
           results.push(result);
           called++;
           if(called == noOfCalls){
              deferred.resolve(results);
           }
        })
   });

    return deferred.promise;
}

However if you know what each api call represents its better to use $.all in this way
function search1(){
      return $http.get(search1Url).then(function(result){
          // do something to it
          return result;
      });
}

function search2(){
      return $http.get(search2Url).then(function(result){
          // do something to it
          return result;
      });
}

function search3(){
      return $http.get(search3Url).then(function(result){
          // do something to it
          return result;
      });
}

function search4(){
      return $http.get(search4Url).then(function(result){
          // do something to it
          return result;
      });
}

function getSearchResult(){

    return $q.all([search1(), search2(), search3(), search4()]).then(function(results){
       // OPTIONAL  aggregate results before resolving
       return results;
    });
}

A: $q.all and a map function are what you need here:
function getSearchData() {
    return {
        // returns a promise for an object like:
        // { abo: resultFromAbo, ser: resultFromSer, ... }
        loadDataFromUrls: function () {
            var apiList = ["abo", "ser", "vol", "con", "giv", "blo", "par"];

            return $q.all(apiList.map(function (item) {
                return $http({
                    method: 'GET',
                    url: '/api/' + item
                });
            }))
            .then(function (results) {
                var resultObj = {};
                results.forEach(function (val, i) {
                    resultObj[apiList[i]] = val.data;
                });
                return resultObj;
            });
        }
    };
}

A: You should add a list of promises in $q ( not resolved promises like in your code ) , which is a $promise service
Example:
var firstPromise = service1.getMethod1().$promise;
var secondPromise = service2.getMethod2().$promise;
$q.all([firstPromise, secondPromise]).then(function(dataList){
     // dataList[0] will be result of `firstPromise`
     // dataList[1] will be result of `secondPromise`
});


text:
Q: Jira Tempo : JSONP does not work? I am struggling with JSONP in Jira Tempo.
I just wanted to make their example work :
fn(
  {"values":
   [
     {
       "key":"",
       "value":"Please select..."
     },
     {
       "key":"0100",
       "value":"This is option ONE"
     },
     {
       "key":"0200",
       "value":"And here is option TWO"
     }
   ]
 }
)

Assuming I would have the script placed on my apache server http://www.example.com/foo.jsonp, what would be the URL I have to add to tempo?
Or does this simply not work with an Apache?
Many thanks!

A: If you're using the cloud version of JIRA which is hosted on an SSL domain, you cannot use a Worklog Attributes service hosted on a non-SSL domain.
If you open the Chrome console when attempting to add a Tempo worklog, you will see the following error:

[blocked] The page at 'https://XXX.atlassian.net/secure/TempoUserBoard!timesheet.jspa' was loaded over HTTPS, but ran insecure content from 'http://XXX?callback=jQuery17203306205284316093_1425058485043&_=1425058490237': this content should also be loaded over HTTPS.

Tempo uses JQuery on the client side to load the values dynamically. If you want to debug your service on a non-SSL server, run Chrome with the following key:

chrome.exe --allow-running-insecure-content

Other potential problems:

*

*Tempo won't load the dynamic attributes until you select a specific issue in the time-booking dialog.

*You have to replace the fn in the example script dynamically based on the callback parameter. A static script won't work.


text:
Q: Linq Subquery with Group by I have the following query which works fine:
 var results = (from p in db.globalMap
                               where p.LId == 1
                               group p by p.GroupId into g
                               select new
                               {
                                   GroupId = g.Key,
                                   client = g.Select(k => k.ClientId).FirstOrDefault(),
                                   cnt = g.Count()
                               }).ToList();

What I like to do is query another table to get the clientname based on the ClientId.
I tried something like but get red swiggly lines. Wondering how I can do a subquery like the way I want to below.
     var results = (from p in db.globalMap
                               where p.LId == 1
                               group p by p.GroupId into g
                               select new
                               {
                                   GroupId = g.Key,
                                   clientName =  (select x in db.client where x.clientId = clientId select x.clientName).FirstOrDefault(),
                                   cnt = g.Count()
                               }).ToList();

A: You can do it similarily how you did the first one:-
var results = (from p in db.globalMap
               where p.LId == 1
               group p by p.GroupId into g
               select new
               {
                   GroupId = g.Key,
                   clientName =  db.client.Where(x => x.clientId == clientId)
                                          .Select(x => x.clientName).FirstOrDefault(),
                   cnt = g.Count()
               }).ToList();


text:
Q: What are the advantages of explicit interface implementation in C#? C# supports built-in mechanism for differentiating methods that have the same names. Here is a simple example below shows how it works:
interface IVehicle{
    //identify vehicle by model, make, year
    void IdentifySelf();
}

interface IRobot{
    //identify robot by name
    void IdentifySelf();
}

class TransformingRobot : IRobot, IVehicle{
    void IRobot.IdentifySelf(){
        Console.WriteLine("Robot");
    }

    void IVehicle.IdentifySelf(){
       Console.WriteLine("Vehicle");
    }
}

What are the use cases or benefits of this distinction? Do I really need to differentiate abstract methods in implementing classes?

A: In your case, there's no real benefit, in fact having two methods like that is just confusing to the user. However, they are key when you have:
interface IVehicle
{
    CarDetails IdentifySelf();
}

interface IRobot
{
    string IdentifySelf();
}

Now we have two methods of the same name, but different return types. So they cannot be overloaded (return types are ignored for overloading), but they can be explicitly referenced:
class TransformingRobot : IRobot, IVehicle
{
    string IRobot.IdentifySelf()
    {
        return "Robot";
    }

    CarDetails IVehicle.IdentifySelf()
    {
        return new CarDetails("Vehicle");
    }
}


text:
Q: How to column-ify an output from a certain program? I have a program that generates and outputs a sequence of simple sample math homework tasks, like:

1 + 1 = ...
  3 + 3 = ...
  2 + 5 = ...
  3 + 7 = ...
  4 + 2 = ...

a sequence can be quite long, and I'd like to save space when this sequence is printed by converting it as follows:

1 + 1 = ...   3 + 7 = ...
  3 + 3 = ...   4 + 2 = ...
  2 + 5 = ...

that is, wrapping the lines into the two or more columns. I was expecting the column linux utility to do the job using the -c N option witn N=2, however, it still outputs the lines in one column whatever the N is.
How would I do the column-ifying of the sequence of lines?

A: Believe it or not, the utility you want is pr, not columns.  If you want your file turned into 3 columns:
pr -3 textfile.txt

If you want to fill in rows first, then columns:
pr -l1 -t -3 textfile.txt

I got these sample invocations from the ever-so-useful UNIX Power Tools.  This is Recipe 21.16.

A: The -c parameter to column is used to specify the number of "columns" your display has, counted in characters.  The column tool then figures out the number of "output columns" that fits in the given number of "character columns".  Passing a small number of "character columns" will almost always yield a single "output column", because more won't fit in the given number of characters.  There does not seem to be a way to pass the number of ouput columns on the command line.


text:
Q: parse key values from JSON object I have a JSON object received from geocod.io API call. I need to parse the object and get at the key values, particularly the key (e.g., "246212") and the lat and lng
    {
   "results":{
      "246212":{
         "query":"1601 Sandhurst Dr, Waxahachie, Texas",
         "response":{
            "input":{
               "address_components":{
                  "number":"1601",
                  "street":"Sandhurst",
                  "formatted_street":"Sandhurst",
                  "city":"Waxahachie",
                  "state":"TX",
                  "zip":"75165",
                  "country":"US"
               },
               "formatted_address":"1601 Sandhurst, Waxahachie, TX 75165"
            },
            "results":[
               {
                  "address_components":{
                     "number":"1601",
                     "street":"Sandhurst",
                     "formatted_street":"Sandhurst",
                     "city":"Waxahachie",
                     "county":"Ellis County",
                     "state":"TX",
                     "zip":"75165",
                     "country":"US"
                  },
                  "formatted_address":"1601 Sandhurst, Waxahachie, TX 75165",
                  "location":{
                     "lat":32.42555,
                     "lng":-96.833181
                  },
                  "accuracy":1,
                  "accuracy_type":"range_interpolation",
                  "source":"TIGER\/Line\u00ae dataset from the US Census Bureau"
               }
            ]
         }
      },
      "246994":{
         "query":"1415 Willow Run Dr, Duncanville, Texas",
         "response":{
            "input":{
               "address_components":{
                  "number":"1415",
                  "street":"Willow Run",
                  "suffix":"Dr",
                  "formatted_street":"Willow Run Dr",
                  "city":"Duncanville",
                  "state":"TX",
                  "zip":"75137",
                  "country":"US"
               },
               "formatted_address":"1415 Willow Run Dr, Duncanville, TX 75137"
            },
            "results":[
               {
                  "address_components":{
                     "street":"Willow Run",
                     "suffix":"Dr",
                     "formatted_street":"Willow Run Dr",
                     "city":"Duncanville",
                     "county":"Dallas County",
                     "state":"TX",
                     "zip":"75137",
                     "country":"US"
                  },
                  "formatted_address":"Willow Run Dr, Duncanville, TX 75137",
                  "location":{
                     "lat":32.635994,
                     "lng":-96.884205
                  },
                  "accuracy":0.8,
                  "accuracy_type":"street_center",
                  "source":"TIGER\/Line\u00ae dataset from the US Census Bureau"
               }
            ]
         }
      },
      "247037":{
         "query":"1800 Windmill Hill Ln, Desoto, Texas",
         "response":{
            "input":{
               "address_components":{
                  "number":"1800",
                  "street":"Windmill Hill",
                  "suffix":"Ln",
                  "formatted_street":"Windmill Hill Ln",
                  "city":"Desoto",
                  "state":"TX",
                  "zip":"75115",
                  "country":"US"
               },
               "formatted_address":"1800 Windmill Hill Ln, Desoto, TX 75115"
            },
            "results":[
               {
                  "address_components":{
                     "number":"1800",
                     "street":"Windmill Hill",
                     "suffix":"Ln",
                     "formatted_street":"Windmill Hill Ln",
                     "city":"Desoto",
                     "county":"Dallas County",
                     "state":"TX",
                     "zip":"75115",
                     "country":"US"
                  },
                  "formatted_address":"1800 Windmill Hill Ln, Desoto, TX 75115",
                  "location":{
                     "lat":32.613862,
                     "lng":-96.907534
                  },
                  "accuracy":1,
                  "accuracy_type":"range_interpolation",
                  "source":"TIGER\/Line\u00ae dataset from the US Census Bureau"
               },
               {
                  "address_components":{
                     "number":"1800",
                     "street":"Windmill Hill",
                     "suffix":"Ln",
                     "formatted_street":"Windmill Hill Ln",
                     "city":"Desoto",
                     "county":"Dallas County",
                     "state":"TX",
                     "zip":"75115",
                     "country":"US"
                  },
                  "formatted_address":"1800 Windmill Hill Ln, Desoto, TX 75115",
                  "location":{
                     "lat":32.614162,
                     "lng":-96.907523
                  },
                  "accuracy":0.8,
                  "accuracy_type":"range_interpolation",
                  "source":"TIGER\/Line\u00ae dataset from the US Census Bureau"
               }
            ]
         }
      }
   }
}

I have searched and tried the following code snippets
// this converts to object
var obj = JSON.parse(geocodedAddress;

console.log('obj ', obj);

for (var key in obj) {
    let value = obj[key];
    console.log('value ', value);
}

console.log('Object.keys ', Object.keys(obj.results));

// This is not returning anything
var getKeys = function(obj) {
    var keys = [];
    for (var key in obj) {
        keys.push(key);
        console.log('key ', key);
    }
    console.log('keys ', keys);
    return keys;
};

I think I am close as you can see from the screenshot. Any help would be much appreciated.
enter image description here


text:
Q: Vue - The Cli gives an error on installing I just installed Ubuntu and tried to install the vue cli but got this error
here's the error
npm WARN deprecated subscriptions-transport-ws@0.11.0: The `subscriptions-transport-ws` package is no longer maintained. We recommend you use `graphql-ws` instead. For help migrating Apollo software to `graphql-ws`, see https://www.apollographql.com/docs/apollo-server/data/subscriptions/#switching-from-subscriptions-transport-ws    For general help using `graphql-ws`, see https://github.com/enisdenjo/graphql-ws/blob/master/README.md
npm WARN deprecated source-map-resolve@0.5.3: See https://github.com/lydell/source-map-resolve#deprecated
npm WARN deprecated resolve-url@0.2.1: https://github.com/lydell/resolve-url#deprecated
npm WARN deprecated urix@0.1.0: Please see https://github.com/lydell/urix#deprecated
npm WARN deprecated source-map-url@0.4.1: See https://github.com/lydell/source-map-url#deprecated
npm WARN checkPermissions Missing write access to /usr/lib/node_modules
npm ERR! code EACCES
npm ERR! syscall access
npm ERR! path /usr/lib/node_modules
npm ERR! errno -13
npm ERR! Error: EACCES: permission denied, access '/usr/lib/node_modules'
npm ERR!  [Error: EACCES: permission denied, access '/usr/lib/node_modules'] {
npm ERR!   errno: -13,
npm ERR!   code: 'EACCES',
npm ERR!   syscall: 'access',
npm ERR!   path: '/usr/lib/node_modules'
npm ERR! }
npm ERR!
npm ERR! The operation was rejected by your operating system.
npm ERR! It is likely you do not have the permissions to access this file as the current user
npm ERR!
npm ERR! If you believe this might be a permissions issue, please double-check the
npm ERR! permissions of the file and its containing directories, or try running
npm ERR! the command again as root/Administrator.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/m/.npm/_logs/2022-08-17T06_58_04_490Z-debug.log

I tried installing other npm packages and it worked, the cli is the only one that doesn't work

A: Most probably it has to do with the user rights. Here's an article on npm addressing your problem.
Boils down to two things you can try:

*

*Reinstall npm with a node version manager

*Manually change npm's default directory

I had this issue many times in the past and tried various solutions. Some of them didn't do much more than f*cking my setup even more, that's why it's really worthy to follow the official path.