text:
Q: DB result ordered by nearest matches (3 numeric criterias) I'm trying to make a system where I can input multiple values, and get all matches with a 15% tolerance from a mysql table. I've made in HTML and CSS the layout and I've managed to achieve it, but the problem is, I need to get the best match on top!
My table has 4 columns Modelo, L, A, H (Model, Length, width, height)
Here's my code:
HTML

            L
            <input id="largo" name="largo" onkeyup="buscar()" required></input>
            A
            <input id="ancho" name="ancho" onkeyup="buscar()" required></input>
            H
            <input id="alto" name="alto" onkeyup="buscar()" required></input>

JS
function buscar() {
 // if (str=="") {
 //   document.getElementById("result-trac").innerHTML="";
 // }
var l = document.getElementById("largo").value;
var a = document.getElementById("ancho").value;
var h = document.getElementById("alto").value;

 var xmlhttp=new XMLHttpRequest();
  xmlhttp.onreadystatechange=function() {
    if (this.readyState==4 && this.status==200) {
      document.getElementById("result-trac").innerHTML=this.responseText;
    }
  }
  xmlhttp.open("GET","busc.php?t="+tipo+"&l="+l+"&a="+a+"&h="+h,true);
  xmlhttp.send();
}

busc.php
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$link = mysqli_connect("localhost", "root", "", "test");
if($link === false){
    die("ERROR: Could not connect. " . mysqli_connect_error());
}
$l = $_GET['l'];
$a = $_GET['a'];
$h = $_GET['h'];

if($l=="" ||$a=="" ||$h==""){
echo("Por favor compelte todos los campos");
exit;
}

$sql = "SELECT * FROM test WHERE L>=($l * .85) AND L<=($l * 1.15) AND A>=($a * .85) AND A<=($a * 1.15) AND H>=($h * .85) AND H<=($h * 1.15)";
$result = $link->query($sql);

if ($result->num_rows > 0) {
echo('

                Modelo
                L
                A
                H

');

  while($row = $result->fetch_assoc()) {
    echo("

".$row['Producto']."
".$row['L']."
".$row['A']."
".$row['H']."

        ");
}
echo('
');
}else{echo($link->connect_error);}

?>

In this picture, the nearest match is BAT 2, but BAT 1 is showing up first.
Some IDs and Classes are in Spanish, but if you need any other information, let me know!
EDIT: What I need to do, is to get the nearest match on top. See in the picture BAT 2 has more near numbers than BAT 1 dora's, but BAT 1 is on top. I want BAT 2 to appear on top
Here's a fiddle with 4 rows http://sqlfiddle.com/#!9/6e705f So if I need, for example, a product that has L=95, A=95 and H=95, I would like to have BAT 3 show up first, and then BAT 2 and BAT 1. But not BAT 4 because is not in the 15% tolerance in all values

A: Let's first fix the SQL-injection issue you have. In busc.php you already use mysqli_connect, which is good.
The problem is about passing the GET values directly in the SQL query. So you need a "prepared statement". Here is a detailled tutorial.
But before that... And beyond the SQL-injection issue, you certainly will want to ensure the values are numeric to properly query the DB. So I suggest you apply this logic to the 3 GET variables:
if (isset($_GET['l']) && is_numeric($_GET['l'])) {
  $l= (int) $_GET['l'];
} else {
  $l= 100;  // Default value if unset or non-numeric
}

Now try this mysqli prepared statement which will result in a $rows associative array:
And notice:

*

*

*

*The usage of BETWEEN here which is a nice alternative to the comparisions you used (make things clearer).

*

*The ? placeholders to bind values via the parametric engine of prepared statements.

$query = 'SELECT * FROM test WHERE
         L BETWEEN (? * .85) AND (? * 1.15) AND
         A BETWEEN (? * .85) AND (? * 1.15) AND
         H BETWEEN (? * .85) AND (? * 1.15)';

$stmt = $link->prepare($query);
$stmt->bind_param("iiiiii", $l, $l, $a, $a, $h, $h);  // iiiiii means 6 integers
$stmt->execute();

$rows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

Here is a SQLFiddle about that BETWEEN usage.
So now, the DB results is fetched and the connection is closed. You have a $rows associative array which is not sorted as you want yet... There is some additional work to be done on that array and that was your main question.

Your main question:
To each "row" of that $rows... Add an additionnal array element to store sum of the absolute the difference of each values. That will be used to order the rows in table.
for($i=0;$i<sizeOf($rows);$i++){
  $L = abs($rows[$i]['L']-$l);
  $A = abs($rows[$i]['A']-$a);
  $H = abs($rows[$i]['H']-$h);
  $diff = $L + $A + $H;
  $rows[$i]["diff"] = $diff;
}

For a $row[$i] like ["L"=>90, "H"=>100, "A"=>95], and the values sent being 100 for all 3 $l, $a and $h variables,  the $diff would be 15.
So now you will sort $rows based on the $diff values... Thanks to that SO anwser about how to filter an array based on a sub-array value.
// Sorting sub array SO answer: https://stackoverflow.com/a/2477524/2159528
usort($rows, function ($a, $b) {
    return $a['diff'] <=> $b['diff'];
});

And finally... Echo the table:
echo('

    Modelo
    L
    A
    H
    diff

');

for($i=0;$i<sizeOf($rows);$i++){  // Loop the "ordered" rows
  echo('

      '.$rows[$i]['Producto'].'
      '.$rows[$i]['L'].'
      '.$rows[$i]['A'].'
      '.$rows[$i]['H'].'
      '.$rows[$i]['diff'].'

  ');
}

echo '
';

I made a PhpFiddle (hit F9 or the RUN button) showing the table would be ordered based on $diff using that sorting (with a fake associative array).


text:
Q: Передать значение из фрагмента в активность В чем проблемам? ругается на final String get_image = getIntent().getStringExtra(EXTRA_IMAGE);
Получатель(активность)
       public static final String EXTRA_TITLE = "get_title";
    public static final String EXTRA_ID = "get_id";
    public static final String EXTRA_IMAGE = "get_image";
   final String get_image = getIntent().getStringExtra(EXTRA_IMAGE);
    final String get_title = getIntent().getStringExtra(EXTRA_TITLE);
    final String get_id = getIntent().getStringExtra(EXTRA_ID);

отправитель (фрагмент)
  @Override
        public void onClick(View v) {
            Context context = v.getContext();
            Intent intent = new Intent(context, DetailInform.class);
            intent.putExtra(DetailInform.EXTRA_TITLE, ho.mBoundTitle);
            intent.putExtra(DetailInform.EXTRA_ID, ho.mBoundID);
            intent.putExtra(DetailInform.EXTRA_IMAGE, ho.mBoundImage);
            context.startActivity(intent);
        }
    });

Если в onCreate получать значения то все нормально (они приходят) но тогда я не могу их вытащить из onCreate

A: Получатель должен быть в on create, потому что именно этот метод вызывается, когда вы запускаете активность с помощью Intent. Чтобы сохранить значение, добавьте поля в класс активности.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Wordpress site not logging in I created a site locally on my machine everything is working fine, I uploaded it to my server a couple of weeks ago for testing/client review.
Everything looked good so the site was launch. The sites been up and running fine for about a month, today I tried to login to the backend but I have'nt been able to.
I'm able to access the login page fine. I insert my username and password and the page does nothing, just refreshes the page and clears the login form. I've tried resetting my admin password using the login form and it just keeps telling my to input a username or email.
I've downloaded the entire site and database installed it locally and it runs great no issues. I've up graded the local version to 3.1.3 it was still working fine so I replaced the live version with the new files, and still no luck.
Any suggestions?

A: I'm still not 100% sure what caused the problem, I'm guessing something in the core wordpress install was corrupted.
I ended up installing a fresh version of wordpress, exporting and then importing my database into a new database, and uploading the media, theme, and plugins separately which seemed to do the trick.

A: When you have a duplicate of a site on localhost or dev server and they have the same security keys it can cause a cookie collision.
Make a change to all of the security keys in the wp-config.php file and it will reset all sessions and cookies.

A: Same issue for me and i already mentioned here what worked for me.
Wordpress 3.8 gives me "You must enable cookies to use WordPress." at login


text:
Q: Can you check to see if an input is the same as a variable name? I am coding in Java Main.
I am writing a program that will count the resources gained from a daily rewards in a game. I have declared an Int variable for every month that holds the value for the number of days in that month. Each variable includes the number of days for itself, and all previous months, as so:
     int month;
        int january = 31;
        int february = 28; 59
        int march = 31; 90
        int april = 30; 120
        int may = 31; 151
        int june = 30; 181
        int july = 31; 212
        int august = 31; 243
        int september = 30; 273
        int october = 31; 304
        int november = 30; 334
        int december = 31; 365

the number that follows is what will be in the statement, i just have not put them in so i can keep the #of days as reference.
Anyway, what I want to do is have the user input the current month and the month they want to know how many resources they will have, saved as String variables currentMonth and laterMonth respectively. What I want to do is check to see if the String variables (say, September and March) have the same name as their int var counterparts, and if so, subtract int march from int september (273 - 90) to get the number of days in between to get int month. Is it possible for there to be such a check? Maybe I need to set up an array? I appreciate your help!

A: You do not need to maintain an array for it. The java.time API provides you with a lot of options which you can leverage to achieve what you need. Given below is an example:
import java.time.LocalDate;
import java.time.Month;
import java.time.temporal.ChronoUnit;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        System.out.println(Month.FEBRUARY.maxLength());

        // Difference between 31st Mar and 30th Sep
        System.out.println(
                Math.abs(ChronoUnit.DAYS.between(LocalDate.of(2020, Month.SEPTEMBER, Month.SEPTEMBER.maxLength()),
                        LocalDate.of(2020, Month.MARCH, Month.MARCH.maxLength()))));

        // ############## Interactive ##############
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter the first month[1-12]: ");
        int first = scanner.nextInt();

        System.out.print("Enter the second month[1-12]: ");
        int second = scanner.nextInt();

        System.out.println(Math.abs(ChronoUnit.DAYS.between(LocalDate.of(2020, first, Month.of(first).maxLength()),
                LocalDate.of(2020, second, Month.of(second).maxLength()))));
    }
}

A sample run:
29
183
Enter the first month[1-12]: 3
Enter the second month[1-12]: 9
183

A: I think the problem can be solved using either a HashMap or two arrays.
The two arrays approach is a bit easier in my opinion:
static String[] monthNames = new String[]{
        "january",
        "february",
        "march",
        "april",
        "may",
        "june",
        "july",
        "august",
        "september",
        "october",
        "november",
        "december"
    };

public static void main(String[] args) {

    int[] numOfDays = new int[]{31,28,31,30,31,30,31,31,30,31,30,31};
    int mo2 =   getConsecutiveMonth("september");
    int mo1 =   getConsecutiveMonth("march");
    int septemberMarch = sumBetween(numOfDays, mo1, mo2);
    System.out.println(septemberMarch);

}

public static int getConsecutiveMonth(String m){
    String lowercaseM = m.toLowerCase();
    for(int i = 0; i<monthNames.length; i++){
        if(monthNames[i].equals(lowercaseM))
            return i;
    }
    return -1;
}

public static int sumBetween(int[] a, int i, int j){
    int sum = 0;
    for (int idx = i; idx < j; idx++) {
        sum += a[idx];
    }
    return sum;
}


text:
Q: How to create a automatic  if there is data in the database, php I have a database created in MySql with 8 tables, with products. I want to automatic, it creates an tr and td in a table, as i have more and more data in the database tables.
*I already try to find information about it, but i couldn't understand how it works.
this is what i have so far:
<?php
        //Connect to DataBase//
        $link=mysqli_connect('localhost','root','','produtos');
        if(mysqli_connect_errno())
        exit("falhou a conexão ao mysql:".mysqli_connect_error());

        //Codification type//
        mysqli_query($link,"set names utf8");

        //Select from DataBase//
        $query="Select * FROM fornos";
        $result = mysqli_query($link, $query);
        if (!$result)
            exit("Erro na query SELECT: " . mysqli_error($link));
        $fornos = mysqli_fetch_assoc($result);
        $imagem = $fornos['image_link'];
        $preco = $fornos['preco'];
        mysqli_free_result($result);

        //Finish the Conection//
        mysqli_close($link);
?>

<?php
                        echo '
';
                    while ($fornos=mysqli_fetch_assoc($result)){
                        echo"
";
                            echo" .$preco 	";
                        echo"
";
                        echo"
";
                            echo"	";
                        echo"
";
                        echo"
";
                            echo"Informações	";
                        echo"
";
                        echo"
";
                            echo"Comprar	";
                        echo"
";
                    }
                        echo '
';

                    ?>

A: Wrap your code in a condition to check whether there are entries or not:
<?php

if(mysqli_num_rows($sql) > 0)
{
    echo '
';

    // YOUR CODE TO PRINT THE TABLE ROWS

    echo '
';
}

?>

A: try this code:
<?php
......
......
$sytax = mysql_query("SELECT * FROM `TABLE`"); // anything you want
echo "

";
while($make_this = mysql_fetch_array($sytax)){
?>
   <?php echo $make_this['Field_in_your_table']; ?>
<?php
}
echo "

";
?>

A: try this....

<?php
   while ($fornos=mysqli_fetch_assoc($id)){

?>

              <?php echo $preco ?>
              // similarly other data

    <?php
        }
       ?>


text:
Q: Session.saveOrUpdate increases id by two I've created method to save entity with new id or update existing via hibernate session. When I use next code:
try {
        Session session = sessionWrapper.getSession();
        sessionWrapper.beginTransaction();
        if (user.getId()==null || session.get(User.class, user.getId())==null) {
            return (long) session.save(user);
        } else {
            session.get(User.class, user.getId());
            session.merge(user);
            return user.getId();
        }
    } finally {
        sessionWrapper.commit();
        sessionWrapper.closeSession();
    }

it works ok, but when I use session.saveOrUpdate instead in case of new entity generated id is increased by two, not one. Why and how to fix it?


text:
Q: Nodejs chproc as simple user and not root Hi this may be a simple question but i can't figure out how could I, using chproc.exec open an application, but my current program is running as root and I need the childprocess to run as a user.
How Could I achieve that?
Current code :
chproc.exec("google-chrome").unref();


text:
Q: How can i add Local Storage to my todolist? I am doing some practice javascript exercise. My project look like 'trello' but much soft and simple.
When i writing some notes to input, javscript adding note dynamically   but if i refresh the page/chrome, all things gone or lost.
So i wanna apply localstorage on my project. How can i do it.
My Note project: https://codepen.io/daniel_134/pen/NWwYKyK[My Note project]1

var input = document.querySelector('#text-input');

document.querySelector("#ad-note-btn").addEventListener("click",  () => {
   if (input.value.length > 1) {
      // GET-INPUT-VALUE
      var getvalue = input.value;
      // CREATE-NEW-NOTE
      const newLi = document.createElement("textarea");
      newLi.value =  getvalue;
      newLi.className =  "note-li";
      // ADD-NEW-NOTE
      var ul = document.querySelector('#list-items');
      ul.appendChild(newLi);

      // EMPTY-INPUT-WHEN-CREATING-NEW-NOTES
      input.value = " ";

      //  DELETE-NOTES
      const dleLi = document.createElement("button");
      dleLi.textContent = "delete";
      dleLi.className = "list-btn";
      ul.appendChild(dleLi);
      dleLi.addEventListener("click", () => {
         newLi.remove();
         dleLi.remove();
         edLi.remove();
         saveLi.remove();
     })

   //   EDIT-NOTES
     const edit = () => {
       if( newLi.value.length > 0 ) {
          newLi.disabled = true;
       } else {
          newLi.disabled = false;
       }
     }

     edit()

    const edLi = document.createElement("button");
    edLi.textContent = "Edit";
    ul.appendChild(edLi);
    edLi.className = "list-btn";
    edLi.addEventListener("click", () => {
       if ( newLi.disabled = true ) {
          newLi.disabled = false;
       }else {
          newLi.disabled = true;
       }
    })

    const saveLi = document.createElement("button");
    saveLi.textContent = "save";
    ul.appendChild(saveLi);
    saveLi.className = "list-btn";
    saveLi.addEventListener("click", () => {
       edit();
    })

   } else {
      ul.appendChild();
   }

})

document.querySelector("#clear-btn").addEventListener("click", () => {
   input.value = " ";
})

2

A: it'll look like that , for example :

*

*when you load your page .

*load todoList var todoList = JSON.parse(localStorage.getItem('todo-list'))

*and display it

*when you add new element to your to-do list

*var todoList = JSON.parse(localStorage.getItem('todo-list'));

*

       var new_todo = [{
             title:'for example ...',
             complete:false
       }];
       localStorage.setItem('todo-list',JSON.stringify(new_todo));

   }else{
       todoList.push({
             title:'for example ...',
             complete:false
       });

        localStorage.setItem('todo-list',JSON.stringify(todoList));

   }


