text:
Q: ArrayAdapter add method casting Illegal state exception I have a problem adding items to my array adapter.
Here is the code
   public void find_BondedDevices (View view) {

        // Look for bonded devices
        pairedDevices = btAdapter.getBondedDevices();

        if (pairedDevices.size() > 0) {
            for (BluetoothDevice device : pairedDevices) {
                String deviceBTName = device.getName();
                String deviceBTMajorClass = getBTMajorDeviceClass(device
                        .getBluetoothClass()
                        .getMajorDeviceClass());
                pairedDevicesAdapter.add(deviceBTName + "\n" + deviceBTMajorClass);
            }
        }

If the code is put in the onCreate method, it works!
If i comment the line
pairedDevicesAdapter.add(deviceBTName + "\n" + deviceBTMajorClass);

it works!
   java.lang.IllegalStateException: Could not execute method of the activity
                at android.view.View$1.onClick(View.java:3638)
                at android.view.View.performClick(View.java:4243)
                at android.view.View$PerformClick.run(View.java:17520)

android.app.ActivityThread.main(ActivityThread.java:5299)
                at java.lang.reflect.Method.invokeNative(Native Method)
                at java.lang.reflect.Method.invoke(Method.java:511)
                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
                at dalvik.system.NativeStart.main(Native Method)
         Caused by: java.lang.reflect.InvocationTargetException
                at java.lang.reflect.Method.invokeNative(Native Method)
                at java.lang.reflect.Method.invoke(Method.java:511)
                at android.view.View$1.onClick(View.java:3633)
                at android.view.View.performClick(View.java:4243)
                at android.view.View$PerformClick.run(View.java:17520)
                at android.os.Handler.handleCallback(Handler.java:725)
                at android.os.Handler.dispatchMessage(Handler.java:92)
                at android.os.Looper.loop(Looper.java:153)
                at android.app.ActivityThread.main(ActivityThread.java:5299)
                at java.lang.reflect.Method.invokeNative(Native Method)
                at java.lang.reflect.Method.invoke(Method.java:511)
                at

com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
                at dalvik.system.NativeStart.main(Native Method)
         Caused by: java.lang.NullPointerException
                at com.voice.benz.instaremote.MainActivity.find_BondedDevices(MainActivity.java:95)
                at java.lang.reflect.Method.invokeNative(Native Method)
                at java.lang.reflect.Method.invoke(Method.java:511)
                at android.view.View$1.onClick(View.java:3633)
                at android.view.View.performClick(View.java:4243)
                at android.view.View$PerformClick.run(View.java:17520)
                at android.os.Handler.handleCallback(Handler.java:725)
                at android.os.Handler.dispatchMessage(Handler.java:92)
                at android.os.Looper.loop(Looper.java:153)
                at android.app.ActivityThread.main(ActivityThread.java:5299)
                at java.lang.reflect.Method.invokeNative(Native Method)
                at java.lang.reflect.Method.invoke(Method.java:511)
                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
                at dalvik.system.NativeStart.main(Native Method)

I've tried almost everything but with no result, i need this code to be in a separate function because in the onCreate method is useless
Here is the complete code of the app:
http://pastebin.com/nZYdSkaA
Any ideas?
Thanks

A: You're assigning the adapter to the local variable pairedDevicesAdapter instead of to instance variable.
It is local to the onCreate() method see this:
 ArrayAdapter<String> pairedDevicesAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);

Therefore, your pairedDevicesAdapter the one you're using to call the method 'add' is null (never initialized).
to fix:
on the onCreate() just do this instead:
this.pairedDevicesAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);

A: The main cause of problem is
 Caused by: java.lang.NullPointerException
                at com.voice.benz.instaremote.MainActivity.find_BondedDevices(MainActivity.java:95)

And it only can if your pairedDevicesAdapter is null(which is), check if you initialized it right


text:
Q: Why is Gravityforms Nested Forms showing view entry links on mini cart for non admin? As the title describes it, Gravityforms Nested Forms is showing view entry links on mini cart. (I don't think it should for non-admins)
Is there any way to hide it?
Screenshot below
https://imgur.com/a/hhnRee7

redpajama_set_name: RedPajamaStackExchange


text:
Q: Configuring a sub-domain DNS in Azure I am new to Azure. I have a linux vm hosted in Azure, on which I am running a springboot application. The springboot app runs behind an Apache httpd.
DNS name for the host is something like xyz.cloudapp.azure.com and i need to create a sub domain (abc.xyz.cloudapp.azure.com) to host few files on my server. I have made following configuration in the httpd conf to route the requests for sub domain
<VirtualHost *:443>
    ServerName abc.xyz.cloudapp.azure.com
    ServerAlias xyz.cloudapp.azure.com
    DocumentRoot /var/pathforsubdomainfiles
    .......................
    enter code here....................
</VirtualHost>

I am not able to figure out how to create a DNS record for the subdomain (abc.xyz.cloudapp.azure.com) in Azure so that it could be resolved over a public network to access the hosted files.
I do not have any DNS zones created in Azure yet.

A: As far as I know, you can create a fully qualified domain name in the Azure portal for a Azure VM. The FQDN is something like abc.eastus.cloudapp.azure.com. It has a subdomain (abc.xyz.cloudapp.azure.com) in Azure.
If this is not what you desired, you need to purchase a public domain like example.com from a domain provider like GoDaddy and create DNS records to map this subdomain like www.example.com to the public IP address or FQDN for the Azure VM because you can not create DNS records for the Azure provided domain xyz.cloudapp.azure.com. In the process of creating DNS records, you have a option to host your domain in Azure DNS and manage your domain in Azure.
For more information, you could read this blog.


text:
Q: Warning: [react-router] Location "/D:/original/22-02-2017/job2.html" did not match any routes I am working with typescript-with-react. And i m using webpack as a compiler . And my directory structure is as follows:
d:/original/22-02-2017/
      -

and my entry point in web.config.js is ./src/index.tsx file.
my components placed inside src/components/demo.tsx

and my index.tsx file is as follows

and inside /job2.html i have following links

but when i am trying to run program it gives me following error
Warning: [react-router] Location "/D:/original/22-02-2017/job2.html" did not match any routes
and i am not using server port i am just running my app at
file:///D:/original/22-02-2017/job2.html
i have tried many  but not get succeed. please help me what is wrong with my code?

A: This one is the very old question for React router. Now we can use React-Router-DOM for routing with react. It is very easy to understand and very simple to use.


text:
Q: Scala Ordinal Method Call Aliasing In Spark SQL we have Row objects which contain a list of records that make up a row (think Seq[Any]). A Rowhas ordinal accessors such as .getInt(0) or getString(2).
Say ordinal 0 = ID and ordinal 1 = Name. It becomes hard to remember what ordinal is what, making the code confusing.
Say for example I have the following code
def doStuff(row: Row) = {
  //extract some items from the row into a tuple;
  (row.getInt(0), row.getString(1)) //tuple of ID, Name
}

The question becomes how could I create aliases for these fields in a Row object?
I was thinking I could create methods which take a implicit Row object;
def id(implicit row: Row) = row.getInt(0)
def name(implicit row: Row) = row.getString(1)

I could then rewrite the above as;
def doStuff(implicit row: Row) = {
  //extract some items from the row into a tuple;
  (id, name) //tuple of ID, Name
}

Is there a better/neater approach?

A: You could implicitly add those accessor methods to row:
implicit class AppRow(r:Row) extends AnyVal {
    def id:String = r.getInt(0)
    def name:String = r.getString(1)
}

Then use it as:
def doStuff(row: Row) = {
  val value = (row.id, row.name)
}

A: Another option is to convert Row into a domain-specific case class, which IMHO leads to more readable code:
case class Employee(id: Int, name: String)

val yourRDD: SchemaRDD = ???
val employees: RDD[Employee] = yourRDD.map { row =>
  Employee(row.getInt(0), row.getString(1))
}

def doStuff(e: Employee) = {
  (e.name, e.id)
}


text:
Q: Strongloop android sdk custom method error Trying to reach an custom method on my server using an android client create a bad request error.
Here is the custom method on the server (tested with strongloop explorer):
Question.remoteMethod(
    'top', {
        http: {path: '/top', verb: 'get'},
        accepts: [
                    {arg : 'start', type: 'number'},
                    {arg: 'pagination', type: 'number'}

                ],
        returns: {arg: 'questions', type: 'array'},
        description: ['Returns an array obj the latest added questions']
    }
);

Code  in the android Question repository :
@Override
public RestContract createContract() {

    RestContract contract = super.createContract();

    contract.addItem(
        new RestContractItem("/" + getNameForRestUrl() + "/top?" +
            "start=" + ":start" + "&pagination=" + ":pagination", "GET"),
        getClassName() + ".top");

    return contract;
}

public void top(int start, int pagination, ListCallback<Question> cb) {
    Map<String, Integer> params = new HashMap<String, Integer>();
    params.put("start", start);
    params.put("pagination", pagination);
    invokeStaticMethod("top", params,
            new JsonArrayParser<Question>(this, cb));
}

When I use this following code to test the created request url :
RestContract contract = this.createContract();
Map<String, Integer> params = new HashMap<String, Integer>();
        params.put("start", 0);
        params.put("pagination", 2);
        String t = contract.getUrl("/" + getNameForRestUrl() + "/top?" +
                "start=" + ":start" + "&pagination=" + ":pagination", params);

t is: "/Questions/top?start=0&pagination=2" which is the right url (according to strongloop explorer).
Still, the use of the fucntion TOP returns a bad request error.
Do you have any idea why I got an error, and how I should modify the function to get the results ?

A: Finally got the answer. The error was within the Question Repository.
Here is the right peace of code :
@Override
public RestContract createContract() {

    RestContract contract = super.createContract();

    contract.addItem(
        new RestContractItem("/" + getNameForRestUrl() + "/top", "GET"),
        getClassName() + ".top");
}

public void top(int start, int pagination, ListCallback<Question> cb) {
    Map<String, Integer> params = new HashMap<String, Integer>();
    params.put("start", start);
    params.put("pagination", pagination);
    invokeStaticMethod("top", params,
        new JsonResponseParser<Question>(this, cb, "questions"));
}

You must not specify filter when you create the rest contract as the using the top method below will automaticaly add the parameters given to the parameters Map as a filter with the form :
http://serverip:port/api/Questions/top?filter=value1&filter2=value2


text:
Q: Group Indicator is not coming in the right side of Expandable List view Group Indicator is  not coming in the right side of Expandable List view  in android Even if I have applied all the  given solution  for it but its not working

A: In the xml file
ExpandableListView
android:groupIndicator="@null"

In adapter
public View getGroupView(int groupPosition, boolean isExpanded,
    View convertView, ViewGroup parent) {

if (isExpanded) {
    groupHolder.img.setImageResource(R.drawable.group_down);
} else {
    groupHolder.img.setImageResource(R.drawable.group_up);
     }
}

You have to use custom image to achieve this.


text:
Q: How to make div occupy 100% of viewport height in browser I have a div tag and I realized that it is not filling 100% of the height as it should.
My code:

#container {
  width: 100vw;
  height: 100vh;
  background: purple;
}

body {
  margin: 0px;
}

