text:
Q: Why does my cost for a clustered index scan increase when narrowing down the where clause on a different table? I have a simplified query like this
SELECT a.OrderInfoID, a.SalesReceiptID, SUM(b.Qty) AS Qty
FROM dbo.OrderInfo a
INNER JOIN dbo.OrderInfoSequential b ON a.OrderInfoSequentialID=b.OrderInfoID
WHERE a.OrderID=12345
GROUP BY a.OrderInfoID, a.SalesReceiptID

The query plan shows a clustered index scan on dbo.OrderInfoSequential for about 1s, which makes sense because there is no index yet.
However when I change the where clause to
WHERE a.OrderID=12345 AND a.SalesReceiptID=123

The time for the clustered index scan increases to over 3s.
I don't understand this because it should search for the exact same thing or even less (because specifying the SalesReceiptID should result in less OrderInfo records found that need to be joined in the first place.
What am I not understanding about this correctly?
Edit: Removed (NOLOCK) statements as they are not relevant to the question


text:
Q: 1084: Syntax error: expecting rightparen before add Whats wrong with my code? I'm getting this error in adobe flash:
Scene 1, Layer 'Layer 2', Frame 2, Line 2, Column 13    1084: Syntax error: expecting rightparen before add.

This is the code:
// create random speed and xpos for this snowflake
set ("xpos" add c], random(200));
set ("speed" add c], Number(random(4))+2);
// duplicae a snowflake
flake0.duplicateMovieClip ("flake" add c, c);
// set x position and random size
this["flake" add c]._x = eval("xpos" add c);
size = Number(random(50))+25;
this["flake" add c]._xscale = size;
this["flake" add c]._yscale = size;
//move each snowflake down by its speed;
for(i=1;i<=maxflakes;i++) {
    this["flake" add i]._y = this["flake" add i]._y + eval("speed" add i);
    i = i+1;
}

A: set ("xpos" add c], random(200));

This is incorrect. Either there will be a comma after "xpos" or you should close the parentheses.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Grub2 re-installation failed with boot-repair I have a MSI mother board and a SSD drive for dual system booting.
It worked fine until suddenly it showed cannot find memory block on hd2 or something like that. I didn't pay attention and rebooted the PC. Then I could only access Windows system. I rebooted again, then I couldn't access either.
I prepared a boot-repair usb drive, and auto-repaired it. But it shows
error: no such device: XXXXXXXXXXX.
Then, it entered rescue mode.
I tried ls
it shows  (hd0)(hd1)(hd2)
then I tried ls (hd0)/, ls (hd1)/ and ls (hd2)/
the results are all Filesystem is unknown
Here is the pastebin log https://paste.ubuntu.com/p/NfhrtD5bXx/
Any help is appreciated.


text:
Q: Objective-C OpenGL game tutorials I would like to start making an iPhone/Ipod game with xCode 4.2 I have registered with apple and have everything I need but information. I know just a little Objective-C and need a tutorial that will explain everything because I do not get a bunch of the code like why they put it there and why it has to be a capital letter or why a space is there. This tutorial needs to also have the OpenGL related content.

A: A good place to start is with lectures from Stanford which are available on iTunesU. Search for iPhone Development by Paul Heagarty


text: Q: theres is a way to change the color map with angular2 google maps I want to change de color of the map, I'm using angular2-google-maps, I have found https://mapstyle.withgoogle.com where I can change the map style, but how can I do this with angular 2?


text:
Q: Nodejs | Chrome Memory Debugging Context:
I have an Node.js application which memory seems to very high, I don't know if that is memory leak or not, because it is reduced after certain period time, but some times on heavy load it keeps on increasing takes much longer to get reduced.
So going through the articles and couple of videos, i figured that i have to heap snapshot and analyse what is causing the memory leak.
Steps:

*

*I have taken 4 snap shots as of now in my local to reproduce the memory leak.

Snapshot 1: 800MB
Snapshot 2: 1400MB
Snapshot 3: 1600MB
Snapshot 4: 2000+MB

*When i uploaded the heapdump files to chrome dev tools I see there a lot of information but i don't know how to proceed from there.

Please check below screenshot, it says there is constructor [array] which has 687206 as shallow Size & Retained Size is 721414 in the columns, so when expanded that constructor i can see there are 4097716 constructors created ( refer the second screenshot attached below ).

Question

*

*What does internal array [] means ? Why is there 4097716 created ?

*How can a filter out the constructor which created by my app and showing me that instead of some system/v8 engine constructor ?

*In the same screenshot one of the constructor uses global variable called tenantRequire function, this is custom global function which is being used internally in some places instead of normal Node.js require, I see the variable across all the constructor like "Array", "Object". This is that global tenantRequire code for reference. It is just patched require function with trycatch. Is this causing the memory leak somehow ?

*Refer screenshot 3, [string] constructor it has 270303848 as shallow size. When i expanded it shows modules loaded by Node.js. Question why is this taking that much size ? & Why is my lodash modules are repeated in that string constructor ?

A: Without knowing much about your app and the actions that cause the high memory usage, it's hard to tell what could be the issue. Which tool did you use to record the heap snapshot? What is the sequence of operations you did when you recorded the snapshot? Could you add this information to your question?
A couple of remarks
You tagged the question with node.js and showed Chrome DevTools. That's ok. You can totally take a heap snapshot of a Node.js application and analyze it in Chrome DevTools. But since both Node.js and Chrome use the same JS engine (V8) and the same garbage collector (Orinoco), it might be a bit confusing for someone who reads the question. Just to make sure I understand it correctly: the issue is in a Node.js app, not in a  browser app. And you are using Chrome just to analyze the heap snapshot. Right?
Also, you wrote that you took the snapshots to reproduce the memory leak. That's not correct. You performed some action which you thought would cause a high memory usage, recorded a heap snapshot, and later loaded the snapshot in Chrome DevTools to observe the supposed memory leak.
Trace first, profile second
Every time you suspect a performance issue, you should first use tracing to understand which functions in your applications are problematic (i.e. slow, create a lot of objects that have to be garbage-collected, etc).
Then, when you know which functions to focus on, you can profile them.
Try these visual tools
There are a few tools that can help you with tracing/profiling your app. Have a look a FlameScope (a web app) and node-clinic (a suite of tools). There is also Perfetto, but I think it's for Chrome apps, not Node.js apps.
I also highly recommend the V8 blog.


text:
Q: Relaying Serial Data in Lion So I have my computer linked up via bluetooth to two different devices, and I'd like to relay the input from one device to the other device automatically.
I figure I can do this with a script, but I'm pretty green with scripting languages, and I'm not even sure if this is possible.
I know that like Linux, OSX treats serial ports as if they were file directories, so I figure this can't be too hard.  I just have no idea where to start.
Can someone point me in the right direction?

A: I would use a simple python script.  Manipulating serial ports is simple with the pyserial module.  Then create thread for each port that reads from one port and writes to the other.


text:
Q: [LDAP: error code 32 - 0000208D: NameErr: DSID-031001EE, problem 2001 (NO_OBJECT), data 0, best match of: '' ]; remaining name '' In my WebSecurityConfigurerAdapter I override the configure method as follows:
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.ldapAuthentication()
            .userSearchBase("DC=unit1,DC=org1,DC=com")
            .userSearchFilter("(sAMAccountName={0})")
            .contextSource().url(ldapUrl).managerDn(mgrDn).managerPassword(mgrPassword);
}

I am passing the following request:
Request Headers: Content-Type: application/x-www.form-urlencoded;charset=UTF-8
Form Data username=user&password=password
But I keep on getting the ldap error.  Please advise.


text:
Q: How do I share a LIST within a site collection WITHOUT using SP Designer?? Using SharePoint 2013 I found this older question and answer on this exchange that pertains to my situation.  However, the answers are incomplete.
Sharing a library between two sites, without designer?
However, I followed the directions and got the HTML Web Part to show a green circle loading.  The person asking the question before me had the same problem.  However, no one answered.
I did try using the Content Query web part.  However, it only showed one column of the list.  (I have a simple POC list with name, title, email, and phone number)  The Content Query web part only shows the names found under one of the columns in the list I want.
I have full admin control.  I do not do coding and we are not allowed to use SP Designer in my organization....not that I would know how to properly use it if I did have access to it...I can follow simple coding steps such as the above link.
Thank-you,
Helen

A: Without SharePoint Designer and Content Query web part, you can't simply achieve your goal! and you will need to write a custom code that I think it is the hardest option especially most of JSOM/JS samples over the internet is not working to show the list view with its traditional structure properly!
So to code that you need to get the list items and show it in Gridview using SSOM as an option! check this Bind SharePoint List Items in a Gridview
So I suggest asking the decision maker to at least allow you to install and use SPD from your machine and follow the steps that mentioned at

*

*Display a SharePoint List from Parent Site in Sub Site

*SP 2016 - Display list from Parent site in sub-site


text:
Q: Where IN query on Doctrine ManyToMany tags relation A little bit of background:

*

*I've got Office entities.

*Offices may have articles.

*Articles have tags.

*Offices can share a tag with other offices (and therefore articles).

Now I'm trying to build a query that says: "Fetch all articles that either belong to my office or have tags that have been shared with my office".
I've tried this in MySQL and the following query works as expected:
SELECT
    *
FROM
    `articles` `a`
WHERE
    (
        `office_id` = 2
        OR
        `a`.`id` IN (
            SELECT
                `at`.`article_id`
            FROM
                `article_tags` `at`
            WHERE
                `at`.`article_id` = `a`.`id`
            AND
                `at`.`tag_id` IN
                (
                    SELECT
                        `st`.`tag_id`
                    FROM
                        `shared_tags` `st`
                    WHERE
                        `st`.`shared_with_id` = 2
                    AND
                        `st`.`article` = 1
                )
            )
    )
AND
    `status` = 1

My entities are as follows:
Article
/**
 * @ORM\ManyToMany(targetEntity="Tag", inversedBy="articles")
 * @ORM\JoinTable(name="article_tags")
 * @var ArrayCollection|Tag[]
 */
protected $tags;

Tag
/**
 * @ORM\ManyToMany(targetEntity="Article", mappedBy="tags")
 * @var ArrayCollection|Article[]
 */
protected $articles;

SharedTag
class SharedTag extends Entity
{

    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     * @var int
     */
    protected $id;

    /**
     * @ORM\ManyToOne(targetEntity="Office", inversedBy="sharedTags")
     * @ORM\JoinColumn(name="shared_with_id", referencedColumnName="id")
     * @var Office
     */
    protected $sharedWith;

    /**
     * @ORM\ManyToOne(targetEntity="Office", inversedBy="sharedTags")
     * @ORM\JoinColumn(name="shared_by_id", referencedColumnName="id")
     * @var Office
     */
    protected $sharedBy;

    /**
     * @ORM\ManyToOne(targetEntity="Tag", inversedBy="sharedTags")
     * @var Tag
     */
    protected $tag;

    /**
     * @ORM\Column(type="boolean", options={"default" = 0})
     * @var bool
     */
    protected $template = 0;

