text:
Q: Webview - How to link it to a android app and then work on the operations Got a pretty hectic task for myself here and i'm done with googling it ..
Im presently working on an app that has to take an

*

*input , (String )(EditText) from the user end .

*Use that string and pass it on to a webview , so that the search is done based on this string , (for eg: lets take youtube as an example so the passed content is a Songs name).

*Once the search has been made the app has to pickup the url of the present search made .... i.e in youtube when we search for something we get the url as
"https://www.youtube.com/watch?v=zS4F49XqLWo" so the app has to store this url .

*Paste the url onto another site and then Click on some buttons on that site (The major problem part -- how do i get the app to automatically click on buttons on another site ??)
Im just a novice at Android Development , espacially at the html side of it ... so kindly bear with me !!...


text:
Q: How to get specific id's from different MySQL Tables I know it sounds awful but I couldn't find a way to express what I need.I am currently constructing a class that checks for a basketball team if the same ticket was "hit' in the same event by getting the id's from 2 different tables. My DB consists of 3 Tables.The 1st is the 'tickets' table in which the user gives the name,the year and the ticket name. The 2nd is the 'events' table where the user gives the basketball event and the year. Now the last table is where I am confused.( I have already checked if the same event occurs in the same year cause it is impossible in a Championship to play 2 times on the same stadium).I have not checked if the same ticket appears on the same event and that is what I am trying to do.
The 3rd table is the 'check' table. I have 3 integer variables( id, ticket_id, event_id) and I want to get the ticket_id from tickets table and 1st column( which is the auto-incremented id) and do the same for the event_id from the events table(1st column is id of course).
Then I want to check and make sure they do not match more than 1 time and return a boolean value.
This is what I have came up so far.
P.S Sorry for the long post but I am so confused about this...
import java.sql.ResultSet;
import java.sql.SQLException;

public class check {

private int ticket_id,event_id;

public int getTicket_id() {
    return ticket_id;
}

public void setTicket_id(int ticket_id) {
    this.ticket_id = ticket_id;
}

public int getEvent_id() {
    return event_id;
}

public void setEvent_id(int event_id) {
    this.event_id = event_id;
}

public check(int ticket_id, int event_id) {
    super();
    this.ticket_id = ticket_id;
    this.event_id = event_id;
}

public boolean checkExistance_3 (){

String errMsg = "";
// class that connects with the MySQL DB
ServerConn sc = new ServerConn();
String sql3 = "SELECT Count(*) AS RowCount FROM events INNER JOIN tickets on tickets.id = events.id WHERE tickets.id = '" + ticket_id  + "' AND events.id =" + event_id ;
 // HOW TO GIVE VALUES AT ticket_id and event_id??? this is my problem
 // I dont now if a need a SELECT with rs.next() because it would return all id's!

 // class that executes queries
 ResultSet rs3 = sc.dbQuery(sql3);

 if (errMsg.equals(""))
   {
    try {
    rs3.next();
    int rows = rs3.getInt("RowCount");
    } catch (SQLException case1) {
    case1.printStackTrace();
    } catch (Exception case2) {
    case2.printStackTrace();}
    return true;
      }
    return false;
 }

}

I chose not to put how the other 4 classes work cause it would be more confusing. In case another class is needed to clarify things, I will add it on my post.
Tickets Table

Events Table

I created a class that saves the id's on the 3rd table but the variables in the sql and sql_1 statements cannot be resolved cause they belong to different classes. Is it possible to inherite variables from different classes?
public String SaveId() {

String errMsg2 = "";

if ( errMsg2.equals("") ) {
   try
   {

        ServerConn sc = new ServerConn();
        // sql_game and ticketNumber appear on other classes. Can I inherit them?
        // wont find the variables, error.
        String sql = "SELECT (id) FROM events WHERE decsrp = '" + sql_game + "'";
        String sql_1 = "SELECT (id) FROM tickets WHERE ticket = '" + ticketNumber + "'";
        ResultSet rs = sc.dbQuery(sql);
        ResultSet rs_1 = sc.dbQuery(sql_1);
        boolean allowed = true;
        while (rs.next())
               allowed = false;
        while (rs_1.next())
               allowed = false;
        if (allowed == true)
{
    try {
        Connection cn = sc.OpenDatabase();
        PreparedStatement ps2 = cn.prepareStatement("INSERT INTO elenxos (event_id,ticket_id) VALUES (?,?)");
        ps2.setInt(1,this.event_id);
        ps2.setInt(2,this.ticket_id);
        ps2.executeUpdate();
        JOptionPane.showMessageDialog(null,"Valid Ticket");
        } catch (SQLException case1) {
            case1.printStackTrace();
        } catch (Exception case2){
           case2.printStackTrace();}
        }
         else if (allowed == false)
            errMsg2 += "Impossible to use the same ticket 2 times!!";
        }catch (SQLException e)
        {
            System.out.println("8");
        }
         catch (Exception e)
        {
            System.out.println("9");
        }
    } else {
            errMsg2 += "FAILURE!!" ;
           }
        return errMsg2;
    }

A: It appears that you are wrestling with how to execute a query that will have different query values each time you execute the query. You should use PreparedStatement to handle this situation. This will allow you to use the same statement, once created, and supply it with different values.  In addition, your database queries could be improved if you are simply trying to see if a duplicate occurs.
Consider the following:
package com.example.db;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class Check {
    // Class fields
    private PreparedStatement check;
    private String checkQuery = "Select Count(*)"
            + "  from events inner join tickets on tickets.id = events.id"
            + " where tickets.id = ? " + "   and events.id = ? ";

    // Object fields
    private int ticket_id;
    private int event_id;

    public Check(int ticket_id, int event_id) {
        super();
        this.ticket_id = ticket_id;
        this.event_id = event_id;

    }

    public int getTicket_id() {
        return ticket_id;
    }

    public void setTicket_id(int ticket_id) {
        this.ticket_id = ticket_id;
    }

    public int getEvent_id() {
        return event_id;
    }

    public void setEvent_id(int event_id) {
        this.event_id = event_id;
    }

    public boolean checkExistance_3(Connection sc) {
        boolean returnValue = false;
        // TODO previously established db connnection passed performance reasons

        try {
            check = sc.prepareStatement(checkQuery);
            // the first argument is the varialbe indes, the second the value to
            // supstitute
            check.setInt(1, ticket_id);
            check.setInt(2, event_id);
            ResultSet results = check.executeQuery();
            results.next();
            int countResult = results.getInt("RowCount");
            if (countResult > 1) {
                returnValue = true;
            }

        } catch (SQLException e) {
            System.out.println("Error querying database: " + e.getMessage());
        }
        return returnValue;
    }
}

A:
Then I want to check and make sure they do not match more than 1 time and return a boolean value.

You don't need any checks for duplicates in Java, this stuff should always be handled on the database side.
Also you don't need a third table at all, because normally a ticket only grants you entry to a certain event. Therefore you should have a 1:n relationship.
You should just be able to use the event_id as a foreign key column in the tickets table and define the primary key as the combination of ticket_id and event_id. This will solve all your problems.

redpajama_set_name: RedPajamaStackExchange


text:
Q: The force vector is not in the direction of the lowest potential
An object moving on a one-dimensional line is subject to a force. The
  force is conservative and the associated potential energy function is
  $$U(x) = x^4 - 2x^2$$
  Find the force vector.

The force vector for this potential function should be $\vec{F} = 4x^3 - 4x$, but if you examine their graph,
we can see that the force vector doesn't always point the lowest energy point, i.e equilibrium point.So, what is the problem ? I mean physically, the force vector must always be in the direction of the lowest energy.Note that the function that is in the shape of reverse M is the potential function.