What's happening?
Well, if I only have this code snippet above that I put the div to occupy 100% of the viewport of course! The problem is that I don't only have this code on my page, I have more things and I inserted this code section inside the body tag, a certain" place "inside the body tag, that is, I inserted some elements, and after these elements have this div, but it does not occupy, 100% of the viewport observe how it is
How is the result visually on your page?

I scrolled the page, but my div was still to occupy 100% of the entire viewport. Am I not correct? and if this was supposed to happen why isn't it happening?
Explanation: Guys, I discovered the problem but I don't know how to solve it, well, here's the thing, the div does not occupy 100% of the viewport when it has an element below the container div or above, look at this image and see:

And the code I used that made this happen:
My code HTML:

body {
  color: red;
  background: green;
  margin: 0;
  padding: 0;
}

#container {
  width: 100vw;
  height: 100vh;
  z-index: 1;
  background: purple;
}

p {
  font-size: 20pt;
}

ksksks

What happens in the image above is the same problem that happens on my page, that is, the div only fills 100% of the viewport's height if it has no elements on the page, and I want to be able to make the height 100% of the viewport even with elements on the page.
Edit:
Well apparently I saw that there are a lot of answers, and most of them don't work or are explaining the error or presenting answers that don't solve the problem, other people suggested using position fixed which in fact solves the problem, but I don't want to have to do it this way  , think that you have a chat because you would want it to have a scrolling bullet and it will be the chat that will occupy the entire viewport and not another div understand?  This solution actually solves the problem, but I don't like jerry-rig.
I would like to know a more elegant way of doing it, for example my div container occupies 100% of the viewport but I don't want other elements to appear, I want the div container to overlap  any element that should appear and I don't want to scroll the page.
Summary:
To summarize everything in a few words, the div should occupy 100% of the viewport and make sure that the body does not have a scroll and the page goes to the top, that is, regardless of which position on the page the user is in, I want the page to go  to the top and disable the scroll, and without javascript preferably, I don't want to write too much javascript being possible to write in html and css :) I will take advantage of the reward in this answer to add this and ask for a solution to this problem.

A: The problem has to do with the fact that the vh and vw units don't take the (added) scrollbar width/height into consideration. As long as the page isn't higher than the viewport, no scrollbar appears and 100vh will be exactly the height of the viewport and everything works as expected.
But as soon as there is more content below or above, a vertical scrollbar appears: Now the width: 100vw is wider  than the window width minus the vertical scrollbar, so a horizontal  scrollbar appears, and now the height: 100vh is higher than the window height minus the (horizontal) scrollbar.
I consider that a kind of bug, but that's the way it is - in most browsers, it seems. I posted this question a long time ago which basically covers the same issue: Problem using vw units when a vertical scrollbar appears (full-width elements in WordPress)
Addition/edit after comments:
There is no 100% safe solution, I would say. But one thing that helps to some extent is to not  use 100vw for the width, but instead 100%, which does consider the (vertical) scrollbar. However, width: 100%; is the default for any block element anyway, so you can simply erase the width setting and only use height: 100vh, which will work (i.e. have the exact viewport height) as long as you don't have any special width requirements.

A: Please use the following meta tag inside your head tag
<meta name="viewport" content="width=device-width, initial-scale=1">

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

ksksks

A: Based On your question you want the div to take up the space instead of the purple background right?
Css:
#container {
  width: 100vw;
  height: 100%;
  background: purple;
}

body {
  margin: 0px;

}

#innerDiv {
  height: 100vw;
  background-color: red;
  width: 100vw;

}

#innerDiv1 {
  height: 100%;
  background-color: blue;
  width: 100vw;

}

Html:

Div #1

Div #2

A: You applied  background purple color upto  height of 100vh,
if you want see purple fully you just add purple in body tag instead green or otherwise you want place div inside container .here is nothing problem.you just want to adjust your code

body {
  color: red;
  background: purple;
  margin: 0;
  padding: 0;
}

#container {
  width: 100vw;
  height: 100vh;
  z-index: 1;

}

p {
  font-size: 20pt;
}

ksksks

A: The simplest solution is to make use of viewport height(vh) and viewport width(vw) units to set the height and width of the block. this block/div will fill up the entire space in the browser window. Here is an example.
div.container {
    height: 100vh;
    width: 100vw;
}

make sure you have the viewport meta tag in your  as given
<meta name="viewport" content="width=device-width, initial-scale=1.0">

This gives the browser instructions on how to control the page's dimensions and scaling. The width=device-width part sets the width of the page to follow the screen-width of the device (which will vary depending on the device).
The initial-scale=1.0 part sets the initial zoom level when the page is first loaded by the browser. Incase of a missing meta tag, the initial scale and zoom may misbehave. Also put your
 inside the container div. Here is the working demo.
My code:

HTML, body {
  margin: 0;
  padding: 0;
}

#container {
  width: 100vw;
  height: 100vh;
  background: purple;
}

p {
  height: 100%;
  width: 100%;
  background-color: rgba(255,255,255, .8);
}

    Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

A: It is just a workaround, I usually used it as mobile hamburger menu with full screen. You have to be careful because it force to cover bfull page, it will hide all element if there is any other element already exists on the page.
.container {
    # it make the container always on the page regardless any element or window margin
    position: fixed;
    top: 0;
    left: 0;
    z-index: 999;

    height: 100vh;
    width: 100vw;
}

A: I have tried it with those codes and it seems like it's working,
You can check them:

body {
  color: red;
  background: green;
  margin: 0;
  padding: 0;
}

#container {
  width: 100vw;
  height: 100vh;
  z-index: 1;
  background: purple;
}

p {
  font-size: 20pt;
}
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link rel="stylesheet" href="main.css">

ksksks

A: Nothing seems to be the problem.

#container {
  width: 100vw;
  height: 100vh;
  background: purple;
}

body {
  margin: 0px;
}

#innerDiv {
  height: 100px;
  background-color: red;
  width: 100vw;
}

#innerDiv1 {
  height: 100px;
  background-color: blue;
  width: 100vw;
}

Div #1

Div #2


text:
Q: XCode 7.3 storyboard kept showing loading revision Two days ago i have updated my Xcode to the version 7.3. It was working fine till yesterday. Today when I was opening a storyboard ViewController in editor(View > Assistant Editor > Show Assistant Editor), my storyboard got converted into the xml source code, and after that it kept showing loading revision, but nothing happens. I am afraid that, closing Xcode might be leads to loose my Storyboard or any unexpected behaviour. So I kept it open, Please suggest me any workaround, its happening since 10 minutes. Attaching screenshot for better understanding.

A: *

*Select your storyboard

*Menu > View > Standard Editor > Show Standard Editor

Hope this helps.

A: Right click the storyboard file and choose open as -> Interface Builder - Storyboard.


text:
Q: Does the Rust compiler convert String to &str implicitly? I implemented the trait Foo for &'a str, but when I call the method test for std::string::String, it works. I checked my code and I'm sure that I don't implement the trait for String, so does the Rust compiler convert String to str implicitly?
The code likes this:
pub trait Foo {
    fn test(self) -> String;
}

impl<'a> Foo for &'a str {
    fn test(self) -> String {
        String::from("da")
    }
}

fn main() {
    let s = String::from("123456789");
    println!("{}", s.test());
}

The Rust plugin for the Jetbrains IDE can't find test method for String, but it works well.
Why does that code work?

A: First off, careful. String != CString. And s.test(var) will not yield anything but an error since your test method takes no parameter but self.
Now, on to what is actually happening.
When you define an extension method like you did by defining a trait then implementing it for &_ str but not on String, and then try to invoke it, the compiler implicitly does the dereferencing (since String implements Deref into &_ str).
As a result, your main function can be written for clarity as:
fn main() {
    let s = String::from("123456789");
    println!("{}", (s.deref()).test());
}

and is entirely analogous to what the compiler does under-the-hood. The compiler essentially saw that you were trying to use this, and did so for you.
I need to warn you, though - your code is extremely weird in multiple ways:

*

*One normally implements trait methods like these on objects, not their Deref counterpart, precisely to avoid this level of indirection

*Your implementation consumes a reference. Consider this for a moment.

A much better, and less indirect way to write it, is as follows:
pub trait Foo {
    fn test(&self) -> String;
}

impl Foo for str {
    fn test(&self) -> String {
        String::from("da")
    }
}

fn main() {
    let s = String::from("123456789");
    println!("{}", s.test());
}

You are not sacrificing anything, the functionality remains identical, but:

*

*You are no longer needlessly consuming a reference

*You are no longer needlessly forcing the compiler to infer a deref call


text:
Q: Excel 2013 Maximum Number of Rows I understand that Excel 2013 has a limit of 1,048,576 rows (according to Microsoft). Is there a command that returns a Boolean value if the maximum number of rows has been reached? I am making a code that outputs data one row at a time to a worksheet and it may very well exceed the max row limit.

A: It's quite simple:
bEndOfSheet = (counter = Sheet1.Rows.Count)

A: An approach you could combine with the suggestions is to use
ActiveWorkbook.Excel8CompatibilityMode

If this returns true, the active workbook is running on Excel 2003 or prior compatibility mode and limited to 65,536 rows. If false you have 1,048,576 rows available. Example air code:
If ActiveWorkbook.Excel8CompatibilityMode = False Then maxrows = 1048576 Else maxrows = 65536

Then check your output row against maxrows when writing to the sheet.


text:
Q: Can I use the chatter api to bypass the need for salesforce standard stylesheets in my visualforce pages? Can I use the chatter api to bypass salesforce standard stylesheets in my visualforce pages?
Short explanation: I have a chatter group that is set to broadcast only, and is used for posting updates from our organization's CEO to the whole team. I'm having trouble displaying this feed on a visualforce page I've constructed with a custom CSS stylesheet.
@Sean
UPDATE: I added in the styling instead of having a separate sheet because I found it easier to work on. Obviously, some of the code you see will be used on other pages. I tried setting off the entire page (except for the chatter component) in a custom class, but it doesn't work. Ideally, I would like one of my columns or a sidebar to channel some kind of blogging capability.
<apex:page docType="xhtml-1.0-strict" showheader="false" sidebar="false" standardstylesheets="false">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<meta name="keywords" content="" />
<meta name="description" content="" />

    <apex:image url="{!$Resource.erplogo2}" alt="" width="352" height="108"/>

ERP Home

Salesforce

Directory

Calendar

How Do I...?

Team Handbook

Mission Statement

 Mission Statement Here.

News

President's Office Letter to Donors

February 1, 2016

In recent weeks I have met with dozens of your fellow supporters and friends, and the conversations inevitably turn to the horse race that is ... (Read more)

Expense Reports due Friday

February 23, 2016

Don't forget: Your expense report is due Friday, February 26. Click here for a tutorial on how to do it. Log into Concur and Amex from the links at the bottom of this page.

March Birthdays

February 23, 2016

Happy Birthday!

Snoop Dog - March 15

Funky Winkerbean - March 22

Starsky and Hutch - March 30

From the Archives

Gordon Wood at Princeton University, June 17, 2010

Links

<apex:image url="{!$Resource.concur}" width="75" height="18"/>

<apex:image url="{!$Resource.mail}" width="75" height="18"/>

<apex:image url="{!$Resource.flickr}" width="50" height="15"/>