    /**
     * @ORM\Column(type="boolean", options={"default" = 0})
     * @var bool
     */
    protected $article = 0;

    /**
     * @ORM\Embedded(class = "\ValueObjects\CreatedAt", columnPrefix=false)
     * @var CreatedAt
     */
    protected $createdAt;

}

So, how can I query this in DQL or with the QueryBuilder? I've tried several methods but I can't seem to use the tag_id from the relationship articles.tags in a WHERE IN() query.
Thank you in advance!

Edit:
After some trial and error and thanks to Jean's answer I was able to query it like this:
SELECT
  a
FROM
  Article a
LEFT JOIN a.tags t
LEFT JOIN a.office o
LEFT JOIN o.sharedTags st
WHERE
  (
    a.office = :office
    OR
    (
      t = st.tag
      AND
      st.sharedWith = :office
      AND
      st.article = 1
    )
  )
AND
  a.status.status = :status
AND
  a.template IS NULL
GROUP BY a.id

A: You should use a join and not subqueries. This way you have better performance and less complicated DQL code:
SELECT DISTINCT `a`
FROM `articles` `a`
LEFT JOIN `a.tags` `t`
LEFT JOIN `t.shared_with_id` `o`
WHERE (`a`.`office_id` = 2 OR `o`.`id` = 2)
AND `status` = 1


text:
Q: How do I configure Android Studio to show hints? Currently learning Flutter. I was watching a video tutorial on YouTube (MTechViral) and the IDE that he was using (Visual Studio Code) showed hints whenever he typed an element as shown here.
See how the IDE lists all the possible elements and then describes it?
Is it possible to configure Android Studio to do this? Thanks!

A: make sure you have installed the flutter and dart plugin, once installed intellisense should work off the bat. Maybe try updating android studio and reinstalling the dart and flutter plugins. CTRL + SPACE on windows and control + space on mac will display intellisense.
Good luck