text:
Q: Compare JSON structures I want to compare received JSON data to a JSON 'template', and if it differs in structure (not in data itself) then do something,like discarding that JSON.
Template:
{
"data":{
    "id":"1",
    "cmd":"34"
}

Succesfull Json:
{
"data":{
    "id":"15",
    "cmd":"4"
}

Unsuccesfull Json:
{
"data":{
    "id":"15"
}

This is only an example, the JSON to evaluate is going to be larger, and I want to avoid checking if each property exists. (This is possible in other languages, hence this question)

A: It sounds like you're looking for JSON Schema or other similar tools.
JavaScript itself doesn't provide anything built-in to do this for you. So you'll need an already-written tool to do it (such as JSON Schema) or you'll have to do it yourself, checking the existence and (depending on how strict you want to be) type of each property in the received JSON. You can do that either after parsing or during parsing by hooking into the parsing process via a "reviver" function you pass into JSON.parse, but either way is going to require doing the checks. (Given the inside-to-outside way JSON.parse works, I suspect using a reviver for this would be quite hard though. Much better to use a recursive function on the parsed data afterward.)

A: I would recommend converting it to object JSON.parse(), so you can use javascript API.
If your structure gets more robust in the future (more levels etc), you would be still able to do deep compares. Libraries like Immutable.js will come handy, as it used to compare complex states in React applications.

A: I recently faced this problem as well. I needed to make some comparisons on some objects (should work for JSON as well). I wrote a package for doing this that might come in handy for people facing this issue in the future (bit late for the topic starter).
https://www.npmjs.com/package/js-object-compare


text:
Q: Move to top inner table How I close this gap between the inner table and the main table cell?
https://jsfiddle.net/w7eekbcL/2/

                    main list

                    list

                    • one

                    • second

                    • thurd

For example I tried to use text-aligment but the result is the same.

A: Add vertical-align: top to the td that contains the table.


text:
Q: HTMX not working when using paginate with infinite-scroll I have a product card in my Django Application, when clicked, adds to cart. I'm using infinite-scroll and django-pagination.
The issue is with the pagination, however. The first page of results works wonderfully with HTMX. However, the second page and all pages beyond does not work on click. Upon inspecting the page, the html does appear to be rendered properly and I can see the hx-get call with the proper url. But upon clicking, nothing happens.
Maybe I'm missing something obvious here, but any help would be appreciated!
HTML

        {% block content %}
        {% include 'includes/cards.html' %}
        {% include 'includes/sidebar.html' %}
        {% endblock content %}

            {% if products.has_previous %}

             {% endif %}

{{ products.number }}

              {% if products.has_next %}

             {% endif %}

views.py
def shop(request):
anabanner = AnaBanner.objects.all()
gender = Gender.objects.all()
categories = Category.objects.all()
colors = Color.objects.all()
materials = Material.objects.all()
query = request.GET.get('query','')
products = Product.objects.all().order_by('-pk')
if query:
    products = products.filter(
        Q(name__icontains=query)|
        Q(sub_name__icontains=query)
    ).distinct()
paginator = Paginator(products, 8)

page = request.GET.get('page')

products = paginator.get_page(page)
context = {'products':products,'categories':categories,'gender':gender,'anabanner':anabanner,'colors':colors,'materials':materials}
return render(request, 'shop.html', context)

Button

  <button name="ekle"
  href ="#"
  hx-get="{% url 'add_to_cart' product.id %}"
  hx-target="#menu-cart-button"
  hx-swap="outerHTML"
  class="btn btn-outline-secondary add-btn update-cart">Sepete Ekle</button>

A: Here i my Infinite scroll pattern django with HTMX
urls.py
highlights_urls = [
path('<slug:slug>/',
     views.highlight_detail,
     name='highlight_detail',
     ),
]

urlpatterns = [
     path('highlights/', include(highlights_urls)),
]

views.py
def highlight_detail(request, slug: str):
object: Highlight = get_object_or_404(Highlight, slug=slug)

template_name = 'highlight/highlight-detail.html'
if request.htmx:
    template_name = 'highlight/partials/highlight-detail-partial-elements.html'

page_number = request.GET.get('page', default=1)
paginator = Paginator(object.products.all(), settings.PAGINATION_PAGE_SIZE)
page_obj = paginator.get_page(page_number)

context = {
    'object': object,
    'page_obj': page_obj
}

return TemplateResponse(request, template=template_name, context=context)

highlight-detail.html

{{ object.name }}

        {% include './partials/highlight-detail-partial-elements.html' %}

highlight-detail-partial-elements.html
{% for product in page_obj %}

{% include 'highlight/includes/product-card.html' with object=product %}

{% endfor %}


text:
Q: Has this series for $\ln(2)$ been discovered yet? $$\ln(2)=\frac{1}{2}+\frac{1}{4}-\frac{1}{5}+\frac{1}{6}-\frac{1}{9}+\frac{1}{10}-\frac{1}{11}+\frac{1}{12}-\frac{1}{13}+...$$
This is something I came up with and was intrigued, and no this isn't random; there's a pattern to this.
Since you guys are asking for a relation, here it is;
$$\ln(2)=1+\sum_{n=1}^∞ \frac{(-1)^{S_n-1}}{S_n-1} $$
Where $S_n$ is the $n$-th number that is not a perfect power (A007916, and $S_1$ is $2$). Proof to this is also somewhat easy to derive.

A: Equivalently, the problem is to compute $L=\sum_{s\in S}(-1)^s/(s-1)$ where $S$ is the set of all perfect powers. A similar problem of computing $\sum_{s\in S}1/(s-1)\color{gray}{[{}=1]}$ goes back to Goldbach as far as I know.
The idea is pretty much the same. Let $N$ be the set of all integers (strictly) greater than $1$. Then each $s\in S$ has a representation $s=a^n$ with unique $a\in N\setminus S$ and $n\in N$; the same is true for $s\in N$ if we also allow $n=1$. Hence (each of the series below is absolutely convergent)
\begin{align}
L&=\sum_{a\in N\setminus S}(-1)^a\sum_{n=2}^{\infty}\frac{1}{a^n-1}\\&=\sum_{a\in N\setminus S}(-1)^a\sum_{n=2}^{\infty}\sum_{k=1}^{\infty}a^{-nk}\\&=\sum_{a\in N\setminus S}(-1)^a\sum_{k=1}^{\infty}\frac{1}{a^k(a^k-1)}\\&=\sum_{s\in N}\frac{(-1)^s}{s(s-1)}=2\ln 2-1.
\end{align}
[The sum in the question is $1+\sum_{s\in N\setminus S}(-1)^{s-1}/(s-1)=1-(\ln 2-L)$.]


text:
Q: In a form, I need to populate the contents of same spreadsheet column like 50 times. Is there a way to script this logic with fewer iterations I'm working on a form where I need to pull the contents of a spreadsheet column like 50 times, to try to input multiple items from a list. I see that I can do this by defining a few variables and redoing a small piece of Script again and again. I want to see if anyone can help me overcome this lengthy script to make it smaller with fewer iterations. Thanks.
function updateForm(){
  // call the form and connect to the drop-down items
  var Form_SQ = FormApp.openById("FORM ID");
  var SQ_IT01_List = Form_SQ.getItemById("ITEM 01").asListItem();
  var SQ_IT02_List = Form_SQ.getItemById("ITEM 02").asListItem();
  //Similarly defining upto 50 dropdown lists.

  var SS01 = SpreadsheetApp.getActive();
  var SQ_IT01_Names = SS01.getSheetByName("Sheet2");
  var SQ_IT02_Names = SS01.getSheetByName("Sheet2");
  //Similarly defining upto 50 names lists.

  // Item_01 Part Number Dropdown
  var SQ_IT01_Values = SQ_IT01_Names.getRange(2, 1, SQ_IT01_Names.getMaxRows() - 1).getValues();
  var SQ_IT01_Items = [];
  for(var i = 0; i < SQ_IT01_Values.length; i++)
  if(SQ_IT01_Values[i][0] != "")
  SQ_IT01_Items[i] = SQ_IT01_Values[i][0];
  SQ_IT01_List.setChoiceValues(SQ_IT01_Items);

  // Item_02 Part Number Dropdown
var SQ_IT02_Values = SQ_IT01_Names.getRange(2, 1, SQ_IT02_Names.getMaxRows() - 1).getValues();
  var SQ_IT02_Items = [];
  for(var i = 0; i < SQ_IT02_Values.length; i++)
  if(SQ_IT02_Values[i][0] != "")
  SQ_IT02_Items[i] = SQ_IT02_Values[i][0];
  SQ_IT02_List.setChoiceValues(SQ_IT02_Items);

  //Similarly defining upto 50 lookup lists.

}

A: Problem
Reusing code and making use of loops. Scripting is all about efficiency (see DRY principle): make as little assignments and same-functionality coding as possible - use loops, move reusable code snippets to functions that can be called on demand, etc.
Solution
This sample makes several assumptions:

*

*SQ_IT01_Names is different for each item (in your sample it always is Sheet2 - if this is the case, you don't have to reassign it 50 times, one variable assignment will do just fine).

*You intended to do something when a value is an empty string (the sample just filters them out). As you use the [index] notation, those values in the resulting Array will be undefined (and that's not something one would want in an Array of choice values).

*All items are choice items (if you need id filtering, the sample is easily expanded).

function updateForm() {
  var form = FormApp.openById("FORM ID");

  //access every item;
  var items = form.getItems();

  var ss = SpreadsheetApp.getActive();

  //loop over items;
  items.forEach(function(item,i){
    var namesSheet = ss.getSheetByName('Sheet'+i); //assuming this is diff each time;
    var namesRange = namesSheet.getRange(2,1,namesSheet.getLastRow());
    var namesValues = namesRange.getValues();

    //map values to first column;
    namesValues = namesValues.map(function(value){
      return value[0];
    });

    //filter out undefined (undefined and false functional equivalence);
    namesValues = namesValues.filter(function(value){
      return value;
    });

    item.asListItem().setChoiceValues(namesValues);
  });
}

Notes

*

*Please, use closures {} with loops and if statements, this way you'll be able to keep track of which statements are enclosed in it and save yourself debugging time when looping / conditioning multiple statements.

*Since you only need rows that have data in them, use the getLastRow() method instead of the getMaxRows()-1 calc you have to perform in your script.

Reference

*

*forEach() method reference;

*filter() method reference;

*map() method reference;

*getLastRow() method reference;


text:
Q: Why is Incognito mode disabled in Google Chrome on my mac? I am trying to enable incognito mode in Google Chrome on my MacBook. However, the option is greyed out in the drop down menu. Why is it disabled and how can I enable it?

A: It might have been disabled at the system preferences level, possibly by another admin user on your machine. This post explains how to DISABLE it.
I assume that to ENABLE it again, you must set the IncognitoModeAvailability to a value of 0


text:
Q: Linear Algebra, Finite v.s., basis, range, and proof Suppose $T∈L(V,W)$ and $w_1, ⋯⋯, w_m$ is a basis of range T. Prove that there exist $\varphi_1,\dots, \varphi_m∈ L(V,F)$ such that $Tv=\varphi_1(v)w_1+ \dots +\varphi_m(v)w_m$ for every $v∈V$.

A: Hint: Let $\mathcal{W}=\{w_1,\dots,w_n\}$ denote the basis of $\text{range}(T)$.
For each $i\in\{1,\dots,n\}$, let $\widehat{\mathcal{W}_i}=\mathcal{W}\setminus\{w_i\}$ and let $\Pi_i:W\longrightarrow W$ be the projection onto $\text{span}\big(\{w_i\}\big)$ along $\text{span}$$\left(\widehat{\mathcal{W}_i}\right)$.
Observe that $\text{span}\big(\{w_i\}\big)\oplus\,\text{span}$$\left(\widehat{\mathcal{W}_i}\right)=\text{range}(T)$ is a direct sum, so this is a well-defined projection.
Notice that if $Tv=\varphi_1(v)w_1+ \dots +\varphi_m(v)w_m$, then $\Pi_i(Tv)=\varphi_i(v)w_i$. Do you think you can conclude?


text:
Q: Setting targetSdkVersion and compileSdkVersion for bazel, android tensorflow I need help in how to set the target and compile Sdk versions separately for bazel.
I want to run tensorflow on the phone following this tutorial. After editing WORKSPACE for bazel as follows:
android_sdk_repository(
    name = "androidsdk",
    api_level = 24,
    build_tools_version = "24.0.1",
    path = "/home/Android/Sdk",
)

android_ndk_repository(
    name="androidndk",
    path="/home/Android/Sdk/ndk-bundle",
    api_level=21)

I get PARSE ERROR on the phone upon apk installing:
adb install -r bazel-bin/tensorflow/examples/android/tensorflow_demo.apk

I have usb debugging and 3rd party apk installation enabled. The phone uses Android 4.4.4 so I changed WORKSPACE configuration to match it (tools and API installed by SDK manager properly) as:
android_sdk_repository(
    name = "androidsdk",
    api_level = 19,
    build_tools_version = "19.1.0",
    path = "/home/Android/Sdk",
)

android_ndk_repository(
    name="androidndk",
    path="/home/Android/Sdk/ndk-bundle",
    api_level=21)

Upon building as:
bazel build //tensorflow/examples/android:tensorflow_demo

I end up with few errors of that type:
Error at 5 : /tmp/android_resources_tmp7060220119759636814/merged_resources/values-v21/values.xml:5: error: Error retrieving parent for item: No resource found that matches the given name 'android:Theme.Material.Light'.

Following this answer, I should build for compile API version > 21 but at the same time target API version 19. It can be easily set for gradle. However I have not found any clue how to do that for bazel. Any suggestions are appreciated!

A: If you want to target a lower Android API level, the file you want to edit is actually tensorflow/examples/android/AndroidManifest.xml. Leave the WORKSPACE file settings at the highest API level you have installed via your sdk (APIs can be installed with $ANDROID_HOME/tools/android).
You can lower the min API level to 19 in AndroidManifest.xml, but be aware you will encounter runtime errors on your phone running the demo unless you replace the demo code that interfaces with the camera2 api (which was added with API level 21) with analogous android.hardware.camera code.


text:
Q: Find the integration of $\frac{1-7x}{(1-x)^2(1+x)}$ $$\frac{1-7x}{(1-x)^2(1+x)} = \frac{1-7x}{(1-x^2)(1-x)} = \frac{A}{1-x}+\frac{Bx+C}{1-x^2}$$
implies $1-7x = A-Ax^2+Bx-Bx^2+C-Cx$
Equating $x^2,x$ terms and constant on both sides, we get
$$A+B = 0,\quad B-C=-7,\quad A+C=1$$
Therefore
$$A+C=7,\quad A+C=1.$$
I am wondering how to resolve it into partial fractions to get the integration. I am not sure if I missed something, though it looks silly.
Thanks for any help.

A: Another hint (a bit ad hoc): Solving $D$ and $E$ from
$$D(x-1)+E(x+1)=7x-1$$
gives $D=4,E=3$. This allows you to rewrite
$$
\frac{1-7x}{(1-x)^2(1+x)}=\frac{4(1-x)-3(x+1)}{(1-x)^2(1+x)}=\frac4{(1-x)(1+x)}-\frac3{(1-x)^2}.
$$
Would this be easier?
Caveat: Only available because the numerator happened to be linear.

A: Your decomposition is not correct and it gives you an unsolvable system of constraints for the coefficients. Note that the  multiplicity of the factor $(1-x)$ at the denominator is TWO. Hence the partial fraction decomposition should be
$$\frac{1-7x}{(1-x)^2(1+x)} = \frac{A}{1-x}+\frac{B}{(1-x)^2}+\frac{C}{1+x}
= \frac{(C-A)x^2  + (B-2C) x +(A+B+C)}{(1-x)^2(1+x)}
.$$
Can you take it from here?


text:
Q: Regex working in regex engine but not in postgresql I tried to match number 13 in pipe separated string like the one below:
13 - match
1|2|13 - match
13|1|2 - match
1|13|2 - match

1345|1|2 - should fail
1|1345|2 - should fail
1|2|1345 - should fail
1|4513|2 - should fail
4513|1|2 - should fail
2|3|4|4513- should fail

So, if 13 only occurs at the beginning or end, or in-between the string as a whole word it should match.
For that I wrote the following regex:
^13$|(\|13\|)?(?(1)|(^13\||\|13$))

In Regex101 it is working as expected. Please click link to see my sample.

But in Postgresql it throws error for the following query:
SELECT * FROM tbl_privilage WHERE user_id = 24 and show_id ~ '^13$|(\|13\|)?(?(1)|(^13\||\|13$))';

Error:
ERROR: invalid regular expression: quantifier operand invalid
SQL state: 2201B

A: Documentation is quite clear, saying that operator ~ implements the POSIX regular expressions. In Regex101 you're using PCRE (Perl-compatible) regular expressions. The two are very different.
If you need PCRE regular expressions in PostgreSQL you can setup an extension. Like pgpcre.

A: Don't use a regex, using an array is more robust (and maybe more efficient as well):
select *
from the_table
where '13' = any (string_to_array(the_column, '|'));

this assumes that there is no whitespace between the values and the delimiter. You can even index that expression which probably makes searching a lot faster.
But I agree with Frank: you should really fix your data model.

A: You need to match 13 within word boundaries.
You need
[[:<:]]13[[:>:]]

This solution should work even if you have spaces around the numeric values.
See documentation:

There are two special cases of bracket expressions: the bracket
  expressions [[:<:]] and [[:>:]] are constraints, matching empty
  strings at the beginning and end of a word respectively.


text:
Q: JTable when searched - not getting right ID So I'm trying to after searching a name click on the table and then edit it in other table, the problem is that I'm not getting the right ID but instead only getting the ID that is the first.
JTable
Search in action
ID wrong
Edit Code
int linha = this.jTable1.getSelectedRow();
int idUtilizador = Integer.parseInt((String)(this.jTable1.getModel() ).getValueAt(linha, 0));
Utilizador uti = UtilizadorJpaController.read(idUtilizador);
CriarCliente updateCliente = new CriarCliente(uti);
updateCliente.setVisible(true);

Search Code
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
TableRowSorter<DefaultTableModel> tr = new TableRowSorter<DefaultTableModel>(model);
jTable1.setRowSorter(tr);
tr.setRowFilter(RowFilter.regexFilter(jTextField1.getText().trim(),1))

A: When you sort or filter a table, the data in the TableModel doesn't change. Only the view of the data changes.
If you want to get the data from the model, then you need to convert the "view row" to the "model row":
int linha = this.jTable1.getSelectedRow();
int modelRow = jTable1.convertRowIndexToModel(linha);
int idUtilizador = Integer.parseInt((String)(this.jTable1.getModel() ).getValueAt(modelRow, 0));
//int idUtilizador = Integer.parseInt((String)(this.jTable1.getModel() ).getValueAt(linha, 0));

Also, why are you using Integer.parseInt(...)? If the data in the model is an integer value, then it should be stored as an Integer value, not a String value.


text:
Q: Plot coth(x): Error in coth(x) : could not find function "coth" can someone help me how to plot coth(x) in R.
I tried following:
h=function(x){coth(x)}

plot(h)

But there was error: Error in coth(x) : could not find function "coth".
Can somebody please help me how to fix it?
Thanks

A: Try this:
library(pracma)
#Code
h=function(x){coth(x)}
plot(h)

Output:

You would need the pracma package.


text:
Q: Remove partial duplicates from table with no unique column I have to clean up records from a table that doesn't have a primary key or a a unique constraint.
Table definition:
create table person(
    name text,
    staff_id integer,
    work_code text,
    location
);

Unsurprisingly, it contains a lot of duplicates and partial duplicates.
What is the best way to transform the records to a unique set. I don't have to care about other columns besides name and staff_id

A: As you

don't have to care about other columns besides name and staff_id

This could be your procedure to clean up the table:
1.) Create a temporary table of unique rows:
CREATE TEMP TABLE p_tmp AS
SELECT DISTINCT ON (name, staff_id)
       name, staff_id, work_code, location
FROM   person
ORDER  BY name, staff_id, work_code, location;

I arbitrarily pick the "first row per (name, staff_id) - minimum work_code and matching location.
2.) Empty table:
TRUNCATE person;

3.) Re-INSERT unique tuples:
INSERT INTO person SELECT * FROM p_tmp;

Make sure, dupes don't creep back in. Add a surrogate primary key:
ALTER TABLE person ADD COLUMN person_id serial PRIMARY KEY;
ALTER TABLE person ADD UNIQUE (name, staff_id);

Or just add a multi-column primary key:
ALTER TABLE person ADD PRIMARY KEY (name, staff_id);

The temporary table will be dropped at the end of the session automatically.
Of course, all of this is best done inside one transaction, so you don't lose anything in the unlikely case that you run into a problem half way. Some clients do that automatically for a batch of SQL statements executed at once.

A: Maybe this?
select t.name, t.staff_id, t.work_code, t.location
from (
    select name, staff_id, work_code, location, count(*) nr
    from person
    group by name, staff_id, work_code, location
) t
where t.nr > 1;


text:
Q: CakePHP: Using ClassRegistry::removeObject() in behaviour I'm currently making a behavior that uses a plugin model internally.
Every time I need to look for a reference I use:

$this->Viewed = ClassRegistry::init('Viewed.Viewed');

So it will init the model that holds the data.
It's a good idea to use

$this->Viewed = ClassRegistry::removeObject('Viewed.Viewed')

to save memory in the excecution time of the script? or will add more time?
This behavior is used a lot in the code... so every gain is necesary.

A: Here's the code for CakePHP's ClassRegistry::removeObject($key) function:
 public static function removeObject($key) {
    $_this = ClassRegistry::getInstance();
    $key = Inflector::underscore($key);
    if (isset($_this->_objects[$key])) {
        unset($_this->_objects[$key]);
    }
}

Really all it's doing is unsetting the relevant key in an array the presumably holds all CakePHP's objects.  The unset() function in PHP will not free up memory immediately, though PHP may reclaim that memory eventually.  Since there's not much going on in ClassRegistry::removeObject() I wouldn't be too concerned with it taking up much more processing.
But keep in mind also that once a PHP script is finished being executed, memory will also be reclaimed.  So there's not much point in calling ClassRegistry::removeObject() if you can only call it near the end of your script.  PHP is not really designed for manual memory management like that.  If memory really starts becoming an issue, you could also consider writing something external in another language that your application can call using exec().


text:
Q: Catching "cursor place change" events inside textareas with jQuery (IE6-compatible) How can I catch the event of "cursor place change" inside textarea with jQuery (also should working in IE6)?
Example1:
Before :text |
After : te|
Example2:
Before :text |
After : text tex|t2
Example3:
Before :text |
After : |

Edit:
After catching the event of cursor- need also to check if cursor change his position (also have to work for IE6)
Edit2:
If you have solution that will not work in IE6 but in IE7+webkit please write it

A: I've found that the select event seems to cover all changes to caret position.

A: There are essentially three events that can cause a cursor to change position,

*

*keystrokes

*mouse clicks

*programmatic events like paste, select, focus...
I would capture those events for whatever it is you are trying to accomplish with 'cursor place change'
code sample added:
$("#myTextInput").bind("keydown click focus", function() {
  alert("Current position: " + $(this).caret().start);
});

Thanks to @Nick Craver


text: Q: How to create a registry analyzer I am trying to make a new type of anti malware program and one of the biggest hurdles that I can't figure out is how to take all the registry values in the Computer to check for unwanted or harmful registries in c or c++ does anyone know how to do this or know where to look at solving this?


text:
Q: How to override the existing module block files in magento2 How to extend the block file functionality?
Because the search popular terms page shows as empty, so I have extended the block file as the following. But it is not working.
/app/code/Talk/CustomSearch/registration.php
<?php

\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'CustomSearch',
    __DIR__
);

/app/code/Talk/CustomSearch/etc/module.xml
<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="CustomSearch" setup_version="1.0.0">
    </module>
</config>

/app/code/Talk/CustomSearch/etc/di.xml
<?xml version="1.0"?>
    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
      <preference for="Magento\Search\Block\Term" type="Talk\CustomSearch\Block\Term" />
    </config>

/app/code/Talk/CustomSearch/Block/Term.php
<?php

/**
 * Search term block
 */
namespace Talk\CustomSearch\Block;

class Term extends \Magento\Search\Block\Term
{

    /**
     * Load terms and try to sort it by names
     *
     * @return $this
     */
    protected function _loadTerms()
    {
        exit('LoadTerms');
    }
}

The function _loadTerms() is not called. How to extend the block in the magento-search module?

A: Module name in registration.php and module.xml is not defined correctly. Has to be Talk_CustomSearch. Please correct and try again.

A: Solution!
Change CustomSearch into Talk_CustomSearch for both registration.php and module.xml
Additionally,  I have implemented the function in the file /app/code/Talk/CustomSearch/Block/Term.php
protected function _toHtml()
    {
        $this->setModuleName($this->extractModuleName('Magento\Search\Block\Term'));
        return parent::_toHtml();
    }

Full Code
<?php

/**
 * Search term block
 */
namespace Talk\CustomSearch\Block;

class Term extends \Magento\Search\Block\Term
{

    /**
     * Load terms and try to sort it by names
     *
     * @return $this
     */
    protected function _loadTerms()
    {
        exit('LoadTerms');
    }

    protected function _toHtml()
    {
        $this->setModuleName($this->extractModuleName('Magento\Search\Block\Term'));
        return parent::_toHtml();
    }
}


text:
Q: Android DOMparser couldnot get the child nodes? I am parsing a xml document which contains
<items>
   <item> a </item>
   <item> b </item>
   .....
   <item> z </item>
</items>

I am able to get the items tag by
document.getElementsByTag("items");

but the problem is i couldn't get all the item tag in to a NodeList  please help ...
Thanks in advance..

A: than apply a loop
Node nodelist = Document.getElementbyTag("parent tab");

for(int i=0;i<nodelist.getlength();i++)
{
    Node node = nodeList.item(i);
    Element fstElmnt = (Element) node;
    NodeList SidList = fstElmnt.getElementsByTagName("sid");//the chils tags
    Element sidElement = (Element) SidList.item(0);
    SidList = sidElement.getChildNodes();
    String nameValue = ((Node) SidList.item(0)).getNodeValue();
    Log.e("Serial_id",nameValue);
}


text:
Q: C# COM Interop Creating New Excel Workbook I am using Microsoft.Office.Interop.Excel in a C# winform but I can't figure out how to create a new Excel workbook.  I have tried everything in the documentation but I get nothing but errors.  Workbook wb = new Workbook() compiles just fine but throws an incomprehensible runtime error.

A: You are probably getting the same error as you would get if you tried to instantiate a Workbook in Excel VBA using
Dim w As Workbook
Set w = New Workbook

Try instantiating the Application object, then call the Application.Workbooks.Add method.  It takes an optional parameter, which is the name of a template.


text:
Q: Download file via POST in one request with JavaScript Sometimes when making an HTTP request to download a file (e.g. PDF, XLSX, etc.) from the own webserver, it is necessary to use the HTTP method POST, because it requires dynamic input data. I have been trying different ways to reduce that to one single HTTP request for best performance, but could not succeed.
As JavaScript with the XMLHttpRequest object (AJAX) can not "download" files, I guess it requires an HTML workaround. The only working solution I found for that case is generating a form element wrapping input elements containing the data. I could not find a way how to send boolean values via this, as AJAX is able to. That would mean: it is not suitable for a standardizable implementation.
My question is: How can I download a file via one POST request which can include boolean values (JavaScript)?
In case it is important: The backend system I use is Ruby on Rails

A: As @Pointy mentioned, boolean values are always translated to strings in HTTP communication. I was wrong about that in my question. That means, converting a JavaScript JSON string or a classic object to an HTML form (then submitting and deleting it) works!
Actually sending an AJAX request and then manually triggering a link click to the generated file has the advantage of being able to use a progressbar.


text:
Q: How to run in background an .exe program withArcGIS? I am working with the ArcGIS program that reads Python language. For that I've already implement scripts as script tool on the ArcGIS.
Now I need to run in background an exe program "gams".
Is it possible to do directly from the ArcGIS? Or is it possible to do with a new python script? And how can I do this?

A: You can try to use a python script and use one of the two following modules. But think of it carefully as running a program out of a script can do many unpleasent things.
import subprocess
subprocess.call(['C:\\folder\\gams.exe'])

import os
os.system('"C:\\folder\\gams.exe"')

Update as it is about a file of the type .gms:
Check out the answers on this post: https://stackoverflow.com/questions/1811691/running-an-outside-program-executable-in-python


text:
Q: Javascript alternative to jquery html() How would you write this jQuery method
$('body').html(node);

for setting html to node in Javascript?
thank you

A: If node is a DOM node rather than an HTML string, you should use DOM methods instead on innerHTML:
while (document.body.firstChild) {
    document.body.removeChild(document.body.firstChild);
}
document.body.appendChild(node);

See MDC docs:

*

*firstChild

*removeChild

*appendChild

A: You are looking for the innerHTML property:
document.getElementById("test").innerHTML = "";

A: Yes thats possible:
document.body.innerHTML="
Hello World
";

http://www.tizag.com/javascriptT/javascript-innerHTML.php

A: document.body.innerHTML = 'my html here';

A: And for the more general case than just setting the body....
// replace a single element by its ID
// i.e. $("#myDivId")
var myDiv = document.getElementById("myDivId");
myDiv.innerHtml = "foo";

// replace all elements of a given tag name
// i.e. $("span")
var allSpanTags = document.getElementsByTagName("span");
allSpanTags[0].innerHtml = "foo"; // or loop over the array or whatever.

// by class name
// i.e. $(".myClass")
var allMyClass = document.getElementsByClassName("myClass");

A: For reference, here's the way that jquery does it:
html: function( value ) {
    if ( value === undefined ) {
        return this[0] && this[0].nodeType === 1 ?
            this[0].innerHTML.replace(rinlinejQuery, "") :
            null;

    // See if we can take a shortcut and just use innerHTML
    } else if ( typeof value === "string" && !rnocache.test( value ) &&
        (jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value )) &&
        !wrapMap[ (rtagName.exec( value ) || ["", ""])[1].toLowerCase() ] ) {

        value = value.replace(rxhtmlTag, "<$1></$2>");

        try {
            for ( var i = 0, l = this.length; i < l; i++ ) {
                // Remove element nodes and prevent memory leaks
                if ( this[i].nodeType === 1 ) {
                    jQuery.cleanData( this[i].getElementsByTagName("*") );
                    this[i].innerHTML = value;
                }
            }

        // If using innerHTML throws an exception, use the fallback method
        } catch(e) {
            this.empty().append( value );
        }

    } else if ( jQuery.isFunction( value ) ) {
        this.each(function(i){
            var self = jQuery( this );

            self.html( value.call(this, i, self.html()) );
        });

    } else {
        this.empty().append( value );
    }

    return this;
},