<apex:image url="{!$Resource.amex}" width="75" height="18"/>

Paid Time Off (PTO) Requests

Strategic Plan

Departments

Development

Programs

Events

HR/Finance

Operations

Company Name

</apex:page>

A: What's happening is your custom css is overriding the standard salesforce css.
And what you want to do is to specifically apply your custom css to your custom components only.
In order to do this you'll need to encapsulate them on a custom css class selector that will not affect all components that is not contained within your specified class name.
On my example below, I've used the custom class in order to specifically style both
 and
 tags that are inside div tags that has the custom class.

     Hello!

    I am not affected by your puny css

    Me too!

    Hi!

This is the same concept as namespacing bootstrap in order for it to not override the standard salesforce css. http://scottvonschilling.com/blog/2014/08/using-bootstrap-in-visualforce/
Based from your css, you haven't put the custom css class in your selectors.
Here's a sample how to put your custom class on all of your css attributes. You'll have to add the custom class on each and everyone of your attributes that you're trying to specify on your css.
.custom html,.custom body {
    height: 100%;
}

.custom body {
    margin: 0px;
    padding: 0px;
    background: #F1E9D4 url(images/bg01.jpg) repeat;
    font-family: 'Open Sans', sans-serif;
    font-size: 10pt;
    color: #747474;
}

.custom h1,.custom h2,.custom h3 {
    margin: 0;
    padding: 0;
}
.custom p, .custom ol, .custom ul {
    margin-top: 0px;
}

.custom p {
    line-height: 120%;
}

.custom strong {
}

.custom a {
    color: #706C53;
}

.custom a:hover {
    text-decoration: none;
}

.custom a img {
    border: none;
}

.custom img.border {
}

.custom img.alignleft {
    float: left;
}

.custom img.alignright {
    float: right;
}

.custom img.aligncenter {
    margin: 0px auto;
}

.custom hr {
    display: none;
}

.custom ul.style1
{
    margin: 0;
    padding: 0;
    list-style: none;
}

.custom ul.style1 li
{
    padding: 15px 0px 15px 0px;
    border-top: 1px solid #E5E5E5;
}

.custom ul.style1 a
{
    color: #747474;
}

.custom ul.style1 .first
{
    padding-top: 0;
    border-top: none;
}


text:
Q: Says "package ... does not exist" despite its JAR is inserted I've built Fresco and copied the created *.jar packages into libs folder that is placed in the root directory of ReactAndroid project like the following:
directory setup:
- node_modules
  - ReactAndroid
    - libs
      - drawee-1.3.0-sources.jar
      - fbcore-1.3.0-sources.jar
    - src
      - main
        - java
        - libraries
    - build.gradle

build.gradle file:
...
dependencies {
    ...
    compile (name:'drawee-1.3.0-sources', ext:'jar')
    compile (name:'fbcore-1.3.0-sources', ext:'jar')
    ...
}

allprojects {
    repositories {
        flatDir {
            dirs 'libs', './libs'
        }
    }
}
...

When trying to run the command of ./gradlew installDebug it throws errors for the all classes that are added in *.jar packages like the below:
/node_modules/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/UIViewOperationQueue.java:13: error: package com.facebook.common.logging does not exist

import com.facebook.common.logging.FLog;

However FLog class is present in fbcore-1.3.0-sources.jar package.
(at com/facebook/common/logging/FLog.java path)
Is there any chance to overcome this issue?

Edit:
Using *.aar packages instead of *.jar has solved the issue.


text:
Q: How to find if part of string belongs to a List I have list as follows:
 readonly List<string> carMake = new List<string>
        {
            "Toyota",
            "Honda",
            "Audi",
            "Tesla"
        };

I have a string at runtime which is as follows:
string strOutput = "Project1:Toyota:Corolla";

Now, I will like to use strOutput and carMake to make sure the string as correct car make. How do I do this using Linq?
I want to:

*

*return true when strOutput = "Project1:Toyota:Corolla" (as Toyota is in list)

*return false when strOutput = "Project1:Foo:Corolla" (as Foo is not in the list)

A: Use the Any() method with a predicate to check if any of the strings in the carMake list is contained inside the strOutput:
return carMake.Any(i => strOutput.Contains(i));

OR, if your runtime string will always be in that format, you can split by ':' and compare to the value in the middle:
string runtimeValue = strOutput.Split(':')[1];
return carMake.Contains(runtimeValue);

A: List<string> carMake = new List<string> { "Toyota", "Honda", "Audi", "Tesla" };
string strOutput = "Project1:Toyota:Corolla";

string carBrand = strOutput.Split(':')[1];

bool result = carMake.Contains(carBrand);


text:
Q: PHPUnit mock return value and number of times called with specific argument for different methods same class My scenario is similar to below:
class ToMock
{
    public function iReturn()
    {
        return time();
    }

    public function callMe1($arg1, $arg2)
    {
        return true;
    }

    public function callMe2($arg1, $arg2)
    {
        return true;
    }
}

class ToTest
{
    public function feedMe(ToMock $toMock)
    {
        if ($toMock->iReturn() > 100) {
            $toMock->callMe1(5, 10);
        }

        if ($toMock->iReturn() < 200) {
            $toMock->callMe2(15, 20);
        }
    }
}

Now, I want to test if ToMock::iReturn() returns 150, ToTest::feedMe() calls ToMock::callMe1() once with 5 and 10, and ToMock::callMe2() once with 15 and 20.
I know I can mock the ToMock::iReturn to return 150, also I can mock ToMock to expect a particular method once with supplied argument. But, is it possible to do all of these together in the same time? if yes, how would it look like?

A: If I understood your question correctly then test code could look like
class MockingExpectationsTest extends PHPUnit_Framework_TestCase
{
    private $obj;
    private $mock;

    public function setUp(){
        $this->mock = $this->createMock(ToMock::class);
        $this->obj = new ToTest();
    }

    public function testExpectations(){
        $this->mock->expects($this->exactly(2))
                   ->method('iReturn')
                   ->willReturn(150);
        $this->mock->expects($this->exactly(1))
                   ->method('callMe1')
                    ->with(5, 10);
        $this->mock->expects($this->exactly(1))
                   ->method('callMe2')
                    ->with(15, 20);
        $this->obj->feedMe($this->mock);
    }
}

A: Yes, it is.
Here's an example of a test that covers ToTest:
<?php

use PHPUnit\Framework\TestCase;

class ToTestTest extends TestCase
{
    /**
     * @dataProvider providerTimeBetween0And100
     *
     * @param int $time
     */
    public function testFeedMeWhenTimeIsBetween0And100($time)
    {
        $toMock = $this->createMock(ToMock::class);

        $toMock
            ->expects($this->exactly(2))
            ->method('iReturn')
            ->willReturn($time);

        $toMock
            ->expects($this->never())
            ->method('callMe1');

        $toMock
            ->expects($this->once())
            ->method('callMe2')
            ->with(
                $this->identicalTo(15),
                $this->identicalTo(20)
            );

        $toTest = new ToTest();

        $toTest->feedMe($toMock);
    }

    public function providerTimeBetween0And100()
    {
        return $this->providerTimeBetween(0, 100);
    }

    /**
     * @dataProvider providerTimeBetween101And199
     *
     * @param int $time
     */
    public function testFeedMeWhenTimeIsBetween101And199($time)
    {
        $toMock = $this->createMock(ToMock::class);

        $toMock
            ->expects($this->exactly(2))
            ->method('iReturn')
            ->willReturn($time);

        $toMock
            ->expects($this->once())
            ->method('callMe1')
            ->with(
                $this->identicalTo(5),
                $this->identicalTo(10)
            );

        $toMock
            ->expects($this->once())
            ->method('callMe2')
            ->with(
                $this->identicalTo(15),
                $this->identicalTo(20)
            );

        $toTest = new ToTest();

        $toTest->feedMe($toMock);
    }

    public function providerTimeBetween101And199()
    {
        return $this->providerTimeBetween(101, 199);
    }
    /**
     * @dataProvider providerTimeGreaterThan199
     *
     * @param int $time
     */
    public function testFeedMeWhenTimeIsGreaterThan199($time)
    {
        $toMock = $this->createMock(ToMock::class);

        $toMock
            ->expects($this->exactly(2))
            ->method('iReturn')
            ->willReturn($time);

        $toMock
            ->expects($this->once())
            ->method('callMe1')
            ->with(
                $this->identicalTo(5),
                $this->identicalTo(10)
            );

        $toMock
            ->expects($this->never())
            ->method('callMe2');

        $toTest = new ToTest();

        $toTest->feedMe($toMock);
    }

    public function providerTimeGreaterThan199()
    {
        return $this->providerTimeBetween(200, 300);
    }

    private function providerTimeBetween($min, $max)
    {
        for ($time = $min; $time < $max; ++$time) {
            yield [
                $time
            ];
        }
    }
}

Note how multiple expectations are set up using expects() and further constraints. All of these can be easily combined.
For reference, see:

*

*https://phpunit.de/manual/current/en/test-doubles.html#test-doubles.mock-objects

*https://phpunit.de/manual/current/en/test-doubles.html#test-doubles.mock-objects.tables.matchers


text:
Q: How to keep OS specific configuration for eslint I currently work in a team which uses atom as the editor of choice but split between windows and OSX. Our .eslintrc.js reports the linebreak-style as an issue on windows(Expect line ending to be LF but found CRLF) but works fine on OSX.
Is there a way to specify to eslint that only check this rule while on OSX

A: The purpose of having this rule enabled is to unify the line endings along all the OS and editors. Probably your coworkers that are using Windows have not configured LF (OSX, Linux) line endings in their editors, and have instead CRLF (Windows). This is normally configurable in most editors.
If you want to allow different line endings on Windows, I think the best option is to configure your version control to unify it on commit, like indicated in this post, i.e. text eol=lf in your project's .gitattributes.
Otherwise, as per the comments, a good solution is to create a end_of_line = lf in a .editorconfig file.


text:
Q: Disabling flow for node_modules in a React Native project? I'm getting the error:

SyntaxError /node_modules/react-native-fetch-blob/polyfill/Blob.js:
  Type annotations must come before default assignments, e.g. instead of
  age = 25:number use age:number = 25 (227:50)

I'm assuming this has something to do with flow. But it seems that having flow check node_modules -- code you don't control -- is a bad idea to begin with. How do I go about disabling it for the whole node_modules dir?
I've tried adding .*/node_modules/.* under the [ignore] header in .flowconfig, but that doesn't seem to do the trick.

A: This pull request solves the same issue for react-native-viewpager: https://github.com/race604/react-native-viewpager/pull/97
You can copy that fix over to react-native-fetch-blob if you want to resolve your issue.

A: I posted the issue in git as well, and wkh237 went and fixed the problem. Use version 0.9.5-beta.4 or above and everything works.
You can see the github issue here: https://github.com/wkh237/react-native-fetch-blob/issues/134


text:
Q: Java copy array - reference I have a array int[3][3] with this initial position:
(A)
block[0][0] = 1;
block[0][1] = 1;
block[0][2] = 1;
block[1][0] = 1;
block[1][1] = 1;
block[1][2] = 1;
block[2][0] = 1;
block[2][1] = 0;
block[2][2] = 1;

