Q: Mail Alert when threshold of 10000 pendingcmds are breached I currently have the below running to monitor replication and send a mail when the threshold of 10000 pendingcmds are breached, however the alert mail is generated every 5 minutes regardless of the threshold. I need assistance to re-code the threshold part as this is not delivering the expected results.
        DECLARE @RESULT nvarchar(100)
        DECLARE @cmd varchar(100)

        SET @RESULT = ('SELECT pendingcmdcount FROM #pendingcmds')
        EXEC sys.sp_executesql @RESULT
        PRINT @RESULT
        IF @RESULT > '10000'

Code used to generate alert
        USE [TestDB]

        create table #pendingcmds
        (pendingcmdcount int,
        estimatedprocesstime int)

        Insert INTO #pendingcmds (pendingcmdcount, estimatedprocesstime)
        select * FROM OPENROWSET('SQLOLEDB',
        'Server=Server\Instance;Trusted_Connection=yes;',
        'set fmtonly off;
        exec distribution..sp_replmonitorsubscriptionpendingcmds
        @publisher=''Server\Instance'',
        @publisher_db=''testproduction'',
        @publication=''Summary_Inventory_TestProduction'',
        @subscriber=''Server'',
        @subscriber_db=''TestReplAzure'',
        @subscription_type=0')

        SELECT * FROM #pendingcmds

        --DECLARE @RESULT nvarchar(100)
        ----DECLARE @cmd varchar(100)
        --
        --SET @RESULT = ('SELECT pendingcmdcount FROM #pendingcmds')
        --EXEC sys.sp_executesql @RESULT
        --PRINT @RESULT
        --IF @RESULT > '10000'
        --
        --BEGIN

         /*************************************************************/
         /****************** HTML Preparation *************************/
         /*************************************************************/

        DECLARE @HTML  VARCHAR(MAX),
                @table VARCHAR(MAX)

        SET @HTML = --HTML layout--
                        '' +
                        '
Publisher to Subscriber has exceeded threshold
' +
                        '' +
                        '' +
                        '
' +
                        '
'+
                        'Pending CMD Count	' +
                        'Estimated Process Time
';

        SELECT @table = CONVERT(nvarchar(max) ,
            (SELECT
             td = CAST(pendingcmdcount as varchar(30)), '',
             td = CAST(estimatedprocesstime as varchar(30)), ''
             FROM #pendingcmds
             FOR XML PATH(N'tr'), TYPE));

        SET @HTML = @HTML + @table + CHAR(10) +
                     N'
';

        SET @HTML = @HTML + '

End of Report
';

        PRINT @HTML

        Declare @MailSubject varchar(100)
        SET @MailSubject = 'Alert - Publisher to Subscriber has exceeded threshold!!! - ' + DATENAME(weekday, getdate())

        IF LEN(@HTML) > 10

            EXEC msdb.dbo.sp_send_dbmail
            @recipients = 'tester@test.com',
            @body_format =  'HTML',
            @body= @HTML,
            @subject = @MailSubject,
            @profile_name = 'MailRelay'

        DROP TABLE #pendingcmds
        --END

        --ELSE
        --DROP TABLE #pendingcmds
        --
        --END

A: The following suggestions are not fully tested.
Immediately after
Insert INTO #pendingcmds (pendingcmdcount, estimatedprocesstime)
select * FROM OPENROWSET('SQLOLEDB',
'Server=Server\Instance;Trusted_Connection=yes;',
'set fmtonly off;
exec distribution..sp_replmonitorsubscriptionpendingcmds
@publisher=''Server\Instance'',
@publisher_db=''testproduction'',
@publication=''Summary_Inventory_TestProduction'',
@subscriber=''Server'',
@subscriber_db=''TestReplAzure'',
@subscription_type=0')

I would delete any rows where your threshold was not met.
DELETE FROM #pendingcmds WHERE pendingcmdcount <= 10000

Then, I would change your test for whether to send the email or not
From
IF LEN(@HTML) > 10

            EXEC msdb.dbo.sp_send_dbmail
            @recipients = 'tester@test.com',
            @body_format =  'HTML',
            @body= @HTML,
            @subject = @MailSubject,
            @profile_name = 'MailRelay'

TO:
IF (SELECT COUNT(*) FROM #pendingcmds) > 0
    EXEC msdb.dbo.sp_send_dbmail
    @recipients = 'tester@test.com',
    @body_format =  'HTML',
    @body= @HTML,
    @subject = @MailSubject,
    @profile_name = 'MailRelay'


Q: How to get a C# Custom TextBox to change cursor location on mouse click I have a custom textbox, which is just a standard textbox with a couple additional small features, and it all works as expected.  The problem I am having is that clicking in the field to change the cursor location does not actually change the location of the cursor, the cursor just stays at the beginning of the field.
Below is the code I am working with, I am hoping someone will be able to tell me what I am missing:
using System;
using System.ComponentModel;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace Test.UI.Controls
{
    public partial class TestTextBox : TextBox
    {
        private Color normalForegroundColor = Color.Gray;
        private Color textChangedForegroundColor = Color.Red;
        private string startingText = string.Empty;

        [Description("TextBox border color when text is changed"), Category("Appearance")]
        public Color TextChangedColor
        {
            get { return textChangedForegroundColor; }
            set { textChangedForegroundColor = value; }
        }

        [Description("Set starting text of textbox, as well as the Text property"), Category("Appearance")]
        public String StartingText
        {
            get { return startingText; }
            set
            {
                startingText = value;
                this.Text = startingText;
            }
        }

        public TestTextBox()
        {
            InitializeComponent();
            normalForegroundColor = this.ForeColor;
        }

        protected override void OnTextChanged(EventArgs e)
        {
            base.OnTextChanged(e);
            this.ForeColor = this.Text == startingText ? normalForegroundColor : textChangedForegroundColor;
        }
    }
}

Below is a screen grab of what the custom textbox looks like with data in it:


Q: Creating Link to Specific Page through Table field I'm pretty new to HTML, PHP, JavaScript, etc.
I have a table that will be uploaded by a Database, with fields such as name, id,email etc.
I would like to show a page with all people in the table, with a link to a details page that will show all the attributes (field in the table) of the person.

I use MySQL and I'm trying to build an Admin interface for better user management.

A: Your link could be like this person.php?id=1243
Where person.php is the page where you display the information about the Person with id = 1243
You can retrieve the id by using $id = $_GET['id'] and then use it on a mysql query:
SELECT * from Person WHERE id = $id; // Don't forget to handle SQL injection

And you're done.
EDIT: For multiple fields
The link person.php?id1=1243&id2=5678
Retrieve the value $id1 = $_GET['id1'] and $id2 = $_GET['id2']
MySQL: SELECT * from Person WHERE id IN($id1, $id2);
EDIT2 : For a range of users
The link person.php?startId=1&endId=5000
Retrieve the value $startId = $_GET['startId'] and $endId = $_GET['endId']
MySQL: SELECT * from Person WHERE id BETWEEN $startID AND $endId;
ALTERNATIVE suggested by @PierreGranger
Your link could be like this person.php?id[]=1243&id[]=5678
Where person.php is the page where you display the information about the Person with id = 1243 and id = 5678
You can retrieve the id by using $id = $_GET['id'][0] and then use it on a mysql query:
if ( isset($_GET['id']) && is_array($_GET['id']) ) // Check if parameter is set
{
    $ids = $_GET['id'] ;
    foreach ( $ids as $k => $v )
        if ( ! preg_match('#^[0-9]+$#',$v) ) unset($ids[$k]) ; // Remove if parameters are not identifiers

    if ( sizeof($ids) > 0 ) // If there is still at least 1 id, do your job
    {
        $sql = ' SELECT * from Person WHERE id in (".implode('","',$ids).") ' ;
        $rq = mysql_query($sql) or die('SQL error') ;
        while ( $d = mysql_fetch_assoc($rq) )
        {
            // Do your SQL request and build your table
        }
    }
}

Wich will result in :
SELECT * from Person WHERE id in ("1234","5678") ;

And you're done.

A: Based on Akram response you can try this one.
There is 2 cases : if you only have 4 or 5 particular ids, you can do this :
page.php?id[]=1&id[]=2&id[]=9
And if you want to reach a range (id from 1 to 1000) :
page.php?from=1&to=1000
unset($sql) ;
if ( isset($_GET['id']) && is_array($_GET['id']) ) // Check if parameter is set
{
    $ids = $_GET['id'] ;
    foreach ( $ids as $k => $v )
        if ( ! preg_match('#^[0-9]+$#',$v) ) unset($ids[$k]) ; // Remove if parameters are not identifiers

    if ( sizeof($ids) > 0 ) // If there is still at least 1 id, do your job
    {
        $sql = ' SELECT * from Person WHERE id in ("'.implode('","',$ids).'") ' ;
    }
}
elseif ( isset($_GET['from']) && isset($_GET['to']) )
{
    if ( preg_match('#^[0-9]+$#',$_GET['from']) && preg_match('#^[0-9]+$#',$_GET['to']) )
    {
        $sql = ' SELECT * from Person WHERE id between "'.$_GET['from'].'" and "'.$_GET['to'].'"' ;
    }
}

if ( isset($sql) )
{
    $rq = mysql_query($sql) or die('SQL error') ;
    while ( $d = mysql_fetch_assoc($rq) )
    {
        // Do your SQL request and build your table
    }
}


Q: EmberJS and web components: extend an existing HTML tag within an initializer (is it possible?) Edit: this issue only seems to be in the .hbs rendering as this code does work when the extended web component is inserted in the top level index.html of the EmberJS project
Edit 2: However, when I put it in a minimal .hbs example, then it did work. So it is clearly an interaction with EmberJS rendering and perhaps with Handlebars, somehow.
Edit 3: The issue also persist when I use Glimmer as a standalone rendering library and build these web components via the constructor() function of a Glimmer component (hacky, I know, but it works for standalone custom web components).
I am trying to understand how to use web components in EmberJS. I know that I could rewrite a web component into an EmberJS component, but that is not the point. I want to know how to directly integrate web components into EmberJS.
There is a tutorial that describes how to make custom web components and put that in EmberJS by making an initializer.
https://tenbit.co/blog/a-simple-way-to-integrate-web-components-with-your-ember-app/
So you'd think, that it is a piece of cake to do the same thing for an extended native HTML component right? It turns out that it isn't.
Here is a minimal example of what isn't working. In this particular example
hello world
 gets displayed but
hello Mars
 does not. However, in the standalone HTML file (see on the bottom of this post) which has the same classes and define() calls, then it does work.
I also made an EmberJS Twiddle, in which you can see it: https://ember-twiddle.com/5b85957f52aba288bfe9e94ce42b811e
// app/initializers/custom-elements.js
class HelloWorld extends HTMLElement {
  constructor() {
    super();
    console.log("constructor() HelloWorld");
    let shadowRoot = this.attachShadow({ mode: "open" });
    shadowRoot.innerHTML = `<p>hello world</p>`;
  }
}

//similar to HelloWorld -- it's simply an extension
class TestingAParagraph extends HTMLParagraphElement {
  constructor() {
    super();
    console.log("constructor() TestingAParagraph");
    let shadowRoot = this.attachShadow({ mode: "open" });
    shadowRoot.innerHTML = `<p>hello Mars</p>`;
  }
}

export function initialize(application) {
  window.customElements.define("hello-world", HelloWorld);
  window.customElements.define("testing-a-paragraph", TestingAParagraph, {
    extends: "p"
  });
}

export default {
  initialize
};

Here is the Handlebars file:
{{!-- my-template.hbs --}}

Bladiebla

<hello-world></hello-world>

A test is coming

Note: this minimal example does work as a standalone HTML file.

<!DOCTYPE html>

Bladiebla

      <hello-world></hello-world>

A test is coming

A: In the answer, my extendable component is an h1 as opposed to a p. As it made things easier to debug.
I figured out that the flow works as stated by jelhan in the comments.

*

*There is a createElement (I'm a 100% positive as I saw in the debugger that my h1 custom tag was breaking on __openElement).

*It then parses all the attributes one by one with setAttribute (100% positive, because debugger). Ultimately, the "is" attribute is set by setAttribute. I know that when setAttribute is used, then the web component will not be instantiated.

*It ends with an insertBefore call, at either a flushElement or somewhere else (I saw this in my debugger, didn't bother to pinpoint it).
There is a Stackoverflow question on how a web component should be added in vanillaJS.
With that knowledge, I created a JS fiddle, in which you see the workflow of how Glimmer does it now (workflow-wise), and how Glimmer could be doing it.
I also created a hacky workaround for statically defined elements in a .hbs file (warning: I don't create libraries, I merely poke around in them)
You need to replace __setAttribute with something like this:
__setAttribute(name, value, namespace) {
  if(name === "is"){ //hack, hack, hackerdeehack
    //I need the actual document, this.dom doesn't cut it. I suppose it's kind of like a shadow DOM, similar to what ReactJS does.
    let webComponent = window.document.createElement(this.constructing.tagName, { is: value });
    //copy attributes that are already parsed
    [...this.constructing.attributes].forEach( attr => { this.dom.setAttribute(webComponent, attr.nodeName, attr.nodeValue, namespace) });
    this.constructing = webComponent;
  }
  this.dom.setAttribute(this.constructing, name, value, namespace);
}

Ultimately, it's up to the EmberJS/Glimmer maintainers to propose a certain way forward. This particular hack was made, because I did not want to mess around with the VM and I also did not want to mess around with the parsing behavior of Glimmer. But I did want to see if I was right in my thinking, and I am (2 days ago, I didn't know that Glimmer existed, so I needed to be a bit thorough).
Some extra info for the curious people
Terminology that I saw:

*

*opcodes: VM thingy, I kind of forgot what it meant in a VM context, but I've seen it in my compiler construction and computer architecture courses. I always translate it as: the table of numbers to which CPUs understand what instruction they should execute.

*System calls: DOM function calls are system calls, as they are what the rendering engine is about.

A couple of handy breakpoints (+ console.log()s) in order to verify the workflow that I outlined:
//element-builder.js
__openElement(tag) {
  console.log('NewElementBuilder - __openElement', tag, [this.element], this.element.attributes, 'modules');
  debugger;
  return this.dom.createElement(tag, this.element);
}

__setAttribute(name, value, namespace) {
  debugger;
  this.dom.setAttribute(this.constructing, name, value, namespace); //this is how the "is" attribute is set
}

//note: it could also be that __flushElement is called... I didn't check this thoroughly
__appendText(text) {
  let { dom, element, nextSibling } = this;
  debugger;
  console.log('__appendText', dom, element, nextSibling, text);
  let node = dom.createTextNode(text);
  dom.insertBefore(element, node, nextSibling);
  return node;
}

// just to be sure
__flushElement(parent, constructing) {
  debugger;
  this.dom.insertBefore(parent, constructing, this.nextSibling);
}


Q: Sequelize get created record's autoincrement id I have an autoincrement id int column. I am trying to retrieve id of a created record during save but I am of course sending DEFAULT within the insert.
Is it possible to retrieve the id without an additional query?
My attempt is below however, auditWithAssignedId's id stays undefined.
void audit.save().then(auditWithAssignedId => {
  console.log('auditWithAssignedId', auditWithAssignedId);
  this.backup(auditWithAssignedId);
});

Model
AccountAudit.init(
  {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true,
    },
    account: { type: DataTypes.STRING },
    action: { type: DataTypes.STRING },
    executedOn: { type: DataTypes.DATE, defaultValue: DataTypes.Now },
  },
  {
    sequelize,
    schema: 'AUDITS',
    tableName: 'ACCOUNT',
    underscored: true,
    timestamps: false,
  }
});

export class AccountAudit extends Model<
  InferAttributes<AccountAudit>,
  InferCreationAttributes<AccountAudit>
> {
  declare id: CreationOptional<number>;
  declare account: string;
  declare action: AuditAction;
  declare executedOn: CreationOptional<Date>;
}


Q: Using ModelAndView object properties inside javascript I am returning a list from my Controller as list to view and I am passing this list object to my javascript function like this
window.onload = function() {
 showDirectory("$(S3DirectoryList)");
};

S3DirectoryList is the object that is returned from controller.
This is my model class
class Directory {
    String folderName;
    HashMap< String, String> objects;
    List<Directory> dChild;
}

I want to use the folderName property of Directory in function.
Currently my javascript function is defined like this
function showDirectory( dirList) {
    var markup="";
    <c:forEach var="dir" items="dirList">
        markup += ${dir.folderName} + "
";
    </c:forEach>
    document.getElementById("dispdir").innerHTML = markup;
}

A: I added some code to your Directory class. If you run it(I also added a Main method for testing purposes), you see it creates a list of directories and serializes this list as JSON. I added a constructor to make it easy to create some directories. I also added a getJSON method that serializes a directory. I added a getJSON(List directories) method to serialize a list of directories.
If you see to it this serialized list gets into your variable S3DirectoryList you can pass it to your javascript function as follows:
function showDirectory(dirList) {
    var markup = "";
    for(var i = 0; i < dirList.length; i++) {
        markup += dirList[i].folderName + "
";
    }
    document.getElementById("dispdir").innerHTML = markup;
}

window.onload = function() {
    showDirectory($(S3DirectoryList));
};

the Directory class:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class Directory{

    String folderName;
    HashMap<String, String> objects;
    List<Directory> dChild;

    public Directory(String folderName, String[] objects) {
        this.folderName = folderName;
        this.objects = new HashMap<String, String>();
        for(int i = 0; i < objects.length; i = i + 2) {
            this.objects.put(objects[i], objects[i + 1]);
        }
        this.dChild = new ArrayList<Directory>();
    }

    public void addChildDirectory(Directory childDirectory) {
        if(this.dChild == null)
            this.dChild = new ArrayList<Directory>();
        this.dChild.add(childDirectory);
    }

    public String toJSON() {
        StringBuilder b = new StringBuilder();
        b.append("{");
        b.append("'folderName': '").append(folderName  == null ? "" : folderName).append("'");
        b.append(",objects: {");
        if(objects != null) {
            Iterator<Map.Entry<String, String>> objectsIterator = objects.entrySet().iterator();
            if(objectsIterator.hasNext()) {
                Map.Entry<String, String> object = objectsIterator.next();
                b.append("'").append(object.getKey()).append("': '").append(object.getValue()).append("'");
            }
            while (objectsIterator.hasNext()) {
                Map.Entry<String, String> object = objectsIterator.next();
                b.append(",'").append(object.getKey()).append("': '").append(object.getValue()).append("'");
            }
        }
        b.append("}");
        b.append(",'dChild': ");
        b.append("[");
        if(dChild != null) {
            if(dChild.size() > 0)
                b.append(dChild.get(0).toJSON());
            for(int i = 1; i < dChild.size(); i++) {
                b.append(",").append(dChild.get(i).toJSON());
            }
        }
        b.append("]");
        b.append("}");
        return b.toString();
    }

    public static String getJSON(List<Directory> directories) {
        StringBuilder b = new StringBuilder();
        b.append("[");
        if(directories.size() > 0)
            b.append(directories.get(0).toJSON());
        for(int i = 1; i < directories.size(); i++) {
            b.append(",").append(directories.get(i).toJSON());
        }
        b.append("]");
        return b.toString();
    }

    private static Directory generateDirectory(int seed) {
        List<Directory> directories = new ArrayList<Directory>();
        for(int i = 0; i < 5; i++) {
            directories.add(
                    new Directory(
                            "folderName_" + seed + "_" + i,
                            new String[]{"k_" + seed + "_" + i + "_1", "v_" + seed + "_" + i + "_1", "k_" + seed + "_" + i + "_2", "k_" + seed + "_" + i + "_2"}));
        }
        Directory directory_root = directories.get(0);
        Directory directory_1_0 = directories.get(1);
        Directory directory_1_1 = directories.get(2);
        Directory directory_1_0_0 = directories.get(3);
        Directory directory_1_0_1 = directories.get(4);
        directory_root.addChildDirectory(directory_1_0);
        directory_root.addChildDirectory(directory_1_1);
        directory_1_0.addChildDirectory(directory_1_0_0);
        directory_1_0.addChildDirectory(directory_1_0_1);
        return directory_root;
    }

    public static void main(String[] args) {
        List<Directory> directories = new ArrayList<Directory>();
        for(int i = 0; i < 2; i++) {
            directories.add(generateDirectory(i));
        }
        System.out.println(toJSON(directories));
    }

}


Q: Create MBtiles from GeoServer? I'm using GeoServer version of 2.7.1.1 and installed plugin for MB tiles, now I want to know how to generate MBtiles after installing the plugins.

A: I would suggest not to use geoserver to publish mbtiles. there are many other softwares that can do same very easily. I would suggest go for tilemill. but here is list feel free to explore.
https://github.com/mapbox/mbtiles-spec/wiki/Implementations

A: You should read the full documentation before going into production, but the short answer is you change the format parameter of your WMS request to be format=mbtiles.
If you need to produce a larger set of tiles then you probably want to explore the WPS mbtiles service.

A: This is the right request for generating mbtiles from geoserver :
http:/Server_Ip:8080/geoserver/wms?service=WMS&version=1.1.0&request=GetMap&layers=MyLayer&transparent=true&styles=&bbox=-17.64404,-1.0,0.54932,36.90597&srs=EPSG:4326&format_options=min_zoom:3;max_zoom:20&width=368&height=768&format=mbtiles


Q: primefaces message not working I am implementing a login form with primefaces but my messages are not displayed, what can be?
I've tried using the id field or passing null in method addMessage ().
my xhtml code:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
  xmlns:h="http://java.sun.com/jsf/html"
  xmlns:p="http://primefaces.prime.com.tr/ui">
    <h:head>
        <title>Test</title>
    </h:head>
    <h:body>
          Wellcome<br/>
        <h:form id="login">
            <p:messages id="messages" showDetail="true" autoUpdate="true" closable="true" />
            <p:growl id="msg" showDetail="true" life="3000" />
            <p:panel header="Login" style="width: 360px;">
                <h:panelGrid id="loginPanel" columns="2">
                <h:outputText value="Email:" for="email" />
                <p:inputText id="email" value="#{loginBean.email}" ></p:inputText>
                <p:spacer></p:spacer>
                <p:message for="email" />

                <h:outputText value="Senha" for="senha" />
                <p:password id="senha" value="#{loginBean.senha}"  feedback="false" minLength="1"></p:password>
                <p:spacer></p:spacer>
                <p:message for="senha" />
                <p:spacer></p:spacer>
                <p:commandButton action="#{loginBean.loginAction}" value="Login" update="loginForm" ajax="true"></p:commandButton>
            </h:panelGrid>
            </p:panel>
        </h:form>
    </h:body>
</html>

my bean:
@ManagedBean
@RequestScoped
public class LoginBean {

    private static final long serialVersionUID = 1L;
    private String email;
    private String senha;

    @ManagedProperty(value="#{usuarioSessionBean}")
    private UsuarioSessionBean usuarioSessao;

    public String loginAction()
    {
        //Valida preenchimento dos campos de email e senha
        boolean campoBranco = false;
        if((email == null) || (email.trim().length() == 0))
        {
            campoBranco = true;
            FacesContext.getCurrentInstance().addMessage(null,new FacesMessage(FacesMessage.SEVERITY_ERROR, "Email não informado!","Preencha o email e tente novamente!"));
        }

        if((senha == null) || (senha.trim().length() == 0))
        {
            campoBranco = true;
            FacesContext.getCurrentInstance().addMessage(null,new FacesMessage(FacesMessage.SEVERITY_ERROR, "Senha não informada!","Preencha a senha e tente novamente!"));
        }

        if(campoBranco)
            return "login";
    }
}

Can anyone tell me what is wrong? He returns to the login page but does not show the messages.

A: If my understanidng is correct you mean to say you want to show the message to the user, try following:
    if((senha == null) || (senha.trim().length() == 0))
            {
                campoBranco = true;
                FacesContext.getCurrentInstance().addMessage(null,new FacesMessage(FacesMessage.SEVERITY_ERROR, "Senha não informada!","Preencha a senha e tente novamente!"));
    return null;

}

this is what you have to add return null; so that it will stay in the same page and show up the message, As you are trying to navigate to the login page once agin after getting the error also, it will simply navigate rather than showing error messages.
 as well try to modify in the xhtml as suggested below:
and in your xhtml:
<p:growl id="growlLoginValidationStatus" showDetail="true" sticky="false" autoUpdate="true" life="4000" redisplay="false" showSummary="true" globalOnly="false" />

and remove your <p:message/> tag and make ajax as false in your command button.
try this, if still not able to show the message, let me know in comment

A: It seems like you're updating the wrong id.
<h:form id="login" >
    <p:commandButton value="Login" update="loginForm"
                     action="#{loginBean.loginAction}"/>
</h:form>

In this case, you need to change loginForm to login or change the id of your form to loginForm.


Q: How to change the default filter operator in kendo ui grid mvc I have managed to change the default filter order for the Kendo Grid using:
.Filterable(filterable => filterable
                        .Extra(true)
                        .Operators(ops =>
                            ops.ForString(str => str.Clear()
                                                    .Contains("Contains")
                                                    .StartsWith("Starts with")
                                                    .EndsWith("Ends with")
                                                    .IsEqualTo("Is equal to"))
                        ))

Is there any way I can change the default operator to OR?

A: This can be done via the filterMenuInit event:
 /* grid configuration snip */
.Events(e => e.FilterMenuInit("filterMenuInit"))
 /* grid configuration snip */

 <script>
 function filterMenuInit(e) {
      e.container
         .find("select.k-filter-and")
         .data("kendoDropDownList")
         .value("or");
 }
 </script>

Here is a live demo: http://jsbin.com/etItEpi/1/edit

A: You can also do this on a per column basis on your grid definition (MVC):
cols.Bound(m => m.xxx).Filterable(f=> f.Cell(cell => cell.Operator("or")));


Q: MySQL SELECT with data from another table Probably it's easier than what i think, but i am loosing my mind about it,
i have a table with product with thousand of entry, something like
ID|NAME
0 |first product
1 |second product
...
N |nth product

every time someone click a product i save and update a table called click
PRODUCT_ID|CLICKS
0         |1
1         |3

so, if a product never received a click does not exist in click table
now i want a list of all the products (or a category subset for example) ordered by clicks.
of course the entry that are not on click table should be present in the result with clicks column to 0 (or empty)
ID|NAME       |CLICKS
0 |first name |1
5 |fifth name |
...
N |nth name   |2

all the joins i tried were only able to give me a combined result for entry that are present in both table, i know its very easy and i am running around it from about two hours... but i cant succeed!
any suggestion?

A: select from master table and make it LEFT JOIN with clicks table.

A: a LEFT JOIN works for your query

CREATE TABLE products (
  `ID` INTEGER,
  `NAME` VARCHAR(14)
);

INSERT INTO products
  (`ID`, `NAME`)
VALUES
  ('0', 'first product'),
  ('1', 'second product'),
  ('2', 'thirdproduct'),
  ('3', 'forth product');

CREATE TABLE ciicks (
  `PRODUCT_ID` INTEGER,
  `CLICKS` INTEGER
);

INSERT INTO ciicks
  (`PRODUCT_ID`, `CLICKS`)
VALUES
  ('0', '1'),
  ('1', '3');

SELECT p.ID,p.NAME,IFNULL(c.CLICKS,0)
FROM products p LEFT JOIN ciicks c ON p.ID = c.PRODUCT_ID

ID | NAME           | IFNULL(c.CLICKS,0)
-: | :------------- | -----------------:
 0 | first product  |                  1
 1 | second product |                  3
 2 | thirdproduct   |                  0
 3 | forth product  |                  0

db<>fiddle here

A: Select p.id, p.name, ifnull(c.clicks,0) as clicks from product p
left join click c on p.id = c.product_id

A: You can use LEFT JOIN (https://www.mysqltutorial.org/mysql-left-join.aspx/) to combine tables where one table may not have matching rows. See http://sqlfiddle.com/#!9/db9d5a/4 for an example:
SELECT
    p.id,
    p.name,
    IFNULL(c.clicks, 0)
FROM
    products p
    LEFT JOIN clicks c ON c.product_id = p.id
ORDER BY c.clicks DESC;

will return the following:
id | name   | clicks
4    fourth   5
2    second   3
1    first    1
3    third    0


Q: Azure automation, PowerShell to fetch a file in private blob container I have an azure blob container set to private. I want to download files in this container using PowerShell.
This is what I put, however it is giving me ResourceNotFound error every time. Even when I put -Credential and my user name/access key. When I switch the container to public access, it always works. So am I missing anything?
Invoke-WebRequest -Uri $uri -OutFile $filePath

A: Using Invoke-WebRequest is analogous to opening a link in your browser.  It's a legitimate way to download files from Azure Storage, however to do that you'll need the URI to include a SAS (Shared Access Signature), which you'll have to have generated before you use it in your code.  The PowerShell to achieve this is:
#Download via URI using SAS
$BlobUri = 'https://yourstorageaccount.blob.core.windows.net/yourcontainer/yourfile.txt'
$Sas = '?sv=2015-04-05&st=2015-04-29T22%3A18%3A26Z&se=2015-04-30T02%3A23%3A26Z&sr=b&sp=rw&sip=168.1.5.60-168.1.5.70&spr=https&sig=Z%2FRHIX5Xcg0Mq2rqI3OlWTjEg2tYkboXr1P9ZUXDtkk%3D'
$OutputPath = 'C:\Temp\yourfile.txt'
$FullUri = "$BlobUri$Sas"
(New-Object System.Net.WebClient).DownloadFile($FullUri, $OutputPath)

Alternatively, if you have the Azure PowerShell module installed, you can do it without any of that added pain:
# Download via Azure PowerShell
$StorageAccountName = 'yourstorageaccount'
$StorageAccountKey = Get-AzureStorageKey -StorageAccountName $StorageAccountName
$StorageContext = New-AzureStorageContext $StorageAccountName -StorageAccountKey $StorageAccountKey.Primary
$FileName = 'yourfile.txt'
$OutputPath = 'C:\Temp'
$ContainerName  = 'yourcontainer'
Get-AzureStorageBlobContent -Blob $FilebName -Container $ContainerName -Destination $OutputPath -Context $StorageContext

A: I ended up to resolve similar requirement with Azure PowerShell Az module as follows:
$BlobFilePath = 'dir\blob.file' # Relative path in blob starting from container
$OutputFilePath = 'C:\temp\blob.file' # Path to download the file to
$StorageAccountName = 'storageaccountname'
$ContainerName = 'blob-container-name'

# Prompt for Azure Account creds, if working from VM with managed identity could add also switch -Identity to use that identity directly
Connect-AzAccount
$StorageContext = New-AzStorageContext -StorageAccountName $StorageAccountName

Get-AzStorageBlobContent -Blob $BlobFilePath -Container $ContainerName -Destination $OutputFilePath -Context $StorageContext

A: $StartTime = $(get-date)
$datetime = $(get-date -f yyyy-MM-dd_hh.mm.ss)

$connection_string = ''
$AzureBlobContainerName = ''

$destination_path = "c:\download"

If(!(test-path $destination_path))
{
    New-Item -ItemType Directory -Force -Path $destination_path
}
$storage_account = New-AzStorageContext -ConnectionString $connection_string

# Download from all containers
#$containers = Get-AzStorageContainer -Context $storage_account

# Download from specific container
$containers = Get-AzStorageContainer -Context $storage_account | Where-Object {$_.Name -eq "$AzureBlobContainerName"}

$containers
Write-Host 'Starting Storage Dump...'
foreach ($container in $containers)
{
    Write-Host -NoNewline 'Processing: ' . $container.Name . '...'

    $blobs = Get-AzStorageBlob -Container $container.Name -Context $storage_account

    $container_path = $destination_path + '\' + $container.Name
    new-item -ItemType "directory" -Path $container_path
    Write-Host -NoNewline ' Downloading files...'
    foreach ($blob in $blobs)
    {
        $fileNameCheck = $container_path + '\' + $blob.Name
        if(!(Test-Path $fileNameCheck ))
        {
            Get-AzStorageBlobContent -Container $container.Name -Blob $blob.Name -Destination $container_path -Context $storage_account
        }
    }
    Write-Host ' Done.'
}
Write-Host 'Download complete.'

$elapsedTime = $(get-date) - $StartTime

$totalTime = "{0:HH:mm:ss}" -f ([datetime]$elapsedTime.Ticks)

Write-Output " -OK $totalTime" | Out-String


Q: area chart with d3 is not rendering on jsp page but working fine with html i sucessfully rendered d3js area chart in a html page here is the code which is rendering sucessfully in chrome or mozilla.The name of the file is say temp.html.Here is the code
<!DOCTYPE html>
<html lang="en" class="no-js">

<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>js graphs and charts libraries</title>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="http://d3js.org/d3.v3.js"></script>

<body>
    <div id="dbar">

    </div>

<script type="text/javascript">
    var margin = {top:10, right: 20, bottom: 30,left: 40},
        width = 960 - margin.left - margin.right,
        height = 400 - margin.top - margin.bottom;
        var svg = d3.select ("#dbar").append("svg").attr("width",
width+margin.left+margin.right).attr("height",height+margin.top+margin.bottom)
.append("g").
attr("transform","translate("+margin.left+","+margin.top+")");
 var parseDate = d3.time.format("%m-%Y").parse;

    var x = d3.time.scale().range([0, width]);
    var y = d3.scale.linear().range([height, 0]);

    var xAxis = d3.svg.axis().scale(x).orient("bottom");

    var yAxis = d3.svg.axis().scale(y).orient("left");

    var area = d3.svg.area().x(function(d) { return x(d.date); })
                .y0(height)
                .y1(function(d) { return y(d.count); });
d3.json("data/json.json", function(error, data) {
      data.StoreVisitGraphCount.list.forEach(function(d) {

        d.date = parseDate(d.date);

        d.count = +d.count;
      });
      //console.log(data.StoreVisitGraphCount.list);
    x.domain(d3.extent(data.StoreVisitGraphCount.list, function(d) {
return d.date; }));
    y.domain([0, d3.max(data.StoreVisitGraphCount.list, function(d) {
return d.count; })]);
console.log(data.StoreVisitGraphCount.list);
  svg.append("path")
      .datum(data.StoreVisitGraphCount.list)
      .attr("class", "area")
      .attr("d", area);

  svg.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + height + ")")
      .call(xAxis);

  svg.append("g")
      .attr("class", "y axis")
      .call(yAxis)
    .append("text")
      .attr("transform", "rotate(-90)")
      .attr("y", 6)
      .attr("dy", ".71em")
      .style("text-anchor", "end")
      .text("Price ($)");
    });
</script>

</body>
</html>

But when i am copy pasting this code to say "temp.jsp" page its not rendering and chart is not coming.I am running this page on tomcat server.
need suggestions

A: It is not because you saved it as jsp or html page. You need to add charset="UTF-8" to your script declaration as d3.js uses UTF characters.
eg.
<script src="http://d3js.org/d3.v3.js" charset="UTF-8"></script>


Q: Extracting highlighted content in pdf automatically as images I have a pdf file in which some text and images are highlighted using highlight text(U) tool. Is there a way to automatically extract all the highlighted content as separate images and save it to a folder? I dont want readable text. I just want all the highlighted content as images. Thanks

A: You would need to use PDF library to iterate through all the Annotation objects and their properties to see which ones are using a highlight annotation.  Once you have found the highlight annotation you can then extract the position and size (bounding box) of the annotation.
Once you have a list of the annotation bounding boxes you will need to render the PDF file to an image format such as PNG/JPEG/TIFF so that you can extract / clip the rendered image of the annotation text you want.  You could use GDI+ or something like LibTIFF
There are various PDF libraries that could do this including
http://www.quickpdflibrary.com  (I consult for QuickPDF) or
http://www.itextpdf.com
Here is a C# function based on Quick PDF Library that does what you need.
    private void ExtractAnnots_Click(object sender, EventArgs e)
    {
        int dpi = 300;
        Rectangle r;
        List<Rectangle> annotList = new List<Rectangle>();

        QP.LoadFromFile("samplefile.pdf", "");

        for (int p = 1; p <= QP.PageCount(); p++)
        {
            QP.SelectPage(p);  // Select the current page.
            QP.SetOrigin(1);   // Set origin to top left.

            annotList.Clear();

            for (int i = 1; i <= QP.AnnotationCount(); i++)
            {
                if (QP.GetAnnotStrProperty(i, 101) == "Highlight")
                {
                    r = new Rectangle((int)(QP.GetAnnotDblProperty(i, 105) * dpi / 72.0),  // x
                                      (int)(QP.GetAnnotDblProperty(i, 106) * dpi / 72.0),  // y
                                      (int)(QP.GetAnnotDblProperty(i, 107) * dpi / 72.0),  // w
                                      (int)(QP.GetAnnotDblProperty(i, 108) * dpi / 72.0)); // h

                    annotList.Add(r); // Add the bounding box to the annotation list for this page.

                    string s = String.Format("page={0}: x={1} y={2} w={3} h={4}\n", p, r.X, r.Y, r.Width, r.Height);
                    OutputTxt.AppendText(s);
                }
            }

            // Now we have a list of annotations for the current page.
            // Delete the annotations from the PDF in memory so we don't render them.

            for (int i = QP.AnnotationCount(); i >= 0;  i--)
                QP.DeleteAnnotation(i);

            QP.RenderPageToFile(dpi, p, 0, "page.bmp");   // 300 dpi, 0=bmp
            Bitmap bmp = Image.FromFile("page.bmp") as Bitmap;

            for (int i=0;i<annotList.Count;i++)
            {
                Bitmap cropped = bmp.Clone(annotList[i], bmp.PixelFormat);

                string filename = String.Format("annot_p{0}_{1}.bmp", p, i+1);
                cropped.Save(filename);
            }

            bmp.Dispose();
        }

        QP.RemoveDocument(QP.SelectedDocument());
    }

A: Do you want each piece of text as a separate highlight or all the higlhights on a separate pane?


Q: Foxx dependencies import by name, not by mounting point As far as I understand from reading this snippet in this documentation regarding 'Defining dependencies':

will allow using any app to be used to meet the dependency.
  sessions or sessions@* will match any app with the name sessions (such as the sessions app in the Foxx application store).
  sessions@1.0.0 will match the version 1.0.0 of any app with the name sessions.

Foxx will look for any dependency with name 'sessions'. However, when I tried it locally, it seems like it tries to find any app mounted at /sessions rather than name 'sessions' and this error populated in the logs if I use like this format 'sessions@1.0.0':
[ArangoError 3007: Mountpoint can only contain a-z, A-Z, 0-9 or _.]: [object Arguments]
Is this an expected behaviour? I really hope if it's possible to import an app by name rather than the mount point though.

A: The blurb in the documentation refers to the value in the manifest.json file. Dependencies in the manifest are defined by an alias mapped to a string in the format of <name>@<version>. The exact meaning of that string is not currently enforced so it just serves as documentation for the app.
If you mount an app that has dependencies, you need to set up the dependencies (e.g. using the web frontend). The web frontend's dependencies dialog lets you enter mount paths of apps you want to use to meet the dependencies.
The code of the app itself will then be able to refer to the exports of the apps mounted at those paths by the aliases defined in the manifest.
For example:

*

*You create an app called example with the following dependencies:
"dependencies": {"mySessions": "sessions@^1.0.0"}

*You install a sessions app (e.g. the sessions app from the Foxx app store) and mount it at /my-sessions.

*You install your example app and mount it somewhere else.

*You open the app details of your example app in the web frontend and open the dependencies dialog (boxes icon in the top right).

*The dialog should show a single input field titled MySessions with a help popup saying sessions@^1.0.0.

*Enter /my-sessions into the input field and save.

*Your example app should now be able to access the exports of the app at applicationContext.dependencies.mySessions.


Q: how to set validation rules in foreach loop in codeigniter I need to set rules dynamically I don't know what will be the name of input type. For example I have input type<input type="text" name="first_name"> I can set rule for it like
$this->form_validation->set_rules("first_name", "First Name", "required");

But I am doing it dynamically suppose I have $_POST array I don't know the input type name value. So I did it this way
foreach($post as $key => val){

  $this->form_validation->set_rules($key, remove_underscore($key), "required");

}

$this->form_validation->set_error_delimiters("
", "
");

    if($this->form_validation->run()){
      //do stuff here..
    }

The validation does not work in this loop way. If I set rules in a string and echo it outside the loop like
$str = '';
   foreach($post as $key => val){
     $str .= '$this->form_validation->set_rules($key'
   }

   echo $str;

That doesn't work either because I have to do echo json_encode(var) at the end. If I echo it first it will stop there only. I hope I have clear my point, if any one can guide me I will appreciate.


Q: Trying to create query to export data as csv I have a Postgresql table I wish to export as CSV on demand using a query, without superuser.
I tried:
COPY myapp_currencyprice to STDOUT WITH (DELIMITER ',', FORMAT CSV, HEADER) \g /tmp/prices.csv

But I get a syntax error at "\g"
So I tried:
\copy myapp_currencyprice to '/tmp/prices.csv' with (DELIMITER ',', FORMAT CSV, HEADER)

But I also get a syntax error at "" from "\copy"

A: Running the command that way works only when connection is done through psql.

A: You can do the following in psql.
SELECT 1 as one, 2 as two \g /tmp/1.csv

then in psql
\! cat /tmp/1.csv

or you can
copy (SELECT 1 as one, 2 as two) to '/tmp/1.csv' with (format csv , delimiter '|');

But You can't STDOUT and filename. Because in manual(https://www.postgresql.org/docs/current/sql-copy.html):
COPY { table_name [ ( column_name [, ...] ) ] | ( query ) }
    TO { 'filename' | PROGRAM 'command' | STDOUT }
    [ [ WITH ] ( option [, ...] ) ]

the Vertical line | means:  you must choose one alternative.(source: https://www.postgresql.org/docs/14/notation.html)


Q: Hamburger menu styling doesn't appear the same on phone I have created a mobile hamburger menu with several items in it. The thing is, when I try to edit the CSS and make changes they appear fine in my inspect preview, but when I actually check the website on the mobile I don't exactly see the styling I was trying to achieve. Here are the things that I tried to do:
I want to change the distance between the borders that are visible on ::focus (make them a bit more far from the text). When I insepct, it looks different than when I check it out on my phone. I tried adding    margin: 30px 0; padding-top: 25px; to the span class on focus, but it doesn't work on phone.
I have tried changing the margins, paddings and using whitespace:nowrap. It looked fine when I previewed the changes on my desktop, but when I checked out my phone my styling looked different.
Here's the HTML of the menu:

?מהי רגולציה

?אודות

?למי זה מתאים

פתרונות

צור קשר

  |  052-6582643

Here's the CSS:
.menu-item-text-mobile {
    -webkit-transition: border 200ms ease-out;
-moz-transition: border 200ms ease-out;
-o-transition: border 200ms ease-out;
transition: border 200ms ease-out;
border-bottom: 2.11px solid transparent;
border-top: 2.11px solid transparent;
margin-left:50px;
  display: inline-block;
    margin: 20px 0;
        padding-top: 25px;

}

.menu-item-text-mobile::after
    bottom: 1px;
}

#who-menu-mobile:hover .menu-item-text,
#who-menu-mobile:focus .menu-item-text,
#who-menu-mobile:active .menu-item-text{
border-bottom: 2.11px solid #61f6ff;
margin-top: 5px;
margin-bottom: 5px;
border-top: 2.11px solid #61f6ff;
bottom: -3px;
}
#solutions-menu-mobile:hover .menu-item-text,
#solutions-menu-mobile:focus .menu-item-text,
#solutions-menu-mobile:active .menu-item-text{
border-bottom: 2.11px solid #61f6ff;
border-top: 2.11px solid #61f6ff;
  display: inline-block;
    margin: 20px 0
}

#regulation-menu-mobile:hover .menu-item-text,
#regulation-menu-mobile:focus .menu-item-text,
#regulation-menu-mobile:active .menu-item-text{
border-bottom: 2.11px solid #61f6ff;
border-top: 2.11px solid #61f6ff; }

 @media(min-width: 300px) and (max-width: 749px){ .elementor-widget-heading .elementor-heading-title > a{ justify-content: center !important; display: flex !important;
 }}

Here's the website if you wanna inspect it: mayabarber.co.il
And here's a screenshot of how I want it to look:

Thanks!

A: 1 and 2:
For adjusting the distance between the options target span and reduce the margin on it to make them closer between each other. You can add the class to your spans like this, then use padding to make the lines farther from text. Play with the values.
Would look something like:

.spanMenu {
    padding: 5px;
    margin-bottom: -20px;
}

3.
To keep the phone number from going onto two different lines use an @media
Currently inspecting and fiddling to get the correct CSS so bear with me.
To resize you can add a class="makeSmall" to the p tag like this:

Then add this @media to your CSS
@media only screen and (max-width: 600px) {
    .makeSmall {
        font-size:12px;
    }
}

This will allow you to adjust just the text size in the p tag. This is a quick and dirty way of doing it; I don't have the time to do the hierarchy of your CSS to just target them with CSS. I hope this helps though. :)

A: Can the issue be that your phone is not cleaning out its cache correctly?
Can you try borrowing someones else's phone, who has never visited the site, and take a look at it with their phone?
If this solves your issue, you should figure out how to clean the cache from your phone to continue development.


Q: How to CountIf items in ListView VB.Net i have a form that has two listviews,
lv = listview
lv1 from textbox
lv2 countif items from lv1.
my question, how i can count the items in lv1 and show it in lv2.
thank you very much.
:)
Best regards,
HMZ

A: You can try this:
ListView1.Items.Add("Buah").SubItems.Add("Apel")
ListView1.Items.Add("Buah").SubItems.Add("Mangga")
ListView1.Items.Add("Buah").SubItems.Add("Jambu")
ListView1.Items.Add("Buah").SubItems.Add("Durian")
ListView1.Items.Add("Buah").SubItems.Add("Rambutan")

ListView1.Items.Add("Sayur").SubItems.Add("Apel")
ListView1.Items.Add("Sayur").SubItems.Add("Apel")
ListView1.Items.Add("Sayur").SubItems.Add("Apel")

Dim firstColDistinctItems() As String = ListView1.Items.Cast(Of ListViewItem).Select(Function(item As ListViewItem) item.Text).Distinct().ToArray()
For i = 0 To firstColDistinctItems.Count - 1
    Dim repeatCount As Integer = ListView1.Items.Cast(Of ListViewItem).Where(Function(item As ListViewItem) item.Text = firstColDistinctItems(i)).Count
    ListView2.Items.Add(firstColDistinctItems(i)).SubItems.Add(repeatCount)
Next

A: Although I haven't tried it, Youssef13's answer should work.
Here's a "more readable" routine that will do just what you want.
Hopefully, the comments are enough to understand how it works.
Private Sub CountItems()
    ' Delete any existing items in lv2
    lv2.Items.Clear()

    ' A dictionary that will contain a list of all unique items from lv1 and their occurrence count
    Dim items As New Dictionary(Of String, Integer)

    ' Simple For loop to scan all items in lv1
    For Each itm As ListViewItem In lv1.Items
        If items.ContainsKey(itm.Text) Then ' Check if the item has already been added
            items(itm.Text) += 1 ' In that case, increment its counter
        Else
            items.Add(itm.Text, 1) ' Otherwise, create add it as a new item and set its internal counter to 1
        End If
    Next

    ' Finally, display the dictionary contents in lv2
    For Each itm In items
        lv2.Items.Add(itm.Key).SubItems.Add(itm.Value.ToString())
    Next
End Sub

UPDATE: Here's a highly optimized (performance-wise) version:
Private Sub CountItems()
    lv2.Items.Clear()

    Dim items As IEnumerable(Of Tuple(Of String, Integer)) = lv1.Items.Cast(Of ListViewItem).GroupBy(Function(i) i.Text).Select(Function(i) Tuple.Create(i.Key, i.Count))
    For Each itm In items
        lv2.Items.Add(itm.Item1).SubItems.Add(itm.Item2.ToString())
    Next
End Sub


Q: Can't bind to Service I have an aidl file defined as follows:
package com.erbedo.callalert;

interface RemoteCallAlert {
    void notifyCallEnded();
}

The service is:
package com.erbedo.callalert;

public class CallAlert extends Service {

    Filter callListener;

    private final RemoteCallAlert.Stub mBinder = new RemoteCallAlert.Stub() {
        @Override
        public void notifyCallEnded() throws RemoteException {
                  // TODO
        }
        };

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Toast.makeText(this, "CallAlert Created", Toast.LENGTH_LONG).show();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Toast.makeText(this, "CallAlert Destroyed", Toast.LENGTH_LONG).show();
    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        Toast.makeText(this, "CallAlert Started", Toast.LENGTH_LONG).show();
        callListener = new Filter();
        TelephonyManager tm =
            (TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE);
        tm.listen(this.callListener, PhoneStateListener.LISTEN_CALL_STATE);
    }

    public void callEnded() {
          // TODO
    }
}