text:
Q: Rnw file doesn't generate plot in pdf I'm working with an .Rnw file, trying to generate a plot. However, when I click Compile PDF, I get a blank pdf with just the figure caption and no plot. It looks like this:
Here is the code:
\documentclass{article}

\begin{document}

<<fasfd, fig.height=10, fig.cap="first", fig.pos="t", echo=FALSE, fig.width=10>>=
barplot(table(mtcars$gear))
@

\end{document}

What am I doing wrong?

A: Sweave does not provide so many options as knitr. To include plots with sweave you need to specify fig= TRUE
\documentclass{article}

\begin{document}
\SweaveOpts{concordance=TRUE}
Without $fig=TRUE$
<<fasfd, fig.height=5, fig.cap="first", fig.pos="t", echo=TRUE, fig.width=10>>=
barplot(table(mtcars$gear))
@
With $fig=TRUE$
<<fig=TRUE>>=
barplot(table(mtcars$gear))
@

A boxplot of the \emph{airquality} data:
\centering
<<fig=TRUE, echo=FALSE>>=
data(airquality)
boxplot(Ozone ~ Month, data = airquality)
@

\end{document}

A: I never used knitr, but the syntax relay reminded me on sweave, in this case you need to correct the tag, for example:
<<label=fig1,fig=TRUE,echo=FALSE>>=

in total:
\documentclass{article}

\begin{document}
\SweaveOpts{concordance=TRUE}

<<label=fig1,fig=TRUE,echo=FALSE>>=

barplot(table(mtcars$gear))
@
\end{document}


text:
Q: How to specify a Blackbox Bundle that maps to `input [127:0]` but acts like a Vec(2, UInt(64)) in the Chisel source? I want to interface with a full AXI crossbar whose ports
look roughly like the following:
input [(NM * AXI_DATA_WIDTH) - 1:0] S_AXI_XYZ0,
...
output [(NS * AXI_SOMETHING_WIDTH - 1:0] M_AXI_XYZ0
...

where NM denotes the number of masters and NS denotes
the number of slaves. As you can imagine, each of the ports of
the crossbar will only partially connected to each slave/master.
Now, Ideally I'd like to define a Chisel Bundle like
class AxiXbar(val AXI_DATA_WIDTH: Int, val NS: Int, ...) extends Bundle {
  val S_AXI_XYZ0 = Vec(NS, UInt(AXI_DATA_WIDTH))
  ...
}

but as soon as I use that in order to give a Blackbox
its interface
class MyXbar extends Blackbox {
  val io = IO(new AxiXbar)
}

Chisel will try to verilogify MyXbar to something like
MyXbar inst #(...) (
  ...
  .S_AXI_XYZ0_0(foo_wire_0)
  .S_AXI_XYZ0_1(foo_wire_0)

  ...
  )

This is fine when Chisel generates the complete design, but
when interfacing with a Blackbox module,
I need Chisel to flatten the Chisel Vec into
only one S_AXI_XYZ0 port instead. How can I achieve that?
I am aware that Chisel3 supports DataView as method to
change the "shape" of a interface bundle, but in their DataView Cookbook they state that subword viewing (split/concat) is not yet supported.
I tried to use Chisel's cast macros asType(...) or asUInt. Without success though as I do not fully grasp what they do under the hood. As such it is hard to apply them correctly.


text:
Q: build recursion function to get parent ids in sqlalchemy I have class in sqlalchemy
class Topics(db.Model):
        tablename = 'topics'

        id = db.Column(db.Integer, primary_key=True, autoincrement=True)
        name = db.Column(db.String(140))
        parent = db.Column(db.Integer, default=0)

        tasks = db.relationship('Tasks',
                                secondary=tasks_topics,
                                back_populates="topics")

I need to make function in class which returns recursivly all parent topics ids in one query. This variant get several queries :
def get_parent_topics(self):
        parent_topics = []
        if self.parent != 0:
            parent_topic = Topics.query.filter_by(id=self.parent).first()
            parent_topics.append(parent_topic)
            parent_topics.extend(parent_topic.get_parent_topics())
        return parent_topics

How should I use @hybrid_property to realise it.


text:
Q: SQL Query to show 3 user names from userID's in one Bug record I would like to show all the usernames who have interacted with a bug in MS Access. I do not understand how to reference the same Users.UserName field 3 times in my select statement?
Here are my tables
--------------------------------------------
Table 'Bugs'
--------------------------------------------
BugID    OpendBy    ClosedBy    LastChangedBy
1           1          3               2
2           3          4               4
3           2          4               4
4           3          1               3

--------------------------------------------
Table 'Users'
--------------------------------------------
ID    UserName
1     Joe
2     Chris
3     Steve
4     Sarah

I would like the query to return
BugID OpendBy ClosedBy LastChangedBy
1       Joe     Steve     Chris
2       Steve   Sarah     Sarah
3       Chris   Sarah     Sarah
4       Steve   Joe       Steve

A: I used a LEFT OUTER JOIN below for ClosedBy, as I assume this value can be NULL. If anyof the others can be NULL, you'll need to change those joins to LEFT OUTER as well.
select b.BugID, uo.UserName as OpendBy,
    uc.UserName as ClosedBy,
    ul.LastName as LastChangedBy
from Bugs b
inner join Users uo on b.OpendBy = uo.ID
left outer join Users uc on b.ClosedBy = uc.ID
inner join Users ul on b.LastChangedBy = ul.ID

A: If you want to avoid all the ugly joining, you could structure this instead as a separate table with BugID, ActionType (OpenedBy, ClosedBy, LastChangedBy) and UserID. Then you could also have a date field, instead of having three different date fields in your but record.
Records are cheap, fields are expensive.


text:
Q: Postgres: Querying whole rows in a many to many relationship My table is currently structured as follows:
PATHS TABLE

UID uuid primary | NAME text | DURATION number
<uuid 0>         | Path 1    | 60

STOPS TABLE