text:
Q: How to find the end_date of django celery in Django? I have a chain like this:
 chain = file_transfer.s(password, source12, destination1) | save_db.s(request.user.id, basename, extension, servername, start_date1, datetime.datetime.utcnow().replace(tzinfo=utc)

While calling save_db.s, I want to call to get the end_date that's why I used datetime.datetime.utcnow().replace(tzinfo=utc) to calculate the end_date. The problem is that it calculates date when the task is initiated. How can I get the end_date of each task and save the end_date in a database for later use. Thanks

A: If you remember save_db.s will get result of file_transfer.s as first arg. Therefore you can return result from file_transfer.s as tuple with datetime.
Example:

from django.utils.timezone import now
def file_transfer(...):
    ...
    return (now(), ...)

def save_db(end_date, ...):
    ...


text:
Q: How dropdown find out that its selected index has changed and need to fire selected index changed event? How dropdown find out that its selected index has changed and need to fire selected index changed event?
Suppose i have a dropdown which is bounded with objectdatasource
and objectdatasource has following items
opt1
opt2
opt3
opt4
then i added default value --select-- to objectdatasource, now dropdown is populated and i can see all the items on it. I have a button and on its client click, through java script i set opt4 to selected item. now if i select --select-- from dropdown then it does not fire selected index changed event but it fires dropdown's data bound event and then if i select any other value it fire both events and then if i again select --select-- then it fire both event, only first time if i select --select--then it will not fire selected index change event but if i select other than --select-- it fire both events.
So my question is how dorpdown find out that its selection index has changed.

A: It looks like OnSelectedIndexChanged should always fire on a DropDownList postback if includeStagesBeforeAsyncPoint is true
System.Web.UI.Page
private void ProcessRequestMain(bool includeStagesBeforeAsyncPoint, bool includeStagesAfterAsyncPoint) {
    if (includeStagesBeforeAsyncPoint) {
        ...
        if (this.IsPostBack) {
            ...
            this.RaiseChangedEvents();

internal void RaiseChangedEvents() {
    ...
    for (int i = 0; i < this._changedPostDataConsumers.Count; i++) {
        ...
        postBackDataHandler.RaisePostDataChangedEvent();
    }
}

System.Web.UI.WebControls.DropDownList
void IPostBackDataHandler.RaisePostDataChangedEvent()
{
    this.RaisePostDataChangedEvent();
}

protected virtual void RaisePostDataChangedEvent() {
    ..
    this.OnSelectedIndexChanged(EventArgs.Empty);
}


text:
Q: Weird ungrammatical PHP error msg when trying to set upload folder I've been getting this error, verbatim:

// PHP setup Edit php.ini (try /usr/local/php5/lib/php.ini search for "tmp" and make sure file uploads are, and that you have a tmp director of that name, with permissions set. To load the new php.ini, restart apache: apachectl restart

What's weird about this, besides the grammatical flaws, is that I get it no matter what I set upload_tmp_dir to in php.ini...or even if I remove php.ini entirely.

*

*I do an apachectl restart after each change. I've also tried rebooting.

*I believe I'm editing the right php.ini, because it's the one listed when I do a phpinfo(): /usr/local/php5/lib/php.ini. It lists whatever upload directory I edit into it.

*This happens under Mac Lion with both Chrome and Firefox

*phpinfo tells me I'm running PHP Version 5.4.6

*I am the opposite of an expert.

Thanks for whatever help you can give me. I am preparing to D'oh slap myself.

A: It was indeed a comment in a buried file.  Aaarrrggghh! Thanks to do those who offered suggestions. I am equally grateful and embarrassed.


text:
Q: How can I make v-slot: cell () - Vue.js I want to make a v-slot like in the Bootstrap Vue table v-slot: cell ().
I have tried several ways, but all of them failed.

<template>

    <slot name="[nama,pakai]" :item="db">

        {{ db }}

    </slot>

</template>

<template v-slot:name(qc)="row">
{{row}}
</template>

Previously I looked for documentation but did not find a way like that.


text:
Q: JBDI - Eating up part of the SQL statement This is my JDBI method
@Override
@SqlQuery("SELECT * FROM " + TABLE_NAME + " WHERE " + COLUMN_CAMPAIGN_ID + " = :campaignId AND " + COLUMN_STATUS
                + " = 0 AND " + COLUMN_STAGE_ID + " IS NULL AND " + COLUMN_MODIFICATION_DATE
                + " < NOW() - INTERVAL '<timeInterval>'")
List<Idea> getDraftIdeasBeforeTime(@Bind("campaignId") long campaignId,
                @Define("timeInterval") String timeInterval);

On execution, it breaks with the following error
ERROR [2021-10-22 10:06:00,041] com.addons.advanced.jobs.DraftIdeasJob: Exception received while trying to delete draft ideas : org.skife.jdbi.v2.exceptions.UnableToExecuteStatementException: org.postgresql.util.PSQLException: ERROR: argument of AND must be type boolean, not type timestamp without time zone
  Position: 127 [statement:"SELECT * FROM ideas WHERE campaign_id = :campaignId AND status = 0 AND stage_id IS NULL AND modification_date < NOW() - INTERVAL '<timeInterval>'", located:"SELECT * FROM ideas WHERE campaign_id = :campaignId AND status = 0 AND stage_id IS NULL AND modification_date ", rewritten:"/* IdeasDaoJdbi.getDraftIdeasBeforeTime */ SELECT * FROM ideas WHERE campaign_id = ? AND status = 0 AND stage_id IS NULL AND modification_date ", arguments:{ positional:{}, named:{campaignId:10}, finder:[]}]

As you can see, post location, it only considers the up until ... AND modification_date and ignores what comes after.
Why is this happening?

A: You need to escape < (change to \\<) symbol in your query since it is the same as used by template engine.
EDIT:
Adding to the answer for more specificity, the issue is at
" < NOW() - INTERVAL '<timeInterval>'"
which needs to be
" \\< NOW() - INTERVAL '<timeInterval>'"


text:
Q: Can't connect to MS SqlServer using php I am trying to connect to an external db which uses sqlserver but after trying many options couldnt find one that works at all.
    $connattempt1 = odbc_connect("Driver={SQL Server Native Client 10.0};Server=XXX.XXX.XXX.XX;1433;Database=IDD",'username','password');
    $connattempt2  = new PDO('sqlsrv:Server=XXX.XXX.XXX.XX,1433;Database=IDD','username','password');
    $connattempt3  = sqlsrv_connect('XXX.XXX.XXX.XX', [
            "Database"      =>      IDD,
            "UID"           =>      'username',
            "PWD"           =>      'password',
            "CharacterSet"  =>      "UTF-8"
        ]);

I will be running this same code on several apache servers all of them on php7. Im looking for a way to connect without having to edit the php.ini on all servers or importing external libraries.
Is there a standard way to correctly make this connection?
Any clue, manual, tips, links are also welcome, thanks!

A: Some Xammp instalations dont come with common libraries, this was the case.
After checking the configurations on some clients it seemed to work well and only my local machine lacked this libraries.
This was the library i used:
https://pecl.php.net/package/sqlsrv/5.9.0/windows
This website is a really great resource to find any dll you might need, so i hope it will help.


text:
Q: java.util.ConcurrentModificationException when i trying to write message to file I'm a starting Java developer. I want to write e-mail client with GUI, but I have a problem when I try to run WriteMessages thread. I'm using JavaMail library.
public class WriteMessages implements Runnable {

    private List<Message> list;
    private Properties properties;
    private Utilities util = new Utilities();

    public WriteMessages(List<Message> list, Properties properties) {
        this.list = list;
        this.properties = properties;
    }

    @Override
    public void run() {

        Iterator<Message> iter = list.iterator();
        while (iter.hasNext()) {

            Message m = iter.next(); //line 42 exception occurs there

            String name = Morda.produceFileName(m);

            File file = new File(properties.getProperty("PathToMessages") + "//" + name);
            try {
                file.createNewFile();
            } catch (IOException ex) {
            }

            try (OutputStream os = new FileOutputStream(file);){
                m.writeTo(os);
                System.out.println("File " + file.getName() + " was wrote succesfuly");
            } catch (IOException | MessagingException ex) {
            }
        }
    }
}

I get:
Message 0 added successfully.
Message 1 added successfully.
Message 2 added successfully.
Message 3 added successfully.
Thread is interrupted.
File 2011_07_17_08_55_27.mes was wrote succesfuly
Exception in thread "Thread-4" java.util.ConcurrentModificationException
    at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:886)
    at java.util.ArrayList$Itr.next(ArrayList.java:836)
    at util.WriteMessages.run(WriteMessages.java:42)
    at java.lang.Thread.run(Thread.java:745)

But, when I remove this snippet of code:
try (OutputStream os = new FileOutputStream(file);){
    m.writeTo(os);
    System.out.println("File " + file.getName() + " was wrote succesfuly");
} catch (IOException | MessagingException ex) {
}

The exception doesn't appear. I think that this problem was already solved, but I can't find how. Please help me to fix this problem.
Thanks.

A: I suspect another thread is accessing the list while this thread is iterating over the messages in the list. This is because the list reference is shared and passed to the thread in its constructor.
Try synchronizing on the list object whenever it is used in this or other threads. You can use a synchronized list:
List<Message> messageList = Collections.synchronizedList(list);

After this you'd still have to synchronize when iterating over the list (and this is actually the most important thing to do here to avoid the ConcurrentModificationException):
synchronized(messageList) {
    Iterator<Message> iter = messageList.iterator();
    while (iter.hasNext()) {
        ...
    }
}

A: In concurrent environment consider using CopyOnWriteArrayList instead of simple ArrayList. When you start iterating it, you will iterate a content of the list which was at the time of iteration start. Usually that's desired behavior. Using Collections.synchronizedList will not actually help preventing ConcurrentModificationException and may make your application less responsive.

A: You should be able to resolve it by synchronizing the access of the method from which this thread is spawned.

A: I think it could be caused that you modify the list with messages in other thread and as the ArrayList is not thread-safe you should consider another List implementation that would be.
Regarding thread-safe implementations you can read more at this post.


text:
Q: No me borra los datos de la base de datos Estoy haciendo una prueba en la cual necesito eliminar los datos de una base de datos, borrando solamente la fila que imprimo en una tabla.
En principio el codigo esta correcto pero no se ejecuta el borrado.
Supongo que estare pasando por alto algun error.
HTML
<?php
    $connect = new mysqli("localhost", "root", "root", "nba");
    $sql ="SELECT nombre, ciudad, conferencia, division FROM equipos";
    $result = mysqli_query($connect, $sql);
?>
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Exportar a csv</title>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />

Exportar datos de BD a un CSV

Datos de Equipos

                Nombre
                Ciudad
                Conferencia
                Division
                Borrar dato

            <?php while($row = mysqli_fetch_array($result)){ ?>

                <?php echo $row["nombre"]; ?>
                <?php echo $row["ciudad"]; ?>
                <?php echo $row["conferencia"]; ?>
                <?php echo $row["division"]; ?>
                Borrar

            <?php } ?>

Y este seria el delete.php
<?php
$id = $_GET['nombre'];
$dbname = "nba";
$connect = new mysqli("localhost", "root", "root", $dbname);

// Check connection
if (!$connect) {
    die("Connection failed: " . mysqli_connect_error());
}

$sql = "DELETE FROM equipos WHERE nombre = $id";

if (mysqli_query($connect, $sql)) {
    mysqli_close($connect);
    header('Location: basenba.php');
    exit;
} else {
    echo "Error deleting record";
}
?>

Siempre me salta el echo "Error deleting record"
Tambien hice un var_dump a $id en el archivo delete.php y me da NULL

A: Fíjate que en el link del formulario le estás pasando un parámetro llamado id (delete.php?id=".$row['nombre']) y en delete.php estás buscando un parámetro llamado nombre ($id = $_GET['nombre']). En delete.php haz esto, por ejemplo:
$id = $_GET['id'];

Por otro lado, en el formulario, a la hora de crear el link, no estás introduciendo correctamente el dato de la variable $row. Deberías hacerlo así:
<a class="btn btn-danger" href="delete.php?id=<?php echo $row['nombre']; ?>">Borrar


text:
Q: How can I pre-generate a BCrypt hashed password for my Spring Boot application? I have a Spring Boot application (code here) with a security configuration that utilizes a BCryptPasswordEncoder:
@Bean
public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
}

I'd like to pre-generate a couple of passwords to initialize my database, for testing or for logging in on a developer machine.  (Not for production.)  My database is PostgreSQL and the schema is based on the Spring Security default schema, with a users table and an authorities table. My SQL statement looks like this:
insert into users (username, password, enabled) values ('joe','$2y$12$XodbOuISPCPQijlY8MIRUepDeURhxDe09/4VQU0Cno5zkTEKjZouO',true);

I don't know much about how the BCrypt hashing algorithm works, but I generated this password hash (for the password "test") using a free online BCrypt hash generator that looks legitimate.  Nevertheless, I cannot log in to my Spring Boot application.  The error in the logs is "bad credentials".  What gives?
PS: This is a follow-up to this other question.

A: The problem turned out to be the prefix $2y in the hash.  This is supposed to represent a version of the BCrypt algorithm but, according to Wikipedia, the prefix is not standard.  To be clear, that online generator isn't using a non-standard algorithm, just a non-standard label.
Incidentally, the next section of the hash, $12, indicates the number of rounds of hashing, and even though it's not the same as the Spring default (10 rounds), it doesn't cause the problem.
The solution is to simply change the y for an a.  $2a is the standard prefix for a BCrypt hash.  You don't need to find a different BCrypt generator or anything, just edit the string.
This works:
insert into users (username, password, enabled) values ('joe','$2a$12$XodbOuISPCPQijlY8MIRUepDeURhxDe09/4VQU0Cno5zkTEKjZouO',true);

A: You can use online BCrypt generator but the thing is that the online generator might generate different regex from your Spring Segurity enconder.
For example the online generator can generate BCrypt with regex "$2y" and your Spring Boot enconder generate with "$2a" regex. If this happen you will get always bad credencials.
I strongly recommend you to generate your passwords using Spring Boot BCrypt Enconder.
@SpringBootApplication
public class QuartzJdbcJobStoreBciApplication extends SpringBootServletInitializer{

public static void main(String[] args {
    SpringApplication.run(QuartzJdbcJobStoreBciApplication.class, args);
    BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
    String password [] = {"Password1", "Password2", "Password3"};
    for(int i = 0; i < password.length; i++)
        System.out.println(passwordEncoder.encode(password[i]));

    }
}


text:
Q: git non-fast-forward updates. How to overcome? Apologies for the double post, but I wasn't getting any further replies in my previous question, so thought I'd try my luck explaining it better ...
I've set my git working structure as follows (thanks to a recommendation in another question git : Small project work)
 /live/website
       |
       |
/path/to/staging (bare)
  |          |
  |          |
dev1        dev2

Currently, both dev1 and dev2, push the projects to the /path/to/staging repo. I have a hook in /path/to/staging, that automatically triggers a cd /live/website && git pull from my  /path/to/staging. This way, I have a working copy of all files there. So really dev1, dev2 and /live/website are git clones of /path/to/staging.
Rudi, recommended finding out if receive.denyNonFastforwards was set to true on path/to/staging by doing:
cd path/to/staging/ && git config --get-all receive.denyNonFastforwards

And unfortunately it is set to true. So for example if I did a git reset --hard <SHA-1> on the /live/website server, it does so successfully. However, when I try to push my changes from /live/website to /path/to/staging:
error: failed to push some refs to '/path/to/staging/' To prevent you from losing history, non-fast-forward updates were rejected. Merge the remote changes before pushing again. See the 'non-fast-forward'

Assumably, I face the same problem when I make the changes within dev1 or dev2 and try to push the changes to /path/to/staging.
I want to have a kind of master reset where I could just log onto /path/to/staging or /live/website and step-down to a stable version instead of figuring out which developer made the change and then doing a git reset. Can this be done? I basically want to have the ability to step down to a different version of a file, if I choose to do so ...

A: From your other questions I guess your situation looks like line 1 in the following diagram.
    current workflow:
                     /live/website    /path/to/staging     dev
1   now              1-2-3-F          1-2-3-F              1-2-3-F
2   reko             1-2-3(-F rm) ->  1-2-3                1-2-3-F
3   hack hack hack   1-2-3            1-2-3                1-2-3-F-5-6-7
4   dev push         1-2-3            1-2-3-F-5-6-7 <-     1-2-3-F-5-6-7
5   auto update      1-2-3-F-5-6-7 <- 1-2-3-F-5-6-7        1-2-3-F-5-6-7

6   revert workflow:
7   now              1-2-3-F          1-2-3-F              1-2-3-F
8   backout          1-2-3-F-~F   ->  1-2-3-F-~F           1-2-3-F
9   hack hack hack   1-2-3-F-~F       1-2-3-F-~F           1-2-3-F-5-6-7
10  dev try push     1-2-3-F-~F       1-2-3-F-~F           1-2-3-F-5-6-7
11  dev pull         1-2-3-F-~F       1-2-3-F-~F       ->  1-2-3-F-5-6-7-8
                                                                \-~F--/

12  dev push         1-2-3-F-~F       1-2-3-F-5-6-7-8  <-  1-2-3-F-5-6-7-8
                                             \-~F--/              \-~F--/

13  auto update      1-2-3-F-5-6-7-8  1-2-3-F-5-6-7-8  <-  1-2-3-F-5-6-7-8
                            \-~F--/          \-~F--/              \-~F--/

In your current workflow you have one defect top commit(F) which you remove(2) with rebase or reset, and then push this removed commit into the central repository. The problems of this workflow arise, when the developer which introduced F did other commits(4) on top of F(which is the default behavior in git), and then pushes this work again. Since the F commit was only stripped from the central repo the developer does not know that F should not be there, and so F reappears(4). Since you set up a hook on the central repo which automatically updates /live/website this means that after this push the fault also reappears on the webside. It's now even worse, because F now is not the HEAD anymore, so you can't easily remove F (you can rebase now, but the problem that F lives in a developer repo is still there).
In the revert workflow you tell git revert F(8), which causes git to create a commit which undoes commit F, here called ~F. Your working copy is now at a state which looks as if F never happened, and you can safely push ~F to the central repository. Now when the other developer has new work done and want to push(10), git will refuse this push, since the ~F commit in the central repository is not an ancestor of any commits in the developers repository, and git now forces the developer to pull ~F from the central repository(11). Then the developer must merge (or rebase) ~F into his branch(12), before the new changes can be pushed to the central repo again(13).
One word about the /live/website repo: Since you have a hook in /path/to/staging which automatically updates this repo on a push, it is not a good idea to do changes in /live/website. The main problem is that if you have local changed files there, or commits which cause merge conflicts, the push-hook in /path/to/staging can fail and leave /live/website in a very ugly state. In a scenario with automatic updates it is better to give the ownership of the directory directly to the updating machinery, which means all file changes there should only come from a git pull, but not from direct edits/commits in there. You can do corrections in a clone of /live/website, and then push these changes into /path/to/staging, which then distributes your changes back to /live/website (but do not push into /live/website[which cause git to screw up your index], nor do pull your clone changes in there, because then you may need to merge different development histories from your clone and /path/to/staging in /live/website, which is definitely not what you want).


text:
Q: Excel nested IF formula I want to set a formula that incorporates my school's attendance policy:

*

*3 tardies = 1 unexcused absence

*6 tardies = 2 unexcused absences

*and so on

The cell must reference not only the cell with the Tardy count, but also the attendance worksheet in the same workbook, and must add the two values.  For example, if the attendance page shows 1 unexcused absence and the tardy count shows 7 tardies, the formula needs to return 3.
This is what I've got:
 =SUM(Attendance!O9+(IF(J4>=3,1,IF(J4>=6,2,IF(J4>=9,3,IF(J4>=12,4,))))))

It works for 4 tardies and 1 unexcused absence, but continues to return 2 for 7 tardies and 1 unexcused absence.
What am I missing?

A: Much easier than using If/Then:
=Attendance!O9+(Int(J4/3))
The Int function returns the floor integer of the calculation, J4/3.  So, if J4 = 7, the result is 2. If J4=9, the result is 3, etc.

A: Your if statements are backwards you should check for bigger numbers first in this case otherwise the first if is always true. so 7 is falling true on >= 3 therefore you get 1 + 1 = 2
EDIT - a better way to do it would be to take your J4 divide it by 3 and return the value without the remainder
QUOTIENT(J4, 3)

A: The if part of your formula should be as follows
IF(J4<3,0,(IF(J4<6,1,(IF(J4<9,2,IF(J4<12,3,4))))))

Bear in mind that this formulae limits you to a maximum of 4 unexcused absences for tardies.
A better solution would be to use the QUOTIENT formula
= Attendance!O9 + QUOTIENT(J4,3)


text:
Q: Unable to get Single Object data from array in react-native I am new in react-native.I am unable to get "present" data from my API and I am getting an error "cannot read property present" so i just want to get my API response.Here is my api data and please check my code too.
{
 "message": "present in this month",
  "data": [
    {
        "present": 10
    }
   ],
  "status": "1"
 }

  async componentDidMount() {
 try {
            const DEMO_TOKEN = await AsyncStorage.getItem('isLoggedIn');
            if (DEMO_TOKEN != null) {
                console.log('Token', DEMO_TOKEN);
                fetch('http://104.197.28.169:3000/userPresentInThisMonth', {
                    method: 'GET',
                    headers: {
                        Authorization: 'Bearer ' + DEMO_TOKEN,
                    },
                })
                    .then(response => response.json())
                    .then(responseJson => {
                          alert(responseJson)
                        console.log(responseJson);
                        this.setState({
                            presentmonthdata : responseJson,
                        });
                    });
            }
        } catch (error) {
            alert(JSON.stringify(error));
            console.error(error);
        }
   }

This is my Text value.
   {this.state.presentmonthdata.data[0] &&
    <Text   style={{color: 'grey',fontSize: 30,   fontWeight: 'bold',  }}>
                            {this.state.presentmonthdata.data[0].present}
                  </Text>

}

A: Try this:
change:
{this.state.presentmonthdata.data[0] &&
    <Text style={{color: 'grey',fontSize: 30,   fontWeight: 'bold',  }}>
                            {this.state.presentmonthdata.data[0].present}
                  </Text>

to
<Text>
{this.state.presentmonthdata.data!= undefined ? this.state.presentmonthdata.data[0].present: null}
</Text>

Hope this helps!

A: the solution is
{this.state.presentmonthdata.data[0]}

A: Try the following:
{this.state.data.length > 0 ? this.state.data[0].present : 0;}
I'm guessing data is either a blank array or another data type...


text:
Q: How limit scan results in DynamoDB .NET i have a question. I want to limit the result of scan over dynamodb. I read in documentation that "Limit" parameter on ScanRequest do this works, but this code it seems not working.
I have 14 records, and this scan returns exactly 14 records, but should return 10. What i am doing wrong?
public IList<Contact> GetContacs(string firstContactToScan)
        {
            using (var context = new DynamoDBContext(new AmazonDynamoDBClient()))
            {
                var data = context.FromScan<Contact>(new ScanOperationConfig {Limit = 10}).ToList();
                return data;
            }
        }

Thanks

A: You can try following code:
AmazonDynamoDBClient client = new AmazonDynamoDBClient();

var request = new ScanRequest
{
    TableName = "yourTableName",
    Limit = 10
};

var response = client.Scan(request);
var result = response.ScanResult;

foreach (Dictionary<string, AttributeValue> item in response.ScanResult.Items)
{
  PrintItem(item);
}

There are other options also which you can specify in the request following is the
Reference Link.
Hope that helps


text:
Q: Losing data-icon when pulling html via ajax I have a php function generating grid data that looks similar to this:

Time

Meal Type

                Delete

02:00 AM

Lunch

However, when I call that same function with ajax to get the same data, it looks like this:

Time

Meal Type

                Delete

02:00 AM

Lunch

Notice I've lost all the extra classes attached to the anchor tag.
It makes this grid:

Look like this:

So my delete data-icon is gone.
I know I call 'refresh' on objects like buttons and select menus:
$('#_mealTime').val('');
$('#_mealTime').selectmenu("refresh");

Is there a similar call I need to make on anchor tags?

A: Yes there is a similar call used for page refresh, it will help you in your case:
$('#_gridData').trigger('create');

Here's an working example created from your code: http://jsfiddle.net/Gajotres/f2BYn/. I am missing your custom css so part of your styling is missing. Still trigger('create'); will style jQM elements.

A: Check your CSS urls, when you use ajax on a different path than where the initial php script executes to render the page your path's are probably getting thrown off.  Try to use root relative paths if possible.
/images/delete_button
instead of
images/delete_button


text:
Q: Discord.py отслеживание роли по нажатию на реакцию Бот должен чекать роль пользователя по реакции, но он почему-то триггерит только свои сообщения и работает нормально, но когда живой человек нажимает на реакцию, он выдаёт такую ошибку:
Ignoring exception in on_raw_reaction_add
Traceback (most recent call last):
  File "C:\Users\User\PycharmProjects\pybot\venv\lib\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\User\PycharmProjects\pybot\main.py", line 38, in on_raw_reaction_add
    add_role = discord.utils.get(member.guild.roles, id=906203003479015484)
AttributeError: 'NoneType' object has no attribute 'guild'

Как это можно исправить? Код:
@bot.event
async def on_raw_reaction_add(payload):
    message_id = payload.message_id
    channel_id = payload.channel_id
    channel = bot.get_channel(channel_id)
    message = await channel.fetch_message(message_id)
    user_id = payload.user_id
    member = channel.guild.get_member(user_id)
    add_role = discord.utils.get(member.guild.roles, id=906203003479015484)
    for role in member.roles:
        if role.name != 'admin':
            await member.add_roles(add_role)

A: member = discord.utils.get(channel.guild.members, id=user_id)
add_role = discord.utils.get(member.guild.roles, id=906203003479015484)
for role in member.roles:
    if role.name != 'admin':
        await member.add_roles(add_role)


text:
Q: redirect non-www to www with correct URL params I need to redirect non-www to www, with correct URL params. A lot of url's (non-www) already in the google index. I need a config that the params in the url is redirect correct. An example:
nice2stay.com/houses/1

redirect to:
www.nice2stay.com/nl/holidayhouses/nameofthehouse

Ideas?
I just tried the code below on my dev laptop.
constraints(:host => "localhost") do
    root :to => redirect("http://www.localhost:3000")
    match '/*path', :to => redirect {|params| "http://www.localhost/#{params[:path]}"}
  end
This work when the requested url is the root domain, but not when the request url is localhost:/houses Is the path config not correct?

A: Edit : I'm sorry I havn't seen the rails tag... The following is still valid : you can do it with your front server (apache or nginx). I guess you can also do the 301 redirect inside the application controller.

It depends of your server.
If you are on apache, ensure that mod_rewrite is installed (this is the case in most of shared hosting), create a .htaccess file at the root of your hosting and type the following rewrite rules in it:
<IfModule mod_rewrite.c>
  Options +FollowSymlinks
  RewriteEngine On
  RewriteCond %{HTTPS} !=on
  RewriteCond %{HTTP_HOST} !^www\..+$ [NC]
  RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
</IfModule>

This will force the www. prefix and does a 301 redirect from the non-www to the www urls, which is the best solution for google.


text:
Q: How do I access Qt qrc folder directly Qt 5.10.1 I am developing an application in qml.
I have a folder qrc folder structure like ,
qrc:

Features

 - Media
 - Audio
 - TV

graphics

 - media_assets
 - audio_assets
 - tv_assets

Features contains respective qml files and graphics contains the graphics.
My issue is, after loading a qml file from the features it set as the current directly then, after that when I try to access the graphics folder I need to go back ../.../ and access the folder. It is making problems when folder structure is changed.
How can I access the graphics directly from qrc like graphics/media_assets/ from any qml files
In the older versions I could access the graphics directly by using "file://sample.png", in qt 5.10.1 it is deprecated.

A: Use:
qrc:///

From url QML Basic Type documentation:

When referring to files stored with the Qt Resource System from within
  QML, you should use "qrc:///" instead of ":/" as QML requires URL
  paths. Relative URLs resolved from within that file will use the same
  protocol.


text:
Q: how to fix my sqlite? database disk image is malformed When I did 'vacuum ;', just found message in below.
" database disk image is malformed."
So, I did like those.
C>sqlite [malformed.db]
sqlite3>.mode insert
sqlite3>.output a.sql
sqlite3>.dump
and continues...
C>sqlite3 new.db
sqlite3>.read a.sql
finally I found the new.db which file size is 0 byte.
any idea?

A: For some reason, this very process that you described, when the database is malformed adds one last line to sql file, which says "rollback" (-- due to errors, it elaborates).
Reminds some anecodes with genies, doesn't it?
While it is intented to prevent disasters when importing data on existing bases, it is a disaster if all you are trying to do is reconstruct your database from scratch.
So, remove this line, replace it with "end transaction;", re-run and you are hopefully ok.


text:
Q: Make a button show/hidden with Place Geometry How to make a widget with place geometry showing/hidden?
I know about grid_forget or grid_remove or pack_forget
But I can't seem to find how to show/hide a widget with place geometry.
Code Example:
import tkinter as tk

def showBtn(e, btn):
    #I want to make btn1 showed

root = tk.Tk()

btn1 = tk.Button(root, text="Close")
btn1.place(relx=0.855, rely=0.1, anchor="center")
#I want to make this btn1 hidden when program started

btn2 = tk.Button(root, text="Show")
btn2.place(relx=0.6, rely=0.1, anchor="center")
btn2.bind("Button-1", lambda event, arg=btn1: showBtn(event, arg))

root.mainloop()

Sorry if this is duplicated, but I can't find any source for this problem. But please do tag it here if you do find one. :)
Thanks!!
DUPLICATE WITH:
Python tkinter: hiding widget after showing it with place() geometry manager (Answered) [For Hiding place, with place_forget]
I still need to show the button.
EDIT: To show after using place_forget, you can use btn.place() function :)


text:
Q: How to select needed records in joining table using LINQ with tables which have many to many relationship? I have many to many relationship between entities user and group, I also have joining table GroupParticipants.
public class User
{
    public string Id {get; set;}

    public ICollection<GroupParticipant> Group { get; set;}
}

public class Group
{
    public int Id { get; set; }
    public ICollection<GroupParticipant> Participants { get; set; }

}

public class GroupParticipant
{
    public int GroupId { get; set; }
    public string ParticipantId { get; set; }

    public User Participant { get; set; }
    public Group Group { get; set; }
}

I need to select groups which user specified user did not join. I want to do something like:
string userId = 5;
var groupsAvailableToJoin = await _context.Groups
    .Where(group => group.Participants.Id != userId);

Thanks!

A: A query like:
_context.Groups.Where(g =>
    !_context.GroupParticipants.Any(gp => gp.UserId == userId && gp.GroupId == g.I'd
);

Should translate to:
  SELECT * FROM Groups g
  WHERE NOT EXISTS(SELECT null FROM groupParticipants gp WHERE gp.UserId = 5 AND gp.GroupId = g.Id)

Which should be a reasonably performant way of getting you what you're looking for.. I'm sure that the GroupParticipants columns are indexed..

There are various ways to write this - if you find a two step approach easier to understand, it's effectively the same as:
var joined = _context.GroupParticipants.Where(gp => gp.UserId == 5).Select(gp => gp.GroupId).ToList();
var notJoined = _context.Groups.Where(g => !joined.Contains(g.Id));

This one translates as a NOT IN (list,of,groups,they,are,in) for a similar effect


text:
Q: Which test statistic is insensitive to the degrees of freedom? I'm beginner in statistics. I would like to know which test statistic is insensitive to the degrees of freedom among Z, T and F statistic. Are all of these sensitive or insensitive? Thanks !

A: First, there might be a misconception to correct. Degrees of freedom are not an external quantity of the statistics. It pertains to the test itself. For example whether you consider when doing a t-test that variances in different groups are the same or not, you won't have the same test and won't have the same numbers of degree of freedom even if it's still a t statistic because you have a different number of quantities to be estimated.
One have to remember how much data we have burned off to estimate some parameters. What remains is the number of degrees of freedom. The idea is that the more you estimate quantities, the less you have degrees of freedom, the more your test must punish this. A statistic with $N$ degrees of freedom would then be more extreme than the same value with $N-1$ degrees of freedom. considered less extreme In your question :

is insensitive to the degrees of freedom

could then be replaced by

do not need to be punished because of estimated parameters.

Sometimes you don't need to punish for these estimated quantities, this is the case for the z test.
Degrees of freedom are a confusing concept, for a deeper understanding I would suggest to have a look on this question How to understand degrees of freedom?


text:
Q: Git multiply accounts issues Multiple Github accounts make me crazy. So I have two my own github accounts.
I found really useful tutorial to add multiply account on my Mac. So first off all I already have working copy on my Mac and seems now it work when I did all steps from that video tutorial.
But when I try to push my changes via Source Tree I see this:
Pushing to https://github.com/SuperApps/SuperApp.git
remote: Repository not found.
fatal: repository 'https://github.com/SuperApps/SuperApp.git/' not found

thought right after this message I open terminal and make:
git push origin new_branch

And I see this:
Counting objects: 16, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (16/16), done.
Writing objects: 100% (16/16), 40.45 KiB | 0 bytes/s, done.
Total 16 (delta 12), reused 0 (delta 0)
To https://github.com/SuperApps/SuperApp.git
   8f89744..0b89b79  new_branch -> new_branch

which means that https://github.com/SuperApps/SuperApp.git exists and I can push to it but not via Source Tree.
Alos when I tried in terminal this:
ssh -T git@github.com
The authenticity of host 'github.com (IP ADDRESS HERE)' can't be established.
RSA key fingerprint is SHA256:kThbg6kBlpJW4l7E1IGO5lpRomTxdCARLviKw7GHSY8.
Are you sure you want to continue connecting (yes/no)? yes

And when I written yes:
Hi MySecondAccountName! You've successfully authenticated, but GitHub does not provide shell access.
But when I am checking commits on github the author is MyFirstAccountName.
I've checked also SourceTree settings and there is MySecondAccountName is default github account. Seems should works but it does not.
To summarise:

*

*I have problem to push changes via SourceTree but not via terminal.

*Does actually ssh -T git@github.com means that I should see current git authorised user. If yes why I see commits from my another git user.

So here few problems.


text:
Q: Al ulitizar Listas en Java ¿cómo puedo obtener el índice al buscar un objeto? La clase Compañia guarda una lista con instancias de la clase Cliente el cual tiene un rut y otros atributos. Al utilizar el método anyMatch() devuelve true o false si lo encuentra dentro de la lista. Pero ademas necesito saber cuál es su índice dentro de la lista.
import java.util.ArrayList;
import java.util.List;

public class Compañia {
    String nombre;
    List<Cliente> clienteCelular = new ArrayList<>();

public boolean buscarCliente(String r){
    return clienteCelular.stream().anyMatch(cli -> cli.rut.equals(r))
}

esta es la Clase Cliente
public class Cliente {
    String rut, nombre,sexo;
    Celular celular;
    int edad;
    boolean plan;

Agradezco cualquier aporte

A: Se puede hacer con streams pero es peligroso:
public int buscarCliente(String r){
        int index  = IntStream.range(0, clienteCelular.size())
            .filter(userInd-> clienteCelular.get(userInd).nombre.equals(r))
            .findFirst().orElse(-1);
        return index;
}

El principal problema es el manejo de nulos en caso de que no encuentre el resultado, el null pointer exception no se atrapará y deberás de regresar el valor bandera, en este caso -1 en caso de error encerrando el valor en un trycatch y silenciando la excepción, lo cual no es muy elegante.
public int buscarCliente(String r){
    int index  = -1;
    try{
        index=IntStream.range(0, clienteCelular.size())
            .filter(userInd-> clienteCelular.get(userInd).nombre.equals(r))
            .findFirst().getAsInt();
    }catch (NoSuchElementException ignored){
    }
    return index;
}

Es más seguro hacerlo a la antiguita ( y posiblemente sea más legible ):
public int buscarCliente(String r){
    int index = -1;
    int bound = clienteCelular.size();
    for (int userInd = 0; userInd < bound; userInd++) {
        if (clienteCelular.get(userInd).nombre.equals(r)) {
            index = userInd;
            break;
        }
    }
    return index;
}

La explicación es sencilla, debes crear los índices y recorrer el vector por índices filtrando por el campo que quieres obtener, si no existiera entonces debes regresar una bandera como por ejemplo -1 para indicar que no se halló.

A: Puedes usar List.indexOf() junto con Stream.findAny():
public int buscarCliente(String r)
{
    Cliente clienteABuscar = clienteCelular.stream()
            .filter(cliente -> cliente.getRut().equals(r))
            .findAny()      // Devuelve Optional<Cliente>
            .orElse(null);  // TODO: decidir qué hacer si no existe

    return clienteCelular.indexOf(clienteABuscar);
}

Recuerda que findAny() devuelve un Optional, lo que puedes usar para lanzar una excepción, o crear un nuevo cliente en caso de que no lo encuentres en la lista.
También puedes usar findFirst() para buscar el primer cliente.

A: Bueno hice un código medio en el aire, sin embargo creo que la estructura se asemeja un toque a lo que pedis, te enumero un par de cambios que le hice.
1) el nombre de la clase sin ñ, desde el vamos, sólo para que lo tengas en cuenta nomas.
2) El método que vos tenías declarado como boolean, lo cambié  a int, porqué? porque el boolean en este caso lo podemos tomar como una condición adentro de un if, que si se da esa condición nos devuelva el si hubo un match en este caso, nunca usé ése Stream pero efectivamente devuelve un boolean, si da true entra en la condición y el index que tenía valor 0 ahora va a tener un valor asignado por el método indexOf(String str); el cual encuentra la posición del primer objeto que cumpla con las características que nombrás.
3) EL método en sí sólo te devuelve la posición del objeto en cuestión. Sin embargo evalúa la condición que pedís.
4) El Stream que hiciste no lo probé debe andar muy bien, sin embargo para tener un control más claro sobre lo que estás codificando quizás podrías hacer lo mismo a manopla de una forma menos fashion que con stream pero sería mérito tuyo completamente.
5) Acá te dejo el código que hice, para aplicar métodos distintos a los comunes, usé iterator para que veas unas formas distintas de recorrer la List<>, otra cosa, copiá el código que te estoy pasando y fijate su te imprime la posición en la cual está declarado el String.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Compania {

List<Cliente> clienteCelular = new ArrayList<>();
int index;
Cliente cliente;

public int buscarCliente(String r) {

    Cliente c1 = new Cliente();
    c1.nombre = "ejemplo1";
    Cliente c2 = new Cliente();
    c2.nombre = "ejemplo2";
    Cliente c3 = new Cliente();
    c3.nombre = "ejemplo3";
    clienteCelular = Arrays.asList(c1, c2, c3);

    /*
     * Recorremos cada elemento de la List<>
     *
     */
    for (Cliente item : clienteCelular) {

        /*
         * Mientras la List<> tenga algún objeto en su contenido que realice una
         * condición adentro del bloque
         */
        while (clienteCelular.iterator().hasNext()) {

            /*
             * Si ése objeto es igual en su contenido a 'r' entonces le asignamos el índice
             * a la variable temporal
             */
            if (clienteCelular.stream().anyMatch(cli -> cli.nombre.equals(r))) {
                /*
                 * Acá es donde al objeto que tiene el String igual al que buscas se le asigna a
                 * la variable int temporal que vamos a usar en el resultado
                 */
                index = clienteCelular.indexOf(item);

                /*
                 * Estos String no son necesarios sólo los pongo para que veas que pasa en cada
                 * bloque
                 */
                System.out.println("El " + item.nombre + " se encuentra en la posición: " + index + " de la Lista");
                break;
            }
        }

    }
    /* Este es el resultado del índice buscado */
    return index;
}

public static void main(String[] args) {
    Compania c = new Compania();
    System.out.println("El objeto con el String seleccionado de parámetro se encuentra en la posición número: "
            + c.buscarCliente("ejemplo3"));
}

}

Como ejemplo agregué tres elementos a la List<> harcodeados, como mala práctica no declaré los atributos como private, sin embargo eso una vez que el código sale andando se hace sobre la marcha. ojalá que te sirva, lo probé en mi entorno funciona bien, sin embargo tiene baches pero para tu objetivo que es encontrar un índice de un objeto que posea un String iría bien, el booleano sigue estando, sólo que embebido dentro del método que al finalizar devuelve un int.

Mucho mas reducido y eficiente sin código extra y más limpio te quedaría así:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Compania {

List<Cliente> clienteCelular = new ArrayList<>();
int index;
Cliente cliente;

public int buscarCliente(String r) {

    Cliente c1 = new Cliente();
    c1.nombre = "ejemplo1";
    Cliente c2 = new Cliente();
    c2.nombre = "ejemplo2";
    Cliente c3 = new Cliente();
    c3.nombre = "ejemplo3";
    clienteCelular = Arrays.asList(c1, c2, c3);

        for (Cliente item : clienteCelular) {

            while (clienteCelular.iterator().hasNext()) {

                if (clienteCelular.stream().anyMatch(cli -> cli.nombre.equals(r))) {
                    index = clienteCelular.indexOf(item);
                    break;
                }
            }
        }

    return index;
}

public static void main(String[] args) {
    Compania c = new Compania();
    System.out.println("El objeto con el String seleccionado de parámetro se encuentra en la posición número: "+ c.buscarCliente("ejemplo3"));
}

}

Usé otra forma diferente de recorrer la List<>, con el método iterator(), sólo para proponer una idea diferente al for clásico.
Axel.

A: Muy fácil bro, utiliza la función IndexOf del ArrayList
    public static int getMasBarato() {

    int indice = 0;

    float aux = lista_vehiculo.get(0).getPrecio();

    for(Vehiculo vehiculo:lista_vehiculo){
        if(vehiculo.getPrecio() < aux){
            indice = lista_vehiculo.indexOf(vehiculo);
        }
    }

    return indice;
}


text:
Q: put words to specific position in line I have a file and it contains data as:
905222105114 BAHADIR ADANA 2122121

905222105114 ISTANBUL ANKARA 213123

0012312554645 ANTALYA BAHADIR 2312312

I want to put these datas in another file.
N.1 value must start in 0 position of line.
N.2 value must start in 20 position of line.
N.3 value must start in 40 position of line.
N.4 value must start in 60 position of line.
By this way, I'll get a file that each value starts at current position of line.

A: awk '{printf "%-20s%-20s%-20s%-20s\n",$1,$2,$3,$4}' file.dat

should do the trick...


text:
Q: Job should fail in SSIS, if user try to import comma separated file in pipe delimited flat file configuration i have created the SSIS package to load the pipe delimited flat file data into the Sql server destination table.To Achieve this i have used Data flow task, flat file source and ole db destination. I have configured the flat file connection manager with pipe delimiter as  a column delimiter and row delimiter as a "CRLF". in this case, for me package is successfully imported pipe delimited flat file data into the SQL server destination table. Now question is, Do we have any option to fail the Job if user try to import comma separated file?. while i am trying to import comma separated file, job is not getting failed and no records have moved to destination table.

A: you can validate the file with a simple script task before running the data flow, suppose you expect 5 pipes on your rows then:
    Dim x As New System.IO.StreamReader("your file")
    Dim pipes As String()

    While x.Peek() <> -1
        pipes = x.ReadLine.ToString().Split("|")
        If pipes.Length <> 6 Then
            Dts.TaskResult = ScriptResults.Failure
            Return
        End If
    End While

    Dts.TaskResult = ScriptResults.Success


text:
Q: Mobile App Authentication Without Login Screen I'm designing a mobile app in which the client app that the user downloads simply opens their browser and opens the web app I designed.  The web app should never be accessible except through the downloaded app.  Before I put the site out there, I want to implement the authentication so people can't get to it until I release it.
The web app is Azure/C#/MVC5/Javascript/Sql Server.  The launch program will differ by platform (Android/iPhone/Windows8Phone).
What I would like to do, if possible, is to implement authentication without requiring a password in order to lessen the burden on the user.  I'm not very concerned from a security standpoint.  The main purpose of the authentication is just to verify that the user did in fact buy the app and that they're not just browsing to the site.
I had assumed this part would be easy, but I've spent many hours searching for a solution and I'm much more confused than when I started.  From what I've read, it sounds like I may need a 'secret' or a 'nonce'.  I have no idea how to implement such things.  Basically, I'm looking for two things here- confirmation that I'm marching down the right path from someone who knows this area (or a course correction if not), and perhaps a link to a site that contains actual implementation details for the appropriate solution.
Thanks in advance!

A: You need to have a secret on your client that the web backend can verify.
Passing the Secret for verification
You may just pass the secret to the web backend using REST like: http://web.app.com/something?secret=XXXXXX
If the secret checks out, you may redirect the client to the appropriate page.
Creating a Secret
It can just be any string you want, very much like a password you create.
More secure secret
You can generate a secret to pass to your web backend that is different each time by doing this:
secret = <random string> + SHA-1(<random string> + <fixed string>)
Javascript Library for SHA-1
Note: <fixed string> is up to you to define, this is the "real" secret that only people that have access to your code will know. (Of course they can disassemble your program and/or watch its running memory space to find out, but that's beyond most)
Testing the secret
On your web backend, split the given secret into <random string> and the SHA-1 parts. Then do SHA-1(<random string> + <fixed string>) (the fixed string is the same on both your client and backend). If the SHA-1 result is the same, it's verified!
Preventing Sharing
A user may still share the secret with others, to prevent that, we can introduce a time stamp in the <random string> giving <random string> + <time stamp>. With that, we can limit the validity of the secret to a particular time. In this case, 30 secs to a few minutes might do to accommodate Internet lag and inaccurate clock on the client.


text:
Q: How do i detect a keyword but fetch the entire link? So right now i have this:
messages = r.text

if 'metalabs' in messages:
    print('Success!')
else:
    print('rip')

so if, for example the link was https://test.metalabs.io, how would i be able to set that link to a variable if the keyword was only metalabs?

A: You could do this with a dictionary:
urls = {'metalabs':'https://test.metalabs.io'}

similar = input('Keyword: ')
print(urls.get(similar, 'rip'))


text:
Q: Java ssl/tls client-server application throwing error on sending data trough socket First of all thank you for your time. So Im developing a game server I want to use ssl/tls for communication between client socket and server socket. Ive generated self signed certificate using keytool and this tutorial https://docs.oracle.com/cd/E19798-01/821-1841/gjrgy/index.html so I have keystore file cer file and certificate is imported in keystore.
Ive used this tutorial to try if its working https://www.owasp.org/index.php/Using_the_Java_Secure_Socket_Extensions and Im running server on localhost 127.0.0.1 on port 6066 client test is launched on same machine in different terminal window the problem is that when Im trying to write data to stream from client and reading it on server server window will throw this error log.
javax.net.ssl.SSLHandshakeException: Received fatal alert: certificate_unknown
    at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
    at sun.security.ssl.Alerts.getSSLException(Alerts.java:154)
    at sun.security.ssl.SSLSocketImpl.recvAlert(SSLSocketImpl.java:2023)
    at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1125)
    at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1375)
    at sun.security.ssl.SSLSocketImpl.readDataRecord(SSLSocketImpl.java:928)
    at sun.security.ssl.AppInputStream.read(AppInputStream.java:105)
    at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:284)
    at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:326)
    at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:178)
    at java.io.InputStreamReader.read(InputStreamReader.java:184)
    at java.io.BufferedReader.fill(BufferedReader.java:161)
    at java.io.BufferedReader.readLine(BufferedReader.java:324)
    at java.io.BufferedReader.readLine(BufferedReader.java:389)
    at Server.models.ClientConnection.run(ClientConnection.java:34)