//Visually
1 1 1
1 1 1
1 0 1

I have a method that takes the "0" element and change with the upper element, so the next state is:
(B)
1 1 1
1 0 1
1 1 1

But the problem is, I want to create a NEW array (called aux) with this positions and DO NOT OVERIDE the block array (A)
Here is my code:
//Creating array B
int[][] aux = new int[3][3];
aux = block; //load the values of original array
aux[line][row] = aux[line-1][row];
aux[line-1][row] = 0;

But when I check the ouput, I have also overridden the original array (block).
So I have the array BLOCK and the array AUX with the same values, and DO NOT kept the array BLOCK with the original data.
===========================================================================
EDIT:
I tried to use the clone and copyOf functions, but the result also affected the original array.
Here is my code:
System.out.println("INITIAL BLOCK VALUES");
            System.out.println(
                            bloco[0][0] +""+
                            bloco[0][1] +""+
                            bloco[0][2] +
                            "\n"+
                            bloco[1][0]+
                            bloco[1][1]+
                            bloco[1][2]+
                            "\n"+
                            bloco[2][0] +
                            bloco[2][1] +
                            bloco[2][2]
                    );

            //Cloning original array to a new one
            int[][] aux = bloco.clone();

            //Here what I'm doing is changing the first element of AUX, just for test
            aux[0][0] = 9;

            // Block array shouldnt be affected! Lets check it out:

            System.out.println("FINAL BLOCK VALUES");
            System.out.println(
                                    bloco[0][0] +""+
                            bloco[0][1] +""+
                            bloco[0][2] +
                            "\n"+
                            bloco[1][0]+
                            bloco[1][1]+
                            bloco[1][2]+
                            "\n"+
                            bloco[2][0] +
                            bloco[2][1] +
                            bloco[2][2]
                    );

And the OUPUT is:
INITIAL BLOCK VALUES
111
111
101
FINAL BLOCK VALUES
911
111
101

any thoughts?
OBS: This code is inside a function of a class called "Node" which contructor is:
public Nodo( int[][] blocos )
        {
            this.bloco = blocos;
        }

A: This Program show The original array is copy into new array without changing original array values
 class Array
 {
public static void main (String[] args) {

   int[][] block = new int[3][3];
 //load the values of original array

  block[0][0] = 1;
  block[0][1] = 1;
  block[0][2] = 1;
  block[1][0] = 1;
  block[1][1] = 1;
  block[1][2] = 1;
  block[2][0] = 1;
  block[2][1] = 0;
  block[2][2] = 1;
  int[] [] aux=new int[3][3];
  for(int i=0;i<3;i++)
  {
for(int j=0;j<block[i].length;j++)
     {
  aux[i][j]=block[i][j];
     }
 System.out.print("\n");
  }
 aux[1][1]=0;//replace array value
 aux[2][1]=1;//replace array value 1
 System.out.print("Old   Array \n");
 for(int i=0;i<3;i++)
 {
for(int j=0;j<block[i].length;j++)
   {
 System.out.print(block[i][j]);
   }
 System.out.print("\n");
 }
 System.out.print("New  Array \n");
 for(int i=0;i<3;i++)
 {
for(int j=0;j<block[i].length;j++)
    {
  System.out.print(aux[i][j]);
    }
       System.out.print("\n");
   }
  }
 }

outpur:Array of aux is
   Old  Array
    111
    111
    101
   New Array
    111
    101
    111


text:
Q: Using jquery from angular directive does not work I am trying to implement jquery-ui's sortable on the elements inside the ng-repeat.
Problem : i cannot actually do the sortable action on the elements inside the ng-repeat.
I've checked for answers. My code seems similar to most answers which apparently work, but my code doesn't work
Below is the html snippet:

                <ng-include src="'views/widget/widget-header.view.client.html'">

                <ng-include src="'views/widget/widget-image.view.client.html'">

                <ng-include src="'views/widget/widget-youtube.view.client.html'">

my app.js:
(function(){
    angular.module("myApp", ['ngRoute', 'myDir']);
})();

below is my custom directive:
(function () {
    angular
        .module("myApp", [])
        .directive("myDir", makeSortable);

    function makeSortable() {
        var directive = {
            restrict : 'ACE',
            link : linker
        };
        function linker(scope, element, attrb) {
            element.sortable();
        }
        return directive;
    }
})();

A: element in linker function args is not jQuery, it is a jqLite wrapper.
If you want to apply jQuery, try this:
$j(element[0]).sortable();


text:
Q: What is the closure of the span of separable functions in $L^2$ Let $X$ denote the space of all finite sums of multiplicative separable functions of two variables, i.e., $X$ consists of functions $f(x_1,x_2)$ of the form:
$$
f(x_1, x_2) = \sum_{k=1}^n g_k(x_1)h_k(x_2).
$$
My question is what is the closure of $X$ in $L^2(\mathbb{R}^2)$?
The above fixes the coordinates $(x_1, x_2)$. If we denote $Y$ as the space of all finite sums of functions each of which is multiplicative separable with respect to some coordinates $(y_1, y_2)$. Then what is the closure of $Y$ in $L^2(\mathbb{R}^2)$?
How about other natural spaces? Is $X$ or $Y$ dense in certain natural spaces?

A: The closure is $L^{2}(\mathbb R^{2})$ because its orthogonal complement is $\{0\}$. If $\iint f(x,y) g(x)h(y)d(x,y)=0$ for all $g , h \in L^{2}(\mathbb  R)$ then  $\int f(x,y)g(x)dx=0$ for almost all $y$. Hence, $f(x,y)=0$ for almost all $x$, for almost all $y$. By Fubini's Theorem this implies that $f=0$ a.e..
This argument works for in $L^{2}(\mu)$.
It may also be noted that if $(e_n)$ and $(f_m)$ are orthonormal bases for $L^{2}(\mathbb  R)$ then $(e_n(x)f_m(y))_{n, m \geq 1})$ is an orhtonormal basis for $L^{2}(\mathbb  R^{2})$.

A: If you want a real sledgehammer approach, the closure is $L^2(\mathbb{R}^2)$ by the Stone-Weierstrass theorem.


text:
Q: CreateFile2, WriteFile, and ReadFile: how can I enforce 16 byte alignment? I'm creating and writing a file with CreateFile2 and WriteFile, then later using readfile with the to read 16 bytes at a time into an __m128i and then performing simd operations on it.  Works fine in debug mode, but throws the access denied (0xc0000005) error code in release mode.  In my experience, that happens when I'm trying to shove non 16-byte-aligned stuff into 16-byte-aligned stuff.  However, I'm unsure where the lack of 16-byte-alignment is first rearing its ugly head.
#define simd __m128i

Is it in the CreateFile2() call?
_CREATEFILE2_EXTENDED_PARAMETERS extend = { 0 };
extend.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
extend.dwFileAttributes = FILE_ATTRIBUTE_NORMAL;
extend.dwFileFlags = /*FILE_FLAG_NO_BUFFERING |*/ FILE_FLAG_OVERLAPPED;
extend.dwSecurityQosFlags = SECURITY_ANONYMOUS;
extend.lpSecurityAttributes = nullptr;
extend.hTemplateFile = nullptr;

hMappedFile = CreateFile2(
    testFileName.c_str(),
    GENERIC_READ | GENERIC_WRITE,
    0,
    OPEN_ALWAYS,
    &extend);

...in the WriteFile() call?
_OVERLAPPED positionalData;
positionalData.Offset = 0;
positionalData.OffsetHigh = 0;
positionalData.hEvent = 0;

bool writeCheck = WriteFile(
    hMappedFile,
    &buffer[0],
    vSize,
    NULL,
    &positionalData);

...in the later ReadFile() call?
const simd* FileNodePointer(
    _In_ const uint32_t index) const throw()
{
    std::vector<simd> Node(8);

    _OVERLAPPED positionalData;
    positionalData.Offset = index;
    positionalData.OffsetHigh = 0;
    positionalData.hEvent = 0;

    ReadFile(
        hMappedFile,
        (LPVOID)&Node[0],
        128,
        NULL,
        &positionalData);

    return reinterpret_cast<const simd*>(&Node[0]);
}

How can I enforce 16-byte-alignment here?
Thanks!

A: TL;DR You have a classic "use after free" error.

None of these functions require 16 byte alignment.  If buffering is enabled, they don't care about alignment at all, and if direct I/O is enabled, they require page alignment which is much more restrictive than 16 bytes.
If your data buffer is unaligned, it's because you created it that way.  The file I/O is not moving your buffer in memory.
But your access violation is not caused by alignment problems at all, it is the dangling pointer you return from FileNodePointer:
return reinterpret_cast<const simd*>(&Node[0]);

That's a pointer into content of a vector with automatic lifetime, the vector destructor runs during the function return process and frees the memory containing the data you just read from the file.


text:
Q: PouchDB detect documents that aren't synced I am trying to sync a local PouchDB instance to a remote CouchDB.  Things work great, but I am not sure how to deal with the following situation:
I have added a validation rule in CouchDB to prevent updating (it will deny all updates).  When I run the sync function on my local PouchDB instance after modifying a document, the "denied" event fires as I would expect.  However, if I run sync a second time, the "denied" event doesn't fire again, even though the local document differs from the CouchDB version.
How can I check if the local database matches the remote database?  If I miss the "denied" event the first time (lets say the user closes the browser), how can I detect on the next run that the databases are not in sync?  How can I force PouchDB to try and sync the modified document again so that I can see the denied event?
Thanks!
syncPouch: function(){
  var opts = {};
  var sync = PouchDB.sync('orders', db.remoteDB, opts);
  sync.on('change', function (info) {});
  sync.on('paused', function(){
  });
  sync.on('active', function () {});
  sync.on('denied', function(err){
    //This only fire once no matter how many times I call syncPouch
    console.log("Denied!!!!!!!!!!!!");
    debugger;
  });
  sync.on('complete', function (info) {
    //This fires every time
    console.log("complete");console.log(info);
  });
  sync.on('error', function(err){
    debugger;
  });
  return sync;
},

A: What I have noticed with validate_doc_update functions is that PouchDb appears to treat any "denied" document as sync-ed. So even if you then remove the validate_doc_update function, the document will not sync into the remote database on future attempts even though it is not the same.
So you can be left with an "out of sync" situation that can only be fixed by editing one of the documents again.
Perhaps you are seeing the same thing? Perhaps the "denied" event does not fire because there is no attempt by PouchDb to sync the document (as it has already attempted to sync it previously)?


text:
Q: Text to speech Speak api is interrupted when talkback is announcing Context:
I am working on Immersive reading of text where user can manipulate reading by clicking forward, rewind, play pause buttons.
For reading text, I am using Google Text to speech engine meanwhile reading we need to highlight words which it is currently reading.
Problem:  [Accessibility Mode]
While reading is in progress, if user had done any swipe or tapped on any control, reading is stopped and contentDescription is being read. When checked on onStop() callback it says utterance is interrupted.
Is there a callback to know whether android is done announcement of contentDescription? I can use that and resume playing/reading text.
Thanks in advance.
Regards,
Venkatesh.

A: There's no way you can get this information from TalkBack, but you may be able to infer it from the TTS api. I suspect the progress listener at least can help you know where you were when you got interrupted.