and the Activity that has to bind to the service is:
package com.erbedo.callalert;
public class DummyStart extends Activity {

    Filter callListener;
    RemoteCallAlert mService;

    private ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className,
                IBinder service) {
            Log.d("CONNECT","OK");
        }

        public void onServiceDisconnected(ComponentName className) {

        }
    };

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LinearLayout l = new LinearLayout(this);
        setContentView(l);
        this.startService(new Intent(this, CallAlert.class));
    }
}

The onServiceConnected isn't called. Am I missing something obvious?

A: startService() does not use a ServiceConnection. bindService() does.

A: Intent intent = new Intent(CallAlert.class.getName());
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);

A:

The onServiceConnected isn't called.

For binding with the service you need to call bindService(). It provide the persistence connection, and after connection establishment onServiceConnected() is called.
Second point:-
 If you are using AIDL IPC mechanism then I think you need the communication between 2 diff processes/Application.  Here you need to have same copy of .aidl file in both service and Activity side in same PACKAGE. Then you need to modify little bit in your Activity side..
you can find here
http://www.zestofandroid.blogspot.com/


Q: How do I add buttons over an image using the netbeans IDE? I am using netbeans as an IDE to make my desktop application.
I have to add 3 buttons over an image. How do I do that? I have been unable to do this using the drag and drop features of netbeans.