UID uuid primary | NAME text | ADDRESS text
<uuid 1>         | Stop 1    | Whatever Str.
<uuid 2>         | Stop 2    | Whatever2 Str.

PATH_STOP TABLE

id int primary | PATH uuid fk | STOP uuid fk
0              | <uuid 0>     | <uuid 1>
1              | <uuid 0>     | <uuid 2>

Meaning that each path has multiple stops assigned to it and one stop can be possibly appear in more than one path, making it a many to many relationship.
I'm finding it confusing querying for paths and get the stops back with it in one single query.
I've been trying for a while to create a function that handles this and this is how far I've come (spoiler, not that far)
create or replace function get_paths() returns setof paths as $$
  declare
    p paths[]
  begin
    select * into p from paths;
    -- not sure how to move on from here.
  end;
$$ language plpgsql;

A: From https://postgrest.org/en/latest/api.html#many-to-many-relationships
Many-to-many relationships are detected based on the join table. The join table must contain foreign keys to other two tables and they must be part of its composite key.
For the many-to-many relationship between films and actors, the join table roles would be:
create table roles(
  film_id int references films(id)
, actor_id int references actors(id)
, primary key(film_id, actor_id)
);

-- the join table can also be detected if the composite key has additional columns

create table roles(
  id int generated always as identity,
, film_id int references films(id)
, actor_id int references actors(id)
, primary key(id, film_id, actor_id)
);

Then you can do
await supabase.from('actors').select('first_name,last_name,films(title)')


text:
Q: how to make a dropdownlist visible once clicking a button I am a beginner,
Hope one can help me with my problem,
I want to make a drop down list visible once I click the button,
It completely like the thing that has been done here:
https://shop.adidas.co.in/#category/Pag-60/No-0/0/All/facet.DIVISION_CATEGORY_ss:%28%22FOOTWEAR%22%29%20AND%20allBrands_ss:%28%22ORIGINALS%22%29
when the customer clicks on Buy button then a drop-down list appear above of the buy button,I think this example in the mentioned website is clear enough,
EDITION
as the code shows, when I click on BUY button it opens up a new link,
I'm not wanna to do this,
at first when someone click the button it has to not work and just show the drop-down list,
secondly, when the user chooses a size from the drop-down list and then click on the button it has to work and open the link,
it is exactly what happen in the above link that I have introduced.
my stuff:
<button name="buySize" id="buySize" type="button" class="btn btn-success btn-sm" onclick="location.href='@Url.Action("AddToCart", "ShoppingCart", new { Barcode = @item.Barcode },"")'">
    خرید »
</button>

    سایز:

        @Html.DropDownListFor(model => model.CartItems[0].Size, new SelectList(Model.Sizes))

this was my drop-down list and button
and also javascript :`
$('#buySize').click(function () {
    if (this.click())
        $('#drpSize').show("fast");
    else
        $('#drpSize').hide("fast");
});

every help is appreciating :),

A: Try this :

*

*Your dropdown is initially hide by the css ie. display:none

Jquery code to show it when user click on buy button:
$('#buySize').click(function () {
   $('#dropdown_id').show();
});

A: You can put drop down list hidden by default using style attribute in drop down div as
style="display:none"

on click of button you can show the drop down list.
For this code will be as follow:
CSHTML

EDIT: You achieve required functionality First remove onclick event
  from button control.

 <button name="buySize" id="buySize" type="button" class="btn btn-success btn-sm">
  خرید »</button>

     سایز:

       @Html.DropDownListFor(model => model.CartItems[0].Size, new SelectList(Model.Sizes))

in js file
 $('#buySize').click(function () {
           $('#drpSize').css('display','block');
        });

EDIT: alternately if want to show drop down with animated effect and
  want to open BUY link after size selection use this script.

 $('#buySize').click(function () {
   $('#drpSize').show('fast');
var val= $('#dropDownId :selected').text();
if(val!='Select'){
location.href= //which ever link you want to open put here
}
 });


text:
Q: What it is the best way to perform a task in background (thread or call method from application_start)? I am using asp.net.
I am going to develop a way to display results from fedex's service (every 2 hours) in my website. I have searched,I found a lot of options, and chose two of them:
1: From application start
private static CacheItemRemovedCallback OnCacheRemove = null;

protected void Application_Start(object sender, EventArgs e)
{
    AddTask("DoStuff", 60*60*2);
}

private void AddTask(string name, int seconds)
{
    OnCacheRemove = new CacheItemRemovedCallback(CacheItemRemoved);
    HttpRuntime.Cache.Insert(name, seconds, null,
        DateTime.Now.AddSeconds(seconds), Cache.NoSlidingExpiration,
        CacheItemPriority.NotRemovable, OnCacheRemove);
}

public void CacheItemRemoved(string k, object v, CacheItemRemovedReason r)
{
    // do stuff here if it matches our taskname, like WebRequest
    // re-add our task so it recurs
    AddTask(k, Convert.ToInt32(v));
}

More info : https://blog.stackoverflow.com/2008/07/easy-background-tasks-in-aspnet/
2: Using thread
System.Threading.Thread OrderStatusFromFedexThread = new System.Threading.Thread(new System.Threading.ThreadStart(OrderStatusChange));
OrderStatusFromFedexThread.IsBackground = true;
OrderStatusFromFedexThread.Name = "OrderStatusFromFedexThread";
OrderStatusFromFedexThread.Start();

  public static bool ShutDown = false;

    static void OrderStatusChange()
    {
        while (!ShutDown)
        {
            System.Threading.Thread.Sleep((1000 * 60) * 60 *2);
              // do stuff here
        }
    }

My question is: what is the best way:

*

*Add a task from application start or

*Using thread?

Which keeps the speed of website faster, and doesn't make it slow?

A: This is how you do it with a timer and an update panel.
//timer that can be set to any time you want. Interval is miliseconds
<asp:Timer ID="UpdateGridTimer" runat="server" Interval="7200000" OnTick="UpdateGridTimer_Tick"></asp:Timer>
<asp:UpdatePanel ID="TimedPanel" runat="server" UpdateMode="Conditional">
    <Triggers>
        //this trigger calls the timer every 2 hours.
        <asp:AsyncPostBackTrigger ControlID="UpdateGridTimer" EventName="Tick" />
    </Triggers>
    <ContentTemplate>
    // Here is where you'd display the fedex information.
    </ContentTemplate>
</asp:UpdatePanel>

This should do it for you. I use this method for an appointment system.
EDIT: The above is the front end of your code, so you will use that to display your information. I'm not sure how you have it set up, but if you're using (for example) a gridview, you can bind that gridview on tick.. and it would look like this..
ASPX
//timer that can be set to any time you want. Interval is miliseconds
    <asp:Timer ID="UpdateGridTimer" runat="server" Interval="7200000" OnTick="UpdateGridTimer_Tick"></asp:Timer>
    <asp:UpdatePanel ID="TimedPanel" runat="server" UpdateMode="Conditional">
        <Triggers>
            //this trigger calls the timer every 2 hours.
            <asp:AsyncPostBackTrigger ControlID="UpdateGridTimer" EventName="Tick" />
        </Triggers>
        <ContentTemplate>
          <asp:gridview id="GridView1" runant="server">
               //gridview content
          </asp:gridview>
        </ContentTemplate>
    </asp:UpdatePanel>

C#
protected void UpdateGridTimer_Tick(object sender, EventArgs e)
{
  //this would be the code to update the gridview.
  //you can use a data table and bind the results to the gridview
  //in your case, you will do whatever it is you have to do get the fed ex information
  // but I'm not sure how you are doing this to show you.

       GridView1.DataBind();

}

Sorry I left the behind code out of it in my previous answer. What the onTick does, after the 2 hours, it will run the code for that timer tick. So every two hours, it will act like your button click, but it requires no human interaction. The website just needs to be up. But since the timer is every two hours, you must make sure that the session timeout doesn't kick you off every two hours. Let me know if you have any questions.

A: In general, you don't want to consume threads in an asp.net site.  However, there are plenty of exceptions.  Either implementation will do what you want (provided you're not blocking Application_Start from finishing in your threading example).   Most likely the caching option will burn some CPU periodically to see if stuff is expired.  You may want to dig into the details of the caching implementation.  This would be more important if you're hosting in Azure and paying for CPU.  The threading example is going to burn a thread, but since it's only one for the app pool it probably does not matter.  Most likely the biggest concern is this whole thing is completely dependent on holding everything in memory.  It seem very odd that you would need to do that.  If you really needed to gather a big chunk of data every couple of hours, some scheduled service that puts data into a local database might make more sense.  Then let your website connect to that database.  Unless you're just trying to do statistical reporting, it seems odd that this stale data would be acceptable to anyone.

A: Personally I would use a JavaScript timer to make an AJAX call to a WebService and reload the page client side without post back.
The solution provided by @Humpty is also good.
I hope this helps.


text:
Q: Next.js api route with IP address Inside one of my next.js api route,
For example: pages/api/example.js
I have the following simple code.
Then, inside this route, I have post request to a server.
export default async function example(req, res) {

  const data = await axios.post(
     https://another_server_Url, // another server api
    {
      data
    })

  res.status(200).json({ name: 'John Doe' })
}

My question is if the another_server api implement a rating-limiting mechanism,
It's possible for me to get the user IP address first, then somehow pass the IP address via the axios request. So the another_server api can recognize the true ip.
As far as I understand the current code, the next.js server somehow becomes a proxy.
The problem now is that because I called the Api inside my next router api, the ip address will always be my next.js server.

A: You may get client's IP from req.headers['x-forwarded-for'] - have a look at: How to determine a user's IP address in node. Then, pass this IP within axios POST request body to another_server.
Edit:
In response to your comment below the implementation largely depends on the configuration of the backend server (another_server) and how it reads the client IP. For example, check if it uses request headers to determine the IP - if so, identify the particular header and overwrite it in axios call to include original client IP, e.g:
  const clientIp = (req.headers['x-forwarded-for'] || '').split(',').pop().trim() ||
    req.socket.remoteAddress;

  const data = await axios({
    method: 'post',
    url: 'https://google.com',
    headers: {
      'x-forwarded-for': clientIp
    },
    // ...
  });

Another solution would be to simply send the request from the client side straight to another_server and skip the problem altogether, but I assume it's not a viable solution in your case.


text:
Q: Why does W3 validation require populated alt and src attribute for images? I don't use these properties as I add the src dynamically later.  I don't need alt either.
I do want my page to validate however. I can bypass this requirement by using CSS backgrounds inside a div.  Is this a valid approach?
Clarification:

*

*I don't care about search engines.

*My images always load.

*I set the src attribute using JavaScript.

*For major modern browsers.

*Accessibility not needed yet.

*Doctype is HTML 5 - <!DOCTYPE html>
Reference
http://validator.w3.org/

A: Because it's validating to a specification
Html has a specific structure which is documented on the w3.org site. The w3 validator validates that the input matches the specification, in this case matching the requirements:
img tag

The src attribute must be present

An img tag with no src has undefined behavior and, for example, may re-request the current page in lieu of a valid image depending on the browser.
alt attribute

the alt attribute must be specified and its value must not be empty

From the same reference, justification for the alt attribute requirement:

[the alt attribute] is supposed to contain replacement text that could be used by users instead of the image

Why serve invalid markup
From the question:

I don't use these properties as I add the src dynamically later. I don't need alt either.

If you're adding the src dynamically (which also implies that without javascript the page, or at least this particular bit of markup, is of no use to anybody) - why not add the img tag dynamically.

A: Alt tags are insisted upon based at least partially on federal laws in various countries, as in some contexts and situations it is considered illegal discrimination against disabled persons that can be punished with some very hefty fines - thus, the W3 standards wisely insist upon it if the page is to be considered standards compliant.
Beyond disabilities, alt tags are used in a variety of contexts such as screen readers, when browsers have images turned off, etc.
If you really want to avoid defining alt tags, use a default one, like alt="Alt tag intentionally left blank due to 'reasons'" or somesuch.
As to the source attribute, it goes to the fact that an html page must be internally valid BEFORE scripts are run to be considered standards compliant. This is due to the complexity and unreliability of checking standards compliance after scripts have run, as well as the fact that the standard has been influenced by the idea of "unobtrusive scripting" - where the page can be enhanced by scripts, but it should not insist on scripting for basic functionality when not strictly necessary.
Now if you have a really good reason that your images must be defined at run time, you have two choices:

*

*Use a blank or placeholder image, such as a 1x1 transparent gif/png at least.

*Remove the images from the HTML entirely and add them at run time, instead of just changing the related src attributes.

As to the src tag, one must also remember that as your application grows the loading time will increase, and things might start looking really weird depending on styles and dimensions, etc.
In summary, always use Alt tags even if you think you don't need them, and use one of the two above solutions regarding the src tag.

A: The alt attribute is useful for text-based browsers, disability accessibility like screen readers, and search engines (some of which are mentioned in comments on your question).
You probably shouldn't have empty image tags lying around, too. This is semantically wrong (not to mention it fails validation as you have said), and can cause technical issues with your site. Instead, perhaps have empty "image holders" (like div or figure) lying around, and populate their inner HTML content with your dynamic image tags.
Setting the src with JS (or even statically) cannot guarantee loading of images. What if the network has a really bad hiccup? You cannot guarantee that all resources will load properly. Dealing with badly loaded JS or CSS can get a bit ridiculous and can be beyond your control, but something as simple as an alt tag on your images can be a pretty easy workaround.
Just because you don't need all of these features doesn't mean the W3C shouldn't take them into consideration when making a generalized spec for the entire world to follow.


text:
Q: Qt unexpected EOF while looking for matching I tried to run the project from
https://courses.cs.washington.edu/courses/cse576/14wi/Assignment1.htm
on
OS X 10.9.5 | Xcode 2 6.1 | Qt Creator 3.2.2(opensource) Based on Qt 5.3.2
But got the following error
> /Users/MyName/Qt/5.3/clang_64/bin/qmake -spec macx-clang CONFIG+=debug
> CONFIG+=x86_64 -o Makefile ../code/ImageStitcher.pro
> /Applications/Xcode
> 2.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang++
> -c -pipe -g -isysroot /Applications/Xcode 2.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk
> -mFile Doesn't Exist, Will Create: /Applications/Xcode Invalid Arguments  -version-min=10.6 -Wall -W -fPIE -DQT_WIDGETS_LIB
> -DQT_GUI_LIB -DQT_CORE_LIB -I../../../Qt/5.3/clang_64/mkspecs/macx-clang -I../code -I../../../Qt/5.3/clang_64/lib/QtWidgets.framework/Versions/5/Headers -I../../../Qt/5.3/clang_64/lib/QtGui.framework/Versions/5/Headers -I../../../Qt/5.3/clang_64/lib/QtCore.framework/Versions/5/Headers -I. -I/Applications/Xcode -I2.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk/System/Library/Frameworks/OpenGL.framework/Headers
> -I/Applications/Xcode -I2.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk/System/Library/Frameworks/AGL.framework/Headers/
> -I. -I. -F/Users/MyName/Qt/5.3/clang_64/lib -o main.o ../code/main.cpp /bin/sh: -c: line 0: unexpected EOF while looking for matching `''
> /bin/sh: -c: line 1: syntax error: unexpected end of file make: ***
> [main.o] Error 2 22:13:50: The process "/usr/bin/make" exited with
> code 2. Error while building/deploying project ImageStitcher (kit:
> Desktop Qt 5.3 clang 64bit) When executing step "Make"