It uses innerHTML when it can, but it also has a fallback method.

A: If it's the body tag that you want HTML to be inserted into, try this:
document.body.innerHTML = node;

or
document.getElementsByTagName('body')[0].innerHTML = node;


text:
Q: Extract rows from a pandas dataframe between two rows This is a sample of the data that I have.
T| 1.42 | Test1 |   1|   0 |   0
A| 1.42 |     1 |   1|   0 |   0
A| 1.42 |     1 |   2|   0 |   0
T| 1.42 | Test1 |   1|   0 |   0
A| 1.42 |     1 |   1|   0 |   0
A| 1.42 |     1 |   3|   0 |   0
A| 1.42 |     1 |   4|   0 |   0
T| 1.42 | Test1 |   1|   0 |   0

Is it possible to extract rows with 'A' in the first column between two rows with 'T' in first column and put into a new dataframe?
For example in this case
dataframe 1 would have
A| 1.42 |     1 |   1|   0 |   0
A| 1.42 |     1 |   2|   0 |   0

and dataframe 2 would have
A| 1.42 |     1 |   1|   0 |   0
A| 1.42 |     1 |   3|   0 |   0
A| 1.42 |     1 |   4|   0 |   0

thank you !

A: A very natural way to split into separate dataframes is to use groupby.  I find where the first column is 'T' and use boolean indexing and cumsum to identify the groups.
m = df.iloc[:, 0].eq('T')
cumgrp = m.cumsum()[~m]
grps = df[~m].groupby(cumgrp)