text:
Q: Problems with GRUB after boot-repair Not so long ago I was asking a question about boot-repair utility aftermath here (because boot-repair logs have linked me to ubuntu site and suggested to ask here if I have any questions), but it didn't get the answer, probabbly because I didn't provide info about what I tried, so here I am reposting it with more info. So basically the original post is here (link). Just wanted to add, what I tried so far: I managed to manually remove old boot option (from my HDD I formatted) from GRUB and now there are only SSD ubuntu and m2 windows are left. But when I tried to remove the boot options from UEFI, they cameback after restarting. I tried to do it from Windows and Linux both (run visual bsd editor and deleted on Windows and run efibootmgr on Linux), but after restarting these boot options come back (options are: ubuntu on nvme and hdd, even tho it's not installed there and old windows boot option from hdd, which got formatted and there's no windows more). What should I do next? Reminding that I also have boot-repair logs, but not sure if they're safe to share, but I can share them if someone says they're safe to share. My disks and partitions look like this right now. Can someone help me out and say what's wrong here?
UPD: Looks like I don't have the logs from boot-repair because I thought they will be saved on ubuntu site, but now they're unaccessible from the link, unfortunately, but I can run commands you tell me to run to provide more info
UPD: I noticed there are 3 efi partitions, one is definitely not the one causing problems, because it's hdd that got formatted. I checked, my Windows runs on EFI that is located on m2 ssd, how can I check this on Ubuntu now? It's strange because before I've did all of that (before my original post), my grub with dual boot was located on ubuntu efi for sure, and I thought when running boot-repair it will keep it the same, but could it be that now grub is on Windows efi and is it normal, how do I change it back to SSD with Ubuntu and should I, how do I get rid of fake boot options now?


text:
Q: Create dissolved buffer from multi-geometry (Union by shared attribute and spatial intersection) I've to create dissolved buffers from multi-point input features. In the example below, the input table contains 4 features. Feature #2 consists of two point geometries. After creating a buffer, I get 4 polygon geometries:

Is there a way to group the result? The buffers of the points #1 and #2 are dissolved and should be a single multi-polygon feature (a).
What I've done so far:
-- collect all buffers to a single multi-polygon feature
-- dissolve overlapping polygon geometries
CREATE TABLE public.pg_multibuffer AS SELECT
    row_number() over() AS gid,
    sub_qry.*
FROM (SELECT
    ST_Union(ST_Buffer(geom, 1000, 8))::geometry(MultiPolygon, /*SRID*/) AS geom
FROM
public.multipoints)
AS sub_qry;

EDIT:
-- create sample geometries

CREATE TABLE public.multipoints (
gid serial NOT NULL,
geom geometry(MultiPoint, 31256),
CONSTRAINT multipoints_pkey PRIMARY KEY (gid)
);

CREATE INDEX sidx_multipoints_geom
ON public.multipoints
USING gist
(geom);

INSERT INTO public.multipoints (gid, geom) VALUES
(1, ST_SetSRID(ST_GeomFromText('MultiPoint(12370 361685)'), 31256)),
(2, ST_SetSRID(ST_GeomFromText('MultiPoint(13520 360880, 19325 364350)'), 31256)),
(3, ST_SetSRID(ST_GeomFromText('MultiPoint(11785 367775)'), 31256)),
(4, ST_SetSRID(ST_GeomFromText('MultiPoint(19525 356305)'), 31256));

A: Starting with some random points, in an attept to imitate those in the OP's image, where the first two spatially intersect, then the 2nd and 3rd have the same attribute id (2), with a couple of other points that neither spatially intersect nor have the same attribute, the following query produces 3 clusters:
WITH
  temp (id, geom) AS
     (VALUES (1, ST_Buffer(ST_Makepoint(0, 0), 2)),
        (2, ST_Buffer(ST_MakePoint(-0.7,0.5), 2)),
        (2, ST_Buffer(ST_MakePoint(10, 10), 2)),
        (3, ST_Buffer(ST_MakePoint(-2, 12), 2)),
        (4, ST_Buffer(ST_MakePoint(5, -6), 2))),
 unions(geoms) AS
      (SELECT ST_Union(geom) FROM temp GROUP BY id),
 clusters(geoms) AS
      (SELECT ST_CollectionExtract(unnest(ST_ClusterIntersecting(geoms)), 3)
         FROM unions),
 multis(id, geoms) AS
      (SELECT row_number() over() as id, geoms FROM clusters)
 SELECT ST_UNION(d.geom) FROM
      (SELECT id, (ST_DUMP(geoms)).geom FROM multis) d GROUP BY id;

There are several steps here:

*

*use ST_Union, grouping by id, to first group by attribute

*use ST_ClusterIntersecting to combine those from same group that intersect spatially

*add an id to each of the clusters (table multis) -- trying to do this directly in the ClusterIntersecting leads to all geometries getting an id of 1

*Union the dumped geometries from step 2, grouping by the id from step 3 -- this is the dissolve part. This causes the two overlapping polygons in your cluster A, to be joined together, rather than being overlapping, as they are at the end of step 2.

Rather long, but it works (and, I am sure there is a shorter way).
Using the WKT tool in QGIS, (and discovering how awful I am with the editing tools) produces clusters like the following, where you can see the cluster your- labelled as a, is all together -- ie, one colour.

If you put an ST_AsText round the final, ST_UNION(d.geom), then you can see the results directly.
EDIT following more information in the comments: As you are starting with points you will need to incorporate the buffer into my original solution -- which I put in the temp CTE at the start to mimic your diagram. It would be easier to add the buffer in the unions CTE, so you can do all the geometries at once. So, using a buffer distance of 1000, as an example, the following now returns 3 clusters, as expected.
WITH temp(id, geom) AS
  (VALUES
      (1, ST_SetSRID(ST_GeomFromText('MultiPoint(12370 361685)'), 31256)),
      (2, ST_SetSRID(ST_GeomFromText('MultiPoint(13520 360880, 19325 364350)'), 31256)),
      (3, ST_SetSRID(ST_GeomFromText('MultiPoint(11785 367775)'), 31256)),
      (4, ST_SetSRID(ST_GeomFromText('MultiPoint(19525 356305)'), 31256))
),
unions(geoms) AS
  (SELECT st_buffer(ST_Union(geom), 1000) FROM temp GROUP BY id),
clusters(geoms) AS
  (SELECT ST_CollectionExtract(unnest(ST_ClusterIntersecting(geoms)), 3)
     FROM unions),
multis(id, geoms) AS
  (SELECT row_number() over() as id, geoms FROM clusters)
SELECT id, ST_UNION(d.geom) FROM
  (SELECT id, (ST_DUMP(geoms)).geom FROM multis) d GROUP BY id;

A: One way to do this is to ST_Union all of the buffers together, ST_Dump the result to get the components of the resulting polygon, and join with ST_Intersects back to the input points to found out how many/which points made up each cluster.
This can be done without requiring a join by grouping the points together before calling ST_Buffer.  For two points to be located within the same dissolved buffer, they must be reachable by hops between points of a distance less than eps.  This is just a minimum-linkage clustering problem, which can be solved using ST_ClusterDBSCAN:
SELECT
  cluster_id,
  ST_Union(ST_Buffer(geom, 1000)) AS geom,
  count(*)                        AS num_points,
  array_agg(point_id)             AS point_ids
FROM (
  SELECT
    point_id,
    ST_ClusterDBSCAN(geom, eps := 2000, minpoints := 1) OVER() AS cluster_id ,
    geom
  FROM points) sq
 GROUP BY cluster_id;

Note that this won't produce exactly the same result as the buffer-first method, because PostGIS buffers aren't perfect circles  and two points 1000m apart may not be connected by two 500m buffers.

A: According to this answer you want to do ST_DUMP within your subquery.
Something like this:
-- collect all buffers to a single multi-polygon feature
-- dissolve overlapping polygon geometries
CREATE TABLE public.pg_multibuffer AS SELECT
    row_number() over() AS gid,
    sub_qry.*
FROM (SELECT
    ST_Dump(ST_Union(ST_Buffer(geom, 1000, 8))::geometry(MultiPolygon, /*SRID*/)) AS geom
FROM
public.multipoints)
AS sub_qry;

The reason why is that ST_UNION returns a dissolved multipolygon of all the features, and ST_DUMP breaks this out into the individual polygon features (which were dissolved).


text:
Q: Django Adding Values to ForeignKey I'm trying to set up a way for users to "watch" certain items (i.e. add items to a list containing other items by other users):
class WatchList(models.Model):
    user = models.ForeignKey(User)

class Thing(models.Model):
    watchlist = models.ForeignKey(WatchList, null=True, blank=True)

How do I add a Thing to a users WatchList?
>>> from myapp.models import Thing
>>> z = get_object_or_404(Thing, pk=1)
>>> a = z.watchlist.add(user="SomeUser")

  AttributeError: 'NoneType' object has no attribute 'add'

How can I add the item to the watchlist? And/or is this the appropriate way to set up my model fields? Thanks for any ideas!

A: z.watchlist is the reference itself, it is not a relationship manager. Just assign:
z.watchlist = WatchList.objects.get(user__name='SomeUser')

Note that this assumes there is only one WatchList per user.

A: As karthikr said you may be getting confused with manytomanyfield, if you really want an intermediary model, you might have something like this:
# Models:
class WatchList(models.Model):
    user = models.ForeignKey(User, related_name='watchlists')

class Thing(models.Model):
    watchlist = models.ForeignKey(WatchList, null=True, blank=True)

# Usage:
user = User.objects.get(name='???') # or obtain the user however you like
wl = WatchList.objects.create(user=user)
thing = Thing.objects.get(id=1) # or whatever
thing.watchlist = wl
thing.save()

# get users watch lists:
user.watchlists
...

Otherwise you might want to extend the user model.


text:
Q: Javascript implicit object creation What's the correct way to initialize an object in this setting:
for(var key in (assoc_array||{other.dict.id: other.dict})){

}

here I get an error that the dot in part "other.object.id" should not be there. So the way that works is:
var default_object = {}
default_object[other.dict.id] = other.dict;
for(var key in (assoc_array||default_object)){
  ...
}

There has to be a way to declare default object implicitly though?

A: I dont think it is possible like that,
you may have to use a function to do it
function createObj(key, val){
    var obj = {};
    obj[key]  = val;
    return val;
}

for(var key in (assoc_array||createObj(other.dict.id, other.dict))){

}

Demo: Fiddle


text:
Q: Using sqlite3 in Tk8.6 To use SQLite3 with Tk8.5 and python, users commonly call the sqlite3 and tkinter modules separately via
from sqlite3 import *
import tkinter as tk

Ever since Tk8.6 was launched with a built-in interface to the SQLite3 database engine, is there a new way to activate SQLite3 directly from tkinter? Or should I continue to use the above import statement to import sqlite3?

A: No, there is no way to activate sqlite3 from tkinter. You need to import tkinter and sqlite3 separately.