I have changed
!host_build:QMAKE_MAC_SDK = macosx10.9
qdevice.pri

Any suggestion? Thanks

A: I fixed it by removing the whitespace in /Applications/Xcode 2.app.  The tricky part is forcing qmake to realize the change.
Solution:

*

*Rename your "Xcode N.app" to something without spaces (I deleted my older Xcode installation and renamed my "Xcode N.app" to /Applications/Xcode.app)

*Run sudo xcode-select --switch /Applications/Xcode.app (or whatever else you named it).

*Delete the file named .qmake.stash in your build directory.  My project was located in ~/test/ and my build directory was ~/build-test-Desktop_Qt_5_3_clang_64bit-Debug/, so I ran rm -f ~/build-test-Desktop_Qt_5_3_clang_64bit-Debug/.qmake.stash to delete the file.

*Build.  It should work now.


text:
Q: Python Dictionary, finding the sum of key values that repeat I have a list of dictionaries that look like the following:
[{
    "id": "42f409d0-2cef-49b0-a027-59ed571cc2a9",
    "cost": 0.868422,
    "environment": "nonprod"
},
{
    "id": "42f409d0-2cef-49b0-a027-59ed571cc2a9",
    "cost": 0.017017,
    "environment": "prod"
},
{
    "id": "aa385029-afa6-4f1a-a1d9-d88b7d934699",
    "cost": 0.010304,
    "environment": "prod"
},
{
    "id": "b13a0676-6926-49db-808c-3c968a9278eb",
    "cost": 2.870336,
    "environment": "nonprod"
},
{
    "id": "b13a0676-6926-49db-808c-3c968a9278eb",
    "cost": 0.00455,
    "environment": "prod"
},
{
    "id": "b13a0676-6926-49db-808c-3c968a9278eb",
    "cost": 0.032458,
    "environment": "prod"
}]

The part im having a hard time understanding is how can I group these by id and environment and add up there costs for the given environment.
End result should be, only having a single pair of prod and nonprod for a given ID and have all costs for prod or nonprod added up under a single id in prod or a single id in nonprod.
I hope this is enough detail, thank you!

A: d = {}
for el in data:
    d[(el["id"], el["environment"])] = d.get((el["id"], el["environment"]), 0) + el["cost"]
d
# {('42f409d0-2cef-49b0-a027-59ed571cc2a9', 'nonprod'): 0.868422,
#  ('42f409d0-2cef-49b0-a027-59ed571cc2a9', 'prod'): 0.017017,
#  ('aa385029-afa6-4f1a-a1d9-d88b7d934699', 'prod'): 0.010304,
#  ('b13a0676-6926-49db-808c-3c968a9278eb', 'nonprod'): 2.870336,
#  ('b13a0676-6926-49db-808c-3c968a9278eb', 'prod'): 0.037008}

A: In addition of above answers, a solution of python by creating a unique key of each transaction id|type will also work. This piece of code does exactly that and can even be made easier to read with defaultdict.
dictCounter = dict()
#assuming test is the list of dicts
for eachEntry in test:
    newUniqueKey = eachEntry["id"]+"|"+eachEntry["environment"]
    if newUniqueKey not in dictCounter.keys():
        dictCounter[newUniqueKey]=eachEntry["cost"]
    else:
        dictCounter[newUniqueKey]+=eachEntry["cost"]

A: Try placing the dict values into a pandas dataframe, then use pandas's groupby function (I set the variable dicts to equal your above list of dictionaries):
import pandas as pd
df = pd.DataFrame(dicts)
df.groupby(["id", "environment"], as_index=False).sum()

Output:

                                      id    environment  cost
0   42f409d0-2cef-49b0-a027-59ed571cc2a9    nonprod      0.868422
1   42f409d0-2cef-49b0-a027-59ed571cc2a9    prod         0.017017
2   aa385029-afa6-4f1a-a1d9-d88b7d934699    prod         0.010304
3   b13a0676-6926-49db-808c-3c968a9278eb    nonprod      2.870336
4   b13a0676-6926-49db-808c-3c968a9278eb    prod         0.037008


text:
Q: Permission denied, AndroidManifest.xml does not work m developing launcher for 2.3.3 via specified STB. And I wrote permissions like
...
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
...

in AndroidManifest.xml.
While debugging -uninstall/install-, sometimes meet "Permission denied" so i should uninstall/install again and again till got no errors with "Permission denied".
Does anyone get this strange bug? Of course, I did not edit AndroidManifest.xml at all.

A: If while debugging your Device is connected to a PC and

Enable copy files to/from your computer.

Then you will see this Permission denied message.

A: I have had recently this problem, when I upgraded the targetSdkVersion to 23. The "problem" was the new system of dynamic permissions in Android. See http://developer.android.com/training/permissions/requesting.html


text:
Q: Creating exclusive profiles in maven I currently have a pom with platform specific profiles (e.g. linux 32bit, windows 64 bit, etc...). Additionally, I have set it up to automatically choose the invoker's platform as a default.
Now, assume I am in a linux 32 machine: I also want to build for win64 by invoking mvn -Pwin64 pakage but in doing so, both the linux32 and win64 profiles get activated. I have tried activating the local platform profile with activeProfiles and using ativation tags. The trouble is that -P does not disable all other profiles as explained in the documentation:

This option takes an argument that is a comma-delimited list of
  profile-ids to use. When this option is specified, no profiles other
  than those specified in the option argument will be activated.

Am I understanding this wrong? How would you handle this?
Note: I know I could run mvn -P-linux32,win64 but that is only valid on linux32 platforms, and any mistakes may result in a bloated build with duplicate classes.
Thanks!

A: This statement from the profile docs:

As of Maven 3.0, profiles in the POM can also be activated based on properties from active profiles from the settings.xml.

Would lead me to try the solution below.  Each developer defines his default platform as a property in his settings.xml file and overrides it on the cmdline if needed.
Developer's settings.xml
<profile>
    <id>platform-config</id>
    <property>
        <name>build.platform</name>
        <value>win32</value>
    </property>
</profile>
....
<activeProfiles>
    <activeProfile>platform-config</activeProfile>
</activeProfiles>

Project's pom.xml
<project>
...
<profiles>
    <profile>
        <id>win32</id>
        <activation>
            <property>
                <name>build.platform</name>
                <value>win32</value>
            </property>
        </activation>
        ...
    </profile>
    <profile>
        <id>linux32</id>
        <activation>
            <property>
                <name>build.platform</name>
                <value>linux32</value>
            </property>
        </activation>
        ...
    </profile>
</profiles>

Then, mvn install should activate the win32 profile because the default value for the build.platform property is win32, while mvn install -Dbuild.platform=linux32 will override the default property setting and use the Linux profile instead.

A: Why don't you use the profile activation by plattform like this:
<project>
    ...
    <profiles>
        <profile>
            <id>win32</id>
            <activation>
                <activeByDefault>false</activeByDefault>
                <os>
                   <name>Windows XP</name>
                                <family>Windows</family>
                                <arch>x86</arch>
                                <version>5.1.2600</version>
                        </os>
            </activation>
            ...
        </profile>
    </profiles>
</project>