We can see the groups and print them by iterating through them.
for n, g in grps:
    print(n)
    print()
    print(g)
    print()

1

   0     1  2  3  4  5
1  A  1.42  1  1  0  0
2  A  1.42  1  2  0  0

2

   0     1  2  3  4  5
4  A  1.42  1  1  0  0
5  A  1.42  1  3  0  0
6  A  1.42  1  4  0  0

You can get a list of these with
list_of_groups = [g for n, g in grps]


text:
Q: Homomorphical Equivalence is NP-complete Two graphs $G,H$ are homomorphically equivalent if there are exists a homomorphism from $G$ to $H$ and a homomorphism from $H$ to $G$.
The task is to prove that this decision problem $\mathrm{HOMEQUIV}$ is $NP$-complete.
Given a mapping $G \to H$ (or $H \to G$) it is possible to check whether it is an homomorphism in polynomial time. Thus, $\mathrm{HOMEQUIV} \in NP$.
Now I am looking for a suitable $NP$-complete problem with an elegant polynomial reduction to $\mathrm{HOMEQUIV}$. I was thinking about $\mathrm{3SAT}$ but I did not come up with a solution up until now.
There is a reduction to $3 ~ \mathrm{COLORING}$ which is pretty easy and I know from internet research that $\mathrm{3SAT} \leq_p 3 ~ \mathrm{COLORING}$. But I think this is cheating somehow because it is not a direct proof and it lacks the complicated part ($\mathrm{3SAT} \leq_p 3 ~ \mathrm{COLORING}$).
Any ideas for an elegant reduction?

A: David Eppstein provides a nice reduction from $\mathrm{CLIQUE}$ to $3 \mathrm{COLORING}$ such that

Given a graph $G$, we construct another graph $H$ such that $H$ is
  $n$-colorable if and only if $G$ has a $k$-Clique.


text:
Q: function is defined when out of loop but not when placed inside a loop? I am trying to run a function within a loop but when I run it I get a robot.rn is not a function. when I run the function outside of the loop I have no problem and everything works as expected. I am sure it is something obvious hopefully and I have just been staring at my code too long. Any help would be greatly appreciated, thanks.
The basic idea i am trying to accomplish is drawing the coins in random positions 30 times(robot.maxCoins = 30);
when i run my code like this (outside of loop) it works
Robot.prototype.rn = function(){
    robot.rn = {
        rnX: robot.rnX = Math.floor(Math.random()*900)-20,
        rnY: robot.rnY = Math.floor(Math.random()*400)-20
    };
    return robot.rn;
};

Robot.prototype.drawCoins = function(){
    robot.rn();
    console.log(robot.rnX);
    ctx.beginPath();
    ctx.arc(robot.rnX,robot.rnY,robot.coinD,0,2*Math.PI);
    ctx.fillStyle = "yellow";
    ctx.fill();
    ctx.stroke();
};

Here is code with function in the loop (return: robot.rn is not a function)
Robot.prototype.rn = function(){
  robot.rn = {
    rnX: robot.rnX = Math.floor(Math.random()*900)-20,
    rnY: robot.rnY = Math.floor(Math.random()*400)-20
  };
  return robot.rn;
};

Robot.prototype.drawCoins = function(){
  for(var i = 0; i<robot.maxCoins; i++){
    robot.rn();
    console.log(robot.rnX);
    ctx.beginPath();
    ctx.arc(robot.rnX,robot.rnY,robot.coinD,0,2*Math.PI);
    ctx.fillStyle = "yellow";
    ctx.fill();
    ctx.stroke();
  }

};

A: You are overwriting robot.rn
robot.rn = {
    rnX: robot.rnX = Math.floor(Math.random()*900)-20,
    rnY: robot.rnY = Math.floor(Math.random()*400)-20
};
return robot.rn;

It doesn't fail when you use it without a loop because you are not trying to call the rn function anymore.

A: The first call to robot.rn replaces the function with an object. The second call in the loop tries to use that object as a function.
Just return you object from rn, don't assign it.


text:
Q: Showing errors of jsp files in IntelliJ IDEA Does IntelliJ IDEA support highlights errors of JSP files in the project window like Netbeans or Eclipse?
If it does, how to enable it?
You can look here and see what I mean


text:
Q: How to extend Doctrine2 by PostgreSQL ~ operator? (Not a custom function)