A: Put the buttons in a custom panel with an image background (example here).
In IDE use a regular JPanel and drag the JButtons over it, then change the code from JPanel to ImagePanel (or whatever name you used for it).

A: This is a little cheeky, but.

*

*Start by setting the layout of the base component to BorderLayout.

*Drop a JLabel into it. Set the labels icon image to the background image you want to use.

*Set the layout manager of the label to what ever you want to use.

*Drop your buttons onto it...

A: 1.Add the JLabel and in Properties, Set text to null and add the image by selecting it from the icons menu (this image should be in your package).
2.Set the appropriate size of the background and set the layout to NULL Layout.
3.Place the background label as the bottom most layer and keep adding buttons or labels as per your need.


Q: RuntimeError: ERROR Mrelation "tablename" does not exist Rails - 2.3.8
Database - Postgres(9.2)
Active record query is not able to generate tablename in double quotes ie
   # this ran fine
      Table.find_by_sql('Select * from "Table" Limit 1')

      Sql generated -    Select * from "Table" Limit 1

But issue comes in,
      Table.find(:first)
      Sql generated -    Select * from Table Limit 1 (Clearly noticed that table not in double quotes)

Active record displaying error
  ActiveRecord::StatementInvalid: RuntimeError: ERROR
  C42P01  Mrelation "Table" does not exist
  P15 Fparse_relation.c L864
  RparserOpenTable: SELECT * FROM Table  LIMIT 1