text:
Q: Problems with camera view and lighting (openGL & GLUT)
I am trying to implement the bottom subwindow with three torus, but failed to display anything on the subwindow..
main function for subwindow:
instrument_window = glutCreateSubWindow(main_window, GAP, view_height + 3*GAP, 2*(view_width+GAP), INSTRUMENT_HEIGHT);
glutDisplayFunc(display);
//lighting
const GLfloat light_ambient[] = { 0.0f, 0.0f, 0.0f, 1.0f };
const GLfloat light_diffuse[] = { 1.0f, 1.0f, 1.0f, 1.0f };
const GLfloat light_specular[] = { 1.0f, 1.0f, 1.0f, 1.0f };
const GLfloat light_position[] = { 600, 1200, 1200, 0.0f };

const GLfloat mat_ambient[] = { 0.7f, 0.7f, 0.7f, 1.0f };
const GLfloat mat_diffuse[] = { 0.8f, 0.8f, 0.8f, 1.0f };
const GLfloat mat_specular[] = { 1.0f, 1.0f, 1.0f, 1.0f };
const GLfloat high_shininess[] = { 100.0f };

//glClearColor(0.33,0.33,0.33,0.33);
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);

glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);

glEnable(GL_LIGHT0);
glEnable(GL_NORMALIZE);
glEnable(GL_COLOR_MATERIAL);
glEnable(GL_LIGHTING);

glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient);
glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse);
glLightfv(GL_LIGHT0, GL_SPECULAR, light_specular);
glLightfv(GL_LIGHT0, GL_POSITION, light_position);

glMaterialfv(GL_FRONT, GL_AMBIENT, mat_ambient);
glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse);
glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular);
glMaterialfv(GL_FRONT, GL_SHININESS, high_shininess);
//end of lighting

glutMainLoop();

for display function:
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

float width = 2*(GAP+view_width);
float height = INSTRUMENT_HEIGHT;
const float ar = (float) width / (float) height;

//glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glFrustum(width/4.0, width*3.0/4.0, height*3.0/4.0, height/4.0, 2.0, 100.0);
//gluPerspective (160.0, 2*view_width/INSTRUMENT_HEIGHT, 0.1, 1000.0);

glMatrixMode(GL_MODELVIEW);
glLoadIdentity() ;
/*
glMatrixMode(GL_PROJECTION);
// Reset transformations
glLoadIdentity();
gluPerspective (160.0, 2*view_width/INSTRUMENT_HEIGHT, 0.1, 1000.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();

// Draw first
draw (view_width+GAP-400, INSTRUMENT_HEIGHT/2);

// Draw second
draw (view_width+GAP-150, INSTRUMENT_HEIGHT/2);

// Draw third
draw (view_width+GAP+100, INSTRUMENT_HEIGHT/2);

for draw function:
void draw(double cx,double cf)
glColor3f(0.34f,0.34f,0.34f);
glPushMatrix();
glTranslated(0.0, cx, cy);
glRotated(-10, 1.0, 0.0, 0.0);
glutSolidTorus(OUTER_DIAL_RADIUS, OUTER_DIAL_RADIUS+30, 100, 200);
glPopMatrix();
end

really frustrating since it just display nothing and don't know how to debug. Any hints are highly appreciate!!!!

A: To be honest, its difficult to answer this question from the code example supplied. Half of the 'displayFunction' is commented out from the /* so nothing below it will get called. Even then its difficult to deduce the problem since there is little code relating to multiple viewports here. Since you are using fixed pipeline GL look at NeHe which has a good tutorial on employing multiple viewports.
http://nehe.gamedev.net/tutorial/multiple_viewports/20002/
Debugging is the single most important tool a developer has in their arsenal to resolve problems. It would be wise to learn how to do this as it would certainly save you time in the long run and you will find the answers to most (if not all) of your coding problems!


text:
Q: Trouble with a single cell formula being converted to a full column formula I have a Google Sheet that has a Google Form populating the results of many games that a friend and I play.  I have created a new column and added a formula to the top cell in that column and just copied it down the column:
=JOIN(" / ",(FILTER(MyDecks!B$2:B,MyDecks!A$2:A=B5)),(FILTER(HisDecks!B$2:B,HisDecks!A$2:A=C5)))

MyDecks column A is a list of deck names.
MyDecks column B is an attribute of each deck, which is the desired return value.
B5 and C5 are both within columns of the Sheet tab where the formula exists.
The output when using the formula above is something like "M / P", for example.
This formula however, currently has to be copied and pasted, or just extended down to the new cells any time I add another entry with the Google Form.
I would like this formula to be altered so that it will function the same as it does currently, but have it reside within the column head itself so that new entries will just accept and render the formula automatically for the new entries that I create.
I have tried:
=ArrayFormula(IF(ROW(D:D)=4,"Matchup",IF(ISBLANK(C:C),"",JOIN(" / ",(FILTER(MyDecks!B$2:B,MyDecks!A$2:A=B$5:B)),(FILTER(HisDecks!B$2:B,HisDecks!A$2:A=C$5:C))))))

and many other iterations of the same idea, to no avail.  I am a novice and am hoping that there is an easy solution to my issue.

A: use:
={"Matchup"; ARRAYFORMULA(IFNA(
 VLOOKUP(B5:B, JoeDecks!A2:B, 2, 0)&" / "&
 VLOOKUP(C5:C, BryanDecks!A2:B, 2, 0)))}


text:
Q: How to compare two date fields with today's date and time I have to write domain for checking that the present date and time is between two Datetime fields. I wrote the domain, but it shows this error:
DataError: invalid input syntax for type timestamp: "date_from"
LINE 1: ...OM "hr_holidays" WHERE (("hr_holidays"."today" >= 'date_from...
                                             ^

My domain is:
<field name="domain">[('today','>=','date_from'),('today','<=','date_to')]</field>
today = fields.Datetime(default=fields.Datetime.now)`

Please help me.

A: just remove the field of today, is pointless, and, in the xml:
<field name="domain">[('date_from', '>', ((context_today()+relativedelta(days=-1)).strftime('%Y-%m-%d'))), ('date_to', '<', ((context_today()+relativedelta(days=1)).strftime('%Y-%m-%d')))]"</field>

I added the relativedelta too so you can play with dates if you need.


text:
Q: LinkedIn SDK Bitcode iOS 9 LinkedIn SDK for iOS still doesn't support Bitcode. When will that be available? Is there any way to workaround this issue on iOS 9?
So far I've tried to disable Bitcode support on my pbxproj file, but that is not a good solution for the whole project.

A: They just released a compatibility page for iOS 9: https://developer.linkedin.com/docs/ios-sdk#ios9
Really bad it doesn't have support for Bitcode yet, but that's we have for now.

A: From the link provided by Pedro Góes:

Bitcode Support
Bitcode compiling for iOS 9 is supported in version 1.0.6+ of the
  LinkedIn Mobile SDK for iOS.

So the answer is: LinkedIn SDK supports bitcode.
EDIT:
Here is the direct download link of version 1.0.6.
I have just checked it. Bitcode is not supported in 1.0.6 as was stated.


text:
Q: Python- How do I retrieve the multiple values associated with the same key in a dictionary-like json string? OK, so I have json source code from a webpage and, in this source code, the same word("author") is used as the key for multiple values. How can I retrieve all the values for "author"?
E.g.
"author": "SampleMan", "author":"NonSampleMan", "author":"BoringMan"

How do I get Python to return ["SampleMan", "NonSampleMan", "BoringMan"]?

A: You could pass object_pairs_hook to json.loads that will collect the values with same keys to lists:
from collections import defaultdict
import json

s = '{"author": "SampleMan", "author":"NonSampleMan", "author":"BoringMan", "foo":"bar", "bar": [1]}'

def hook(pairs):
    d = defaultdict(list)
    for k, v in pairs:
        d[k].append(v)

    return {k: v if len(v) > 1 else v[0] for k, v in d.items()}

print(json.loads(s, object_pairs_hook=hook))

Output:
{'bar': [1], 'author': ['SampleMan', 'NonSampleMan', 'BoringMan'], 'foo': 'bar'}

In above hook receives list of (key, value) tuples that it stores to defaultdict where values are lists. Once it has iterated over the tuples it will generate result dict where value is list if there were multiple items with given key.
Python documentation has following description of the hook:

object_pairs_hook is an optional function that will be called with the result of any object literal decoded with an ordered list of pairs. The return value of object_pairs_hook will be used instead of the dict. This feature can be used to implement custom decoders that rely on the order that the key and value pairs are decoded (for example, collections.OrderedDict() will remember the order of insertion). If object_hook is also defined, the object_pairs_hook takes priority.


text:
Q: Navigation Sub Menu first a quick thank you to all who have helped me previously :)
The issue I have now is my navigation bar, when it goes to Tablet size it seems to transition the li's to the left, this also happens to my sub menu's.
My second is issue is that my sub menu don't work how them are meant to in mobile size, in mobile size the nav menu doesn't show the sub menus.
When I click on the sub menu there seems to be a transition on the li sub menu color hard to explain but you can see it on the full media size.
Thank You in advance.
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>title</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="description" content="" />
    <meta name="keywords" content="" />
    <meta name="robots" content="index,follow" />
    <link rel="stylesheet" type="text/css" href="styles.css" />

Contact Us

Media

Sermons

Gallery

Blah

Ministries

Evangelism

Youth

Newsletter

Services

About Us

Home

                First Words

                *secondsection secondsection secondsection secondsection secondsection secondsection secondsection
                secondsection secondsection secondsection secondsection secondsection secondsection secondsection
                secondsection secondsection secondsection secondsection secondsection secondsection secondsection
                secondsection secondsection secondsection secondsection secondsection secondsection secondsection
                secondsection secondsection secondsection secondsection secondsection secondsection secondsection
                secondsection secondsection secondsection secondsection secondsection secondsection secondsection
                secondsection secondsection secondsection secondsection secondsection secondsection secondsection
                secondsection secondsection secondsection secondsection secondsection secondsection secondsection
                secondsection secondsection secondsection secondsection secondsection secondsection secondsection

        Footer Footer Footer Footer Footer

        Footer Footer Footer Footer Footer

        Footer Footer Footer Footer Footer

        Footer Footer Footer Footer Footer

        Footer Footer Footer Footer Footer

        Footer Footer Footer Footer Footer

 body{
            width:100%;
            height:100%;
            background:url(images/glasgow.jpg);
            background-position: center center;
            background-repeat:  no-repeat;
            background-attachment: fixed;
            background-size:  cover;
            background-color: #999;

 }

 *{
     padding:0px;
     margin:0px;
 }

 #MainContainer{
width:100%;
height:auto;
 }

 #Header{
     width:100%;
     height:auto;
     position:fixed;
    right: 0;
    top: 0;
    left:0;
    z-index:2;
}

 #share{
     top:102px;
     position:fixed;
     z-index:5;
 }

 /*Top Logo*/
 #Logo
 {
    width:115px;
    height:auto;
    float:left;
    margin:15px;
    cursor:pointer;
    position: fixed;
    z-index:1;
 }

 /*Navigation ul*/
     .nav {
     width:100%;
     background:black;
     line-height:100px;
     position:fixed;
     border-bottom: 2px red solid;
}

 /*Navigation li*/
    nav .nav li{
    list-style-type: none;
    float: right;
    position:relative;
}

#NavBar ul:after{content:"";display:block;clear:both}

 /*Navigation a*/
    nav .nav li a{
    color:white;
    text-decoration: none;
    padding:20px;
}

 /*Navigation a*/
    nav .nav li a:hover{
    color:red;
    text-decoration: none;
    padding:20px;
    background:navy;
    transition:all 0.80s;
}

/*Navigation li HOVER*/
    nav .nav li:hover{
     background:black;
     transition:all 0.80s;
}