I use Symfony and Doctrine with a PostgreSQL backend and I would like to use the PostgreSQL ~ operator to get the whole power of POSIX regular expression instead of the restricted LIKE.
I would like to write something like this
entityManager->createQuery(
        'SELECT e FROM MyBundle:Entity e WHERE e.name ~ :name'
    )->setParameters(
        array( "name" => "some regex here" )
    )->getResult();

I already found this example and the official documentation. However they only cope with custom functions. But I do not need a function (or term) that evaluates to some value but a custom predicate.
Even if I created a custom DQL function – say REGEXP – with two parameters that translated to ~ at the SQL level, then the DQL parser would still expect an operator. Hence, WHERE REGEXP( a, b ) alone would create an DQL parsing error and WHERE REGEXP( a, b ) = true would satisfy the DQL parser but would translate to insane WHERE a ~ b = TRUE on the SQL level.
Any solutions?


text:
Q: Passing TextView details from RecycleView to next activity I have a problem here, how can I pass this RecycleView selected item to another Activity and get data from database to Detail Activity?
Thanks in advance!

AdapterList
 @Override
        public void onBindViewHolder(final ViewHolder holder, final int position){
            Glide.with(context)
                    .load("http://192.168.56.1/signalss/image/" + list_data.get(position).get("Icon"))
                    .crossFade()
                    .placeholder(R.mipmap.ic_launcher)
                    .into(holder.imgsignals);
            holder.txtsignals1.setText(list_data.get(position).get("SignalsId"));
            holder.txtsignals2.setText(list_data.get(position).get("PairName"));
            holder.txtsignals3.setText(list_data.get(position).get("SignalsPosition").equals("B") ? "BUY" : "SELL");
            holder.txtsignals4.setText(list_data.get(position).get("AreaOpenPrice1"));
            holder.txtsignals5.setText(list_data.get(position).get("AreaOpenPrice2"));
            holder.txtsignals6.setText(list_data.get(position).get("StopLoss"));
            holder.txtsignals7.setText(list_data.get(position).get("TargetProfit1"));
            holder.txtsignals8.setText(list_data.get(position).get("TargetProfit3"));
            holder.txtsignals9.setText(list_data.get(position).get("AddDate"));
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent i = new Intent(v.getContext(), DetailSignals.class);
                    i.putExtra("SignalsId", list_data.get(position));
                    v.getContext().startActivity(i);
                }
            });

            if (list_data.get(position).get("SignalsPosition").equals("B")){
                ((LinearLayout)holder.linearLayout).setBackgroundColor(Color.parseColor("#FF00F449"));
                ((LinearLayout)holder.linearLayout1).setBackgroundColor(Color.parseColor("#FF00F449"));
            }else{
                ((LinearLayout)holder.linearLayout).setBackgroundColor(Color.parseColor("#f40000"));
                ((LinearLayout)holder.linearLayout1).setBackgroundColor(Color.parseColor("#f40000"));
            }
        }

tab1
@Override
        public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {

        String url = "http://192.168.56.1/signalss/getActive.php";

        View v =inflater.inflate(R.layout.tabmenu,container,false);
        recyclerView = (RecyclerView) v.findViewById(R.id.rvtab1);
        LinearLayoutManager llm = new LinearLayoutManager(getActivity());
        llm.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(llm);

        requestQueue = Volley.newRequestQueue(getActivity());

        list_data = new ArrayList<HashMap<String, String>>();
        stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {

                Log.d("response", response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    JSONArray jsonArray = jsonObject.getJSONArray("listactive");
                    for (int a = 0; a < jsonArray.length(); a++) {
                        JSONObject json = jsonArray.getJSONObject(a);
                        HashMap<String, String> map = new HashMap<String, String>();
                        map.put("SignalsId", json.getString("SignalsId"));
                        map.put("Icon", json.getString("Icon"));
                        map.put("PairName", json.getString("PairName"));
                        map.put("SignalsPosition", json.getString("SignalsPosition"));
                        map.put("AreaOpenPrice1", json.getString("AreaOpenPrice1"));
                        map.put("AreaOpenPrice2", json.getString("AreaOpenPrice2"));
                        map.put("StopLoss", json.getString("StopLoss"));
                        map.put("TargetProfit1", json.getString("TargetProfit1"));
                        map.put("TargetProfit3", json.getString("TargetProfit3"));
                        map.put("AddDate", json.getString("AddDate"));
                        list_data.add(map);
                        AdapterList adapter = new AdapterList(tab1.this, list_data);
                        recyclerView.setAdapter(adapter);

                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getActivity(), error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });

        requestQueue.add(stringRequest);

        //Calling asyn task to get json
        new tab1.GetContacts().execute();
        return v;

        }

DetailActivity
public class DetailSignals extends AppCompatActivity {

TextView posisi, status, entry, profit, stop, stat, result;

private static String url = "http://192.168.56.1/signalss/getId.php";

// JSON Node Names
private static final String TAG_CONTACTS = "listactive";

private static final String TAG_POSISI = "SignalsPosition";
private static final String TAG_STATUS = "PairName";
private static final String TAG_ENTRY = "AreaOpenPrice1";
private static final String TAG_PROFIT = "TargetProfit1";
private static final String TAG_STOP = "StopLoss";
private static final String TAG_STAT = "Status";
private static final String TAG_RESULT = "Result";

// contacts JSONArray
JSONArray contacts = null;

// Progress Dialog
private ProgressDialog pDialog;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail_signals);

posisi = (TextView)findViewById(R.id.posisi);
status = (TextView)findViewById(R.id.status);
entry = (TextView)findViewById(R.id.entry);
profit = (TextView)findViewById(R.id.target);
stop = (TextView)findViewById(R.id.stop);
stat = (TextView)findViewById(R.id.stat);
result = (TextView)findViewById(R.id.result);

//Loading in Backgtound Thread
new GetContext().execute();
}

class GetContext extends AsyncTask<String, String, String>{

@Override
protected void onPreExecute(){
    super.onPreExecute();
    pDialog = new ProgressDialog(DetailSignals.this);
    pDialog.setMessage("Please Wait...");
    pDialog.setIndeterminate(false);
    pDialog.setCancelable(false);
    pDialog.show();
}

@Override
protected String doInBackground(String... args) {
    ServiceHandler sh = new ServiceHandler();

    String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

    Log.d("Response : ", "> " + jsonStr);

    if (jsonStr !=null){
        try {
            JSONObject jsonObj = new JSONObject(jsonStr);

            // Getting JSON Array node
            contacts = jsonObj.getJSONArray(TAG_CONTACTS);

            // looping through All Contacts
            for (int i = 0; i < contacts.length(); i++){
                JSONObject c = contacts.getJSONObject(i);

                String posisi = c.getString(TAG_POSISI);
                String status = c.getString(TAG_STATUS);
                String entry = c.getString(TAG_ENTRY);
                String target = c.getString(TAG_PROFIT);
                String stop = c.getString(TAG_STOP);
                String stat = c.getString(TAG_STAT);
                String result = c.getString(TAG_RESULT);

                HashMap<String, String> contact = new HashMap<String, String>();

                contact.put(TAG_POSISI, posisi);
                contact.put(TAG_STATUS, status);
                contact.put(TAG_ENTRY, entry);
                contact.put(TAG_PROFIT, target);
                contact.put(TAG_STOP, stop);
                contact.put(TAG_STAT, stat);
                contact.put(TAG_RESULT, result);

            }
        } catch (JSONException e){
            e.printStackTrace();
        }
    } else {
        Log.e("ServiceHandler", "Couldn't get any data from the url");
    }
    return null;
    }
  }
}

I already make the DetailActivity, but I don't know how to intent and get data from database to my activity.

A: you used interface for click event and pass the data when recycler view in click any item like ... make adapter few changes
OnRecyclerItemClickListener onRecyclerItemClickListener;

public void setOnRecyclerItemClickListener(OnRecyclerItemClickListener onRecyclerItemClickListener) {
    this.onRecyclerItemClickListener = onRecyclerItemClickListener;
}

public interface OnRecyclerItemClickListener {
    void onViewItemClicked(MyData myData);// your pojo class you bind in recyclerview.
}
 @Override
public void onBindViewHolder(ItemViewHolder holder, int position) {
    final MyData data=mDataList.get(position);
    holder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            onRecyclerItemClickListener.onViewItemClicked(data);
        }
    });

then after when you get response value and set adapter that time call below code..
 mAdapter.setOnRecyclerItemListener(new HomeAdapter.OnRecyclerItemClickListener() {
        @Override
        public void onViewItemClicked(MyData myData) {
            Intent i = new Intent(v.getContext(), DetailSignals.class);
            i.putExtra("SignalsId", myData.getSifnalsId());//set your value to pass.
            startActivity(i);
        }
    });

and i hope you define all the activity in android manifest file.


text:
Q: instabug IBGInvocationEventTwoFingersSwipeLeft not work Sorry for my english. I try use service instabug, they i try use IBGInvocationEventTwoFingersSwipeLeft but this is not successful. I try somthing like this:
ParseAnalytics.trackAppOpenedInBackground(getIntent());
        Instabug.initialize(getApplication(), "mykey");
        Instabug.getInstance().setInvocationEvent(Instabug.IBGInvocationEvent.IBGInvocationEventTwoFingersSwipeLeft);

and like this
  ParseAnalytics.trackAppOpenedInBackground(getIntent());
    Instabug.initialize(getApplication(), "mykey").setInvocationEvent(Instabug.IBGInvocationEvent.IBGInvocationEventTwoFingersSwipeLeft);