text:
Q: Hyphenation when using \verb command I'm having a problem using \verb command.
Usually when I want some verbatim font in the current line (not in a new paragraph) I use the \verb command, not the verbatim environment.
So, when I use something like \verb"HereSomeLongText" no hyphenation is done, so I get my text out of page margins.
How I can get hyphenation inside \verb? Please note that I want inline (inside the same line) verbatim like text.
Here is some minimal (non) working example where you can see the problem described.
\documentclass[a4paper,10pt]{article}
\usepackage[english]{babel}
\usepackage[left=2cm, right=2.2cm,height=25cm]{geometry}

\DeclareFontFamily{OT1}{cmtt}{\hyphenchar \font=`\-}

\begin{document}
\noindent Here is some TeX example of text  that looks nice, but when
I Want to type some text like  \verb"myDataFileLongName.csv" using the
verb command, there is no hyphenation nor like break adequately, so the
text inside the verb command get out of the page margins.

\\[0.25cm] So I would appreciate so much any help in order to solve this
problem. Thanks, thanks,  thanks,  thanks,  thanks,  thanks,  thanks,
thanks,  thanks,  thanks,  thanks,  thanks,  thanks,  thanks,  thanks,
thanks,  thanks,  thanks,  thanks.
\end{document}

A: I can't recommend hyphenating a file name, because this introduces an ambiguity: does the hyphen belong to the name or not?
You may consider using the \path command provided by the url package, by supplementing it with code allowing it to break before capital letters, for instance:
\documentclass[a4paper,10pt]{article}
\usepackage[english]{babel}
\usepackage[left=2cm, right=2.2cm,height=25cm]{geometry}
\usepackage{url,etoolbox}
\appto\UrlSpecials{%
  \do\F{\penalty0 \mathchar`\F }%
  \do\L{\penalty0 \mathchar`\L }%
  \do\N{\penalty0 \mathchar`\N }%
}
\begin{document}
Here is some TeX example of text  that looks nice, but when
I Want to type some text like  \path{myDataFileLongName.csv} using the
verb command, there is no hyphenation nor like break adequately, so the
text inside the verb command get out of the page margins.

\end{document}

I didn't add all capital letters, do it if you want, or judge from your real cases what's the real need.

The \path command (and also \url) works by cleverly exploiting TeX's math mode features. It would be too long to describe completely how it works; for this application, we can make use of the \UrlSpecials list macro; the characters contained in the list are made (locally) math active and so their appearance triggers substitution with the prescribed replacement text.
With the proposed code, F will become \penalty0 \mathchar`\F (saying \penalty0 F would enter an infinite loop, but \mathchar`\F is safe): the penalty will allow a line break before the F.
If you don't want to globally modify the \path command, you can add to the \UrlSpecials list only locally inside the working of a new command.
\documentclass[a4paper,10pt]{article}
\usepackage[english]{babel}
\usepackage[left=2cm, right=2.2cm,height=25cm]{geometry}
\usepackage{url,etoolbox}

\let\breaktt\path
\patchcmd{\breaktt}
  {\begingroup}
  {\begingroup\apptourlspecials}
  {}{}