/*hide submenu*/
    nav .nav li ul {
    width:auto;
    display: none;
}

/*Show submenu at hover*/
    nav .nav li:hover ul {
    width:auto;
    display:block;
    position:absolute;
    top:100px;
    background-color:black;
    border-bottom:2px red solid;
}

/*Make submenu vertical*/
    nav .nav li ul li{
    width:100%;
    display: block;
    float:none;
    line-height:60px;
}

 /*Navigation sub li* xxxxxxxxxxxxxxxxxxxxxxxx yellow to navy*/
    nav .nav li ul li:hover{
        width:100%;
     color:red;
    text-decoration: none;

    background:yellow;
}

 /*Navigation axxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx */
    nav .nav li ul li a:hover{
        width:auto;
    color:yellow;
    text-decoration: none;
    background-color:pink;

}

.nav-btn{display:none;}

.firstsection{
    width:100%;
    min-height:600px;
    margin-top:100px;
    padding-top:50px;
    background:url(images/1.jpg);
    background-position: center center;
    background-repeat:  no-repeat;
    background-attachment: fixed;
    background-size:  cover;
    color: Black;
}

.secondsection{
        width:100%;
    min-height:500px;
    margin-top:0px;
    padding-top:50px;
    background:url(images/bk2.jpg);
    background-position: center center;
    background-repeat:  no-repeat;
    background-attachment: fixed;
    background-size:  cover;
    color: Black;
}

.firstsection p {
    width:80%;
    margin: auto;
    display:block;
}

.secondsection p
{
    width:80%;
    margin: auto;
    display:block;
}

#WelcomeBox {
  width: 100%;
  height: 300px;
  position: relative;
}

#WelcomeImage {
  max-width: 100%;
  max-height: 200px;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
}

* {box-sizing:border-box}

body {font-family: Verdana,sans-serif;}
    .mySlides {display:none}

/* Slideshow container */
.slideshow-container {
    max-width: 100%;
    position: relative;
    margin: auto;
    margin-top:50px;
    border-top:2px black solid;
    border-bottom:2px black solid;
}

/* Caption text */
.text {
    color: #f2f2f2;
    font-size: 15px;
    padding: 8px 12px;
    position: absolute;
    bottom: 8px;
    width: 100%;
    text-align: center;
}

/* Number text (1/3 etc) */
.numbertext {
    color: #f2f2f2;
    font-size: 12px;
    padding: 8px 12px;
    position: absolute;
    top: 0;
}

/* The dots/bullets/indicators */
.dot {
    height: 13px;
    width: 13px;
    margin: 0 2px;
    background-color:aqua;
    border-radius: 50%;
    display: inline-block;
    transition: background-color 0.6s ease;
}

.active {
    background-color: #717171;
}

/* Fading animation */
.fade {
    -webkit-animation-name: fade;
    -webkit-animation-duration: 1.5s;
    animation-name: fade;
    animation-duration: 1.5s;
}

@-webkit-keyframes fade {
    from {opacity: .4}
    to {opacity: 1}
}

@keyframes fade {
    from {opacity: .4}
    to {opacity: 1}
}

#Footer{
    width:100%;
    background: rgba(255, 255, 255, 0.6);
    color:black;
    font-weight:bold;
    border-top: 2px black solid;
    text-align:center;
}

/* media queries*/

@media only screen and (max-width: 660px)){

    .nav{
    text-align:left;
    display:none;
    }

    .nav > li{
        display:block;
    }

    .nav-btn{
        display:block;
        background-color:#333;
        color:#FFF;
        font-size:40px;
        text-align:center;
        cursor:pointer;

    }

    .nav-btn:before{
        content: "Menu";
    }

}

/*TABLET*/
@media (max-width: 780px){
/*Navigation a*/
    nav .nav li a{
    padding:10px;
}

}

/*MOBILE PHONE*/
@media (max-width: 660px){
    .nav{
    text-align:left;
    display:none;
    }

    .nav > li{
        display:block;
    }

    .nav-btn{
        display:block;
        background-color:#333;
        color:#FFF;
        font-size:40px;
        text-align:center;
        cursor:pointer;

    }

    .nav-btn:before{
        content: "Menu";
    }

}

/* On smaller screens, decrease text size */
@media only screen and (max-width: 300px) {
  .text {font-size: 11px}
}

A: Firstly It's to do with your padding on the hover if you were to set it to "padding: 10px;" then it would not push everything to the left.
Secondly if you add a "z-index: 100;" onto (nav .nav li ul) that will sort your issue.
z-index is basically layers on the page, so by setting it to 100 it will sit over the over content on the hover.
Bad reply i know... My first answer too!
Hope this helps!