but my method dont work(

A: This could happen if you haven't finished the SDK integration steps. Specifically, if your Activity classes don't extend Instabug activities.


text:
Q: NGINX Multiple Sites on Same Host I'm fairly new to Nginx. When I connect to my server I would like to have multiple sites on the same host. Each site is a separate docker container being server by an Nginx image, serving an Angular app. I'm using proxy pass because we will eventually be leveraging the load balancer function.
For example when I go to <host name>/teamsite it should be proxy to the upstream server http://teamsite.
The following code works perfectly using just 1 site, navigating to .
upstream teamsite {
    server localhost:8200;
}

server {

    listen 80;
    location / {

        proxy_pass          http://teamsite;
        proxy_redirect      off;

        proxy_set_header    Host $host;
        proxy_set_header    X-Real-IP $remote_addr;
        proxy_set_header    X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header    X-Forwarded-Host $server_name;

        gzip on;
        gzip_types          text/plain application/xml application/javascript;
        gzip_proxied        no-cache no-store private expired auth;
        gzip_min_length     1000;

    }

}

When I try to add in the /teamsite it stops working.
Example:
upstream teamsite {
    server localhost:8200;
}

server {

    listen 80;
    location /teamsite {

        proxy_pass          http://teamsite;
        proxy_redirect      off;

        proxy_set_header    Host $host;
        proxy_set_header    X-Real-IP $remote_addr;
        proxy_set_header    X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header    X-Forwarded-Host $server_name;

        gzip on;
        gzip_types          text/plain application/xml application/javascript;
        gzip_proxied        no-cache no-store private expired auth;
        gzip_min_length     1000;

    }

}

It looks like Nginx is looking for the files in localhost:8200/teamsite/index.html instead of localhost:8200/index.html. Any ideas why the extra /teamsite/ is being added to the upstream server?
Thank you for your help.
Edit:
I did try the following config:
server {

    listen 80;
    location /teamsite/ {

        proxy_pass          http://localhost:8200/;
        }
}

Now when connecting to <host name>/teamsite the reverse proxy is throwing connection refused errors. The webserver version of Nginx is not showing any connections or errors. I am able to connect to the webserver version of Nginx from the server and my local machine.

A: This answer https://serverfault.com/a/725433 shows the proper syntax for what are you trying to do and shows how the url rewriting works.


text:
Q: Viewing how Windows syscalls are handled by OS I am trying to figure out how syscalls are performed on kernel, Are there any good explanation about what exactly happens on kernel, when a "syscall" instruction is encountered. What are the ways to view those kernel-mode callbacks and maybe documenting some undocumented functions.
Basically what I'm asking
mov eax, 23h ; NtQueryVirtualMemory
syscall      ; Any way to view what OS does, how it fills registers, sets return value etc. after executing this instruction

Thanks.

A:
Viewing how Windows syscalls are handled by OS

The most important thing to understand about how system calls are handled by Windows (and how they're supposed to be handled by almost all modern operating systems) is that they are abstracted (e.g. by a library - a DLL or shared library); so that:
a) It doesn't matter if the mechanism is changed - e.g. if kernel and library internally use the syscall instruction or the sysenter instruction, or call gates or software interrupts or something else; or if different mechanisms are used on different computers (due to different CPUs supporting different features). Note that currently both Intel and AMD have proposals for future "Supervisor Entry" extensions, so it's reasonable to expect that (at some point in the future) the syscall instruction will be obsolete and not used.
b) It doesn't matter if the kernel is changed. E.g. if an older kernel had a specific function but the kernel designers want to replace it with a newer/better function with different parameters then they can do that, and the new library (for the new kernel) can emulate the old function so that all the old software doesn't break when the kernel (and library) is updated.
c) Whether something is a kernel system call or not becomes irrelevant. A good example of this is functions to get the current time on 80x86 - if hardware/CPU is old and doesn't support the "monotonic time stamp counter" feature then something like QueryPerformanceCounter() involves a system call, but on newer hardware it can be done purely in user-space by the library (avoiding the overhead of a system call completely) by relying on the rdtsc instruction instead.
For these reasons; Microsoft deliberated do not document the kernel's API/system calls (for any specific version of their kernel) in an attempt to prevent people from creating dodgy software that can/will break.
For assembly language programmers (especially those coming from MS-DOS) this is annoying (because calling functions in a DLL is more complex); but there isn't a good solution for that problem.

Any way to view what OS does, how it fills registers, sets return value etc. after executing this instruction?

You could run the OS inside a virtual machine that supports debugging, and examine what it does one instruction at a time. This won't help much though (it'll be a confusing mess and different versions of the kernel may be different).

A: to add a bit more info to the post above me, syscall will go into kernel at the at the syscall handler KiSystemCall64(Shadow). Here it makes a context switch and calls to the corrosponding function in the SSDT, the identifier for wich function to call is stored in EAX. To learn more about it you can consider going in kernel and hooking the syscall handler by getting the MSR register and then changing the LSTAR index of the MSR. The LSTAR points to the syscall handler. And you can overwrite it to handle it yourself / log it. Might be a fun project if you want to get to learn more about it.


text:
Q: Swift '(int, int) -> $T4' is not identical to 'Point' I'm fairly new to swift and get this error. All I want the declaration to do is assign the 4 values to create 2 Point objects for a Line object. So Line(10, 20, 20, 40) should create two points at (10,20) and (20,40). But I get the error '(Int, Int) -> $T4' is not identical to 'Point'
class Point {
var x: Int = 0
var y: Int = 0

init(){
    x = 0
    y = 0
}

init(x: Int, y: Int) {
    self.x = x
    self.y = y
  }
}

class Line: Point {
var pointA: Point
var pointB: Point

init(p1x: Int, p1y: Int, p2x: Int, p2y: Int) {
    self.pointA(p1x, p1y)
    self.pointB(p2x, p2y)
  }
}

var lineA = Line(p1x:10, p1y:20 , p2x:20 , p2y:40)

A: Your code in Line's init is meaningless. This is not valid Swift:
self.pointA(p1x, p1y)
self.pointB(p2x, p2y)

You can't just stick parentheses after the name of a variable like that! Plus you are not writing your init correctly. Here's a possible fix:
class Line: Point {
    var pointA: Point
    var pointB: Point

    init(p1x: Int, p1y: Int, p2x: Int, p2y: Int) {
        self.pointA = Point(x:p1x, y:p1y)
        self.pointB = Point(x:p2x, y:p2y)
        super.init()
    }
}

But as Antonio has already said, it all depends on what you're trying to do. My code above will cause your code to compile correctly, but I have no idea whether it does what you want, because what you're trying to do is utterly impossible to guess.

A: In the initializer you are missing to create instances - you are just trying to reference 2 properties as if they were methods. The correct way is:
init(p1x: Int, p1y: Int, p2x: Int, p2y: Int) {
    self.pointA = Point(x: p1x, y: p1y)
    self.pointB = Point(x: p2x, y: p2y)
}

There is an architectural mistake though: Line inherits from Point, but I see no relationship between the 2 classes - you should at least call the superclass initializer, but what to pass?
I would instead define only 1 new property in Line, and reuse the property already available in Point:
class Line: Point {
    var pointB: Point

    init(p1x: Int, p1y: Int, p2x: Int, p2y: Int) {
        self.pointB = Point(x: p2x, y:p2y)
        super.init(x: p1x, y: p1y)
    }
}

I don't know if that makes sense (depending on what you want to achieve) - if not, then I would just make Line not inherit from Point. If you need a common interface, but with different implementations, then you can use a protocol adopted by the 2 classes.


text:
Q: angular 5 form validation: I get this error on my angular 5 form:
ERROR TypeError: Cannot read property 'invalid' of undefined
    at Object.eval [as updateDirectives] (AccountPage.html:56)

on the name variable.
I am using FormBuilder as you can see below.
It seems like I need a getter or there's a missing declaration?
Controller:
import { FormBuilder, FormGroup, FormControl, Validators } from '@angular/forms';
...
export class AccountPage  implements OnInit {

    accountError: string;
    form: FormGroup;
...