\newcommand{\apptourlspecials}{%
  \appto\UrlSpecials{%
    % add to this list
    \do\F{\penalty0 \mathchar`\F }%
    \do\L{\penalty0 \mathchar`\L }%
    \do\N{\penalty0 \mathchar`\N }%
  }%
}
\begin{document}
Here is some TeX example of text  that looks nice, but when
I Want to type some text like  \breaktt{myDataFileLongName.csv} using the
verb command, there is no hyphenation nor like break adequately, so the
text inside the verb command get out of the page margins.

\end{document}

The command \path expands to \leavevmode\begingroup\urlstyle{tt}\Url, so we define \breaktt to do the same but we also add something just after \begingroup, precisely the addition to the list \UrlSpecials we need. In this way \path and \url will behave as before.

A: You can force hyphenation by using \texttt instead of \verb:
\documentclass[a4paper,10pt]{article}
\usepackage[UKenglish]{babel}
\begin{document}
Here is some TeX example of text that looks nice, but when
I type \verb!Sonification! using the
verb command, there is no hyphenation nor like break adequately, so the
text inside the verb command get out of the page margins.

Here is some TeX example of text that looks nice, but when
I type \texttt{Soni\-fi\-cation} using the
verb command, there is no hyphenation nor like break adequately, so the
text inside the verb command get out of the page margins.
\end{document}


text:
Q: IntelliJ directories error class not found I'm fairly new to IntelliJ and I have tried making a hello world program in some other directory other than ~/IdeaProject. When I did so although my code is correct it gives me ClassNotFoundException. But when I copy the files into ~/IdeaProject and open the project from that directory, I can run it just fine and it isn't from my code since I tried different ones and I already uninstalled and installed IntelliJ and still got the same result anybody can tell me why?
Any help is greatly appreciated!
Update: I can run my codes fine in all directories except a directory called: /Course Material/Week 2/Web Server: Reflection/
I can also run my program from command line in that directory and it works fine I suppose the problem is with IntelliJ.
 ~/U/S/I/C/W/W/untitled folder> ls
out/                 src/                 untitled folder.iml
 ~/U/S/I/C/W/W/untitled folder>
cd src/com/company/
 ~/U/S/I/C/W/W/u/s/c/company> ls
Main.java
 ~/U/S/I/C/W/W/u/s/c/company> javac
Main.java
 ~/U/S/I/C/W/W/u/s/c/company> cd ../..
 ~/U/S/I/C/W/W/u/src [1]> java
com.company.Main
write your code here

Does anybody have any idea why?
simple program in the stated directory
same program  in the relative path ../

A: Your project is not properly initialized and IntelliJ sees the classes as just plain files in ordinary folders and not as a project which classes interact with each other.
Start by creating a new project through File → New → Project, define your project in a way that suits your needs and after the setup is complete copy your classes under src/main/java. This is default, but basically your main classes need to be under a folder which is marked as "Sources Root". Afterwards you can also doublecheck if your SDK is configured properly (File → Project Structure → SDKs) and if you're using the correct language level in your project(File → Project Structure → Modules → Language Level).

A: The problem was that I had a '/' (slash) in my file name which intelliJ replaced with ':' when I changed the slash the errors went away.


text:
Q: For what $m,\ k$ values does this series converge?
$\sum_{n=1}^{\infty}{\sqrt[m]{n!}\over{\sqrt[k]{(2n!)}}}$

I am inclined to think that factorial type questions are best solved with the ratio test. I was able to reach the following:

$\frac{a_n+1}{a_n} =...= \frac{\sqrt[m]{n+1}}{\sqrt[k]{(2n+1)(2n+2)}} = \frac{\sqrt[m-k]{n+1}}{\sqrt[k]{2(2n+1)}}  $

How do i find which $k,\ m$ values make the sum converge/diverge?

A: Hint:Use the fact that $$\sum \frac {1}{n^k}$$ converges iff $k>1$  where $k$ is not necessarily integer.


text:
Q: How to capture a MultibodyPlant's geometry hierarchy in an output port's callback I have a system consisting of a MultibodyPlant (and scene graph), which loads an iiwa manipulator from a URDF file, and a LeafSystem that is creating ROS TF messages corresponding to the geometry stored in the MultibodyPlant.
The LeafSystem has an input port that receives a graph query object, and an output port that produces ROS TF messages. The input port is connected to the scene graph's graph query port. The output port is connected elsewhere, which is not relevant to my problem.
The LeafSystem's output port's value is calculated by this callback. It inspects the scene graph and creates a TF frame for every frame in the scene graph.
The problem I'm having is that the scene graph has no knowledge of the hierarchical relationship between bodies in the MultibodyPlant. This means that the TF messages produced contain a set of frames that are all rooted in the world frame. I would like to instead have them reflect the actual hierarchy of joints and links that is in the URDF. The MultibodyPlant has this information. What architecture or ports should I use to make the information available in my LeafSystem's output port value-calculating callback?
Can the solution to this be generic to any system that contains geometry, or does it only make sense for a MultibodyPlant? (I may not be understanding systems correctly here - I'm relatively new to Drake.)


text:
Q: ¿Cómo encriptar una variable php en un link? Tengo este código:
<?php
//...
// me busca el nombre de una varible que viene por el metodo get y me da un id que es una url del archivo de streaming
$canal = array_search($nombre, $array);
//...

Reproductor de video
<script src="http://btcmax.me/chanel/repro/build/jquery.js"></script>
<script src="http://btcmax.me/chanel/repro/build/mediaelement-and-player.min.js"></script>

<link rel="stylesheet" href="http://btcmax.me/chanel/repro/build/mediaelementplayer.min.css"/>
<link rel="stylesheet" href="http://btcmax.me/chanel/repro/build/mejs-skins.css"/>

<video autoplay="true" width="700" height="450" id="player1">
    <!-- Pseudo HTML5 -->
    <source type="application/x-mpegURL" src="<?php echo $canal; ?>"/>
</video>

<script>
    $('audio,video').mediaelementplayer({
        success: function (player, node) {
            $('#' + node.id + '-mode').php('mode: ' + player.pluginType);
        }
    });
</script>

Este código funciona bien, lo que quiero es que al dar ctrl + U a la página web no muestre el valor de la variable, para que no me tomen la url y lo usen en otras web sin mi permiso.
Espero haberme explicado bien, no soy programador solo estoy aprendiendo por mi cuenta por Internet.

A: Lo que tienes que hacer es:

*

*Crear una función que encripte el código de la variable y ese código sea el que se muestre en el enlace.

*Cuando el usuario entre a ese enlace sera redirigido, supongamos a http:://tupagina/link.php?adfake234dfae2.

*Cuando el usuario accese supongamos a esta URL link.php? este archivo link.php recibirá lo que está encriptado que es adfake234dfae2, lo deberá transformar en una URL válida. Algo como http://tupagina/video1.html y redirigirá.

Es la única forma que se me ocurre, si no quieres utilizar PHP porque solo quieres cargar el contenido en una sola página, tu código de encriptación y desencriptación tendrás que hacerlo con JavaScript, pero el contenido final sí se verá.


text:
Q: Entity Framework and Anonymous Types in F# Trying to get a query with an anonymous type working:
let temporaryBookModel =
  query <@ context.Books
    |> Seq.filter (fun book -> book.Id = bookId)
    |> Seq.map(fun item -> (item.Id, item.ParentUser.Id, item.ParentUser.Alias, item.Tagline, item.Title, item.Visible, item.CreatedDate))
    |> Seq.head @>

And I keep getting:

{"Only parameterless constructors and initializers are supported in
  LINQ to Entities."}

Which would make sense if I were mapping the values to a type directly, but anonymous types shouldn't throw this exception I would think since they are based on the object initializer functionality?  Unfortunately anything I found on anonymous types seem to say this is the correct syntax.  That or something like this:
let temporaryBookModel =
  query <@ context.Books
    |> Seq.filter (fun book -> book.Id = bookId)
    |> Seq.map(fun item -> (("a", item.Id), ("b", item.ParentUser.Id), ("c", item.ParentUser.Alias), ("d", item.Tagline), ("e", item.Title, item.Visible), ("f", item.CreatedDate)))
    |> Seq.head @>

A: Does F# supports anonymous types?
As I know - it doesn't. But there are 2 possible ways for workarounds:

*

*use tuples (as you're using)

*use record types, but in this case you'll need to define record before. Something like this:

type Book =
    {
        Id: int;
        ParentId: int;
        ParentAlias: string;
        TagLine: string;
        Title: string;
        Visible: bool;
        CreatedDate: DateTime;
    }

And usage code line will looks like:
...
|> Seq.map
    (fun item ->
        {
            Id = item.Id;
            ParentId = item.ParentUser.Id;
            ParentAlias = item.ParentUser.Alias;
            TagLine = item.Tagline;
            Title = item.Title;
            Visible = item.Visible;
            CreatedDate = item.CreatedDate
        })

More explanations you can find in similar question here
Update:
Record types usage as for me is more elegant solution, BUT it looks like it doesn't not work with Entity Framework - F# -> Record with parameterless constructor?.
So according to Tomas Petricek answer - it has to be declared explicit type with parameters less constructor and necessary properties.

A: I don't have EF setup or your model but using the new F# 4.6 Anonymous Records feature this example which is very close to what you were attempting should work.
open System
open System.Linq

type Parent = {
    Id: int;
    Alias: string;
}

type Book = {
    Id: int;
    ParentUser: Parent;
    Tagline: string;
    Title: string;
    Visible: bool;
    CreatedDate: DateTime }

[<EntryPoint>]
let main argv =

    let books = [| { Id = 1; ParentUser = { Id = 1; Alias = "ParentBook"; }; Tagline = "BattaBoom"; Title = "clear"; Visible = true; CreatedDate = DateTime.UtcNow }|]

    let bookId = 1

    let res =
        books
        |> Seq.filter (fun book -> book.Id = bookId)
        |> Seq.map(fun item -> {| Id = item.Id; ParentId = item.ParentUser.Id; ParentAlias = item.ParentUser.Alias; Tagline = item.Tagline; Title = item.Title; Visible = item.Visible; CreatedDate = item.CreatedDate |})
        |> Seq.head

    printfn "result %A" res

    0 // return an integer exit code

Notice the use of the | character on the insides of the curly braces of the anonymous record. This is what now distinguishes regular records from anonymous records in F#. Additionally in the example above notice that the property names in the Anonymous Record type need to be specified explicitly as unlike in C# the property names are not implicit based on their source property/field from the assignment. The feature to allow for implicit property names is suggested as a followup change in future language specifications.


text:
Q: Best practice of implementing javascript promise Hi guys I am pretty new to js and asynchronous programming. I use node.js and express to start learning js serverside and asynchronous programming. I have probleom to implement something like callback promise async. I had used callback but I think my code becomes so messy and hard to maintain. Now I try to implement promise in my code below. My question is: do the way I use promise there is a good practice? Cause I think There's no different comparing to callback hell if I implement "nested" promise like my code below. How is the best practice of using promise? Thank you
update_data_profil(req, res) {
        var nama_unit_org = req.body.nama_unit_org;
        var nama_ketua_unit_org = req.body.nama_ketua_unit_org;
        var nip_nim = req.body.nip_nim;
        var email = req.body.email;
        var no_hp = req.body.no_hp;
        var params;
        var user;
        if (helper.isExist(nama_unit_org) && helper.isExist(nama_ketua_unit_org) && helper.isExist(email)
            && helper.isExist(nip_nim) && helper.isExist(no_hp)) {
            if (nip_nim !== req.user.nip_nim) {
                params = {
                    nip_nim: nip_nim
                }
                user = new User_Model(params);
                user.getDataProfilByNIPorNIM()
                    .then(function (result) {
                        if (result) {
                            req.flash('message_err', "NIP/NIM telah dipakai akun lain.");
                            res.redirect('/manajemen_profil');
                        }
                        else {
                            params = {
                                id_user: req.user.id_user,
                                nip_nim: nip_nim,
                                nama_ketua_unit_org: nama_ketua_unit_org,
                                nama_unit_org: nama_unit_org,
                                email: email,
                                no_hp: no_hp,
                            };
                            user = new User_Model(params);
                            user.editDataProfil()
                                .then(function () {
                                    params = {
                                        session_id: req.sessionID
                                    };
                                    user = new User_Model(params);
                                    user.clearSession()
                                        .then(function () {
                                            req.flash('message_success', 'Edit data profil berhasil. Silahkan login untuk melanjutkan');
                                            res.render('index/login',
                                                {
                                                    message_success: req.flash('message_success')
                                                });
                                        }).catch(function (err) {
                                            req.flash('message_err', "Internal server error");
                                            res.redirect('/');
                                        });
                                })
                                .catch(function (err) {
                                    req.flash('message_err', "Internal server error.");
                                    res.redirect('/');
                                });
                        }

                    }).catch(function (err) {
                        req.flash('message_err', "Internal server error.");
                        res.redirect('/');
                    })
            }
            else {
                params = {
                    id_user: req.user.id_user,
                    nama_ketua_unit_org: nama_ketua_unit_org,
                    nama_unit_org: nama_unit_org,
                    email: email,
                    no_hp: no_hp
                };
                user = new User_Model(params);
                user.editDataProfil()
                    .then(function () {
                        req.flash('message_success', "Berhasil update profil.");
                        res.redirect('/manajemen_profil');
                    })
                    .catch(function (err) {
                        req.flash('message_err', "Internal server error");
                        res.redirect('/manajemen_profil');
                    });
            }
        }
        else {
            req.flash('message_err', "Tidak boleh ada field yang kosong!");
            res.redirect('/manajemen_profil');
        }
    }

A: One of the most beautiful advantages of Nodejs promises is to avoid the callback hell process. And with promises, if you are again nesting one inside the other then you are creating a promise hell ;) .
Below is one of the better approach to use promises.
Chaining:
 // Promises example using 'then'
user.getDataProfilByNIPorNIM().then(function(user) {
    ...
    return user.editDataProfil();
}).then(function(editDataProfilResults) {
    ....
    return user.clearSession();
}).then(function(clearSessionResult) {
   ....
   return
}).catch(function(err){
   .....
   process error
})

I have come across below link, which explain usage of promises. It might be helpful.
https://www.joezimjs.com/javascript/javascript-asynchronous-architectures-events-vs-promises/

A: For now best practice is to use async/await.

The word async before a function means it always returns a promise. If the code has return
   in it, then JavaScript automatically wraps it into a
  resolved promise with that value.
The keyword await makes JavaScript wait until that promise settles
  and returns its result.

It makes code pretty and easy to handle.
It is quite simple to use, as you can see on following links.
Link 1.
Link 2.
Link 3
Example:
 async function getData(url) {
  let v;
  try {
    v = await downloadData(url);
  } catch(e) {
    v = await downloadFail(url);
  }
  return processAnother(v);
}

or you can use it like :
async FunctionFun( ) {

  const groups = await this.variableGroupsService.find();

  const groups2 = await this.pageMarkersService.find();

  const groups3  = await this.funnelStepsService.findFunnelSteps()

  return anyOtherFunction(groups, groups2, groups3);

  }

A: I'd say best practice as of 2018 is to use async/await instead of using promises in this way.
This article from MDN gives some good examples of how they can be used.
To give a very simple example, a small part of your code using promises:
user.getDataProfilByNIPorNIM()
    .then(function (result) {
        if (result) {
            req.flash('message_err', "NIP/NIM telah dipakai akun lain.");
            ...
    });

could be rewritten as:
try {
    const result = await user.getDataProfilByNIPorNIM();
} catch(e) {
    // catch errors here.
}

To briefly quote the abovementioned article:

An async function can contain an await expression that pauses the execution of the async function and waits for the passed Promise's resolution, and then resumes the async function's execution and returns the resolved value.

This feature has become a fundamental part of how asynchronous development in Javascript is done in 2018, and I'd personally say it's a de-facto standard.


text:
Q: Letting every user mount a partition I can mount a partition with
sudo mount -t ntfs -U "G9E575D9C8EA4" /media/pierrebenoir/wpartition.
In my /etc/fstab I have
UUID="G9E575D9C8EA4" /media/pierrebenoir/wpartition ntfs user,exec,noauto,rw,sync         0       0.
I hoped that this would let me mount this partition when needed, without sudo. But no, when I click on the partition through Nautilus, I get the message that I'm not authorized to perform this operation. I thought the 'noauto' and the 'user' bits would imply that the partition does not get mounted by start-up, but can be mounted by a normal user.

A: AutoFS is designed to solve this problem.  Take a look at it here: https://wiki.archlinux.org/index.php/autofs


text:
Q: Understanding of Example of Linear Independent Lemma. The two functions $e^{t},e^{2t}$ are linearly independent. To prove this, suppose that there are numbers $a,b$ such that $ae^{t}+be^{2t}=0$ (for all values of $t$). Differentiate this relation. We obtain
$ae^{t}+2be^{2t}=0$
Subtract the first from the second relation. We obtain $be^{2t}=0$, and hence $b=0$. From the first relation, it follows that $ae^{t}=0$, and hence $a=0$. Hence, $e^{t},e^{2t}$ are linearly independent.
My question that why did we differentiate of this equation?

A: We differentiate to prove the linear independence of these functions. That is the functions you have provided are $e^t$ and $e^{2t}$. One (relatively simple) way to prove its linear independence is to just differentiate since it results in a simple expression that is equivalent and equally powerful in showing that $a, b$ must both $0$. That is that:
$$\frac{dae^t + be^{2t}}{dt} = \frac{d0}{dt}$$
Of course, there are many other ways to prove its linear independence, this is just one way and probably the most easiest to use. If we continually differentiate, we can show that $a = b = 0$


text:
Q: Convert pd dataframe into list I've this txt input:
["A" "B" "C" "D"]
[8 3 6 11]
[5 7 4 3]
14

I read the file by using:
df = pd.read_csv("data.txt", header = None, engine = 'python')

Then, I would like to convert this dataframe into lists.
I've tried to do this:
L = df[0].iloc[0]
>>> '["A" "B" "C" "D"]'

But then, if I want to get the first value, the output is
L[0]

>>> '['

I've already tried to do
ast.literal_eval(L)

without sucess. I get:
['ABCD']

Any suggestion?
Thanks!

A: You can use Series.str.strip with Series.str.split:
df['new'] = df[0].str.strip('[]').str.split()
print (df)
                   0                   new
0  ["A" "B" "C" "D"]  ["A", "B", "C", "D"]
1         [8 3 6 11]         [8, 3, 6, 11]
2          [5 7 4 3]          [5, 7, 4, 3]
3                 14                  [14]

If mixed data are necessary - lists with scalar(s) add Series.mask for apply solution only for values starting by [ checked by Series.str.startswith:
df['new'] = df[0].mask(df[0].str.startswith('['), df[0].str.strip('[]').str.split())
print (df)
                   0                   new
0  ["A" "B" "C" "D"]  ["A", "B", "C", "D"]
1         [8 3 6 11]         [8, 3, 6, 11]
2          [5 7 4 3]          [5, 7, 4, 3]
3                 14                    14


text:
Q: ResourcesNotFoundException I have a value in my dimens.xml defined as follows:
<dimen name="input_text_width">250dp</dimen>

I want to use it to dynamically size the width of a TextView, as follows:
tv.setWidth(activity.getResources().getInteger(R.dimen.input_text_width));

The resource exists (checked in R.java). I have run "clean" on my project more than once. Why do I keep getting this exception?
android.content.res.Resources$NotFoundException: Resource ID #0x7f050012 type #0x5 is not valid

A: I have taken this from Android Docs
<?xml version="1.0" encoding="utf-8"?>
<resources>
   <dimen name="textview_height">25dp</dimen>
   <dimen name="textview_width">150dp</dimen>
   <dimen name="ball_radius">30dp</dimen>
   <dimen name="font_size">16sp</dimen>
</resources>

And in code
//Retreive dimension
Resources res = getResources();
float fontSize = res.getDimension(R.dimen.font_size);

In your xml
<TextView
android:layout_height="@dimen/textview_height"
android:layout_width="@dimen/textview_width"
android:textSize="@dimen/font_size"/>

I hope this will help!

A: You have to get the dimension pixels...
int size = activity.getResources().getDimensionPixelSize(R.dimen.input_text_width);
textView.setWidth(size);

A: Might it be because you use :
activity.getResources().getInteger(R.dimen.input_text_width)

Instead of :
activity.getResources().getDimension(R.dimen.input_text_width);


text:
Q: Change component when button is clicked reactjs I am trying to change the component after button is clicked. I have defined a changeComp() function in the class of my component and when the button is clicked I want to route it to the wallet-connect component but it doesnt seem to work. Kindly, help me out what am I missing here or why this practise is wrong?
changeComp(){
return (
            <Router>
                <Switch>
                    <Route exact path="/wallet-connect" component={WalletConnect} />
                </Switch>
            </Router>
        );}

<button className="btn w-100 mt-3 mt-sm-4" onClick={(event) => this.changeComp(event)} type="submit">Sign In</button>

A: changeComp(){

const history = useHistory();

return (
            <Router>
                <Switch>
                    <Route exact path="/wallet-connect" component={WalletConnect} />
                </Switch>
            </Router>
<button className="btn w-100 mt-3 mt-sm-4" onClick={(event) => history.push("/wallet-connect")} type="button">Sign In</button>
        );}

A: You can't return JSX from an event handler and expect it to be rendered into the DOM.
In your case you need to render the "/wallet-connect" Route into your main router and in the changeComp callback invoke an imperative navigation.
Main router:
<Switch>
  ...
  <Route path="/wallet-connect" component={WalletConnect} />
  ...
</Switch>

In component with button:
changeComp(event) {
  this.props.history.push("/wallet-connect");
}

<button
  className="btn w-100 mt-3 mt-sm-4"
  onClick={(event) => this.changeComp(event)}
  type="submit"
>
  Sign In
</button>

If the component doesn't have the route props injected then you'll need to decorate it with the withRouter Higher Order Component.
Suggestion:
Since the button is a type="submit" and if it's rendered within a form, then just issue the imperative navigation from the form's onSubmit handler.
submitHandler = event => {
  event.preventDefault();
  ...
  this.props.history.push("/wallet-connect");
}

...

<form onSubmit={this.submitHandler}>
  ...
  <button
    className="btn w-100 mt-3 mt-sm-4"
    type="submit"
  >
    Sign In
  </button>
</form>

If the button is not part of a form then specify the button type to be a "button" so it doesn't interfere with any form elements.
<button
  className="btn w-100 mt-3 mt-sm-4"
  onClick={(event) => this.changeComp(event)}
  type="button"
>
  Sign In
</button>


text:
Q: wkhtmltopdf anchor text having HTML. issue wkhtmltopdf 0.12.3.2 (with patched qt) -- Windows 8
If I include some html inside anchor tag then the generated pdf doesn't make it clickable.
e.g
TreeMap!

Command : wkhtmltopdf.exe --enable-internal-links D:\A.html D:\test.pdf
Can anyone help me in this regard ?
----------------------- HTML -----------------------
<!DOCTYPE html>

<meta charset="utf-8">

TreeMap!

nbsp
Bar Chart!

nbsp
Text Chart !

PieChart

------------------------END-------------------------


text:
Q: Significant runtime increase after employing list::size() I have a huge code size. I recently added some new code and it works fine until I added a new simple if statement. After adding this add statement the runtime increases by 100X which is nonsense.
Some part of my code is below. The if statement is added in terminate_ongoing function and even if I remove everything inside if statement, the program is still slow. But if I comment this if statement, it becomes fast again.
The if statement is
if ( emitted_vulnerable_list.size() > 100000 ){
}

As you can see, I removed everything inside if, but the problem is not resolved. Could you please provide some hints to find the source of problem and solve it.
class flip_flop_vulnerable_time{
public:
   list <vulnerable_time> emitted_vulnerable_list;
   list <vulnerable_time> ongoing_vulnerable_list;

   void terminate_ongoing(int PO, int minimum_delay , int cycle, long long elimination_time){
     for (list<vulnerable_time>::iterator it=ongoing_vulnerable_list.begin(); it!=ongoing_vulnerable_list.end(); it++){
       if ( it-> PO_signal_number == PO && it->cycles_passed == cycle && it->min_delay == minimum_delay ){
         it-> elimination_time = elimination_time;
         if ( cycle == 0 && elimination_time - it->appearance_time < 500 )
           ongoing_vulnerable_list.erase(it);
         else{
           emitted_vulnerable_list.splice(emitted_vulnerable_list.end(),ongoing_vulnerable_list, it);
           if ( emitted_vulnerable_list.size() > 100000 ){
           }
         }
         return;
       }
     }
     cout<<"\tError: can't find the following ongoing vulnerable_time object"<<endl;
     exit(0);
   }

   // Some other functions here
};

A: The list::size() implementation in gcc is of O(n) and in huge lists, calling this function multiple times might be very time consuming.

A: the problem with list::size() is that you are using list::splice(), and there is no way to track list sizes unless moved items are counted. but it doesn't look that hard to track the sizes manually using two variables.


text:
Q: SVG Path Intersection in html page So, I'm trying to find the intersection of an SVG path with an another path or svg element. I have tried some APIs like https://github.com/amatiash/svg.intersections.js#module_SVGIntersections and https://github.com/signavio/svg-intersections. But i think svg.intersection.js requires SVG objects but i have SVG predefined in my html page so i am not able to use functions of API. Is there anyway i can find intersection easily.
I have also added an image to make it clear like i want to stop these intersection between black and green, red and green stripes(these are svg paths) also i will be really helpfully if you can tell me any way to stop the intersection of the obj(.png) and svg path( i.e., battery and green line).


text:
Q: A smooth map which has full rank at a point is locally a submersion/immersion. Let $F:M\rightarrow N$
  be a smooth map between manifolds and let $p\in M$
 .

*

*If $dF_{p}$
is surjective, then there exists a neighbourhood $U$
of p
such that $F|_{U}$
is a submersion.

*If $dF_{p}$
is injective, then there exists a neighbourhood $U$
of $p$
such that $F|_{U}$
is an immersion.
I saw this theorem in Lee's Introduction to Smooth Manifolds. This is his proof:

What I don't understand is the part where says "by continuity". Is he talking about a function that is continuous? If so, what function is it?

A: In coordinates, $\Bbb d F$ is represented by a matrix. Since $\Bbb d F _p$ has full rank, there exists a minor in it of maximal dimension that is non-zero at $p$. The determinant of this minor is a continuous (in fact polynomial, being a sum of products of entries in the matrix) function of the coordinates, so if it's non-zero at $p$, by continuity it will be non-zero on some small neighbourhood of $p$, so the rank will be maximal on this neighbourhood.

A: Suppose $U$ is a coordinate neighbourhood of $p$ in $M$, contained in the preimage under $F$ of a coordinate neighbourhood of $F(p)$ in $N$. We have a continuous map
$$ x \in U \subset \mathbb R^n \mapsto (dF)_x \in {\rm M}(n \times m , \mathbb R).$$
(Of course, I used the coordinate charts to identify $U$ with $\mathbb R^n$ and to identify the respective tangent spaces with $\mathbb R^n$ and $\mathbb R^m$.)
Since $F$ is a submersion at $x = p$, we know that the $n \times m$ matrix $(dF)_x$ is of maximal rank at $x = p$. Said another way, at least one of the $m \times m$ submatrices of $(dF)_p$ has non-vanishing determinant.
This suggests that we should consider the map $g : U  \to \mathbb R^{\frac{n!}{m!(n-m)!}}$
that sends each point $x \in U$ to an $\frac{n!}{m!(n-m)!}$-component vector containing the determinants of all $m \times m$ submatrices of $(dF)_x$. Clearly $g$ is also continuous.
Finally, $g(p) \neq 0$. By continuity of $g$, there is an open neighbourhood $V \subset U$ of $p$ such that $g(x) \neq 0$ for all $x \in V$. This means that, for all $x \in V$, the matrix $(dF)_x$ has at least one $m \times m$ submatrix with non-vanishing determinant. So the original $F$ is a submersion on $V$.


text:
Q: rails join of a join (rails 2.3.5 and ruby 1.8.7) I have
data_records, brands and influencers
data_records have many brands
data_records have 1 influencer
brands have many influencers via brand_influencers association which has an attribute called top (boolean).
here are my models:
class DataRecord < ActiveRecord::Base
  belongs_to :influencer
  has_and_belongs_to_many :brands
end

class Brand < ActiveRecord::Base
 has_and_belongs_to_many :data_records
end

class Influencer < ActiveRecord::Base
  has_many :brands_influencers
  has_many :brands, :through => :brands_influencers
end

class BrandsInfluencer < ActiveRecord::Base
  belongs_to :brand
  belongs_to :influencer
end

I would like to do one query to get all data_records for a given brand where the influencers are in the brands top influencers (top = true).
I need to start on the data_record model because there are other dynamic queries that can be bolted on to this query (this is a typical big filter type screen).
So my question, is it possible to join in a realtionship of a join. I have used joins brands and it works fine, but I cant figure out a way to join in the brand_influencers relationship
thanks
Joel

A: The rails 2.3.5 version of it is,
DataRecord.find :all, :conditions => ['brands.name = ? AND influencers.top = ?', 'name', true], :joins => {:brands => :influencers}

I am supposing there's a name for a brand and you're looking for the brand by name. And you need to change Brand like this:
class Brand < ActiveRecord::Base
    has_and_belongs_to_many :data_records
    has_and_belongs_to_many :influencers
end

A: Sounds like you want to use
has_many :foos, :through=>:bar

or
has_one :foo, :through=>:bar

Try this:
class DataRecord < ActiveRecord::Base
  # how does this relate to the other models?
end

class Brand < ActiveRecord::Base
 has_and_belongs_to_many :influencers
end

class Influencer < ActiveRecord::Base
  has_and_belongs_to_many :brands
end

class BrandsInfluencers < ActiveRecord::Base
  # notice the name change in this class (pluralization)
  belongs_to :brand
  belongs_to :influencer
end

A: You can get a join from another and reference them in a where like this:
DataRecord.joins(:influencers => {:brand_influencers}, :brands).
  where(:brands => {:id => 123}).
  where(:brands => {:brand_influencers => {:top => true}})

I'm pretty sure it works similarly in 2.3.x. Try this:
DataRecord.joins(:influencers => {:brand_influencers}, :brands).
  conditions(:brands => {:id => 123}).
  conditions(:brands => {:brand_influencers => {:top => true}})

I would suggest you build up the relation bit by bit and check the SQL that's being generated. Good luck!