A: The reason your links are moving to the left on hover is because you have set this media query:
/*TABLET*/
@media (max-width: 780px){
/*Navigation a*/
    nav .nav li a{
    padding:10px;
}

However you have not set a :hover for padding: 10px; so it is taking padding: 20px; from the previous set style, therefore adding an extra 10px padding to your links and moving them.
Add this to your media query:
nav .nav li a:hover {
padding:10px;
}

For your second problem, when your menu shrinks in size, your submenu links goes underneath the main menu links, and instead of your mouse hovering over submenu, it hovers over the main links stacked up underneath. Add position: relative and z-index to solve this problem :
/*Make submenu vertical*/
  nav .nav li ul li{
  width:100%;
  display: block;
  float:none;
  line-height:60px;
  position: relative; /*add this to make z-index work*/
  z-index: 10; /*give z-index so submenu goes above the main menu links*/
}


text:
Q: How do I save multiple dropdown menus in an application relaunch? I have a program that has multiple dropdown menus and I am running it as a chrome unpacked extension but I cannot get any of the dropdown menus to save after I reopen the app. How can I achieve this? I have already attempted some  solutions but they have not worked. The dropdowns are in a table format.(Note: This is not all of my code but to make it more simple I only included two of my dropdowns). Thanks!

    Name
    ID
    In Use
    Quantity
    Connected to...
      *Based on OUTPUT*
    Comment

1/4 Inch Audio Cables
1-2
--
2
<select align="center" id="master01dropdown">
  <option value="option01">option01</option>
  <option value="option02">option02</option>
  <option value="option03">option03</option>
  <option value="option04">option04</option>
  <option value="option05">option05</option>
  <option value="option06">option06</option>
  <option value="Null">Null</option>
  <option value="Not Defined">Not Defined</option>
  <option value="Not in Use">Not in Use</option>
 </select>

6 feet
1
<input align="center" checked type="checkbox" name="void" value="In use">

1
<select id="cable01dropdown">
  <option value="option01">option01</option>
  <option value="option03">option02</option>
  <option value="option03">option03</option>
  <option value="option04">option04</option>
  <option value="option06">option05</option>
  <option value="option07">option06</option>
  <option value="Null">Null</option>
  <option value="Not Defined">Not Defined</option>
  <option value="Not in Use">Not in Use</option>
 </select>

I added the suggested code and it still will not work. *Note: I am not very good with JavaScript.*

    chrome.storage.sync.set({ items: 'master01,cable01,cable02'});
chrome.storage.sync.get('items', function(data) {
     var items = data.items.split(',');
     items[0] => (master01)
     items[1] => (cable01)
     items[2] => (cable02)
});

A: Store items in chrome storage:
Suppose you save comma separated items
chrome.storage.sync.set({ items: 'item1,item2,item3,item4'});

fetch it using:
chrome.storage.sync.get('items', function(data) {
     var items = data.items.split(',');
     // items[0] => item1
     // items[1] => item2
});

A: I'll detail how to save and load an example options menu, containing a textbox and a checkbox. In your example, you'll want to use document.getElementById('master01dropdown').value in your save.
Setting up
First, create a file options.html in the root of the project, containing your form.
Next, make sure this options page is registered in your manifest.json:
"options_ui": {
    "page": "options.html",
    "chrome_style": true
}

At the bottom of your options.html, before , include a JavaScript file:

Your form should also include a Save button somewhere with id save:
<button id="save">Save</button>

Saving
Inside your /js/options.js file, register the save() function to run when your save button is clicked:
document.getElementById('save').addEventListener('click', save);

Your save() function should use Chrome Storage to save every element from your form. For example, to save a textbox and a tickbox:
function save() {
    var sitesToSave = document.getElementById('sites').value;
    var displayPopup = document.getElementById('popup').checked;
    chrome.storage.sync.set({
        sites: sitesToSave,
        popup: displayPopup
    }, displaySavedMessage);
}

Loading
Inside your /js/options.js file again, register the load() function when your form is loaded:
document.addEventListener('DOMContentLoaded', load);

Now set those form fields from earlier with the saved values (and provide default values), again using Chrome Storage:
function load() {
    chrome.storage.sync.get({
        sites: 'supersecretsite.com',
        popup: false
    }, function(items) {
        document.getElementById('sites').value = items.sites;
        document.getElementById('popup').checked = items.popup;
    });
}

Done! Settings can now be saved and loaded.
All code in this answer is from a very simple example Chrome Extension I made, which also has an accompanying detailed tutorial.


text:
Q: Temporarily storing data in array while wiping source We are using Core Data to store information locally on our iOS App. When we update information remotely, the app deletes the local data in the core data, and replaces it with the new. This is the way we designed it, and it works perfectly. However, now we need some of the data to stay. We have included some user-editable fields, and need one of the entities to have some of the old information. I tried to make a fetch-request for the entire entity, store them in an array, and delete the entity, then update to new data, and then push over the old data from the stored array. However, all the data on the array gets wiped when I clear out the Core Data.. We have tried with NSArray, NSMutableArray, and initializing with initWithArray:a copyItems:YES.. How can we store information in an array and then delete the source?

A: Save the data from your array using NSUserDefaults
[[NSUserDefaults standardUserDefaults] setObject:<#(id)#> forKey:<#(NSString *)#>];

Pull the Data using
NSString *myString = [[NSUserDefaults standardUserDefaults] objectForKey:<#(NSString *)#>];


text:
Q: MySQLi Query To Excel Generating Two Blank Row I am trying to generate excel file for my dynamic query using below codes.
$cname = $_POST["cname"];
        $cnote = $_POST["cnote"];
        $ccondition = $_POST['sql'];
        $crange = $_POST['start'] . "-" . $_POST['end'];
        $sql_query = $ccondition;

        $filename = "export".date('Ymd') . ".xls";
        header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        header("Content-Disposition: attachment; filename=\"$filename\"");
        $show_coloumn = false;

        $resultset = mysqli_query($mysqli, $sql_query) or die("database error:". mysqli_error($mysqli));

        $rowcount=mysqli_num_rows($resultset);

        $developer_records = array();
        while( $rows = mysqli_fetch_assoc($resultset) ) {
        $developer_records[] = $rows;
        }

        if(!empty($developer_records)) {
            foreach($developer_records as $record) {
                if(!$show_coloumn) {

                    echo implode("\t", array_keys($record)) . "\n";
                    $show_coloumn = true;
                }
                echo implode("\t", array_values($record)) . "\n";
            }
        }

I am facing two issue in it.
1) When I try to open it in excel 2016, its giving error like below but when I press yes its opening file.

2) each my exported excel file have two blank row on top before header row, I don't know from where its coming and how I can fix it.

I have searched lot for it but I have not found any working solution for it. Let me know if someone can help me for solve the issues. Thanks


text:
Q: How to sync an invitation on Iphone to Google Calendar I have sync setup between my Google Calendar and my Iphone5 calendar.  This works perfectly in both directions.
Yesterday my squash buddy created an event in his own (Iphone) calendar and invited me.  I accepted this and it now shops up in my own (Iphone) calendar.
However, it doesn't seem to sync to Google Calendar. This is probably caused by the fact that it is somehow still 'his' event and not mine?
Is there any way to get this event to also sync to my Google Calendar?


text:
Q: Fixing data source of same layer in multiple MXDs? I have this one specific layer in a bunch of mxd files with a broken data source. I am working on a script to automate fixing the data source. I am having trouble getting it to loop through a folder and fix the layer on all mxd files in that same folder.
This is the script I have so far:
#Import modules
import arcpy
from arcpy import env

#Put file path for the folder containing mxds, where I have my sample file path
env.workspace = r"G:\Geomatics\Map Requests\2017-07-24_TrailClosures"

#Looping through all mxd documents, list layers and replace those layers MRGTrails layer with proper data source
for file in arcpy.ListFiles("*.mxd"):
    mxd = arcpy.mapping.MapDocument(file)
    df = arcpy.mapping.ListDataFrames("*.mxd", "Layers")[0]
    for lyr in arcpy.mapping.ListLayers(mxd, "*", df):
      if lyr.name == "Trails":
        lyr.replaceDataSource(r'G:\Geomatics\Data\Regional\MRG.gdb', "FILEGDB_WORKSPACE", "Trails_Sentiers", validate=False)

    mxd.save()

A: You had a few minor typos. Honestly, this question will probably get closed for being unique to your particular set of mistakes. But here's a solution, with comments describing changes from the original:
import arcpy
from arcpy import env

env.workspace = r"G:\Geomatics\Map Requests\2017-07-24_TrailClosures"

for file in arcpy.ListFiles("*.mxd"):
    mxd = arcpy.mapping.MapDocument(file) # Changed 'files' to file
    # Iterate over all data frames, because what if one has a different name...or if a map has multiple data frames
    # And pass the mxd object to the function--not the mxd wildcard
    for df in arcpy.mapping.ListDataFrames(mxd):
        for lyr in arcpy.mapping.ListLayers(mxd, "*", df):
            if lyr.name == "Trails":
                lyr.replaceDataSource(r'G:\Geomatics\Data\Regional\MRG.gdb', "FILEGDB_WORKSPACE", "Trails_Sentiers", validate=False)
    mxd.save()


text:
Q: Как использовать repeatCount в Android AnimationSet? Как использовать repeatCount  в Android AnimationSet?
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">

    <scale
        android:duration="900"
        android:fromXScale="0"
        android:fromYScale="0"
        android:toXScale="1"
        android:toYScale="1"
        android:pivotX="50%"
        android:pivotY="50%"/>

    <scale
        android:startOffset="1000"
        android:duration="200"
        android:fromXScale="1"
        android:fromYScale="1"
        android:toXScale="2"
        android:toYScale="2"
        android:pivotX="50%"
        android:pivotY="50%"/>

    <alpha
        android:startOffset="500"
        android:duration="700"
        android:fromAlpha="1"
        android:toAlpha="0"/>
</set>

Почему то в Set repeat не работает. Как именно надо написать чтобы заработало?

A: попробуйте воспользоваться таким вот классом слушателя анимации
public class AnimationRepeater implements Animation.AnimationListener
{
private View view;
private Animation animation;
private int count;

public AnimationRepeater(View view, Animation animation)
{
    this.view = view;
    this.animation = animation;
    this.count = -1;
}

public AnimationRepeater(View view, Animation animation, int count)
{
    this.view = view;
    this.animation = animation;
    this.count = count;
}

public void start()
{
    this.view.startAnimation(this.animation);
    this.animation.setAnimationListener(this);
}

@Override
public void onAnimationStart(Animation animation) { }

@Override
public void onAnimationEnd(Animation animation)
{
    if (this.count == -1)
        this.view.startAnimation(animation);
    else
    {
        if (count - 1 >= 0)
        {
            this.animation.start();
            count --;
        }
    }
}

@Override
public void onAnimationRepeat(Animation animation) { }
}

для бесконечного цикла использовать:
Animation a = AnimationUtils(Context, R.anim.animation);
new AnimationRepeater(View, a).start();

если необходимо кстановить количество повторов:
Animation a = AnimationUtils(Context, R.anim.animation);
new AnimationRepeater(View, a, int N).start();

где N - количество повторов анимаций

A: <scale
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="1000"
    android:repeatCount="infinite"
    android:repeatMode="reverse"
    android:fromXScale="0.75"
    android:fromYScale="0.75"
    android:toXScale="1"
    android:toYScale="1"
    android:pivotX="50%"
    android:pivotY="50%" />

IDE давно не реагирует на 2 тега в схеме, но они инфлейтятся, просто пропишите ручками, как выше.
android:repeatCount
android:repeatMode

Анимашка будет работать что-то типо wave эффекта, сами запустите. Но и вариант указать сеттерами и геттерами, тоже все работаете, если анимашка не поломана.


text:
Q: Working with optionals in dartjs Newbie in dart js. OK, I understand the concept of optional parameters, very similar to C#, but I am not quite sure why the following gives the result it does:
void main() {
  print(SayInFunction('Joe', suffix : ' Sir'));
}

String SayInFunction(name, {suffix : " Junior"}) => SayHello(name + suffix);

String SayHello(name, {suffix : " Senior"}) => ('Hello $name $suffix');

Here is the return:
Hello Joe Sir  Senior

Why am I wrong in thinking it should be:
Hello Joe Sir

PS: If it has to do with the $signs, how should I restructure the SayHello function to return 'Hello Joe Sir' ?
Answer:
String SayInFunction(name, {suffix : " Junior"}) => SayHello(name, suffix: suffix);

A: You would need to call SayHello(name, suffix: suffix); to get the desired result.
You effectively call SayHello('Joe Sir') and because you don't provide a suffix SayHello takes the default ' Senior'


text:
Q: SQLite Delete Slow I got a SQLite database (First project with SQLite) where I need to delete a bulk of records at once, this is like 14.000 records. The quere is as follows (I changed the names for better read) :
delete from table_1 where table_2_id in (
    select id from table_2 where table_3_id in (
        select id from table_3
        where (deleted = 1 or
               table_4_id in (select id from table_4 where deleted = 1))));

This query takes like 8 minutes to delete. But when I do
select * from table_1 where table_2_id in (
    select id from table_2 where table_3_id in (
        select id from table_3
        where (deleted = 1 or
               table_4_id in (select id from table_4 where deleted = 1))));

it gives me a result in 3 seconds.
I tried using a transaction, cache size, journal mode, but I do not get it to work to get a better performance. What am I missing?

A: I had the same problem. Solution was to divide it to many smaller chunks, and do it again and again until no more rows are affected (sqlite3_changes() returns zero).
Of course this way the operation is not completed sooner, but the table is not locked for too long continuously.
Hope this helps someone.

A: It was 30MB and also turned of the virusscanner, but without any result. So I tried multiple things, I copied the database, delete all foreign keys and tried again, and it was much faster. So then I put an index on all foreign keys and it also deleted fast. So this was solution, but I do not know why it then select fast and deletes super slow. But hope this helps anyone!

A: Do you have an index on any of the columns involved? If so, consider dropping it for a large delete and then rebuilding it. If you don't, try adding one.

A: I have a script in python to delete entries in sqLite DB, lfl is a list of files that I want to delete from DB, in statement speeds process a lot:
while len(lfl)>0:
    print ("Deleting entries in DB: ",len(lfl))
    sql="""delete from md5t where file in ('%s')"""%('\',\''.join(tuple(lfl[:500])))
    cursor.execute(sql)
    db.commit()
    del lfl[:500]


text:
Q: Why does writing a string to a file and then reading the same file as a string result in different strings? I'm trying to write some code to save photo data to a file.
I read in the photo data, which comes in as base64 string from react native (Expo), and then I decode it. I immediately write that decoded string to a file.
When I read that file that should contain all of the photo data, all I'm getting back are 4 characters when I expect many megabytes-worth of characters.
Does anybody know how to write this decoded base64 string to a file using Expo? Below is my code ...
  const fileUri = `${directoryPath}/${today.getTime()}/${fileName}`;

  // this reads us the base64 encoded image data
  const imageString = await FileSystem.readAsStringAsync(
    image.uri,
    { encoding: FileSystem.EncodingType.Base64 }
  );

  const fooString = Base64.decode(imageString);

  // write the decoded photo data to a file
  await FileSystem.writeAsStringAsync(fileUri, fooString);

  // read back the file so we can make sure all the data was written
  const blah = await FileSystem.readAsStringAsync(fileUri);

  const photoInfo = await FileSystem.getInfoAsync(fileUri);

  console.log({
    fileUri,
    fooStringLength: fooString.length,
    blahLength: blah.length,
    equals: blah === fooString,
    photoInfo
  });

You can see it's pretty straightforward, so I must be missing something? Below is the output of that console.log ...
Object {
  "blahLength": 4,
  "equals": false,
  "fileUri": "file:///var/mobile/Containers/Data/Application/33EB7A6F-AA1A-42BF-B252-9A5088A906C6/Documents/ExponentExperienceData/%2540anonymous%252FWIB-mobile-12902e68-9c57-4230-a3df-aaa355c3edf1/20220328184945/1648511392902/Right.jpg.enc",
  "fooStringLength": 2953317,
  "photoInfo": Object {
    "exists": true,
    "isDirectory": false,
    "modificationTime": 1648511394.334474,
    "size": 4415423,
    "uri": "file:///var/mobile/Containers/Data/Application/33EB7A6F-AA1A-42BF-B252-9A5088A906C6/Documents/ExponentExperienceData/%2540anonymous%252FWIB-mobile-12902e68-9c57-4230-a3df-aaa355c3edf1/20220328184945/1648511392902/Right.jpg.enc",
  },
}

You can see the lengths don't match. Also, if I print out both fooString and blah, which are the before and after strings for comparison, the fooString looks correct to me and how I expect it to look but the blah is only like 4 characters worth of data. Below is the incorrect content of blah string and the file ...

I modified an existing snack to show my situation. This snack gives the option to take a photo or select an existing photo. I put my code in the select an existing photo from the photo library handler. This snack shows that when I write my data to a file and then read it back the data does not match. Any ideas why?
https://snack.expo.dev/@rcoleils/camera

A: What you're actually saving is the raw binary data that comes from the original file, then reading back. Problem is that it isn't really supported on Expo with writeAsStringAsync and readAsStringAsync, as it's not really a string but arbitrary binary data.
There is a bug report on this here: https://github.com/expo/expo/issues/2453. So far it has been ignored with the only workaround of saving the base64 representation of the original. While this could work, it renders the file useless for any other program, increases storage needs by 33% for it and requires special decoding before using.


text:
Q: How do you validate the token is correct in an app launched from a main app? We want to build a main React App which after login shows a number of apps (list of apps the users has access to once authenticated). When the user clicks on one of the apps, the token from the main app is sent to the other app.
How will the second app know the token is valid?
Do the apps need to be on the same domain for this to work?
Also each app will have its own authorization (i.e. what the user can do in each app), would the token contain all this information or can we get this latter for each app using the same token?
Sorry for the large number of questions.
I am new to identity server and openID connect so any pointers would be great.
Thanks

A: Firstly, you should not pass tokens between your apps. All of your apps should be separate client, but the common thing they will have is the same central authority url (your identity server) that they would use to retrieve tokens. This would all be seamless from user's point of view due to the single sign on achieved on the central authority using cookie authentication - once the user logs in to your main app, whenever other apps redirect user to get the token, they will bypass login page due to cookie auth and would go directly into consent page (can also skip consent page via setting client property RequireConsent to false which is commonly done for first party apps).
To answer some of your questions:

How will the second app know the token is valid?

Well this is not really needed if you don't pass around token between apps, but technically it could verify the token via its signature or using introspection endpoint.

Do the apps need to be on the same domain for this to work?

They don't have to be on same domain.

would the token contain all this information or can we get this latter
  for each app using the same token?

The claims that the token contains is largely controlled based on the scope that the client requests (at least by default). So if you have each app requesting their own token, then it would have to request all the scopes that it is interested on. A lot of this behaviour can be overridden and extended due to the insane flexibility of Identity Server 4 so almost always you will have a way to accomplish what you want.


text:
Q: Сделать navigation bar видимым на одном экране и невидимым на другом Создал свой Search bar, при активации которого navigation bar становится hiden. Но как только перехожу на следующий экран, он соответственно остается спрятан, а нужно чтобы не был. Делать его не hiden с помощью методов контроллера: viewDidAppear и тд - не вариант, так как nav бар будет резко появляться на предыдущем экране. Вот так это выглядит как только перехожу на след экран.

А нужно, чтобы было был виден nav bar

Ну и соответственно то, для чего все это делалось (почему не использовал стандартный эпловский серч бар) - в момент свайпа на предыдущий экран, серч бар должен находиться на предыдущем экране, а не залезать поверх нынешнего, с которого переход еще не закончен.
То есть на первом экране он получается спрятан, а на втором - нет. И это все одновременно. Должно получиться примерно как в приложении Почта:

В приложении фото, как мне кажется, в этот момент на последнем экране не nav bar, а просто UIView с кнопками, но я не уверен в этом, да и может есть более приятные способы решить эту проблему, чем отрисовывать лишнюю вьюшку..

A: А зачем Вы скрываете Navigation bar? Просто когда начинается поиск помещаете SearchBar на NavigationBar:
navigationItem.titleView = searchBar

Результат:


text:
Q: How do you produce iron? So this is the first time I've played the Kittens Game and I have no idea what I have to do to get iron? I need it for some upgrades but so far I don't get how to produce it.
Help??

A: Iron is produced by Smelters from Minerals and Wood. Smelters can be built once you've discovered Metal Working. You also need to research Construction to unlock Iron.

A: To make your first iron:
1) Research [Science] 'Mining' to unlock the 'mine' building.
2) Research [Science] 'Metal Working' to unlock the 'smelter' building.
3) Assign at least one kitten as a miner to produce minerals.
4) Assign at least one kitten as a woodcutter to produce wood (fuel).
5) Build a smelter and turn it on.
6) A smelter consumes minerals and wood and produces iron.