Im new to this topic so I will be glad for pointing me in right direction and for every help you can provide.


text:
Q: Permission denied at hdfs I am new to hadoop distributed file system, I have done complete installation of hadoop single node on my machine.but after that when i am going to upload data to hdfs it give an error message Permission Denied.
Message from terminal with command:
hduser@ubuntu:/usr/local/hadoop$ hadoop fs -put /usr/local/input-data/ /input
put: /usr/local/input-data (Permission denied)

hduser@ubuntu:/usr/local/hadoop$

After using sudo and adding hduser to sudouser:
hduser@ubuntu:/usr/local/hadoop$ sudo bin/hadoop fs -put /usr/local/input-data/ /inwe
put: org.apache.hadoop.security.AccessControlException: Permission denied: user=root, access=WRITE, inode="":hduser:supergroup:rwxr-xr-x

hduser@ubuntu:/usr/local/hadoop$

A: I solved this problem temporary by disabling the dfs permission.By adding below property code
to conf/hdfs-site.xml
<property>
  <name>dfs.permissions</name>
  <value>false</value>
</property>

A: I've solved this problem by using following steps
su hdfs
hadoop fs -put /usr/local/input-data/ /input
exit

A: I had similar situation and here is my approach which is somewhat different:
 HADOOP_USER_NAME=hdfs hdfs dfs -put /root/MyHadoop/file1.txt /