 constructor(
        fb: FormBuilder,
        private navCtrl: NavController,
        private auth: AuthService,
        private afs: FirestoreService,
        private fcmProvider: FcmProvider,
    ) {

        console.log("%c constructor de account", "color: #bada55");
        this.form = fb.group({
            // name: ['', Validators.compose([Validators.required, Validators.minLength(2), ])],
            // firstname: ['', Validators.compose([Validators.required, Validators.minLength(2), ])],
            // add1: ['', Validators.compose([Validators.required, Validators.minLength(6), ])],
            // add2: ['', Validators.compose([])],
            // zip: ['', Validators.compose([Validators.required, Validators.minLength(5), NumberValidator.numeric, ])],
            // city: ['', Validators.compose([Validators.required, Validators.minLength(3), ])],
            // phone: ['', Validators.compose([Validators.required, Validators.minLength(10), ])],
            name: [null, [Validators.required]],
            firstname: [null, [Validators.required]],
            add1: [null, [Validators.required]],
            add2: '',
            zip: [null, [Validators.required]],
            city: [null, [Validators.required]],
            phone: [null, [Validators.required]],
        });

template:
 <div *ngIf="auth.authenticated">
    <form (ngSubmit)="submitForm()" [formGroup]="form">
      <ion-list inset>

        <ion-item>
          <ion-input type="text" placeholder="Nom" formControlName="name"></ion-input>
        </ion-item>

        <div *ngIf="form.name.invalid && (form.name.dirty || form.name.touched)" class="text-danger">
          <div *ngIf="form.name.errors.required">
            Entrez votre nom
          </div>
          <div *ngIf="form.name.errors.minlength">
            2 caractères minimum
          </div>
        </div>

EDIT
This seems to work:
    <ion-item>
      <ion-input type="text" placeholder="Nom" name="name" formControlName="name"></ion-input>
    </ion-item>

    <div *ngIf="form.controls['name'].invalid && (form.controls['name'].dirty || form.controls['name'].touched)" class="text-danger">
      <div *ngIf="form.controls['name'].errors.required">
        Entrez votre nom
      </div>
      <div *ngIf="form.controls['name'].errors.minlength">
        2 caractères minimum
      </div>
    </div>

With
this.form = this.formBuilder.group({
        name: new FormControl( null, Validators.compose([Validators.required, Validators.minLength(2), ]) ),
    });

but can't I avoid the heavy syntax: form.controls['name'] in the template ?

A: if you console.log(this.form) inside of ngOnInit lifecycle hook, you can see that this.form object does not contain attribute name. Each control inside of FormGroup is stored inside of controls attribute of object. So, you have to either declare variable that will point to this.form.controls or you can make check validity of form with this.form.controls['name'].valid

A: Try checking the validity in your template with form.controls['name'].invalid

A: Here's the answer:
template:
   <ion-item>
      <ion-input type="text" placeholder="Nom" name="name" formControlName="name"></ion-input>
    </ion-item>

    <div *ngIf="name.invalid && (name.dirty || name.touched)" class="text-danger">
      <div *ngIf="name.errors.required">
        Entrez votre nom
      </div>
      <div *ngIf="name.errors.minlength">
        2 caractères minimum
      </div>
    </div>

controller:
import { FormBuilder, FormGroup, FormControl, Validators } from '@angular/forms';

export class AccountPage  implements OnInit {

    accountError: string;
    form: FormGroup;
    name: FormControl;
    firstname: FormControl;
    add1: FormControl;
    add2: FormControl;
    zip: FormControl;
    city: FormControl;
    phone: FormControl;

 constructor(
        private formBuilder: FormBuilder,
        private navCtrl: NavController,
        private auth: AuthService,
        private afs: FirestoreService,
        private fcmProvider: FcmProvider,
    ) {
        this.form = this.formBuilder.group({
            name: new FormControl( null, Validators.compose([Validators.required, Validators.minLength(2), ]) ),
            firstname: new FormControl( null, Validators.compose([Validators.required, Validators.minLength(2), ]) ),
            add1: new FormControl( null, Validators.compose([Validators.required, Validators.minLength(6), ]) ),
            add2: '',
            zip: new FormControl( null, Validators.compose([Validators.required, Validators.minLength(5), NumberValidator.numeric, ]) ),
            city: new FormControl( null, Validators.compose([Validators.required, Validators.minLength(3), ]) ),
            phone: new FormControl( null, Validators.compose([Validators.required, Validators.minLength(10), ]) ),
        });

}


text:
Q: How to add similar items in one using UNION query I am currently getting similar items in 2 places when joined using UNION.
What I want is that it should sum up and show a single item for similar items.
Here is my Query
select
(Case
When DHB = 'ABC.com' Then 'ABC Hospital'
When DHB = 'AOC.com' Then 'ABC Hospital'
When DHB = 'coe.com' Then 'EFG Hospital'
End) DHB
, count(*) NumberOfActiveUsers from (
select distinct Ltrim(Rtrim(substring(userid, charIndex('@', userId)+1, Len(userId)))) as DHB, userId from [RecordDB].[dbo].Event ae
where userId like '%@%'
) as Temp
where DHB in ('ABC.com','AOC.com','coe.com')
group by DHB

UNION

select distinct DHB,
 count(userid) NumberOfActiveUsers from (
SELECT DISTINCT userid,
CASE WHEN DHB in ('2.1','ABC001') THEN 'ABC Hospital'
     WHEN DHB in ('3.1','CDE001') THEN 'EFG Hospital'
ELSE DHB END
FROM
(
SELECT
    userid,
    CASE
       WHEN CHARINDEX('-', e.name) > 0
          THEN Ltrim(Rtrim(substring(e.name,0, charIndex('-', e.name))))
       ELSE e.name
    END as DHB
FROM
    [RecordDB].[dbo].Event ae
JOIN
    [Portal].[dbo].cUser cu ON cu.name = ae.userID
JOIN
    [Portal].[dbo].UAttribute ua ON ua.cUser = cu.uniqueId
JOIN
    [Portal].[dbo].[EIdentifier] ei ON ei.cUser = cu.uniqueId
JOIN
    [Portal].[dbo].[EIdentifierType] e ON e.uniqueId = ei.externalIdentifierType
WHERE
    (e.name LIKE '%ABC001%' OR e.name LIKE '2.1' or e.name LIKE '%CDE001%' OR e.name LIKE '3.1')
) as aa
)as Temp2
group by DHB

OUTPUT
DHB            NumberOfActiveUsers
ABC Hospital           2
ABC Hospital           5
EFG Hospital           3
EFG Hospital           8

Expected OUTPUT should be
DHB            NumberOfActiveUsers
 ABC Hospital          7
 EFG Hospital          11

A: quick and dirty solution:
select distinct * from (
  select * from part1
  union all
  select * from part2
) t;

(this is an alternative to the group by suggested in the comments, which is another valid, perhaps equivalent, avenue.)
Edit 1
As written in the comments, this "quick and dirty" way of doing things does not work since the OP requires the aggregate function SUM. Grouping by DHB, I believe this would work:
select DHB, SUM(NumberOfActiveUsers) as NumberOfActiveUsers
from (
      select /*your first statement*/ from part1
      union all
      select /*your second statement*/ from part2
) t;


text:
Q: JAVA LZW decompression algorithm not yeilding decompressed file import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Map.Entry;
import java.util.stream.Collectors;

public class LZW {

    private static Map<String, Integer> baseDict = new HashMap<String, Integer>();
    private static Map<Integer, String> revDict = new HashMap<Integer, String>();
    private static Scanner in = new Scanner(System.in);

    public static void makeText() {
        try {
            FileOutputStream fos = new FileOutputStream("text.txt");
            for (int n = 0; n < 5000; n++) {
                for (int i = 0; i < 256; i++) {
                    char ch = (char) i;
                    fos.write(ch);
                }
            }
            fos.close();
        } catch (IOException e) {
        // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    public static void deflate(String fileName) {

        Map<String, Integer> dict = baseDict;
        try {
            FileInputStream fis = new FileInputStream(fileName);
            FileOutputStream fos = new FileOutputStream("compressed.lzw");
            DataInputStream dis = new DataInputStream(fis);
            DataOutputStream dos = new DataOutputStream(fos);
            int iBuf;
            char cBuf;
            String sBuf = "";

            iBuf = fis.read();
            cBuf = (char) iBuf;
            sBuf += cBuf;

            while ((iBuf = fis.read()) != -1) {

                cBuf = (char) iBuf;
                String temp = sBuf + cBuf;

                if (dict.containsKey(temp)) {
                    sBuf += cBuf;
                } else {
                    fos.write(dict.get(sBuf));
                    dict.put(temp, dict.size());
                    sBuf = "";
                    sBuf += cBuf;
                }

            }
            fos.write(dict.get(sBuf));

            fis.close();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void inflate(String fileName) {

        Map<Integer, String> dict = revDict;
        try {
            FileInputStream fis = new FileInputStream(fileName);
            FileOutputStream fos = new FileOutputStream("decompressed.pdf");
            DataInputStream dis = new DataInputStream(fis);
            DataOutputStream dos = new DataOutputStream(fos);

            String entry, w;
            char ch;
            int prev, curr;

            prev = dis.read();
            w = dict.get(prev);
            dos.writeBytes(w);
            while ((curr = dis.read()) != -1) {
                if (dict.containsKey(curr)) {
                    entry = dict.get(curr);
                    dos.writeBytes(entry);
                    dict.put(dict.size(), (w + entry.charAt(0)));
                    w = entry;
                } else {
                    entry = w + w.charAt(0);
                    dos.writeBytes(entry);
                    dict.put(dict.size(), entry);
                    w = entry;
                }
            }

            dis.close();
            dos.close();
         } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void init() {
        for (int i = 0; i < 256; i++) {
            char ascii = (char) i;
            baseDict.put(("" + ascii), i);
            revDict.put(i, ("" + ascii));
        }
        deflate("original.pdf");
        inflate("compressed.lzw");
    }

    public static void main(String[] args) {
        init();
    }

}

So I've been working on using LZW compression to compress diffenent files. My compression function seems to work fine as I'm able to compress a 5000kb pdf into approx 2200kb. However my decompression algorithm fails to decompress the pdf. The resulting file is still the same size as the compressed file and the pdf is corrupted. I was taking following some psuedo code :
read a character k;
output k;
w = k;
while ( read a character k )
/* k could be a character or a code. */
{
    if k exists in the dictionary
        entry = dictionary entry for k;
        output entry;
        add w + entry[0] to dictionary;
        w = entry;
    else
        output entry = w + firstCharacterOf(w);
        add entry to dictionary;
        w = entry;
}

Could anyone steer me in the right direction as to why my decompression function is wrong?


text:
Q: Ajax auto suggest does not show letters in sequential order. I am making a small script with javascript to find/display text from an array as I am typing. Sort of like, Google auto suggest tool.
Here is Js script:
<script>
$(function() {
    var availableTags = <?php echo json_encode( $foo ); ?>;
     $( "#tags" ).autocomplete({ source: availableTags });
});
</script>

and the arrays in PHP
  <?php
        $foo = array("ambiguious","brown",
        "corps","demanding job","eat the pomes","fooling with it");
    ?>

Notice how each words in the array have different first letters than the rest ie.?
 good, now when I type a instead of showing words that being with a (in this case "ambiguious"), it shows me all words which has a in them.

I thought about making strpos() to search through similar words, but it does not work.
Any thoughts would be nice. Thank you.

A: have a look at the API:
http://api.jqueryui.com/autocomplete/
Example: Using a custom source callback to match only the beginning of terms
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>autocomplete demo</title>
  <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.1/themes/base/jquery-ui.css">
  <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
  <script src="http://code.jquery.com/ui/1.10.1/jquery-ui.js"></script>
</head>
<body>

<label for="autocomplete">Select a programming language: </label>
<input id="autocomplete">

<script>
var tags = [ "c++", "java", "php", "coldfusion", "javascript", "asp", "ruby" ];
$( "#autocomplete" ).autocomplete({
  source: function( request, response ) {
          var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( request.term ), "i" );
          response( $.grep( tags, function( item ){
              return matcher.test( item );
          }) );
      }
});
</script>

</body>
</html>

A: Refer my LIVE DEMO
HTML:
List: <input id="myContent" />

JQuery:
var myTags = ["c++", "java", "php", "coldfusion", "javascript", "asp", "ruby"];
$( "#myContent" ).autocomplete({
    source: function( request, response ) {
        var matches = $.map(myTags, function(tag) {
            if (tag.toUpperCase().indexOf(request.term.toUpperCase()) === 0) {
                return tag;
            }
        });
        response(matches);
    }
});


text:
Q: C++ String Length problems so im practicing the STL string class, but i can not figure out why the string->length function won't come up with the correct answer of 5, and only 2 (no matter the actual length). Here's the program i'm trying to run but it thinks that there are only 2 items between ->begin and ->end:
void testFunc(string _string[])
{
      int _offset = 0;
      string::const_iterator i;
      for (i = _string->begin(); i != _string->end(); i++)
      {
           cout << _offset << "\t";
           cout << _string[_offset] << endl;
           _offset ++;
      }
};

int main()
{
     string Hello[] = {"Hi", "Holla", "Eyo", "Whatsup", "Hello"};

     testFunc(Hello);

     char response;
     cin >> response;
     return 0;
}

The output is:
0     Hi
1     Holla

Thanks! =)

A: You're iterating through the first string, which is "Hi" - it has two characters, so you see two entries.
If you want to go all STL, you'd need a vector instead of a C-style array (i.e. vector<string>, and use an iterator on that.
If you don't want STL:
    void testFunc(string *strings, int stringCount)
    {
        int _offset = 0;

        while (stringCount--)
        {
            cout << _offset << "\t";
            cout << _strings[_offset] << endl;
            _offset ++;
        }
    };

int main()
{
    string Hello[] = {"Hi", "Holla", "Eyo", "Whatsup", "Hello"};

    testFunc(Hello, sizeof(Hello) / sizeof(Hello[0]));

    char response;
    cin >> response;
    return 0;
}

A: The issue is with the expressions:
_string->begin()
_string->end()

Thinking of a->b as the same as (*a).b, we can see that they are:
(*_string).begin()
(*_string).end()

*x is the same as x[0], so we have:
_string[0].begin()
_string[0].end()

As _string[0] contains "Hi", you can see why the iteration is only two steps.

A: The problem is that you are trying to is iterate a c array.


text:
Q: Gmail returns 534-5.7.14 Please log in via your web browser I found this error while i'm trying to send an email from one Gmail account to another. How to solve this error ? Help me on it.
There were an error:

534-5.7.14 Please log in via your web browser and 534-5.7.14 then try again. 534-5.7.14 Learn more at 534 5.7.14 https://support.google.com/mail/answer/78754 hw7sm51688135pac.12 - gsmtp

A: You need to allow less secure apps, you can do it by click below link
https://www.google.com/settings/security/lesssecureapps
also try this one
https://accounts.google.com/DisplayUnlockCaptcha
if still not works try changing password for gmail

A: I have tried with all the below options none of them worked, changing the password solves the issues.
Allow less secure apps ON
Passed correct user/password
Tried this https://accounts.google.com/DisplayUnlockCaptcha
All are correct in my case but still getting error Username and Password not accepted.
My Gmail password didn't change for a long time, after updating the password it works.

A: I was not able to send email with gmail stmp from 000webhost. In the error message there was this:"Gmail returns 534-5.7.14 Please log in via your web browser". the problem was that google blocked the connection.
they asked if the connection request were from me. I haved change my password and fix the problem.

A: You need to set the Allow less secure apps: ON, login to google using the account desired, and go to the security page and set the Allow less secure apps to be ON.

A: Check multiple-factor authentication is off and the Less secure app is turned on as mentioned by others in this thread. If you still face the issue follow the below steps.

*

*On your computer, open Gmail.

*In the top right, click Settings and See all settings.

*Click the Forwarding and POP/IMAP tab.

*In the "IMAP access" section, select Enable IMAP.

*Click Save    Changes.


text:
Q: JS jquery and ajax problem Hi i have problem with some things
Here is the code
function get_char_val(merk) {
 $.ajax({
  type: "POST",
  url: "char_info2.php",
  data: { name: merk },
  dataType: "html",
  success: function(data){return(data);}
});

}
alert(get_char_val("str"));

when alert comes out it's output the undefined please help fast i'm making this two days xC

A: get_char_val does not return anything.  The success callback needs to have alert(data) in it to return the data from AJAX.
$.ajax is asynchronous - meaning it doesn't happen in order with other code, that is why the callback exists.

A: Your return; statement will return the value to the anonymous function you pass into the success handler. You cannot return a value like this, you need to invoke another callback instead.
function get_char_val(merk, cb) {
   $.ajax({
      type: "POST",
      url: "char_info2.php",
      data: { name: merk },
      dataType: "html",
      success: function(data){cb.apply(this, data);}
   });
}

get_char_val("str", function(data) {
    alert(data);
});

A: You can either set the async:false config parameter in the ajax call options or use the call back.
Using Async:false -
    function get_char_val(merk)
    {
      var returnValue = null;
        $.ajax
        (
            {
                type: "POST",
                async:false,
                url: "char_info2.php",
                data: { name: merk },
                dataType: "html",
                success: function(data){returnValue = data;}
            }
        );
     return returnValue;
    }
    alert(get_char_val("str"));

P.S: Note that making ajax calls synchronous is not advisable.

A: Since you do an asynchronous ajax call, the response of the server is handled in the "success" function. The return in your success function is useless, you should use the "data" parameter directly in the function

A: This should work. Use it like this.
function get_char_val(merk) {
var myReturnData= "";
 $.ajax({
  type: "POST",
  url: "char_info2.php",
  data: { name: merk },
  dataType: "html",
  success: function(data){myReturnData = data;}
});
return myReturnData;
}
alert(get_char_val("str"));

Just understand the problem with your piece of code. Use the return statement under the right function.


text:
Q: Field Formula to Count Contact Number of Cases I have done some researching and just trying to verify that this is not possible to count the number of cases a contact has created with a formula field. Is the only option a trigger? I'm assuming I then would need to mass update current contact records. Is this correct?
I can write a trigger if necessary and then write a bulk update class to implement, but would rather not do that if it's something possible with a formula.
Thanks in advance.

A: It's not possible to do this with a trigger. If the relationship of Contact-Case were Master-Detail it would be possible with a rollup summary. But it isn't, so it isn't.


text:
Q: Sequence Detector forced to wait a specific number of bits So I have this little problem, where I am supposed to build a sequence detector which is forced to wait a specific number of bits before going into the reset state. It's kind of like pin codes work. You put the whole 4-digit sequence number and in the end it says if the output is true (1) or not (0).
An example our professor gave is:
A sequence detector waits for 4 bits and outputs 1 if the 4-bit sequence has at least two 1s.
If anyone does not mind explaining how to build a system like this or find me a lecture/notes/site/tutorial where I can understand this concept.
I can only use Mealy machines state diagrams.

A: You have two possible inputs -- a "0" or a "1". What happens when one of those is entered?
It seems like you need to maintain TWO counters, one with how many digits have been entered, and one with how many of them are "1".
There are shortcuts you can take to minimize the number of states. For example, if you've already got two "1"s or three "0"s, there's no longer a need to maintain the counter with the number of "1"s. Also, history of the sequence doesn't count in your example case; e.g., if you have reached one "1" after two inputs, you don't care if the history that got you there was "01" or "10", so you don't need to maintain a state for each.
Generalizing these things involves truth tables, Karnaugh maps, and tedium. I don't think you really need to do that. In your sequence, you have 2^4 possible combinations of inputs. Brute force will thus bring you to 16 states you can end up in, plus a starting state, plus 2+4+8 intermediate states. Truth tables will show you some duplicate states, so you can reduce.
I've drawn up something real quick.  The left to right columns are the number of inputs entered, and the down to up rows basically correspond to how many ones have been entered.  I've labeled the states with how many "1" have been entered so far, and you can see where I've reduced duplicate states, as those states are labeled with \$<\$ or \$\geq\$ signs, or have more than one input path to them.  You can also see that the arrows with two numbers show that success or failure (given you reach four inputs) has already been determined.  Note that I did not include the final step of returning to the starting state.

A: I always find it mind bogging why anybody would write a huge many-states FSM for this sort of code.
In practice I would use two counters:

*

*First counter counts the number of keys pressed.

*Second counter counts the number of ones pressed.

Both reset if the first counter gets to four. At that same time you output a one if the second counter is above a certain threshold .e.g 2.
Yes, you might use a register or two more then needed, but you save hours in development time and the code will be a lot easier to read and thus to maintain. My guesstimate is that the Verilog FSM code is about ten times bigger than the two counters code.


text:
Q: C++/WinRT Console app for IoT Core stuck on splash screen This is just out-the-box (as directed from here) from the template and pushed to the (virtualbox) emulated device by doing a Remote Machine debug session.
Why is it stuck on the splash-screen? Anybody come across the same? Have I missed something?
When I run it it deploys fine giving this debug output (nothing to speak of, I don't think):
'ConsoleCppWinRt3.exe' (Win32): Loaded 'U:\Users\DefaultAccount\AppxLayouts\cc60f819-ef47-4858-b213-8af8c3669919VS.Debug_Win32.nm1\ConsoleCppWinRt3.exe'. Symbols loaded.
'ConsoleCppWinRt3.exe' (Win32): Loaded 'C:\Windows\System32\ntdll.dll'. Cannot find or open the PDB file.
'ConsoleCppWinRt3.exe' (Win32): Loaded 'C:\Windows\System32\KernelBase.dll'. Cannot find or open the PDB file.
'ConsoleCppWinRt3.exe' (Win32): Loaded 'C:\Windows\System32\combase.dll'. Cannot find or open the PDB file.
'ConsoleCppWinRt3.exe' (Win32): Loaded 'C:\Windows\System32\msvcrt.dll'. Cannot find or open the PDB file.
'ConsoleCppWinRt3.exe' (Win32): Loaded 'C:\Windows\System32\rpcrt4.dll'. Cannot find or open the PDB file.
'ConsoleCppWinRt3.exe' (Win32): Loaded 'C:\Windows\System32\kernel32legacy.dll'. Cannot find or open the PDB file.
'ConsoleCppWinRt3.exe' (Win32): Loaded 'C:\Windows\System32\bcryptprimitives.dll'. Cannot find or open the PDB file.
'ConsoleCppWinRt3.exe' (Win32): Loaded 'U:\Programs\WindowsApps\Microsoft.VCLibs.140.00.Debug_14.0.26428.1_x86__8wekyb3d8bbwe\vcruntime140d_app.dll'. Cannot find or open the PDB file.
'ConsoleCppWinRt3.exe' (Win32): Loaded 'U:\Users\DefaultAccount\AppxLayouts\cc60f819-ef47-4858-b213-8af8c3669919VS.Debug_Win32.nm1\ucrtbased.dll'. Cannot find or open the PDB file.
'ConsoleCppWinRt3.exe' (Win32): Loaded 'C:\Windows\System32\kernel.appcore.dll'. Cannot find or open the PDB file.
'ConsoleCppWinRt3.exe' (Win32): Loaded 'C:\Windows\System32\procthreadexthost.dll'. Cannot find or open the PDB file.
The thread 0xd38 has exited with code 0 (0x0).

Edit
If I pause the debugger it's in console code. But the splash screen is still in the way or something. e.g. In this code the debugger is in the getchar() call:
int main()
{
    wprintf(L"Hello IoT");
    getchar();
}

But in this code:
int main()
{
    wprintf(L"Hello IoT");
    Sleep(10000);
}

...it's in the Sleep call, but after the 10sec it closes causing Visual Studio to declare:

Unable to activate windows store app [...]. The myapp.exe process
  started but activation request failed with error 'The app didn't
  start'.

I'm not supposed to call something to close the splash screen or something obvious, am I?


text: Q: Spotify SDK iOS: While Playing Music in background application will be crashed after few second I am playing Spotify music in background mode. It works fine. But after few seconds application will be crashed. I had tried to found solution but still i could not found any Proper Solution. Please help me.


text:
Q: How to use animation as background image enter image description here
Taking a look at that picure, animation is use as background in the left and on the right side of the page, an image is used as the background. Please hw can i go about using both backgrounds on one webpage.


text:
Q: xunit.runner.visualstudio not working on Visual Studio 2013 Update 4 I got the following constellation:
Machine 1:
- Windows 8.1
- Visual Studio 2013 Update 3.
- XUnit Test Runner installed via "Tools" / "Extensions"
Machine 2:
- Windows Server 2012 (Hyper V Virtual Box)
- Visual Studio 2013 Update 4
I've loaded a project, which I've created on Machine 1, on Machine 2. The project already contained Unit Tests which ran perfectly on Machine 1.
The installation of the XUnit Testrunner via "Tools" / "Extensions" got unavailable recently. Therefore I installed the package xunit.runner.visualstudio as a Nuget Package into my solution on machine 2. After I rebuilt my solution on machine 2 not tests are visible in Visual Studio on the newly setup box. What do I have to do to get my unit and integration tests back into the test runner? Is there anything else I need to install?
Thanks a lot for all your help


text:
Q: link_to many tags instead of a single string I am building a list of user notifications. When the current user clicks an
 tag, which contains the entire notification content, they should be redirected to the mentioned post or user etc.
Here is what I am trying right now and can't seem to get it to work.
<%= link_to activity.activable do %>
  <%= link_to(image_tag(activity.actor.avatar.url(:thumb)), user_path(activity.actor.username)) %>

    <%= link_to activity.actor.name, user_path(activity.actor.username), class: "us-rt-usnm" %>
    <%= activity.action %> on
    <%= link_to personalize_owner(activity, recepient), user_path(activity.activable.user.username) %>
    <%= link_to 'Post', activity.activable %>

    <%= time_ago_in_words(activity.created_at) %>

<% end %>

Once I get this to work, I will remove the line <%= link_to 'Post', activity.activable %>, because the entire
 will be a link when clicked.

I also tried this on my activities main view page.

  <%= link_to activity.activable do %>
    <%= render "activities/#{activity.action}", activity: activity, recepient: recepient %>
  <% end %>

Can someone show me what I need to do? Because so far everyhing I've done has not worked.

A: The wrapping link_to and the internal links are going to give you a headache. You have to decide what's most important in the element.
On the face of it, where you have a notification that should be clickable and link to the specified activity, you should remove the internal links and just link the whole content to the activity. Once they arrive at the activity, then you can include links to author, owner, and so on without worrying about a wrapping link.

A: It looks like you are attempting to nest anchor links, which is against the W3C standard.  You won't be able to use the link_to tag from within a link to block.  You can, however, make the on Click event handler fire by assigning an id and using the data attributes to store the destination
<li class="clickable" data-destination="<%=activity.activable%>"
  <%= link_to activity.actor.name, user_path(activity.actor.username), class: "us-rt-usnm" %>
   xxxxxx

#JQuery example
$('.clickable").on('click', function () {window.location.href = $(this).attr('data-destination') });