I feel that postgresql adapter is not able to generate tablename in double quotes.

A: I never get a chance to work on Postgres. But I have a workaround solution for this. Try as follows:
table_name = '"Table"'
table_name.find(:first)

I haven't try this in my machine since I do not have the required setup. I hope it should work.


Q: Git commit command is not working properly with atom editor When I give the command "$git commit" to git bash, then

$ git commit
hint: Waiting for your editor to close the file... atom --wait: atom: command not found
error: There was a problem with the editor 'atom --wait'.
Please supply the message using either -m or -F option.

this error is thrown by git. I have configured atom in git using this command :-
$ git config --global core.editor "atom --wait"

A: If this problem appears, you have to :
1 - Go to the Atom menu.
2 - Select "Install Shell Commands".
3 - Restart the terminal
It's magic it works :D

A: Here are some tools to figure this out.
Check current configuration:
git config --list

Check Status:
git status

See which configuration below works for the atom text editor:
git config --global core.editor "atom"
git config --global core.editor "atom --wait"
git config --global core.editor "atom -w -s"

Be sure to leave a message in the file that opens after running "git commit" in terminal. Save and completely exit the editor.

A: Walking down the error you included:
hint: Waiting for your editor to close the file...

tells you that git has attempted to open your specified editor to write a commit message. This much is normal. The next part:
atom --wait: atom: command not found