What you actually do is you read local file in accordance to your local permissions but when placing file on HDFS you are authenticated like user hdfs. You can do this with other ID (beware of real auth schemes configuration but this is usually not a case).
Advantages:

*

*Permissions are kept on HDFS.

*You don't need sudo.

*You don't need actually appropriate local user 'hdfs' at all.

*You don't need to copy anything or change permissions because of previous points.

A: Start a shell as hduser (from root) and run your command
sudo -u hduser bash
hadoop fs -put /usr/local/input-data/ /input

[update]
Also note that the hdfs user is the super user and has all r/w privileges.

A: For Hadoop 3.x, if you try to create a file on HDFS when unauthenticated (e.g. user=dr.who) you will get this error.
It is not recommended for systems that need to be secure, however if you'd like to disable file permissions entirely in Hadoop 3 the hdfs-site.xml setting has changed to:
<property>
  <name>dfs.permissions.enabled</name>
  <value>false</value>
</property>

https://hadoop.apache.org/docs/stable/hadoop-project-dist/hadoop-hdfs/hdfs-default.xml

A: You are experiencing two separate problems here:

hduser@ubuntu:/usr/local/hadoop$ hadoop fs -put /usr/local/input-data/ /input put: /usr/local/input-data (Permission denied)

Here, the user hduser does not have access to the local directory /usr/local/input-data. That is, your local permissions are too restrictive. You should change it.