text:
Q: Calculating a running mean of a generic type I'm trying to do something that would be easy if I could use type classes in F#.
I want to be able to calculate a running average on an arbitrary type upon which I have defined addition, scalar multiplication and scalar division.  This is my non-compiling attempt so far:
let updateMean<'a when 'a : (static member (*) : 'a -> float32 -> 'a) and 'a : (static member (/) : 'a -> float32 -> 'a) and 'a : (static member (+) : 'a -> 'a -> 'a)> (newObservation : 'a) (currentMean : 'a) (currentNumberOfRecords : int) =
    (newObservation + (currentMean * (currentNumberOfRecords |> float32))) / float32 (1 + currentNumberOfRecords)

and this is the confusing error message:
A type parameter is missing a constraint 'when ( ^a or  ^?766914) : (static member ( + ) :  ^a *  ^?766914 ->  ^?766915)'

A: You can get a bit further if you add inline (which is a requirement for using static member constraints) and rename the static variable from 'a to ^a (which is a syntax used by statically resolved type parameters) and remove the explicit specification of constraints. The compiler will then attempt to infer the type of the constraints based on the code (which makes it a bit more usable):
let inline updateMean (newObservation : ^a) (currentMean : ^a)
                      (currentNumberOfRecords : int) =
    (newObservation + (currentMean * (currentNumberOfRecords |> float32))) /
       (float32 (1 + currentNumberOfRecords))

However, this still does not work, because you are restricting currentMean to float32 - in general, the compiler requires that both of the parameters of an operator have the same type. You can keep the currentNumberOfRecords as a value of the same type - then the only tricky part is adding one, which can be done using LanguagePrimitives.GenericOne:
let inline updateMean newObservation currentMean currentNumberOfRecords =
    (newObservation + (currentMean * currentNumberOfRecords)) /
      (LanguagePrimitives.GenericOne + currentNumberOfRecords)

This works nicely, but I would probably use a slightly different approach and keep the total sum together with the total count (and then just divide them to get the mean - this will probably have better numerical properties as you avoid repeated rounding):
let inline updateState (currentSum, currentCount) newObservation =
  (currentSum + newObservation, currentCount + 1)

let inline currentMean (currentSum, currentCount) =
  LanguagePrimitives.DivideByInt currentSum currentCount

The trick is to use operations from the LanguagePrimitives module and let the F# compiler figure out the type constraints automatically (because they are pretty ugly).


text:
Q: replacing jruby script path with some other abstraction notion other than file paths I am just guessing but would like some commentary about how to set my own ruby script loader rather than just letting the runtime take file paths.
I have not tried to load scripts, but from reading it would appear the "script path" that is searched is ...
ScriptingContainer {

   /**
 * Changes a list of load paths Ruby scripts/libraries. The default value
 * is an empty array. If no paths is given, the list is created from
 * java.class.path System property. This value can be set by
 * org.jruby.embed.class.path System property, also.
 * Call this method before you use put/get, runScriptlet, and parse methods so that
 * the given paths will be used.
 *
 * @since JRuby 1.5.0.
 *
 * @param paths a new list of load paths.
 */
public void setLoadPaths(List<String> paths) {
    provider.getRubyInstanceConfig().setLoadPaths(paths);
}
}

My understanding is the runtime expects file paths, i would like the ability to load scripts from my own provider such as a Apache commons Virtual FileSystem.


text:
Q: WPF DispatcherTimer not stop working once I started it more than once I want to make a timer to update the UI counter using DispatcherTimer class.
Here's my code:
private static DispatcherTimer timer;
private static int count;

//counter is TextBlock in WPF xaml

private void countdownBtn_Click(object sender, RoutedEventArgs e)
{
    count = 3;
    timer = new DispatcherTimer();
    timer.Interval = new TimeSpan(0, 0, 0, 0, 500);
    timer.Tick += CountDown;
    timer.Start();
}

private void CountDown(object sender, EventArgs e)
{
    //if counter becomes 0, stop the counter
    if (count <= 0)
    {
        counter.Visibility = Visibility.Hidden;
        timer.Stop();
        return;
    }

    if (counter.Visibility == Visibility.Hidden)
    {
        counter.Text = count.ToString();
        counter.Visibility = Visibility.Visible;
    }
    else
    {
        count--;
        counter.Visibility = Visibility.Hidden;
    }
}

This code works fine if I click the button one time and wait it to complete its task for 3 seconds. But if I clicked the button 2 times in a row, it will continue following this:

*

*If I click the button, the counter will be updated with more than 1 threads (make it visible and hidden faster than usual).

*It will continue working even after timer.Stop() is executed ( it will enter loop CountDown -> if(count<=0) -> timer.Stop() -> return; -> CountDown -> if(count<=0) -> ... ).

And if I want to do something after the timer is stopped, where should I modify my code?

A: Every time you click the button a new DispatcherTimer is created with the previous ones still running.
You should stop and then dispose the old timer before create new ones.


text:
Q: Can't convert my C++ PELoader from x86 to x64 I have this PELoader project which basically loads a PE into memory. and it's working fine with x86 PEs but when tried to make it work with x64s I got stuck.
What I've tried is:

*

*I replaced some of the data types with the x64 equivalent such as
IMAGE_NT_HEADERS* with IMAGE_NT_HEADERS64*

*Even though it automatically uses the right one when you switch the
architecture. but didn't make any difference.

*I also replaced this casting (DWORD) with
reinterpret_cast<DWORD_PTR> and the exception changed. I guess it
was necessary but not enough.

*I tried making data types bigger. and it solved some but I still have
bad reallocation.

Update 2
I just found out that the problem is in the reallocation. (check the code)
I've fixed an Error before I discovered this and it was in the data type that stores the base address from the optional header.
it was stored in a DWORD but I've changed it to char* and problem solved.
so I think the Error is in the casting or some data types of some values.
Here is the relocation Code:
/** Handle relocations **/

    //this is how much we shifted the ImageBase
    DWORD_PTR delta_VA_reloc = (reinterpret_cast<DWORD_PTR>(ImageBase)) - p_NT_HDR->OptionalHeader.ImageBase;

    // if there is a relocation table, and we actually shitfted the ImageBase
    if (data_directory[IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress != 0 && delta_VA_reloc != 0) {
        printf("\n[*] The allocated address is not the prefered address, started relocating\n");
        //calculate the relocation table address
        IMAGE_BASE_RELOCATION* p_reloc = (IMAGE_BASE_RELOCATION*)(ImageBase + data_directory[IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress);

        //once again, a null terminated array
        while (p_reloc->VirtualAddress != 0) {
            // how many relocations in this block
            // ie the total size, minus the size of the "header", divided by 2 (those are words, so 2 bytes for each)
            //std::cout << sizeof(WORD) << "\n"; sizeof word is 2
            DWORD size = (p_reloc->SizeOfBlock - sizeof(IMAGE_BASE_RELOCATION)) / sizeof(WORD);

            // the first relocation element in the block, right after the header (using pointer arithmetic again)
            WORD* reloc = (WORD*)(p_reloc + 1);
            for (int i = 0; i < size; ++i) {

                //type is the first 4 bits of the relocation word
                int type = reloc[i] >> 12;

                // offset is the last 12 bits
                unsigned long long int offset = reloc[i] & 0x0fff;
                //printf("--------------- %#llx\n", offset);

                //this is the address we are going to change
                DWORD* change_addr = (DWORD*)(ImageBase + p_reloc->VirtualAddress + offset);

                // there is only one type used that needs to make a change
                // When you relocate you should look if the flag HIGHT_LOW is active for PE32 and DIR64 for PE32+
                switch (type) {
                case IMAGE_REL_BASED_HIGHLOW://for x86
                    *change_addr += delta_VA_reloc;
                    break;
                case IMAGE_REL_BASED_DIR64://for x64
                    *change_addr += delta_VA_reloc;
                    break;
                default:
                    break;
                }
            }

            // switch to the next relocation block, based on the size
            p_reloc = (IMAGE_BASE_RELOCATION*)((reinterpret_cast<DWORD_PTR>(p_reloc)) + p_reloc->SizeOfBlock);
        }
    }

A: I found the problem:
I don't know exactly but when using DWORD* in this line:
DWORD* change_addr = (DWORD*)(ImageBase + p_reloc->VirtualAddress + offset);

and I printed the chnage_addr, in x86 it prints the whole 6 bytes that represents the address.
but in x64 it only prints 4 bytes. I think in windows DWORD* is smaller in x64.
So the solution I found is using long data types
unsigned long long int* change_addr = (unsigned long long int*)(ImageBase + p_reloc->VirtualAddress + offset);