tells you that git tried to execute $ atom --wait, but couldn't find the atom command. This indicates that the atom command was either never installed, or is not on your path. (For reference, the executable to run Atom on my Mac is located at /usr/local/bin/atom)
The solution depends on your operating system.
Solution for Mac
This exactly matches the problem described by the Installing Atom on Mac official documentation:

When you first open Atom, it will try to install the atom and apm commands for use in the terminal. In some cases, Atom might not be able to install these commands because it needs an administrator password.

Therefore...

To install the atom and apm commands, run "Window: Install Shell Commands" from the Command Palette, which will prompt you for an administrator password.

Alternatively, the steps given in Fizik26's Answer will accomplish the same thing.
Note: the "Window: Install Shell Commands" action only seems to be available on Mac, not Windows or Linux.

A: In my case for Windows 10, I only uninstalled Git (v2.32) and kept Atom. I re-installed Git, and I chose Atom to be my default editor from the drop-down menu that appears in the installation wizard.
If you kept pressing the NEXT button during the installation, you will end up with VIM as your default editor, and we sure don't want that.

A: This is because there is no atom command at least in the PATH. To enable opening Atom from the command-line, you will need to install shell commands from the either the Atom menu or the Atom Command Palette. Next ensure that atom is in your path.


Q: Yahoo Currency Exchange Rates in Android 4 In my application, I need to get the current exchange rates for different currencies. As it has been suggested by this, this and this question a nice way to do it, is to use the Yahoo Finance service.
So, when I want to find, for example, the rate between USD and Canadian dollars, I simply send this link: http://download.finance.yahoo.com/d/quotes.csv?s=USDCAD=X&f=sl1d1t1ba&e=.csv
This is working fine for both my Motorola Atrix phone with Android 2.3.4 and the emulator again with Google API 2.3.3. However, when I try the exact same link from a Galaxy SII with Android ICS 4.0 and an emulator with Google API 4.0, in both cases the quotes.csv file contains only the "Missing Symbols List".
After digging around, I found out that this response can happen in case the rates were not found. But this response is for ANY currency I try under Android 4.0 (either Galaxy SII or emulator). Hence, I cannot get the rates with Android 4.0, but I can with Android 2.x.
Does anyone have experienced the same problem? Is there any workaround?
EDIT: This is the thread code that deals with downloading rates from the Yahoo Currency Service:
//show the progress dialog
downloadingDialog.show();
Runnable getRates = new Runnable() {
   public void run(){
      dataNotFound = false;
      final String baseDir = getApplicationContext().getFilesDir().getAbsolutePath();
      //download the rates from yahoo to a CSV file
      downloadFileViaHTTP (baseDir);
      //read the file line
      String filePath = baseDir + "/" + "quotes.csv";
      Log.d(tag, "-> filePath = " + filePath);
      try {
         // open the file for reading
         InputStream instream = new FileInputStream(filePath);
         // if file the available for reading
         if (instream != null) {
            // prepare the file for reading
            InputStreamReader inputreader = new InputStreamReader(instream);
            BufferedReader buffreader = new BufferedReader(inputreader);
            //read the line
            String fileLine = buffreader.readLine();
            Log.d(tag, "fileLine = " + fileLine);
            instream.close();
         }
      }
      catch (Exception ex) {
         // print stack trace.
      }

   }
};
final Thread t = new Thread(getRates);
t.start();