hduser@ubuntu:/usr/local/hadoop$ sudo bin/hadoop fs -put /usr/local/input-data/ /inwe put: org.apache.hadoop.security.AccessControlException: Permission denied: user=root, access=WRITE, inode="":hduser:supergroup:rwxr-xr-x

Here, the user root (since you are using sudo) does not have access to the HDFS directory /input. As you can see: hduser:supergroup:rwxr-xr-x says only hduser has write access. Hadoop doesn't really respect root as a special user.

To fix this, I suggest you change the permissions on the local data:
sudo chmod -R og+rx /usr/local/input-data/

Then, try the put command again as hduser.


text:
Q: Java Thread Implementation Below is my sample implementation code, where code running without proper threading takes less time than code running with proper threading implementation, Kindly advice what mistake I am making or issues in my code
   @Override
   public Integer timeTakenWithoutThreading() {
       System.out.println("StartTime" + new Date());
       Date startDate = new Date();
       int value = 1000000;
       int value2 = 2000000;
       for (int i = 0; i <= value; i++) {
           System.out.println("Value 1" + i);
       }
       for (int i = 0; i <= value2; i++) {
           System.out.println("Value 2" + i);
       }
       System.out.println("StartTime" + startDate);
       System.out.println("endTime" + new Date());
       return null;
   }

   @Override
   public String timeTakenWithThreading() {
       Date start = new Date();
       Date firstThread = new Date();
       threadPoolExecutorService.execute(new Runnable() {
           final int value = 1000000;

           @Override
           public void run() {
               for (int i = 0; i <= value; i++) {
                   System.out.println("Thread 1 Value" + i);
               }

           }
       });

       threadPoolExecutorService.execute(new Runnable() {
           final int value2 = 2000000;

           @Override
           public void run() {
               for (int i = 0; i <= value2; i++) {
                   System.out.println("Thread 2 Value" + i);
               }
               System.out.println("Start Date" + start);
               System.out.println("End Date" + new Date());
           }
       });

       return "You Will Get Response So Soon But Thread Will Execute At the Background";
   }
}```

A: You count the start time even when the parallel execution is not started. So the time measurement is actually wrong. You should initialize the start time inside the Runnable.
for example:

       threadPoolExecutorService.execute(new Runnable() {

           final int value = 1000000;

           @Override
           public void run() {
               // time started.
               Date firstThread = new Date();
               System.out.println("First thread started at" + firstThread);
               for (int i = 0; i <= value; i++) {
                   System.out.println("Thread 1 Value" + i);
               }
               // time ended.
               System.out.println("First thread ended at" + new Date());
           }
       });

Also apply this for the second thread. You'll see that both thread many run in parallel. And in combined it would take less time than the non-threaded one.


text:
Q: Tomcat 8: SSL session ID not available I'm having a problem trying to migrate from Tomcat7 to Tomcat8. Things seems to work fine, but when I access my application it logs this Exception:
09-Nov-2016 13:23:09.192 WARNING [https-openssl-nio-9443-exec-3] org.apache.coyote.AbstractProcessor.populateSslRequestAttributes Exception getting SSL attributes
 java.lang.IllegalStateException: SSL session ID not available
    at org.apache.tomcat.util.net.openssl.OpenSSLEngine$OpenSSLSession.getId(OpenSSLEngine.java:1048)
    at org.apache.tomcat.util.net.jsse.JSSESupport.getSessionId(JSSESupport.java:156)
    at org.apache.coyote.AbstractProcessor.populateSslRequestAttributes(AbstractProcessor.java:619)
    at org.apache.coyote.AbstractProcessor.action(AbstractProcessor.java:359)
    at org.apache.coyote.Request.action(Request.java:392)
    at org.apache.catalina.connector.Request.getAttribute(Request.java:900)
    at org.apache.catalina.connector.RequestFacade.getAttribute(RequestFacade.java:282)
    at org.apache.cxf.transport.http.AbstractHTTPDestination.propogateSecureSession(AbstractHTTPDestination.java:411)
    at org.apache.cxf.transport.http.AbstractHTTPDestination.setupMessage(AbstractHTTPDestination.java:395)
    at org.apache.cxf.transport.http.AbstractHTTPDestination.invoke(AbstractHTTPDestination.java:238)
    at org.apache.cxf.transport.servlet.ServletController.invokeDestination(ServletController.java:234)
    at org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:208)
    at org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:160)
    at org.apache.cxf.transport.servlet.CXFNonSpringServlet.invoke(CXFNonSpringServlet.java:180)
    at org.apache.cxf.transport.servlet.AbstractHTTPServlet.handleRequest(AbstractHTTPServlet.java:298)
    at org.apache.cxf.transport.servlet.AbstractHTTPServlet.doPost(AbstractHTTPServlet.java:217)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
    at org.apache.cxf.transport.servlet.AbstractHTTPServlet.service(AbstractHTTPServlet.java:273)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:108)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:589)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:784)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:802)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1410)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)

My connector is defined this way:
<Connector port="9443"  URIEncoding="utf-8" protocol="HTTP/1.1"
    scheme="https"  secure="true" SSLEnabled="true"
    maxPostSize="-1"
    useAprConnector ="false"
    sslProtocol="TLSv1.2" clientAuth="want"
    disableSessionTickets="true"
    keystoreFile="${catalina.home}/conf/keystore.jks"
    keystorePass="..."
    truststoreFile="${catalina.home}/conf/truststore.jks"
    truststorePass="..."
/>

Things works fine on Tomcat7, and also in tomcat8 the secure conection is fine.

A: It looks like you are hitting Bug 59811 - TLS Session ID not available if session tickets are used.
I suspect that this is because in switching to Tomcat 8.5.x OpenSSL is used for TLS if it is available.
You have a couple of options:

*

*Add an explicit SSLHostConfig element and include disableSessionTickets="true" to disable session tickets

*Set sslImplementationName="org.apache.tomcat.util.net.jsse.JSSEImplementation" on the Connector to use JSSE for TLS rather than OpenSSL

The second option is closest to what you had with Tomcat 7.


text:
Q: Replacing a div that is called by jQuery onclick I have a list object and each contains an upvote div that is called onclick by my jQuery (I essentially flip the vote button in each div and asynchronously change the vote for that div via Ajax).
All object divs are contained within row.replace which I use to sort the objects asynchronously. The thing is that once I click on the sorter and sort the content of the .row.replace div, the upvote divs in the sorted list of objects stop getting called onclick ie. I can upvote and remove my upvote before sorting with jQuery+ajax, once the sort is applied and the contents of the div are replaced, my upvote button stops working.
Here is the jQuery:
$(document).ready(function () {
  $('.sorter').click(function () {
    $('.row.replace').empty();
    $('.row.replace').append("

");
    var sort = $(this).attr("name");
    $.ajax({
      type: "POST",
      url: "/filter_home/" + "Lunch" + "/" + "TrendingNow" + "/",
      data: {
        'name': 'me',
        'csrfmiddlewaretoken': '{{csrf_token}}'
      },
      dataType: "json",
      success: function (json) {
        //loop through json object
        //alert("yoo");
        $('.row.replace').empty();
        for (var i = 0; i < json.length; i++) {
          $('.row.replace').append("

 " + json[i].fields.name + "

 posted by " + json[i].fields.creator.username + "

 {% if 0 %}
 <button type='button' class='btn btn-grove-one upvote' id='upvote' name='" + json[i].pk + "'>Upvoted " + json[i].fields.other_votes + "</button>

 <button type='button' class='btn btn-grove-two upvote' id='upvote' name='" + json[i].pk + "'>Upvote " + json[i].fields.other_votes + " </button>
 {% else %}
 <button type='button' class='btn btn-grove-two upvote' id='upvote' name='" + json[i].pk + "'>Upvote " + json[i].fields.other_votes + " </button>

 <button type='button' class='btn btn-grove-one upvote' id='upvote' name='" + json[i].pk + "'>Upvoted " + json[i].fields.other_votes + "</button>
 {% endif %}

 <button type='button' class='btn btn-grove-two'>" + json[i].fields.comment_count + "</button>

");
        }
        //json[i].fields.name
      },
      error: function (xhr, errmsg, err) {
        alert("oops, something went wrong! Please try again.");
      }
    });
    return false;
  });
  $('.upvote').click(function () {
    var x = $(this).attr("name");
    $.ajax({
      type: "POST",
      url: "/upvote/" + x + "/",
      data: {
        'name': 'me',
        'csrfmiddlewaretoken': '{{csrf_token}}'
      },
      dataType: "json",
      success: function (json) {
        var y = "vote-count" + x;;
        $('i[class= "' + y + '"]').text(json.vote_count);
        //flip button
        $('.flip' + x).find('.card').toggleClass('flipped');
      },
      error: function (xhr, errmsg, err) {
        alert("oops, something went wrong! Please try again.");
      }
    });
    return false;
  });
});

A: The click event handler only binds to elements that exist in the DOM when the function is actually called. You need to use a delegated on() event listener to bind to future elements as well. So for your code:
$('.upvote').click(function(){

change to:
$("body").on("click", '.upvote', function(event){

Should catch future click events. I'm using "body" as the outer selector because I don't know what your HTML looks like, but it's best to "outer-bind" to the nearest ancestor to the '.upvoteelements (so if they are all contained in aul` with id "vote-list" bind to that instead of "body").