And this is my function for downloading the quotes.csv file from the Yahoo site:
public void downloadFileViaHTTP (String localPath) {
   Log.d(tag, "downloadFileViaHTTP...");

   try {
      //this is the Yahoo url
      String urlFile = "http://download.finance.yahoo.com/d/quotes.csv?s=" + fromCurrency + toCurrency + "=X&f=sl1d1t1ba&e=.csv";
      Log.d(tag,"urlFile = " + urlFile);
      URL url = new URL(urlFile);
      //create the new connection
      HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
      urlConnection.setRequestMethod("GET");
      urlConnection.setDoOutput(true);
      urlConnection.connect();

      //pointer to the downloaded file path
      String localFileName = localPath + "/" + "quotes.csv";
      //this is the actual downloaded file
      File MyFilePtrDest = new File(localFileName);
      Log.d(tag,"localFileName = " + localFileName);

      //this will be used in reading the data from the Internet
      InputStream inputStream = urlConnection.getInputStream();

      //this will be used to write the downloaded data into the file we created
      FileOutputStream fileOutput = new FileOutputStream(MyFilePtrDest);

      byte[] buffer = new byte[1024];
      int bufferLength = 0; //used to store a temporary size of the buffer

      //write buffer contents to file
      while ((bufferLength = inputStream.read(buffer)) > 0 ) {
         //add the data in the buffer to the file in the file output stream (the file on the sd card
         fileOutput.write(buffer, 0, bufferLength);
      }

      inputStream.close();
      //close the output stream when done
      fileOutput.flush();
      fileOutput.close();
      urlConnection.disconnect();
   }
   catch (IOException e) {
      //data were not found
      dataNotFound = true;
      // TODO Auto-generated catch block
      e.printStackTrace();
   }
}

This is the log from the Google API 2.3.3 emulator:
12-18 11:04:24.091: D/CurrencyConverter(414): downloadFileViaHTTP...
12-18 11:04:24.091: D/CurrencyConverter(414): urlFile = http://download.finance.yahoo.com/d/quotes.csv?s=EURUSD=X&f=sl1d1t1ba&e=.csv
12-18 11:04:24.282: D/CurrencyConverter(414): localFileName = /data/data/com.myapps.currencyconverter/files/quotes.csv
12-18 11:04:24.461: D/CurrencyConverter(414): -> filePath = /data/data/com.myapps.currencyconverter/files/quotes.csv
12-18 11:04:24.461: D/CurrencyConverter(414): fileLine = "EURUSD=X",1.3172,"12/18/2012","4:03am",1.317,1.3174

And this is the log from the Google API 4.0 emulator:
12-18 11:47:36.130: D/CurrencyConverter(668): downloadFileViaHTTP...
12-18 11:47:36.130: D/CurrencyConverter(668): urlFile = http://download.finance.yahoo.com/d/quotes.csv?s=EURUSD=X&f=sl1d1t1ba&e=.csv
12-18 11:47:36.449: D/dalvikvm(668): GC_CONCURRENT freed 306K, 4% free 11714K/12167K, paused 5ms+10ms
12-18 11:47:36.951: D/CurrencyConverter(668): localFileName = /data/data/com.myapps.currencyconverter/files/quotes.csv
12-18 11:47:37.159: D/CurrencyConverter(668): -> filePath = /data/data/com.myapps.currencyconverter/files/quotes.csv
12-18 11:47:37.159: D/CurrencyConverter(668): fileLine = Missing Symbols List.

As you can see the "fileLine" String variable, in the first case it gets the proper rates, while at the second, the quotes.csv file merely contains the "Missing Symbols List." value.
EDIT2: I have uploaded to a shared folder the complete Android project, so everyone can try it. You may compile and run with both Android 2.x and 4 emulators (or phones if you have :-))
EDIT3: Although this is not a direct answer, still it is a workaround. I use the Google currency calculator instead of the Yahoo one. To use the Google currency calculator, simply change the Yahoo url with this one: http://www.google.com/ig/calculator?hl=en&q=1" + fromCurrency + "=?" + toCurrency. Click this link to see an example of converting 78 Euros to USDs. I checked and it works with both Android versions. However if anyone finds out why this is happening with the Yahoo site, it would be good to share it with us..

A: Try to remove  urlConnection.setDoOutput(true); when you run in ICS. Because ICS turns GET request to POST when setDoOutput(true).
This problem is reported here and here


Q: Hadoop: ERROR conf.Configuration: error parsing conf core-site.xml Trying to set up a single-node system and am getting this error when running
hadoop jar HadoopWordCount.jar HadoopWordCount input.txt output

from the command line. and getting the following error. Input, output, and jar file are all in the same directory.
2018-08-30 10:43:23,266 ERROR conf.Configuration: error parsing conf core-site.xml
com.ctc.wstx.exc.WstxParsingException: Illegal to have multiple roots (start tag in epilog?).
 at [row,col,system-id]: [22,2,"file:/usr/local/Cellar/hadoop/3.1.1/libexec/etc/hadoop/core-site.xml"]

Runs perfectly in IntelliJ but assignment calls for the command line. Below is the core-site.xml file.
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<!--
  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License. See accompanying LICENSE file.
-->

<!-- Put site-specific property overrides in this file. -->

<configuration>
</configuration>

<property>
<name>hadoop.tmp.dir</name>
<value>/usr/local/Cellar/hadoop/hdfs/tmp</value>
<description>A base for other temporary directories.</description>
</property>
<property>
<name>fs.default.name</name>
<value>hdfs://localhost:9000</value>
</property>

A: property tag should be within configuration tag
<configuration>
  <property>
    <name>hadoop.tmp.dir</name>
    <value>/usr/local/Cellar/hadoop/hdfs/tmp</value>
    <description>A base for other temporary directories.</description>
  </property>
  <property>
    <name>fs.default.name</name>
    <value>hdfs://localhost:9000</value>
  </property>
</configuration>


Q: How to display the Navigation item title in IOS 7? I'm using this code.suggest me.
UINavigationItem *navigationItem = [[UINavigationItem alloc] init];
    [self.navigationController.navigationBar setBarTintColor:[UIColor redColor]];
    [self.navigationController.navigationBar setTranslucent:NO];
    self.navigationItem.title=@"Mliestones";

A: use this
self.navigationItem.title = @"The title";


Q: EF6 Many to Many Relationship: SqlException: Invalid column name 'SubAccount_SubAccountID' I'm getting an error while loading my data from Entity Framework EF6 with:
SqlException: Invalid column name 'SubAccount_SubAccountID'.
This is my query to EF6:
var subAccounts = Context
            .SubAccount
            .Include(i => i.Users)
            .ToList();

Exception Image
this ICollation Users is a many to many relationship using Fluent API.
This is the Fluent API configuration in the UserConfiguration class:
HasMany(p => p.SubAccounts)
            .WithMany(r => r.Users)
            .Map(mc =>
            {
                mc.MapLeftKey("UserID");
                mc.MapLeftKey("SubAccountID");
                mc.ToTable("MOB_USER_SUBACCOUNT");
            });

Can someone help me please?

A: Try this guide:
https://www.entityframeworktutorial.net/code-first/configure-many-to-many-relationship-in-code-first.aspx
It will guide you trough the configuration of a Many To Many relationship, using EF6 Code First and Fluent Api


Q: Is having a active MySQL Connection for long periods of time bad? I'm developing an MMORPG, it's pretty far along.
However, I'm noticing now that the MySQL Server has a automatic connection terminate time limit. So after x time, a connection is terminated. So what's happening with my server is after about 8 hours of run time, users can't login or update their characters on logout.
A simple fix would be to make the time out value very very large, but I want to know if this is a bad idea?
Another solution would be, to check if the connection is still valid before making a SQL Query, and if not start a new connection. Although I prefer the first option if it has no bad side-effects.

A: In case you're not already doing that I'd like to say that the best option would be to use a proper connection pool on the server instead of reusing a single connection.
Now, increasing the timeout SHOULD be safe, but MySQL might have memory leaks (of sorts) that are tied to the connection, so dropping the connection from time to time might be much safer.
For example, if you're using dynamically generated prepared queries (some APIs do that to make the queries safe from the SQL injection attacks) then MySQL might have a problem caching all the prepared queries in memory.
You might have to implement such eviction yourself, unfortunately.


Q: Textarea startswith function not working I am trying to apply starts with function on textarea, but obviously I am doing something wrong. I don't understand javascript, so I am sorry for obvious mistakes or problems. At least I tried what seemed logical to me... Fiddle here: http://jsfiddle.net/SVxbW/235/
HTML:

$("textarea").bind(function () {
  if ($(this).startsWith("Hello") {
      $(".kuk").show();
  }
  else {
   $(".kuk").hide();
  }
});
.kuk {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<textarea></textarea>
<button class="kuk">Clear</button>

And what if someone pastes the text "Hello" with right click of mouse? How to recognize that action too?

A: You need to get the val() then use startsWith(). Additionally you need to bind proper event handler. Here I have used keyup
$("textarea").on('keyup', function() {
    if ($(this).val().startsWith("Hello")) {
        $(".kuk").show();
    } else {
        $(".kuk").hide();
    }
});

Updated Fiddle

A: Try this. You need to bind an event also you need to get val to check whether it startswith hello or not.
 $("textarea").bind('keyup',function () {
       if ($(this).val().startsWith("Hello")) {
          $(".kuk").show();
       }
       else {
          $(".kuk").hide();
       }
    });

Here is jsfiddle

A: I made jsfiddle for those wondering which code I am using right now. I added few kinds of input options and now it works in chrome as well.
final fiddle
$("textarea").bind('change keyup paste blur input',function () {
   if ($(this).val().startsWith("Hello") || $(this).val().startsWith("HELLO") || $(this).val().startsWith("hello")) {
      $(".kuk").show();
   }
   else {
      $(".kuk").hide();
   }
});


Q: nested object JSON sorting JavaScript I'm not sure I am asking the right question or not.
I get a JSON response like this from my server request
{
"20150917":
     {
         "Daily01sec":
            {
                "TG01152600000": "\/20150917\/Daily01sec\/TG0115260.bin",
                "TG01152600600": "\/20150917\/Daily01sec\/TG0115260.bin",
            }
        },
"201510":
        {
            "05":
            {
                "Daily01sec":
                {
                    "TG01152780600": "\/201510\/05\/Daily01sec\/TG01152780600.bin",
                }
            }
        },
"201509":
        {
            "05":
            {
                "Daily01sec":
                {
                    "TG01152780600": "\/201510\/05\/Daily01sec\/TG01152780600.bin",
                }
            }
        }
}

I want to count all folders and sort them.
I want to get sorted like this for master folders:
"201509"
"201510"
"20150817"

please check the example data at here
http://jsfiddle.net/ebrahimmm/ncykb0qq/1/
here is the code receiving via $http at angularJS
angular.module('app',[])
    .controller('cntl',function($scope,$http){
    $http.get('http://'+'server' + "/getdatalogtree").
    then(
       function (response) {
        var data=response.data;
       //here i need sorting
       },function(response){
    });
});

I also want to put each mast folders and its content to be an element of an array.

A: You can use Object.keys(Your_JSON_Response) method, to get array of keys.
And then Array.sort() method...

A: Edit :: One-Liner
This should do the job :
function foo(dataString) {
  return Object.keys(JSON.parse(dataString)).map(parseFloat).sort(function(a,b) {return a[0]-b[0]}).map(String); //datastring -> Your JSON string which you get from the server
}

A: This one line will do this job:
function foo(dataString) {
    return Object.keys(dataString).sort();}


Q: Rails 4 - ActiveModel::ForbiddenAttributesError with has_many and accepts_nested_attributes_for I have a problem with accepts_nested_attributes_for..
Here's my Zone model
class Zone < ActiveRecord::Base
  has_many :zones_users, inverse_of: :zone, dependent: :delete_all
  has_many :users, through: :zones_users
  accepts_nested_attributes_for :zones_users, :update_only => true, :allow_destroy => true
end

and ZonesUser model for the many-to-many association with the User model
class ZonesUser < ActiveRecord::Base
  belongs_to :zone
  belongs_to :user
end

now in the ZonesController I'm permitting attributes and nested attributes for the ZonesUser association as follows
def zone_params
  params.require(:zone)
.permit(:id, :name, :description, :image, zones_users_attributes: [:user_id, :zone_id, :is_admin])
end

so that I can update the Zone's data and the association all at once as follows
def update
  @zone = Zone.find_by_id(zone_params[:id])
  @zone.update(zone_params)
end

but this gives me the error ActiveModel::ForbiddenAttributesError
and the error goes like this:
ActiveModel::ForbiddenAttributesError - ActiveModel::ForbiddenAttributesError:
  activemodel (4.2.4) lib/active_model/forbidden_attributes_protection.rb:21:in `sanitize_for_mass_assignment'
  activerecord (4.2.4) lib/active_record/attribute_assignment.rb:33:in `assign_attributes'
  activerecord (4.2.4) lib/active_record/core.rb:564:in `init_attributes'
  activerecord (4.2.4) lib/active_record/core.rb:281:in `initialize'
  activerecord (4.2.4) lib/active_record/inheritance.rb:61:in `new'
  activerecord (4.2.4) lib/active_record/reflection.rb:131:in `build_association'
  activerecord (4.2.4) lib/active_record/associations/association.rb:250:in `build_record'

I'm using rails 4, and have read that attr_accessible is no longer used to allow access to nested models/associations, and that I should permit the attributes on a controller level (the permit zones_users_attributes part).. what have I missed?


Q: Create Interface All Optional Fields from class I have a constructor that takes as a parameter an object containing properties of the object.
class MyObj {
    a = 0;
    b = 0;
    c = 0;
    d = 0;
    constructor(params){
        for(var i in params)
            this[i] = params[i];
    }
}

My goal is to have autocompletion when writing something like new MyObj({a:1}).
Right now, I need to create a separated interface to have autocompletion
interface MyObjOptions {
    a?:number;
    b?:number;
    c?:number;
    d?:number;
}

with constructor(params:MyObjOptions){...}
Is there a way to do that without having to duplicate all fields in an interface?

A:
Is there a way to do that without having to duplicate all fields in an interface?

You can put the object into a config property:
interface MyObjOptions {
    a?:number;
    b?:number;
    c?:number;
    d?:number;
}

class MyObj {
    constructor(public options:MyObjOptions) {
    }
}

But if you want defaults you have to list them in the interface + write them out so you must write e.g. a twice. No way around it


Q: Collision detection between ImageViews I need help getting two ImageViews to collide, I looked around on this website and many youtube videos and think I have found one solution to my problem. I found some code from another person post,
how to detect when a ImageView is in collision with another ImageView?
and I'm just wondering where I should place that code in my program because when it's at the bottom i try to log.d to show if I was succesful on trying to detect whether the imageViews collided and nothing shows. Anyways here is my code and the code I used from the other question is at the very bottom and used as a comment. YOUR HELP IS EXTREMELY APPRECIATED, THANK YOU IF YOU HELPED ME!
Main.java
package com.example.admin.basketball;

import android.graphics.Point;

import android.os.Handler;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import android.view.Display;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

//Layout
private RelativeLayout myLayout = null;

//Screen Size
private int screenWidth;
private int screenHeight;

//Position
private float ballDownY;
private float ballDownX;

//Initialize Class
private Handler handler = new Handler();
private Timer timer = new Timer();

//Images
private ImageView net = null;
private ImageView ball = null;

//for net movement along x-axis
float x;
float y;

//points
private int points = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    myLayout = (RelativeLayout) findViewById(R.id.myLayout);

    //score
    final TextView score = (TextView) findViewById(R.id.score);

    //imageviews
    net = (ImageView) findViewById(R.id.net);
    ball = (ImageView) findViewById(R.id.ball);

    //retrieving screen size
    WindowManager wm = getWindowManager();
    Display disp = wm.getDefaultDisplay();
    Point size = new Point();
    disp.getSize(size);
    screenWidth = size.x;
    screenHeight = size.y;

    //move to out of screen
    ball.setX(-80.0f);
    ball.setY(screenHeight + 80.0f);

    //start timer
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    changePos();
                }
            });
        }
    }, 0, 20);
}

public void changePos() {
    //down

    ballDownY += 10;
    if (ball.getY() > screenHeight) {
        ballDownX = (float) Math.floor((Math.random() * (screenWidth -
ball.getWidth())));
        ballDownY = -100.0f;

    }
    ball.setY(ballDownY);
    ball.setX(ballDownX);

    //make net follow finger
    myLayout.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent event) {
            MainActivity.this.x = event.getX();
            y = event.getY();

            if (event.getAction() == MotionEvent.ACTION_MOVE) {
                net.setX(MainActivity.this.x);
                net.setY(y);

            }
            return true;
        }
    });
}

}

/*
private boolean viewsOverlap(ImageView net, ImageView ball) {

    int[] net_coords = new int[2];
    net.getLocationOnScreen(net_coords);
    int net_w = net.getWidth();
    int net_h = net.getHeight();
    Rect net_rect = new Rect(net_coords[0], net_coords[1], net_coords[0] +
net_w, net_coords[1] + net_h);

    int[] ball_coords = new int[2];
    ball.getLocationOnScreen(ball_coords);
    int ball_w = ball.getWidth();
    int ball_h = ball.getHeight();
    Rect ball_rect = new Rect(ball_coords[0], ball_coords[1], ball_coords[0]
+ ball_w, ball_coords[1] + ball_h);

    return net_rect.intersect(ball_rect) || net_rect.contains(ball_rect) ||
ball_rect.contains(net_rect);

}*/

A: Collision detction and score increase ;-)
public class MainActivity extends AppCompatActivity
{
   //Layout
   private RelativeLayout myLayout = null;

   //Screen Size
   private int screenWidth;
   private int screenHeight;

   //Position
   private float ballDownY;
   private float ballDownX;

   //Initialize Class
   private Handler handler = new Handler();
   private Timer timer = new Timer();

   //Images
   private ImageView net = null;
   private ImageView ball = null;

   //score
   private TextView score = null;

   //for net movement along x-axis
   public float x = 0;
   public float y = 0;

   //points
   private int points = 0;

   @Override
    protected void onCreate(Bundle savedInstanceState)
    {
         super.onCreate(savedInstanceState);

         this.setContentView(R.layout.activity_main);
         this.myLayout = (RelativeLayout) findViewById(R.id.myLayout);

         this.score = (TextView) findViewById(R.id.score);

         this.net = (ImageView) findViewById(R.id.net);
         this.ball = (ImageView) findViewById(R.id.ball);

         //retrieving screen size
         WindowManager wm = getWindowManager();
         Display disp = wm.getDefaultDisplay();
         Point size = new Point();
         disp.getSize(size);
         screenWidth = size.x;
         screenHeight = size.y;

         //move to out of screen
         this.ball.setX(-80.0f);
         this.ball.setY(screenHeight + 80.0f);

          //Error here
         /*//Run constantly
         new Handler().postDelayed(new Runnable()
         {
           @Override
           public void run()
           {
              Render();
           }
         }, 100); //100 is miliseconds interval than sleep this process, 1000 miliseconds is 1 second*/

     Thread t = new Thread() {
     @Override
     public void run() {
     try {
        while (!isInterrupted()) {
             Thread.sleep(100);
             runOnUiThread(new Runnable() {
             @Override
             public void run(){Render();}});}
             }catch (InterruptedException e) {}}};

     t.start();

    }

    public void Render()
    {
        changePos();
        if(Collision(net, ball))
        {
          points++; //You dont need findView Textview score for that exists in OnCreate Method
          this.score.setText("Score:" + points);
        }
    }

    public void changePos()
    {

        //down
        ballDownY += 10;
        if (ball.getY() > screenHeight) {
        ballDownX = (float) Math.floor((Math.random() * (screenWidth - ball.getWidth())));
        ballDownY = -100.0f;

    }
    ball.setY(ballDownY);
    ball.setX(ballDownX);

      //make net follow finger
      myLayout.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent event) {
            x = event.getX();
            y = event.getY();

            if (event.getAction() == MotionEvent.ACTION_MOVE) {
                net.setX(x);
                net.setY(y);
            }
            return true;
        }

    });

    public boolean Collision(ImageView net, ImageView ball)
    {
       Rect BallRect = new Rect();
       ball.getHitRect(BallRect);
       Rect NetRect = new Rect();
       net.getHitRect(NetRect);
       return BallRect.intersect(NetRect);
    }
}

A: Let me give you an example how I implemented working collision detection in only 10 rows of code. It is not exactly the same problem but it can give you an idea how to manipulate objects based on coordinates.
 // update the canvas in order to display the game action
    @Override
    public void onDraw(Canvas canvas) {

        super.onDraw(canvas);
        int xx = 200;
        int yy = 0;
        if (persons != null) {
            synchronized (persons) {
                Iterator<Person> iterate = persons.iterator();
                while (iterate.hasNext()) {
                    Person p = iterate.next();
                    if (p.getImage() != 0) {
                        bitmap = BitmapFactory.decodeResource(getResources(), p.getImage()); //load a character image
                        // Draw the visible person's appearance
                        if(xx > canvas.getWidth())
                            xx = 0;
                        canvas.drawBitmap(bitmap, xx , canvas.getHeight()- bitmap.getHeight() , null);
                        // Draw the name
                        Paint paint = new Paint();
                        paint.setStyle(Paint.Style.FILL);
                        canvas.save();
                        paint.setStrokeWidth(1);
                        paint.setColor(Color.WHITE);
                        paint.setTextSize(50);
                        canvas.drawText(p.name, (float)(xx+0.25*bitmap.getWidth()), (float) (canvas.getHeight() ), paint);
                        xx += bitmap.getWidth()*0.75;
                    }
                }
            }
        }
        canvas.save(); //Save the position of the canvas.
        canvas.restore();
        //Call the next frame.
        invalidate();
    }
}

In the above code, I just check if xx collides with an array of other images, then I just update xx accordingly. You are welcome to check out my open source repository with this code.


Q: How to find probability of drawing ball from a given container? A container having 2 balls, one is red and second one is black.
One ball is drawn each time and placed again in the container.Drawing of ball is done ntimes where 1<=n<=10^6.I want to find out the probability of drawing red ball at least rwhere 0<=r<=n.For example, let n=3and r=2then probability pcan be calculated as :
p=( C(3,2)+C(3,3) ) / (2^3)
p=(3+1)/8
p=0.5

where C(n,r) = n!/(n-r)!r!.
It can also be solved using binomial distribution.
But, it is difficult to calculate for given nand r.

A: You can try using logarithms, i.e. instead of
 P(r, n) = n! / ((n-r)! * r! * r**n)

compute just
 log(P(r, r)) = log(n!) - log((n-r)!) - log(r!) - r*log(n)

All factorials are easy computable as logarithms:
 log(n!) = log(n) + log(n - 1) + ... + log(2) + log(1)

When obtain log(P(r, n)) all you have to do is to exponentiate. As a further improvement you can use Stirling's approximation for the factorials in case n is large:
 n! ~ (n / e)**n * sqrt(2 * PI * n)

so (ln stands for the natural logarithm)
 ln(n!) ~ n * ln(n) - n - ln(n)/2 - ln(2 * PI)/2

Edit: If you are looking for CDF (Cumulative Distribution Function, probability that random value is less or equal given x), it can be represented as regularized imcomplete beta function:
https://en.wikipedia.org/wiki/Binomial_distribution
P(x <= k) = I(1 - p, n - r, r+1)
p = 1/2 in your case

in case C++, the implementation can be found in Boost


Q: Broken/missing handler after reinstall my site recently got deleted by a possible hack. I uploaded backed up folders and the db but now my views are not showing. everything else works.  i can't think of anything that changed, just uploaded a backup from a few days ago.
the fields are showing this in admin/build/views/edit/nameofview
Broken/missing handler: node_data_field_guru_photo > field_guru_photo_fid
Broken/missing handler: node > title
Broken/missing handler: views > nothing
Broken/missing handler: node_revisions > body
Broken/missing handler: node_data_field_guru_link > field_guru_link_url

I tried clearing cache
I rearanged the fields in views and updated them and got this error
Display "Defaults" uses fields but there are none defined for it or all are excluded.

A: Normally just clearing Drupal's cache would fix this but if not go into the 'Manage Fields' screen for the content type to which node_data_field_guru_photo, node_data_field_guru_link etc. are attached, make a temporary change (e.g. to the order of the fields) and save. That should force a refresh of the field cache and you should be on your way.

A: Just rearrange the order of you content type fields and then save it. In my case broken or missing handler was showing for Class content type. rearranging the content type fields solved my problem.


Q: Does TeX always insert the macro \par? When the input processor encounters two characters with category code 5 in a row (in other words, a blank line), it inserts the \par macro.
When \vbox{Abc.} ends, TeX ends the current paragraph, but not by inserting the \par macro. It seems that TeX is inserting the \par primitive instead. Am I understanding correctly what TeX is doing in this case? What about other places where TeX inserts \par? When is it the macro \par, and when the primitive?
\catcode`@=11
\let\@@par\par
\def\par{\typeout{Macro!}\@@par}

Abc.

\vbox{Abc.\tracingall}

A: There are exactly 7 places in the TeX program where TeX executes the paragraph builder internally, i.e. turning a horizontal list (if there is one under construction) into a paragraph. This happens not by inserting a \par token into the input stream but by executing the procedure end_graf implemented in module §1096 in the TeX program.
This procedure does nothing if TeX is not in horizontal mode, more or less nothing if in horizontal mode but with an empty list (null paragraphs are ignored by TeX), and executes the procedure line_break otherwise (and that one does all the magic about adding parfillskip penalties, etc.).
The seven places are

*

*at the end of the internal vertical structures like the closing brace of a \vbox but also \noalign or \vcenter or an alignment cell

*when the primitive par_end is sensed (which is available on the macro level initially as the meaning of the token \par)

*immediately after an output routine (OR) has ended (thus any horizontal list started in the OR will not continue with material from the galley but form a paragraph by its own)

In none of these cases there is a \par token inserted (that might be subject to redefinitions); instead, the end_graf procedure is executed!
\par tokens are only inserted when in horizontal mode and primitives incompatible with horizontal mode (like \vskip, \hrule, ... the full list in is §1094 in the TeX code) are encountered. And of course in the tokenization process when TeX replaces two endline chars by \par (i.e., making empty lines equivalent to \par).

A: There is a reason why TeX puts the "original meaning" of \par at the end of a \vbox: consider the following silly input
\vbox{\let\par\empty a}

When TeX finds }, it backs it up, terminates horizontal mode by inserting the "original \par" and then rereads the } that closes the internal vertical mode.
We can emulate what would happen if TeX inserted the current meaning of \par before rereading the } by
\vbox{\let\par\empty a\vskip0pt}