text:
Q: How to get multiple rows of JSON data and put it into some sort of Array? I tried to retrieve multiple rows of JSON data and display it but im not able to retrieve all the rows,im only getting the top(first) row of the database table.And im confused about how can i put the retrieved JSON data into some sort of array and access the individual rows?
I have provided the code relevant to the problem.
Yes i have done enough research before posting this question.I actually found one question which was some what similar to mine but nobody has answered it so i'm making this post.
Thank You
Below is the code from my Freebies.java class where i'm trying to retrieve JSONdata by calling getAllFreebies function from UserFunctions.java class
UserFunctions uf = new UserFunctions();
JSONObject json = uf.getAllFreebies();
System.out.println(json);

Below is the code of the function getAllFreebies() in the class UserFunctions.java
public JSONObject getAllFreebies(){
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("tag", getAllFreebies_tag));
    JSONObject json = jsonParser.getJSONFromUrl(getAllFreebiesURL,params);
    return json;
}

Below is the code from index.php where im calling getFreebies() function from DB_Function.php file
else if($tag = 'getAllFreebies'){
                    $getAllFreebies = $db->getFreebies($username,$catagory,$subcatagory,$title,$condition,$description,$address,$city,$state,$country,$zipcode,$posted_on);
                    if($getAllFreebies)
                    {
            $response["success"] = 1;
            $response["getAllFreebies"]["username"] = $getAllFreebies["username"];
            $response["getAllFreebies"]["catagory"] = $getAllFreebies["catagory"];
            $response["getAllFreebies"]["subcatagory"] = $getAllFreebies["subcatagory"];
            $response["getAllFreebies"]["title"] = $getAllFreebies["title"];
            $response["getAllFreebies"]["item_condition"] = $getAllFreebies["item_condition"];
            $response["getAllFreebies"]["description"] = $getAllFreebies["description"];
            $response["getAllFreebies"]["address"] = $getAllFreebies["address"];
            $response["getAllFreebies"]["city"] = $getAllFreebies["city"];
            $response["getAllFreebies"]["state"] = $getAllFreebies["state"];
            $response["getAllFreebies"]["country"] = $getAllFreebies["country"];
            $response["getAllFreebies"]["zipcode"] = $getAllFreebies["zipcode"];
            $response["getAllFreebies"]["posted_on"] = $getAllFreebies["posted_on"];
            echo json_encode($response);
                        }else {
                            $response["error"] =1;
            $response["error_msg"] = "Error in getAllFreebies";
            echo json_encode($response);

                            }
                    }// end of getAllFreebies tag

Below is the code of my getFreebies() function of DB_function.php which is responsible for performing queries on MySQL database.
public function getFreebies(){
$result = mysql_query("SELECT * FROM freebie") or die(mysql_error());
return mysql_fetch_array($result);
}

Below is the logcat:
05-30 00:13:23.960: E/JSON(318): {"tag":"getAllFreebies","success":1,"error":0,"getAllFreebies":{"username":"viking","catagory":"Art","subcatagory":"Potrait","title":"Potrait","item_condition":"Good","description":"potarit","address":"Blah St","city":"lalaland","state":"NA","country":"NA","zipcode":"blah","posted_on":"2012-05-27"}}

A: mysql_fetch_array() only returns a single row of the query result set as an array. It does not fetch ALL of the rows. Since you're returning the results of the fetch from your getFreebies method, instead of the result handle itself, it is impossible for the calling code to get any other results from the query, other than the one row you've fetched.
As such, you should have:
public function getFreebies() {
   $result = ...
   return($result);
}