because \vskip inserts a (current) \par and TeX rereads \vskip. The result is an infinite loop!
(Found in a 1993 discussion on comp.text.tex.)

A: According to The TeXbook, the rule for end-of-lines is as follows

If TeX sees an end-of-line character (category 5), it throws away
  any other information that might remain on the current line. Then if
  TeX is in state N (new line), the end-of-line character is
  converted to the control sequence token \par (end of
  paragraph); if TeX is in state M (mid-line), the end-of-line
  character is converted to a token for character 32 ( ) of
  category 10 (space); and if TeX is in state S (skipping
  blanks), the end-of-line character is simply dropped.

Here, it's important to note that the TeX inserts the \par token, and not the \par primitive. That means that \par has to be defined under all circumstances. Knuth illustrates this point when discussing commands which force horizontal mode:

The appearance of a <vertical command> in restricted horizontal mode
  is forbidden, but in regular horizontal mode it causes TeX to insert
  the token \par into the input; after reading and expanding this
  \par token, TeX will see the <vertical command> token again.
  (The current meaning of the control sequence \par will be used;
  \par might no longer stand for TeX's \par primitive.)

Now, what does not seem to be mentioned anywhere is what happens at the end of internal vertical mode. Clearly, the rules above do not allow for the insertion of a \par token as there are no end-of-line markers to deal with. (You do get a \par inserted if there is a blank line between the last material in the \vbox and the end of the box.)
Reading the trace output, there is no mention of the \par primitive at the end of the box, but the shipout does show
....\penalty 10000
....\glue(\parfillskip) 0.0 plus 1.0fil

and of course there is clearly a paragraph built. So my conclusion is that the end of internal vertical mode implicitly inserts a \par primitive, and thus inserts the usual end-of-paragraph material and then runs the paragraph builder.


Q: Is there any way to add markers above overlay in google maps react? I am trying to add overlay above the map and place the marker above the overlay. but I am not able to do so. how I can do it? and I am using the google-maps-react library as a dependency.

    <Map
      key={active}
      google={google}
      containerStyle={containerStyle}
      zoom={5}
      disableDefaultUI
      initialCenter={{
        lat: markers[0].position.lat,
        lng: markers[0].position.lng,
      }}
    >

      <Marker
        title="The marker`s title will appear as a tooltip."
        name="SOMA"
        position={{ lat: 37.778519, lng: -122.40564 }}
      />
    </Map>

the view right now

A: You can do this by using the GroundOverlay object of Google Maps JavaScript API. But you need to get the current map object used in your google-maps-react code and you will use this to setMap the overlay into this map ref.
See the sample code and code snippet below:
import React, { Component } from 'react';
import { Map, GoogleApiWrapper, Marker } from 'google-maps-react';

const mapStyles = {
  width: '100%',
  height: '100%',
};

const imageBounds = {
  north: 40.773941,
  south: 40.712216,
  east: -74.12544,
  west: -74.22655,
};

class MapWithOverlay extends Component {
  mapRef = (ref) => {
    let historicalOverlay = new google.maps.GroundOverlay(
      'https://storage.googleapis.com/geo-devrel-public-buckets/newark_nj_1922-661x516.jpeg',
      imageBounds
    );
    historicalOverlay.setMap(ref.map);
  };

  render() {
    return (
      <>

          <Map
            ref={(ref) => {
              this.mapRef(ref);
            }}
            google={this.props.google}
            zoom={12}
            style={mapStyles}
            initialCenter={{ lat: 40.74, lng: -74.18 }}
          >
            <Marker position={{ lat: 40.74, lng: -74.18 }} />
          </Map>

      </>
    );
  }
}

export default GoogleApiWrapper({
  apiKey: 'YOUR_KEY',
})(MapWithOverlay);


Q: Find the generating function for the sequence ${1, 2, 1, 4, 1, 8, ...}$ I have tried a few basic technique. But it seems still can't come up with a closed form for this sequence ${1, 2, 1, 4, 1, 8, ...}$. See if anyone can give me a hint?

A: Hint:

*

*Find the generating function for 1,1,1,1, ...

*Deduce the generating function for 1,0,1,0,1,0,1, ...

*Find the generating function for 2,4,8,16, ...

*Deduce the generating function for 2,0,4,0,8,0,16, ...

*Deduce the generating function for 0,2,0,4,0,8,0,16, ...

*Deduce the generating function you are interested in.