and
$getAllFreebies = $db->getFreebies(...);
$data = array();
while($row = mysql_fetch_assoc($getAllFreebies)) {
   $data[] = array(
      .... your variable assignments here ...
   );
}
echo json_encod($data);


text:
Q: IMAP doesn't connect to the mailbox I'm trying to read mails from an Exchange server for a specific g1ant account.
I want to use mails to provide as attachment to g1ant files to process and instructions for processing them.
But when I try to connect to the mailbox I receive this exception:

The folder is not currently open in read-write mode.

I'm using the following syntax:
mail.imap host <servername> login <user> password <password> result ♥emails sincedate ♥yesterday

Any suggestions to solve the issue?
Salvatore

A: Don't worry about the exception. Although it is thrown, the emails are retrieved correctly.
In order to just ignore it, use errorcall argument and create an empty procedure like in the following.
mail.imap imap.gmail.com login ♥login password ♥password result ♥emails sincedate ♥yesterday ignorecertificateerrors true errorcall IgnoreError

foreach ♥email in ♥emails
    dialog ♥email
end

procedure IgnoreError
end procedure


text:
Q: error converting an object into a List >; and The getter 'length' was called on null In the function below, I am getting an error. If the error is clear, I do not know how to fix that problem. I am willing to get return, returning List <MultiSelectItem>.Many thanks in advance for your help.
ERROR : The getter 'length' was called on null. This is coming from package:multi_select_flutter/bottom_sheet/multi_select_bottom_sheet.dart
 @override
  void initState() {
    _selectedContext = _context;
    _selectedStatus = _status;
    getAllContextInFirebaseV1();
    super.initState();
  }

List <MultiSelectItem<dynamic>>allContexts;

Future <List<MultiSelectItem>> getAllContextInFirebaseV1() async {
    CollectionReference ref = FirebaseFirestore.instance.collection('Users')
        .doc((FirebaseAuth.instance.currentUser.uid))
        .collection('contexts');

    QuerySnapshot contextsQuery = await ref
        .get();

    final allContexts = contextsQuery.docs.map((snap) => snap.data()).toList();
    //allContexts.asMap();

    print(allContexts.asMap());
    return allContexts  ; //allContexts as Future<List<MultiSelectItem<dynamic>>> ; Does not work neither
  }
}

I have also tried this. If I do this, I am getting an other error.
The getter 'length' was called on null.
Receiver: null
Tried calling: length

//NOT WORKING PROPERLY - TO FIX
                  MultiSelectBottomSheetField(
                    key: _multiSelectKeyContext,
                    initialChildSize: 0.7,
                    maxChildSize: 0.95,
                    title: Text("Context", style: TextStyle(fontSize: 19),),
                    buttonText: Text(
                      "Context 66", style: TextStyle(fontSize: 19),),
                    searchTextStyle: TextStyle(fontSize: 19),
                    searchHintStyle: TextStyle(fontSize: 39),
                    itemsTextStyle: TextStyle(fontSize: 19),
                    items: allContexts,//getAllContextInFirebaseV1(),
                    searchable: true,
                    onConfirm: (valueContext) {
                      setState(() {
                        _selectedContext = valueContext;
                      });
                      _multiSelectKeyContext.currentState.validate();
                    },
                    chipDisplay: MultiSelectChipDisplay(
                      onTap: (item) {
                        setState(() {
                          _selectedContext.remove(item);
                        });
                        _multiSelectKeyContext.currentState.validate();
                      },
                    ),
                  ),

if I use this, below, I am getting this error:The argument type 'Future<List<MultiSelectItem>>' can't be assigned to the parameter type 'List<MultiSelectItem>'.
/NOT WORKING PROPERLY - TO FIX
                  MultiSelectBottomSheetField(
                    key: _multiSelectKeyContext,
                    initialChildSize: 0.7,
                    maxChildSize: 0.95,
                    title: Text("Context", style: TextStyle(fontSize: 19),),
                    buttonText: Text(
                      "Context 66", style: TextStyle(fontSize: 19),),
                    searchTextStyle: TextStyle(fontSize: 19),
                    searchHintStyle: TextStyle(fontSize: 39),
                    itemsTextStyle: TextStyle(fontSize: 19),
                    items: getAllContextInFirebaseV1(),
                    searchable: true,
                    onConfirm: (valueContext) {
                      setState(() {
                        _selectedContext = valueContext;
                      });
                      _multiSelectKeyContext.currentState.validate();
                    },
                    chipDisplay: MultiSelectChipDisplay(
                      onTap: (item) {
                        setState(() {
                          _selectedContext.remove(item);
                        });
                        _multiSelectKeyContext.currentState.validate();
                      },
                    ),
                  ),

A: The problem is return types, you need to change the return types from Firebase and also that of the function and all will be fine. So you can have the following:
Future<List<dynamic>> getAllContextInFirebaseV1() async {
    CollectionReference ref = FirebaseFirestore.instance.collection('Users')
        .doc((FirebaseAuth.instance.currentUser.uid))
        .collection('contexts');

    QuerySnapshot contextsQuery = await ref.get();

    final allContexts = contextsQuery.docs
      .map((snap) => (snap.data() as Map<String, dynamic>)['context_Name'])
      .toList() as List<dynamic>;

    print(allContexts);
    return allContexts;
  }
}


text:
Q: Select Distinct Query Left JOIN, Still getting duplicates in my result I am writing a select query with distinct but I am still getting duplicates in my result. The Oracle View do have duplicates and I am trying to get back only 1 occurrence of that value.
Here is my query
select
person.person_id,
person.last_name,
person.first_name,
person.first_name,
person.middle_name,
skill.skills_id,
(case
when trim(skills.skill_description) = 'typing fast' then 'TP1'
when trim(skills.skill_description) = 'courier district 9' then 'CD9'
when trim(skills.skill_description) = 'helpdesk shift 3' then 'HD3'
when trim(skills.skill_description) = 'helpdesk shift 5' then 'HD5'
....
else ''
end) AS skill_description
from person_view person
left join (select distinct person_id, skill_id, skill_description, updated_date
from skill_view) skills
on skills.person_id = person.person_id and
((trunc(sysdate) - PHONE.UPDATED_DT <= 1))  and
trim(skills.skill_description) in ('skill1', 'skill2', 'skill3' ...)

There is a lot of values for skill_description, so I add the IN clause to filter for 15 - 20 specific skill_description values.
My case will take a the value and set the code for it.
I thought when I used the 'distinct' keyword it would filter out the duplicates but it is not working.
Here is my output so far
105 John E Doe SKILL1

105 John E Doe SKILL1

105 John E Doe SKILL2

105 John E Doe SKILL2

105 John E Doe SKILL3

105 John E Doe SKILL3

Any help is appreciated. Thanks

A: The problem is the DISTINCT is in an inner level and maybe the duplicates are outside the LEFT JOIN, you must put the DISTINCT clause in the first SELECT.
This should give you the desire output:
SELECT DISTINCT
       person.person_id,
       person.last_name,
       person.first_name,
       person.first_name,
       person.middle_name,
       skill.skills_id,
OMMITED CODE...

A: You are selecting updated_date in the subquery, but you don't use it in the outer query. QUESTION: Why? Did you mean to use it for something, perhaps to only select the most current info from the table?
In any case, if you have the same person_id, skill_id and skill_description values but different updated_date, DISTINCT won't help; the rows may very well be distinct in the inner query, but cease to be distinct in the outer query (if you don't include updated_date in the projection).


text:
Q: Attaching js to a html button I am trying to attach this script to a HTML button but can't seem to get my head around it.
Javascript:
var $ = function (id) {
        return document.getElementById(id);
        if (getElementById(button));
        var sumOfNumbers = 0;
        var numberOfLoops = 20;
        var counter = 1;
        while (counter <= numberOfLoops){
            alert(sumOfNumbers);
            sumOfNumbers += counter;
            counter++;
        }
}

HTML:

<input type="button" id="button" value="Loop"/>

A: Why don't you just add an event listener to the button?
See DEMO
var button = document.getElementById('button');

if (button.addEventListener){
    button.addEventListener('click', function() { $(); });
} else if (button.attachEvent){ // IE < 9 :(
    button.attachEvent('onclick', function() { $(); });
}

var $ = function() {
        var sumOfNumbers = 0;
        var numberOfLoops = 20;
        var counter = 1;
        while (counter <= numberOfLoops){
            alert(sumOfNumbers);
            sumOfNumbers += counter;
            counter++;
        }
}

Also, if you have Firebug or Chrome developer console, swap the alert() call with a console.log() call. Alerts can get annoying, especially if they are displayed back-to-back; consecutively.
Local File Example:

<input type="button" id="button" value="Loop" />


text:
Q: How convert string in phone number format? objective c I want to convert string into phone number format. For example I have string in which I have value, "456897012". Now I want to convert it in phone number format like as (456)897-012.
So what is process for that? How can I do that?

A: Something like this should work out I guess;
NSString *unformatted = @"5129876985";
NSArray *stringComponents = [NSArray arrayWithObjects:[unformatted substringWithRange:NSMakeRange(0, 3)],
                             [unformatted substringWithRange:NSMakeRange(3, 3)],
                             [unformatted substringWithRange:NSMakeRange(6, [unformatted length]-6)], nil];

NSString *formattedString = [NSString stringWithFormat:@"(%@)%@-%@", [stringComponents objectAtIndex:0], [stringComponents objectAtIndex:1], [stringComponents objectAtIndex:2]];
NSLog(@"Formatted Phone Number: %@", formattedString);

A: Ok
Suppose you have the oldPhone
[oldPhone insertString: @"(" atIndex: 0];

[oldPhone insertString: @")" atIndex: 4];

[oldPhone insertString: @"-" atIndex: 9];

Have not test it.
Hope that helps


text:
Q: How bilinear interpolation works when down scaling? I can clearly understand how bilinear interpolation works when up scaling the image, like fill the values while taking 4 nearest neighbours, but i can't understand how it works while down scaling the image. It would mean a lot to me if someone clarify for me.

A: Scaling an image requires mapping pixels from the input to pixels on the output.  If those pixel coordinates don't map to an integer, interpolation is required to estimate what the pixel value would have been.  The "Bi" part of bilinear means it's linear interpolation applied in two dimensions independently.  If for example output pixel 2,3 needs to come from input coordinates 1.5,7.2 you would interpolate in the X direction by taking 0.5 of each of the pixels at 1.0 and 2.0, then interpolate in the Y direction by taking 0.8 of the pixel at 7.0 and 0.2 of the pixel at 8.0.  Usually these operations are combined into a single set of equations, but they can be applied separately if needed.
Bilinear is a poor choice for downscaling because it leads to aliasing artifacts.  This is when you attempt to create spatial frequencies that are beyond the Nyquist sampling limit,  and high frequency detail turns into low frequency artifacts.  You can minimize this by blurring the image before you downscale it.  Or you can choose an interpolation algorithm that incorporates some low pass filtering.