text:
Q: Não to conseguindo deletar no banco de dados Firebase com Flutter Não to conseguindo deletar um dado no Firebase pessoal.
Criei um CRUD
Já to conectado com o Firebase, o projeto ta configurado, e consegui adicionar alguns dados. Mas não to conseguindo deletar. Não ta funcionando.
Segue abaixo meu código
Classe Model
advogado.dart
class Advogado {
  String id;
  String nome;
  String email;
  String telefone;
  String endereco;
  String numeroOAB;

  Advogado(
      {this.id,
      this.nome,
      this.email,
      this.telefone,
      this.endereco,
      this.numeroOAB});

  Advogado.fromMap(DocumentSnapshot document) {
    id = document.id;
    nome = document.data()['nome'];
    email = document.data()['email'];
    telefone = document.data()['telefone'];
    endereco = document.data()['endereco'];
    numeroOAB = document.data()['numeroOAB'];
  }

  Map toMap() {
    var map = <String, dynamic>{};
    map['nome'] = nome;
    map['email'] = email;
    map['telefone'] = telefone;
    map['endereco'] = endereco;
    map['numeroOAB'] = numeroOAB;

    return map;
  }

  String documentId() => id;
}

Classe CRUD
dbadvogad.dart
class DBAdvogado with ChangeNotifier {
  DBAdvogado({this.fromMap, this.collection});

  final Advogado Function(DocumentSnapshot document) fromMap;
  Advogado advogado;

  String collection;

  CollectionReference collectionReference =
      FirebaseFirestore.instance.collection('advogado');

  Future<String> add(Advogado advogado) async {
    var collection = collectionReference;
    var document = await collection.add(advogado.toMap());
    return document.id;
  }

  Future<void> update(Advogado advogado) async {
    var collection = collectionReference;
    await collection.doc(advogado.documentId()).update(advogado.toMap());
  }

  Future<void> delete(String documentId) async {
    var collection = collectionReference;
    await collection.doc(documentId).delete();
  }

  Future<Advogado> getById(String documentId) async {
    var collection = collectionReference;
    var snapshot = await collection.doc(documentId).get();
    return fromMap(snapshot);
  }

  Future<List<Advogado>> getAll() async {
    var collection = collectionReference;
    List<Advogado> list = [];
    var querySnapshot = await collection.get();
    querySnapshot.docs.forEach((element) {
      list.add(fromMap(element));
    });

    return list;
  }

  CollectionReference filter() {
    return collectionReference;
  }

  List<Advogado> fromSnapshotToAdvogadoList(
      List<DocumentSnapshot> documentList) {
    List<Advogado> list = [];
    documentList.forEach((element) {
      list.add(fromMap(element));
    });
    return list;
  }
}

Lista que vai aparecer os dados para remover ou editar
lista_advogado.dart
class ListaAdvogado extends StatelessWidget {

@override
  Widget build(BuildContext context) {
    var snapshots =
        FirebaseFirestore.instance.collection('advogado').snapshots();

    Advogado advogado = Advogado();
    DBAdvogado advogados = DBAdvogado();
    String documentId;

    return Scaffold(
      appBar: AppBar(
        title: Text('Lista de Advogados'),
        actions: <Widget>[
          IconButton(
            icon: Icon(Icons.add),
            onPressed: () {
              Navigator.of(context).pushNamed(
                RotasApp.FORM_ADVOGADO,
              );
            },
          ),
        ],
      ),
      body: StreamBuilder(
        stream: snapshots,
        builder: (
          BuildContext context,
          AsyncSnapshot<QuerySnapshot> snapshot,
        ) {
          if (snapshot.hasError) {
            return Center(child: Text('Erro: ${snapshot.error}'));
          }

          if (snapshot.connectionState == ConnectionState.waiting) {
            return Center(child: CircularProgressIndicator());
          }

          if (snapshot.data.docs.length == 0) {
            return Center(child: Text('Nenhuma tarefa ainda'));
          }

          return ListView.builder(
              itemCount: snapshot.data.docs.length,
              itemBuilder: (ctx, i) {
                var lista = snapshot.data.docs[i].data();
                return ListTile(
                  leading: CircleAvatar(child: Icon(Icons.person)),
                  title: Text(lista['nome']),
                  subtitle: Text(lista['email']),
                  trailing: Container(
                    width: 100,
                    child: Row(
                      children: <Widget>[
                        IconButton(
                          icon: Icon(Icons.edit),
                          color: Colors.green,
                          onPressed: () {
                            Navigator.of(context).pushNamed(
                              RotasApp.FORM_ADVOGADO,
                              arguments: advogado,
                              //advogado
                            );
                          },
                        ),
                        IconButton(
                          icon: Icon(Icons.delete),
                          color: Colors.red,
                          onPressed: () {
                            showDialog(
                              context: context,
                              builder: (ctx) => AlertDialog(
                                title: Text('Excluir Advogado'),
                                content: Text('Tem certeza???'),
                                actions: <Widget>[
                                  FlatButton(
                                    child: Text('Não'),
                                    onPressed: () =>
                                        Navigator.of(context).pop(false),
                                  ),
                                  FlatButton(
                                    child: Text('Sim'),
                                    onPressed: () =>
                                        Navigator.of(context).pop(true),
                                  ),
                                ],
                              ),
                            ).then((confirmed) async {
                              if (confirmed) {
                                await advogados.delete(documentId);                                  }
                            });
                          },
                        ),
                      ],
                    ),
                  ),
                );
              });
        },
      ),
    );
  }
}

A: Você está passando para a função delete um documentId em branco, pois em nenhum ponto você está alimentando esta propriedade...
Aqui nesse ponto:
await advogados.delete(documentId);
Altere para:

Se estiver com o package do firestore na versão mais recente
await advogados.delete(snapshot.data.docs[i].id);

Se estiver com o package do firestore em uma versão antiga
await advogados.delete(snapshot.data.docs[i].documentId);


text:
Q: Unable to launch Chrome Desktop App
*

*I've created my first Chrome Desktop App from https://developer.chrome.com/apps/first_app

*There is instruction to launch the application using parameter line --load-and-launch-app=/path/to/app/ at the bottom section of the above help page.

*So I created a Chrome shortcut and added the line "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"  --load-and-launch-app=/T:/Chrome Projects/Hello World"

*But unfortunately, it isn't working and giving error saying missing manifest though it isn't Error Screenshot

*I can run the app normally if i execute it from chrome browser>Apps section

*Also there is no issue if i run the app using ID "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"  --profile-directory="Profile 4" --app-id=geipneggnldmjggcpfhniohfnfnccopo

*The App is saved at the folder T:\Chrome Projects\Hello World on my system

Any help is much appreciated
Regards,

A: The correct and full code is:
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --load-and-launch-app="T:\Chrome Projects\Hello World"

redpajama_set_name: RedPajamaStackExchange


text:
Q: cold boot : the host gpu has changed I am using Android Studio to debug my application,when I install my app in the AVD pixel2 API 21, it get following error
cold boot : the host gpu has changed
but before this, I did not change anything.
I tried to change the AVD boot option to cold boot, and the error disappeared.
I want to know what is the difference between cold boot and quick boot and why this error occurs ?
thank you


text:
Q: Why is contains(text(), "string" ) not working in XPath? I have written this expression //*[contains(text(), "Brand:" )] for the below HTML code.

Informazioni prodotto

  Brand: Ava
 SKU: 8002910009960
 Peso Lordo: 0.471 kg
 Dimensioni: 44.00 × 145.00 × 153.00 mm

    AVA BUCATO A MANO E2 GR.380

The xpath that I have written is not working I want to select Node that contains text Brand:. Can someone tell me my mistake?

A: Your XPath,
//*[contains(text(), "Brand:")]

in XPath 1.0 will select all elements whose first text node child contains a "Brand:" substring.  In XPath 2.0 it is an error to call contains() with a sequence of more than one item as the first argument.
This XPath,
//*[text()[contains(., "Brand:")]]

will select all elements with a text node child whose string value contains a "Brand:" substring.
See also

*

*XPath 1.0 vs 2.0+ different contains() behavior explanation

*Testing text() nodes vs string values in XPath


text:
Q: How to make Highlight from Click-Drag on the Panel I want to make a feature that when the user click and drag the cursor on the Panel, it will show a temporary highlighted rectangle. And when the user releases his drag, the rectangle will disappear immediately.
This feature would be similar like when you click and drag on your Desktop:

I have known about MouseMove, but it still makes me somehow confuse. I would appreciate any help. Thank you in advance.
Edited:
Ok, I have found the way with the MouseMove now, and here is my code:
using System.Drawing;
using System.Windows.Forms;

namespace WindowsFormsApplication7
{
public partial class Form1 : Form
{
    int x;
    int y;
    int width;
    int height;
    public Form1()
    {
        InitializeComponent();
    }

    private void pictureBox1_Paint(object sender, PaintEventArgs e)
    {
        Rectangle ee = new Rectangle(x, y, width, height);
        using (Pen pen = new Pen(Color.Red, 2))
        {
            e.Graphics.DrawRectangle(pen, ee);
        }
    }

    private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Right)
        {
            width = e.X - x;
            height = e.Y - y;
            pictureBox1.Invalidate();
        }
    }

    private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Right)
        {
            x = e.X;
            y = e.Y;
        }
    }

    private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Right)
        {
            x = 0;
            y = 0;
            width = 0;
            height = 0;
            pictureBox1.Invalidate();
        }
    }
}
}

But still, I have a problem when I tried to click and drag from right to the left or from bottom to the top, which will result in negative values for the rectangle. Is there any idea for this matter? Thank you in advance. :)

A: In Windows Forms every Control provides the Event DragEnter, DragOver and  DragLeave which is fired if the cursor enters, hovers or leaves the bounds of the control during drag and drop.
The MSDN description of this event shows you an example implementation.
Instead of an effect to the item you can also change the background or start to flash smth or whatever you want.


text:
Q: If $x$ is a set of ordinals, then $\bigcup x=\alpha$. Why is $x\subseteq \alpha+1$ rather than $\alpha$ If $x$ is a set of ordinals, then $\bigcup x=\alpha$ is an ordinal and the $\text{sup}(x)$. Why is $x\subseteq \alpha+1$ rather than $\alpha$?
$\alpha+1$ is from notes by J. Roitman. I think it should be $\subseteq\alpha$.
After all as the least upper bound, every element of $x$ is $\leq\alpha$. And as $\alpha$ and the members of $x$ are ordinals, they are transitive. So aren't the members of members of $x$, i.e., $\bigcup x$, members of $\alpha$ making $x$ a subset of $\alpha$?
Thanks

A: You've shown that every element of an element of $x$ is also an element of $\alpha$, but you want to prove that every element of $x$ is also an element of $\alpha$.  This is false.  Consider the case of a singleton set $x = \{\alpha\}$.  Then $\bigcup x = \alpha$, but $x \nsubseteq \alpha$ because $\alpha \notin \alpha$.


text:
Q: SQL case with exists not working The idea is to check for the last time the systems were synced up by selecting the start time of the last sync. The problem is that the table that holds the sync info is new and as it moves to production the table will be empty so this query breaks the system because it does not return anything:
select ST_DT_TM
from SYNCJOBLOG
where SYS_ID = 'MF' and STAT_CDE = 'FN'
and SYNC_ID = (select MAX(SYNC_ID)
               from SYNCJOBLOG
               where SYS_ID = 'MF' and STAT_CDE = 'FN')

I've tried going the route of using a case to check if anything exists like this:
select case
          when exists (select ST_DT_TM
                       from SYNCJOBLOG
                       where SYS_ID = 'MF')
          then ST_DT_TM
          else ''
       end as ST_DT_TM
from SYNCJOBLOG
where SYS_ID = 'MF' and STAT_CDE = 'FN'
and SYNC_ID = (select MAX(SYNC_ID)
               from [XREFDB].[dbo].[SYNCJOBLOG]
               where SYS_ID = 'MF' and STAT_CDE = 'FN'))

When something does exist in the table then it works but if nothing does then it returns an empty set of rows and breaks the system. If I take out the outer where clause and nothing is in the table then it works to return the blank row but if something is in the table then it returns multiple rows and I can't have that. Is there another way to go about checking if anything exists in the table and if not then return a blank row otherwise just return the row of the max SYNC_ID?

A: I would change your system code to check the count of records retunred and solve your issue that way.  If that isn't possible try:
select ST_DT_TM
from SYNCJOBLOG
where SYS_ID = 'MF' and STAT_CDE = 'FN'
and SYNC_ID = (select MAX(SYNC_ID)
               from SYNCJOBLOG
               where SYS_ID = 'MF' and STAT_CDE = 'FN')
union
select ''
where not exists(
select 1
from SYNCJOBLOG
where SYS_ID = 'MF' and STAT_CDE = 'FN'
and SYNC_ID = (select MAX(SYNC_ID)
               from SYNCJOBLOG
               where SYS_ID = 'MF' and STAT_CDE = 'FN'))

A: Try this:
select top 1 ST_DT_TM
from (
    select ST_DT_TM,
       0 as IsAlternate
    from SYNCJOBLOG
    where SYS_ID = 'MF' and STAT_CDE = 'FN'
    and SYNC_ID = (select MAX(SYNC_ID)
                   from SYNCJOBLOG
                   where SYS_ID = 'MF' and STAT_CDE = 'FN')

    union all

    select 0 as ST_DT_TM, 1 as IsAlternate
) t
order by IsAlternate;

A: Couldn't you just outer join back to the same table, or a CTE?
with CTE as (
select MAX(SYNC_ID) as sync_id
               from SYNCJOBLOG
               where SYS_ID = 'MF' and STAT_CDE = 'FN')

select s1.ST_DT_TM
from SYNCJOBLOG s1
left outer join CTE
  on s1.sync_id = cte.sync_id
where s1.SYS_ID = 'MF' and s1.STAT_CDE = 'FN'

A: It seems that there are sys-ids ='MF' but with st_dt_tm empty so this should fix it:
select case
          when exists (select ST_DT_TM
                       from SYNCJOBLOG
                       where SYS_ID = 'MF')
          then ST_DT_TM
          else ''
       end as ST_DT_TM
from SYNCJOBLOG
where SYS_ID = 'MF' and STAT_CDE = 'FN'
and isnull(st_dt_tm,'')<>''
and SYNC_ID = (select MAX(SYNC_ID)
               from [XREFDB].[dbo].[SYNCJOBLOG]
               where SYS_ID = 'MF' and STAT_CDE = 'FN'))

A: SELECT ISNULL(ST_DT_TM,'') AS 'ST_DT_TM'
FROM SYNCJOBLOG

Essentially, ISNULL will test the first parameter, if it's null, it'll return whatever's in the second parameter (in this case, an empty string).
http://msdn.microsoft.com/en-us/library/ms184325.aspx


text:
Q: Different types of variables with the same name into a function I have this code and I'm wondering if it is possible to do something like that:
    switch (typeActivity) {
    case 0:
        Type1Activity aux=activity1;
        break;
    case 1:
        Type2Activity aux=activity2;
        break;
    case 2:
        Type3Activity aux=activity3;
        break;

    default:
        break;
    }

Great thanks to you in advance.

A: Assuming from the similar names of your types they extend a baseclass called something like TypeActivity, or at least should do it this way ;)
Then you could use:
TypeActivity aux = null;

switch (typeActivity) {
  case 0:
    aux = activity1;//Type1Activity
    break;
  case 1:
    aux = activity2;//Type2Activity
    break;
  case 2:
    aux = activity3;//Type3Activity
    break;
  default:
    break;
}

Only other way would be using Object as Class Object aux = null; which i wouldn´t recommend since it seems polymorphism / extends are the correct way to go here.

A:  Type1Activity aux = null;

switch (typeActivity) {
    case 0:
        aux=activity1;
        break;
    case 1:
        aux=activity2;
        break;
    case 2:
        aux=activity3;
        break;

    default:
        break;
    }

A: No you can't, the scope of a variable declared within a switch statement is the whole switch statement. So your code should generate a compile error ("variable aux is already defined", or something like that).
Besides, you never use those variables so the whole code is pointless. If this is a simplification of an actual use case, you should explain in more details what you are trying to achieve.


text:
Q: C# Find top 3 in Collection list box Find Top 3 Button – which processes the data to find the 3 highest sales amounts
and displays these sales persons names along with their place (1st, 2nd, 3rd),
and sales amount.
I have two list boxes I just want to find the top 3 highest sales persons with their sales amount and show them as message box to the user in 3 separate lines
Picture of the application:
http://s17.postimg.org/6dvo3a4qn/Untitled.jpg
Listboxes names: lstNames, lstTotalSales
My find top 3 button code is:
private void btnFindTop3_Click(object sender, EventArgs e)
{
    decimal dec1HighestAmount = 0;
    decimal dec2HighestAmount = 0;
    decimal dec3HighestAmount = 0;
    for (int Index = 0; Index < lstTotalSales.Items.Count; Index++)
    {
        if (Convert.ToDecimal(lstTotalSales.Items[Index]) > dec1HighestAmount)
        {
            dec1HighestAmount = Convert.ToDecimal(lstTotalSales.Items[Index]);
        }
        if (Convert.ToDecimal(lstTotalSales.Items[Index]) < dec1HighestAmount)
        {
            dec2HighestAmount = Convert.ToDecimal(lstTotalSales.Items[Index]);
        }
        if (Convert.ToDecimal(lstTotalSales.Items[Index]) < dec2HighestAmount)
        {
            dec2HighestAmount = Convert.ToDecimal(lstTotalSales.Items[Index]);
        }
    }
    MessageBox.Show("Highest Amount is " + dec1HighestAmount + " and " + dec2HighestAmount + " and " + dec3HighestAmount);
}

This is the code that I used to fill the listboxes:
public partial class Form1 : Form
{
    List<decimal> lstTotal = new List<decimal>();
    public Form1()
    {
        InitializeComponent();
    }

    private void btnReadInSalesData_Click(object sender, EventArgs e)
    {
        openFileDialog1.FileName = "SalesNumbers.txt";
        if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) //If and Open Dialog OK
        {
            StreamReader srFile = File.OpenText(openFileDialog1.FileName);

            decimal decTotal = 0;

            while (!srFile.EndOfStream)
            {
                string strline = srFile.ReadLine();
                string[] strSplit = strline.Split('$');

                foreach (string strSplittedOutput in strSplit)
                {

                    if (decimal.TryParse(strSplittedOutput, out decTotal))
                    {
                        lstTotal.Add(decTotal);
                        lstTotalSales.Items.Add(strSplittedOutput);
                    }
                    else //else than decimals add strings
                    {
                        lstNames.Items.Add(strSplittedOutput); //add the Sales men names to lstNames listbox
                    }
                }
            } //End of while

            srFile.Close(); //Close StreamReader
        }
        else
            MessageBox.Show("User Cancel Read File Operation."); // if the user cancel the read file operation show this messagebox

        // ... ??
    }

    // ...
}

Thank you

A: something like
var top_three = (from sales in lstTotalSales.Items
                 orderby sales descending
                 select sales).Take(3);

will hold your top 3 using linq...

Argh ... ok ... the bad news ... you have lots of work ahead of you ... the good news, this will set you on the right way:
public partial class Form1 : Form
{
    List<decimal> lstTotal = new List<decimal>();
    List<SalesPerson> lstSalesPerson = new List<SalesPerson>;

    public Form1()
    {
        InitializeComponent();
    }

    private void btnReadInSalesData_Click(object sender, EventArgs e)
    {
        openFileDialog1.FileName = "SalesNumbers.txt";
        if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) //If and Open Dialog OK
        {
            StreamReader srFile = File.OpenText(openFileDialog1.FileName);

            decimal decTotal = 0;
            decimal tempSales =0;
            string tempName = "";

            while (!srFile.EndOfStream)
            {
                string strline = srFile.ReadLine();
                string[] strSplit = strline.Split('$');

                // I'll seriously assume this happens only twice ...
                foreach (string strSplittedOutput in strSplit)
                {

                    if (decimal.TryParse(strSplittedOutput, out decTotal))
                    {
                        lstTotal.Add(decTotal);
                        lstTotalSales.Items.Add(strSplittedOutput);
                        tempSales = strSplittedOutput;
                    }
                    else //else than decimals add strings
                    {
                        lstNames.Items.Add(strSplittedOutput); //add the Sales men names to lstNames listbox
                        tempName = strSplittedOutput;
                    }
                }

                    // Adding this to our people list ...
                    lstSalesPerson.Add(new SalesPerson {Name=tempName,TotalSales=tempSales});

            } //End of while

            srFile.Close(); //Close StreamReader
        }
        else
            MessageBox.Show("User Cancel Read File Operation."); // if the user cancel the read file operation show this messagebox

        // ... ??
    }

    // ...
}

public class SalesPerson {
    public string Name {get; set;}
    public decimal TotalSales {get; set;}
}

I've added a class called SalesPerson ... this objects has a Name and a TotalSales ... doooohhh ... In your loop, I'm assuming you a have a text file with lines and in each one name and sales value ... I've added at the end the creation of a SalesPerson that goes into your lstSalesPerson (added at the top).
Now we're almost there ... Please go read and understand this article: http://www.codeproject.com/Articles/671544/Understanding-SelectedValue-SelectedValuePath-Sele .
Once you do, you'll realize you don't need to have the lstTotalSales and the lstNames, because you can just link those listboxes to the DisplayMemberPath of your lstSalesPerson.
Now, when you select your top 3 using the linq above, you have 3 objects. For each object you can use the values Name and TotalSales since they are just properties on that object.
var top_three = (from person in lstSalesPerson
             orderby person.TotalSales descending
             select person).Take(3);

foreach (var person in top_three) {
     // do something with person.Name
     // do something with person.TotalSales
}


text:
Q: Finding all names in a list that contains a substring without changing the characters I'm doing a key-search in a list for a search system and having a little bit of trouble in the exhibition. I found that if I lowercase both, the list with all my pages titles and the key I could do a simple search. It worked.
But in the end, to exhibit the searched titles as related results, I'm displaying the names lowercased, as I did it for comparing. I was wondering if there is any way that I could display the names as they were before comparing or a better way to do this search, looking for maintaining the original title.
This is my search function
def search(request):
    q = request.GET['q']
    if util.get_entry(q):
        #redirect to the existing page calling entry()
        return redirect("entry", title=q)

    #searching for matching entries titles

    #getting all the entries titles in a list
    all_entries = util.list_entries()
    #lowering case of the list and the key to avoid comparision problems
    all_entries = [item.lower() for item in all_entries]
    key = q.lower()
    #making a new list with the matching results
    match_entries = [i for i in all_entries if key in i]

    #renders the results page passing the list of matching titles
    return render(request, "encyclopedia/search.html",{
        'title' : q,
        'entries' : match_entries
    })

And this is my search page in HTML
{% extends "encyclopedia/layout.html" %}

{% block title %}
    Search results for {{ title }}
{% endblock %}

{% block body %}

"{{ title }}" Search results

    There is no page with the title "{{ title }}"

Similar results:

        {% for entry in entries %}

{{ entry }}

        {% endfor %}

{% endblock %}

A: You haven't provided a sample of what the lists actually contain, but it should work if you only call the .lower() method during the check rather than making all the entries lowercase then doing the check
Rather than:
all_entries = [item.lower() for item in all_entries]

You can use
#proxy for your line all_entries = util.list_entries()
all_entries=['AaAaA','Baaa','cccccAAA','Dddddaa']
q='AAA'
match_entries=[i for i in all_entries if q.lower() in i.lower()]
['AaAaA', 'Baaa', 'cccccAAA']

A: you can use str like str(item).lower() that will make a new object and will change that object but not your item.


text:
Q: Arabic site search not working online I've created a simple site search and I am using the following code
 <form  id="search" name="form1" method="post" accept-charset="utf-8" />
 <input id="sitesearch" name="sitesearch" type="text" value="<?php echo $search; ?>" />
 <input name="search" id="search" type="submit" />
 </form>

on my local server it works ok an I can see on url bar
    search.php?sp=العلامة%20البيضاء
on my online server though I get
    search?sp=%25D8%25A8%25D8%25B1%25D9%2586%25D8%...
On the online the weired thing is that I get the correct results on IE9 but not on Chrome and Firefox
Anyoe has a clue?

A: The problem is because of encoding . It is not converting to utf8.
Use utf8_encode for encoding the text and use utf8_decode for decoding.

A: in php.ini on the server
find
; http://php.net/default-charset
replaced withe
; http://php.net/default-charset
default_charset = "utf-8"

add to your file on head
 <head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>

and your file save as use utf-8 encoding
change your browser withe safari or chrome to be right  100% متأكد


text:
Q: How do I update a CentOS server's time from an authoritative time server? I have CentOS machine and each time I've noticed that the server loses correct time after a while. It is usually behind by several minutes after time passes from having manually set the correct time. Is there a mechanism whereby I can update the server with the time from a specific time server?

A: You'll need to configure ntpd for the server.  I suspect it is already installed but needs to be configured.  Note: if it is a virtual server, you probably have the option of syncing with the virtual host.

A: For centos 7.x installation:
yum install ntp
systemctl enable ntpd

initial sync, with:
ntpdate pool.ntp.org

start the daemon with:
systemctl start ntpd

A: ntpd.
Ntpd does exactly what you're looking for - synchronizes your system clock with one or more known-good time servers.

A: Basically there are two ways. NTP daemon and the ntpdate command. The most important difference is that ntpdate will synchronize the time at once even though it means that the system time will change. On the other hand NTP daemon will take care of the time synchronization and it will adjust the time by small steps - you can think about it like slowing down/speeding up the time of the computer to synchronize it to the correct time. Thats why people suggest to do the initial synchronization by ntpdate and then leave it to ntp daemon.

A: Yes.
NTP.
yum install ntp
chkconfig ntpd on

Do an initial sync, with
ntpdate pool.ntp.org

and start the time daemon with:
/etc/init.d/ntpd start

A: Use the ntp daemon. Run yum install ntp and ensure that the service is started via ntsysv or chkconfig ntpd on.
To get an immediate sync, run ntpdate time.apple.com (or something similar).

A: You need to install and configure ntp.
yum install ntp
chkconfig ntpd on
ntpdate pool.ntp.org
service ntpd start

should get things set up and running. You may find that the ntp package is already installed and just needs configuring.

A: Yea I'd use NTP, install ntp with yum and turn it on.
yum install ntp
chkconfig ntpd on

Then sync it to any ntp server of your liking with the ntpdate command

A: Also if using CPanel like I was and had this issue. I think using rdate. Changing to ntpd as per above fixes all issues with email, especially dovecot,etc.

A: In the case of Centos 8, I just start/enble chronyd like below:
systemctl start chronyd
systemctl enable chronyd


text:
Q: UICC: How to change ARA? I have an UICC (by Gemalto), which has some very strict APDU Access Rules. I would like to access an applet on UICC from an Android app, but these rules do not allow me to send any APDUs.
So I need to change these rules.
I tried following:

*

*Sending "Store Data - Store AR-DO" command directly to ARA applet => I get status word "security status not satisfied"

*Authenticating to Issuer Security Domain, sending Install For Personalization command to Issuer Security Domain and then sending Store Data through ISD. => The same result, "security status not satisfied".
Am I doing something wrong? Any idea? Do I need any extra authentication, passwords or keys to be able to change Access Rules? Is it even possible to change Access Rules once they are already set up?

A: It is possible to change access rule you can...
1.Select ARA applet and then authenticate via SCP02. For this you should know the associated security domain of ARA applet and of course the keys.
2.Via install for personalization command what you are doing in this case is right but first check whether ARA is associated with ISD or some other SD.
It is possible to change ARA rules at any time.

A: *

*Security Status Not Satisfied error code occurs only when some pre-requisite authentication conditions are not satisfied before sending the APDU command.

*Updating APDU access rules (i.e. Access rules stored in ARA) required proper authentication, without doing proper authentication you can not update the AR in ARA applet, so only selecting applet and sending store data command is not enough, you need to do proper authentication, because in this case once the command routes to theUICC(or application exist on UICC) from any terminal or sever, then first authentication and integrity are checked to verify that the command comes from authenticated server or terminal. If authentication fails then the APDU command will fail with Security Status Not Satisfied error, which is happening in your case.

*The Access Rule (AR) is stored in the ARA and can be updated over the air with standardized Global Platform Secure Messaging or Remote Applet Management functionality, i.e. you need to send the APDU command (i.e. Store Data) under the security of Secure Channel Protocol (SCP02) or SCP80. Please refer Global Platform and ETSI specification for details of these protocols.

*After proper authentication, send Install[For Personalisation] command to the Security Domain,
(generally the AR applet is associate to the ISD, so here the Security Domain may be ISD), then send Store Data command to change the ARA entry, as preceding command is Install[For Personalisation] so the next Store Data command will route to the ARA Applet.

*Please make it sure that all these APDU command should transfer after establishment of proper secure channel (in case of SCP02) or within proper secure envelope (in case of SCP80).
Thanks, Happy to help.


text:
Q: How to disable the save as prompt?
        If IsWorkbookOpen("CONTRACT\CONTRACTLIST_Cement.xlsx") Then
            x = 0
        Else
            Application.DisplayAlerts = False
            ActiveWorkbook.Close savechanges:=True
            Application.DisplayAlerts = True
        End If

Hi, despite using the above code, the save as prompt still occasionally appears and affect the program. Does anyone know how to stop it completely? The problem is that after I click save as, it will alert me that it was still open.

A: Try below code
Its always good to explcilty refer the workbook rather than ActiveWorkbook
Sub test()
   If IsWorkbookOpen("CONTRACT\CONTRACTLIST_Cement.xlsx") Then
            x = 0
    Else
        Application.DisplayAlerts = False
        ThisWorkbook.Save
        ThisWorkbook.Close False
        Application.DisplayAlerts = True
    End If

End Sub

A: You can use Workbook_BeforeSave Event in the ThisWorkbook object to capture the user selecting SaveAs (or using the keyboard shortcut), which would result in the Save As prompt being displayed and the SaveAsUI being set to true. If SaveAsUI is true, this means the user is trying to save the file as something else, so you can then cancel the save As operation.
Open up the Visual Basic Window (Alt + F11) and put the following code in ThisWorkbook.
Disable Save As
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)

    If (SaveAsUI = True) Then
        MsgBox "Sorry. I can't have you saving this file as something else."
        Cancel = True
    End If
End Sub

You can delete the MsgBox line if you want; i put it there as an example if you wanted to notify the user that the function was disabled
To disable both the Save and Save As functionalities, you would remove the if statement and cancel the Save operation, regardless of if the Save as prompt is displayed.
Disable Save and Save As
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)

    MsgBox "Sorry. I can't have you saving this file at all."
    Cancel = True
End Sub

If you just want to disable the Save operation, you would only need to look for the occurrence where the user is saving, but the SaveAsUI is not being displayed (i.e. user is simply saving the file).
Disable Save
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)

    If (SaveAsUI = False) Then
        MsgBox "Sorry. I can't have you saving any updates to this file."
        Cancel = True
    End If
End Sub

Finally, note that the user will still get a prompt to save if the user simply closes the file. The user won't be able to save and the file will close, but if you want the experience to be a bit cleaner, you'll need to make an additional change. When a user closes a file, Excel checks the ThisWorkbook.Saved variable to see if the file has been saved. If it is false, it will prompt the user to Save the file. To prevent this as well, we can set this boolean to true without saving, thus "tricking" Excel into thinking the file has been saved
Disable Save and Save As, including after User attempts to close file
Add the following code after your Workbook_BeforeSave code.
Private Sub Workbook_BeforeClose(Cancel As Boolean)
    ActiveWorkbook.Saved = True
    MsgBox "Click OK to continue closing this file. Changes will not be saved."
End Sub


text:
Q: Separate background fade on Bootstrap Modal I have a website that uses Bootstrap Modals quite a bit. They worked in their normal fashion with a black faded background that would blur out the content that was on the page.
I then needed a modal that opened when a page was loaded so I used:
<div class="modal-backdrop fade in" id="purchaseModal" tabindex="-1" role="dialog">

Originally this was really transparent, so I found an answer on here that said I had to overwrite the styles using:
.modal-backdrop.fade.in{
opacity: 1 !important;
filter: alpha(opacity=100) !important;
background: #fff;
}

It worked pretty well and stopped the modal from being transparent and instead made the background white. This is fine.
However when I go back to any of the other modals on my site they no longer have the black fade that they used to, and it is now completely transparent. I'm not sure if maybe I overwrote the wrong thing, or do I need to perhaps write another class for the second modal that I need.

A: Try to override class with its ID or ClassName.
#purchaseModal.modal-backdrop.fade.in{
opacity: 1 !important;
filter: alpha(opacity=100) !important;
background: #fff;
}

It will only work/override with purchaseModal id, and other will remain same with their default styles.
Hope this helps you.

A: You are applying that style to all bootstrap modals. What you should be doing is giving that modal an additional class to style is accordingly.
For example, you could name your modal with no faded background modal-with-no-background. This means you can get rid of the bad practice of overriding style declarations with !important.
.modal.no-fade + .modal-backdrop {
  opacity: 0;
}

A: Are you using a external style sheet for the CSS? If so this would apply across the whole site.
It sounds as though you are looking for all modals to have the black background except the one page your looking for a different white background, is this correct?
if so you have a couple options,
You could create .modal-backdrop.fade.in.black & .modal-backdrop.fade.in.white
and change the colour accordingly in the external CSS
Or you could have your standard .modal-backdrop.fade.in overwritten to black in external CSS & in the pages where you would like the background white, simply overwrite the same style in the individual page with a style tag.
Here are examples if you require: http://www.inmotionhosting.com/support/edu/website-design/using-css/linking-your-css-to-your-website


text:
Q: Sine and Cosine - Complex integration I want to show that for all $w \in \mathbb{C}$ we have
$$
\int_{\gamma_w} \sin (z) d z=0, \quad \int_{\gamma_w} \cos (z) d z=0,
$$
where the curve $\gamma_w:[0,2 \pi] \rightarrow \mathbb{C}$ is given by
$$
\gamma_w(t)=t+w .
$$

Can I just say
$$
  \int_{\gamma_w} \sin (z)  d z =\int_{0}^{2\pi} \sin(t+w) d t=[-\cos(t+w)]=0.
  $$
and for $\cos(z)$ likewise?

A: Yes, given this parametrisation one finds that $d \gamma_{w} (t) = dt$ which gives that the integral is equal to $-cos(t+w)|_{0}^{2 \pi} = 0$.


text:
Q: Can't call the function with onclick in html/php/javascript HTML/PHP:
<?php foreach($lines as $line): ?>
<form method="GET" action="nextpage">
   <?php
       global $unitPRICE;
       $unitPRICE=(float) $line[1];
       global $quantity;
       $quantity=(float) $line[2];
   ?>

 <?php echo "
".$line[0]."
"; ?>

          <input class="btn" name="delbtn" type="button" onclick="deleteproduct(this.form)" value="Delete">

              <input type="text" name="FIXEDP" value="<?php echo $unitPRICE; ?>" readonly>

       <input type="number" id="quantity" class="qty" oninput="modPrice(this.form)" value="<?php echo $quantity;?>" >

              <input id="price"type="text" name="price" value="<?php echo $unitPRICE*$quantity; ?>" readonly>

</form>
<?php endforeach; ?>

Javascript:
function deleteproduct(frm){
    var deletebtn= frm.elements['delbtn'];
    console.log(typeof deletebtn);
}

The Error:
Uncaught ReferenceError: deleteproduct is not defined
at HTMLInputElement.onclick (cart.php:55)
Also, the main goal of this function is to print the text the div with the id "Nomp".


text:
Q: jQuery/AJAX form submit and result with no return I'm using an AJAX caller function to submit a login form as below, but the page it is directed to only responds when the user is found not to exist (working correctly), but when the login information is deemed correct, nothing is returned in alert or otherwise, what am I missing?

Here is the PHP:
<?php

include_once($_SERVER['DOCUMENT_ROOT'].'/wp-config.php');
include_once($_SERVER['DOCUMENT_ROOT'].'/wp-load.php');
include_once($_SERVER['DOCUMENT_ROOT'].'/wp-includes/wp-db.php');

global $userdata;
global $wpdb;

//get the posted values

$posted_username = 'matt-inovate';
$posted_password = 'Qazplm10';

$user_name = htmlspecialchars($posted_username,ENT_QUOTES);

$pass_word = wp_hash_password($posted_password);

$pass_md5 = md5($posted_password);

$pass = $pass_word;

$userinfo = get_userdatabylogin($user_name);

$passcheck = $userinfo->user_pass;

$conn = mysql_connect("127.0.0.1", "fw1359063030", "75ozg3cMxM47kRlJEPdLl2iOPb3f4R") or mysql_error();
    $conn = mysql_select_db("db8760018806", $conn);

    $sql = "SELECT * FROM wp_users WHERE user_login = '$posted_username'";
    $result = mysql_query($sql) or mysql_error();
    $rows = mysql_num_rows($result);

    if ($rows == 1) {
        $row = mysql_fetch_array($result);
        echo $passcheck."
";
        echo $row[2]."
";
        if ($passcheck == $row[2]) { echo "Login Success."; } else { echo "Login Failed."; }
    }
    else { echo "Could not find user."; }
?>


text:
Q: Is it bad to bind behaviours to document unconditionally? The pagination controls on a page I am working on were being bound conditionally on there being more than 1 page. I don't like to see the following code in my projects,
if (pages > 1) {
  $('.some_class').bind('event', function() {});
}

because I feel it represents a disorganized coding style. I would put it on the same level as sprinkling return statements here and there rather than using control. I feel like binding events to globally available objects has no place in the local scope of a function call. So what I usually do is make two javascript files, for example: pagination.js and pagination-controls.js. In the one I have logic about building the html and displaying the the pagination controls. In the other I have statements like the following:
$(document).on('click', '.pagination .next', function() {});
Which fires regardless of whether there is a $('.pagination .next') element anywhere on the page. I like the way that feels: the website has behaviours and it only knows about ids and classes, not about instance variables in some local scope somewhere.
EDIT: this is definitely bad practice, as mentioned below. However:

As of jQuery 1.7, the .on() method is the preferred method for
  attaching event handlers to a document.

and the discussion on direct and delegated events is relevant. In particular I think the following describes my usage:

By picking an element that is guaranteed to be present at the time the
  delegated event handler is attached, you can use delegated events to
  avoid the need to frequently attach and remove event handlers. This
  element could be the container element of a view in a
  Model-View-Controller design, for example, or document if the event
  handler wants to monitor all bubbling events in the document.

EDIT: So I guess now I'm wondering "is it bad to prefer binding behaviours to parent elements unconditionally over binding based on logic?" That's perhaps just a question of style, and my original question has been answered so I think I will accept the answer.

A: Yes, this is causing significant unnecessary overhead, and it is a "bad practice".
Binding your event handling to the top-level document object means that every single click that occurs on any element anywhere in your page will bubble up to the document object, where the event's target is checked to see if it matches .pagination .next.
In fact, the documentation itself recommends against your usage:

Attaching many delegated event handlers near the top of the document tree can degrade performance. Each time the event occurs, jQuery must compare all selectors of all attached events of that type to every element in the path from the event target up to the top of the document. For best performance, attach delegated events at a document location as close as possible to the target elements. Avoid excessive use of document or document.body for delegated events on large documents.

So, you're misusing on. It's for binding directly to elements or to parent elements which may have dynamically created children, and you are meant to bind to the closest possible parent element. Binding to the document is certainly not meant to be the only way you handle events in your page.


text:
Q: Learning rate adjustment in tensorflow import tensorflow as tf

slim = tf.contrib.slim

def create_learning_rate(curr_step, lr_config):
    base_lr = lr_config.get('base_lr', 0.1)
    decay_steps = lr_config.get('decay_steps', [])
    decay_rate = lr_config.get('decay_rate', 0.1)

    scale_rates = [
        lambda: tf.constant(decay_rate**i, dtype=tf.float32)
        for i in range(len(decay_steps) + 1)
    ]

    conds = []
    prev = -1
    for decay_step in decay_steps:
        conds.append(tf.logical_and(curr_step > prev, curr_step <= decay_step))
        prev = decay_step
    conds.append(curr_step > decay_steps[-1])

    learning_rate_scale = tf.case(
        list(zip(conds, scale_rates)), lambda: 0.0, exclusive=True)
    return learning_rate_scale * base_lr

global_step = slim.create_global_step()
train_op = tf.assign_add(global_step, 1)
lr = create_learning_rate(
    global_step, {"base_lr": 0.1,
                "decay_steps": [10, 20],
                "decay_rate": 0.1})

with tf.Session() as sess:
    init = tf.global_variables_initializer()
    sess.run(init)
    for i in range(30):
        curr_lr, step, _ = sess.run([lr, global_step, train_op])
        print(curr_lr, step)

I want to decay the learning rate at certain times. However, it is always 0.001. Any ideas? Or is there a better method to adjust learning rate?
Thanks for your help.

A: It is because lambda function captures variable by reference instead of value.
So the correct manner is
def create_learning_rate(global_step, lr_config):
    base_lr = lr_config.get('base_lr', 0.1)
    decay_steps = lr_config.get('decay_steps', [])
    decay_rate = lr_config.get('decay_rate', 0.1)

    prev = -1
    scale_rate = 1.0

    cases = []
    for decay_step in decay_steps:
        cases.append((tf.logical_and(global_step > prev,
                                    global_step <= decay_step),
                    lambda v=scale_rate: v))
        scale_rate *= decay_rate
        prev = decay_step
    cases.append((global_step > decay_step, lambda v=scale_rate: v))
    learning_rate_scale = tf.case(cases, lambda: 0.0, exclusive=True)
    return learning_rate_scale * base_lr


text:
Q: left property attribute having no effect on element Here I am trying to move a touchable element by changing "top" and "left" values as can be seen below. The problem is, for "(number > 4)" it doesn't work as it should. To add to this, only "top" value change has an effect on the element, whereas change in "left" has no effect. I am clueless here, please help
Move function:
moveTo(index, number, onMoveFinish) {
 const x = index % 9;
 const y = (index - x) / 9;
 const gap = 2;

 var left = CellSize * x - gap
 var top = CellSize * (y - 9) - CellSize - gap

 if(number > 4){
   left = (BoardWidth / 9 * (number + 1) + (BoardWidth / 9 - CellSize) / 2)
   top = top - ((2 + CellSize * 1.1) + (CellSize / 3))
 }

 LayoutAnimation.configureNext(spring);
 this.setState({ left, top });
 setTimeout(() => {
   onMoveFinish && onMoveFinish();
 }, 25000);
}

Render function:
render() {
if (this.state.hide) return null;
const { number } = this.props;
var { left, top } = this.state;

if(number > 4){
  top = top + ((2 + CellSize * 1.1) + (CellSize / 3))
  left = (BoardWidth - (CellSize * 4.4 + ((CellSize / 3) * 3) + 16)) / 2 +
          (number - 5) * ((CellSize / 3) + (CellSize * 1.1))
}

return (
  <Touchable onPress={this.onPress} style={[styles.container, {top, left}]} >
    <View style={styles.cell} >
      <Text style={styles.text}>{number + 1}</Text>
    </View>
  </Touchable>
 );
 }
}

Style:
 const styles = StyleSheet.create({
  container: {
    position: 'absolute',
    width: CellSize,
    height: CellSize,
  },
  cell: {
   width: CellSize * 1.1,
   height: CellSize * 1.1,
   backgroundColor: 'transparent',
   alignItems: 'center',
   justifyContent: 'center',
  },
});


text:
Q: Default button in JFrame is not firing when the enter key is being pressed I have a JFrame with three JButtons on it. I have set txtSearch (a JTextField component) to have the focus when JFrame loads. One of the buttons is set as the default button. This is my code:
private void formWindowOpened(java.awt.event.WindowEvent evt)
{
     // btnRefresh.setMnemonic(KeyEvent.VK_R); // Even if this line
                                               // is not commented, but
                                               // still the event wouldn't fire.
     this.getRootPane().setDefaultButton(btnRefresh);
}

When it loads, the button is just selected, but it did nothing when the Enter key was being pressed. How do I correctly implement it?
btnRefresh.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
        btnRefreshActionPerformed(evt);
    }
});

private void btnRefreshActionPerformed(java.awt.event.ActionEvent evt) {
    JOptionPane.showMessageDialog(this, "Pressed!");
    // Other codes here (Replace by JOptionPane)
}

A: What component has focus when the JFrame comes up?  I ask because some components "eat" the Enter key event.  For example, a JEditorPane will do that.
Also, when you assign an ActionListener to JTextField, the ActionListener will be called instead of the DefaultButton for the root pane.  You must choose either to have an ActionListener or a DefaultButton, but you can't have both fire for the same JTextField.  I'm sure this applies to other components as well.

A: I don't see what you are doing incorrectly from what is posted.  Here is a short example that works.  Perhaps it will reveal something useful to you.
import java.awt.BorderLayout;
public class ExampleFrame extends JFrame
{
  private JPanel    m_contentPane;
  private JTextField m_textField;

  /**
   * Launch the application.
   */
  public static void main(String[] args)
  {
    EventQueue.invokeLater(new Runnable()
    {
        public void run()
        {
            try
            {
                ExampleFrame frame = new ExampleFrame();
                frame.setVisible(true);
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    });
  }

  /**
  * Create the frame.
   */
  public ExampleFrame()
  {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 450, 300);
    m_contentPane = new JPanel();
    m_contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    m_contentPane.setLayout(new BorderLayout(0, 0));
    setContentPane(m_contentPane);

    m_textField = new JTextField();
    m_contentPane.add(m_textField, BorderLayout.NORTH);
    m_textField.setColumns(10);

    JButton btnNewButton = new JButton("Default");
    btnNewButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            JOptionPane.showMessageDialog(ExampleFrame.this, "Default.");
        }
    });
    m_contentPane.add(btnNewButton, BorderLayout.CENTER);

    JButton btnNewButton_1 = new JButton("Not default");
    btnNewButton_1.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            JOptionPane.showMessageDialog(ExampleFrame.this, "Not default.");
        }
    });
    m_contentPane.add(btnNewButton_1, BorderLayout.WEST);
    m_textField.requestFocus();
    getRootPane().setDefaultButton(btnNewButton);
  }
}


text:
Q: Why a complementary inequality for function values does not simplify to False? I have a general assumption of a function to be positive. The direct inequality (f[x]>0) does simplify to True, but a complementary one (f[x] < 0) does not simplify at all despite the fact that I explcitly assumed that funciton is not zero.
$Assumptions = K[_] > 0 && K[_] != 0

FullSimplify[K[15] > 0]
True
FullSimplify[K[12] == 0]
False
FullSimplify[K[15] < 0]
K[15] < 0

Thansk in advance,
UPD
Following a comment I tried the same with another function name (f[_]) to avoid possible issues with capital K which is reserved, however the problem persists.


text:
Q: Energy bond and number of photons If I am given the energy bond of a specific bond in a molecule, is that the energy of one photon? and if I have, for example 2 bonds like this, there will be needed 2 photons, etc...? (In other words- does each photon required to break one bond)?
Thank you very much

A: Good question, but no, it is not like that. One should not regard the chemical notation literally. In the nitrogen molecule N$_2$, there is a covalent bond between the atoms. One should not regard the three sticks in the diagram as sticks that could be broken seperately. Without going into details, the molecular orbitals are similar to those in molecular oxygen O$_2$ with just two sticks in a chemical diagram.
A more physics way of looking at photodissociation is to regard the equipotential surfaces. There is the ground state, where the binding energy as a function of interatomic distance of is like a Morse potential.
When the molecule absorbs a photon, it is excited to a higher equipotential surface. If that is a dissociative state, the atoms fly apart.


text:
Q: typedef Char* does not name a type I'm facing some kind of problem as a beginner in C++.
I want to specify my own types with pointers. But my code doesn't compile.
Here's a glimpse of what i'm trying to do :
namespace mynamespace
{
    typedef os_uchar Boolean;
    typedef Boolean& Boolean_out;
    typedef Boolean* Boolean_ptr;

    [...]
}

And i'm getting errors for these lignes :
'os_uchar' does not name a type
'Boolean' does not name a type
'Boolean' does not name a type

How can I specify Boolean* and Boolean& as defined types ? Is it possible ?
I'd be grateful for your answers :)

A: All your errors come from the first one - 'os_uchar' does not name a type. Simply include the header where the type os_uchar is defined and it should work.


text:
Q: Speed limits with HERE REST API with PDE I've looked into stack overflow for questions similar to mine, namely HERE Maps API - get speed limit of all roads in a tile?
So this effectively means that https://developer.here.com/api-explorer/rest/routing/link-information-for-a-location will be deprecated, correct?
I also understand that the PDE is the way to go.
However, I couldn't find a simple example on the API Playground (just a simple REST call) that shows how to perform that functionality, e.g. get speed limits for a road.
Is anyone able to provide some clearance? I've read about the key concepts such as tiles and layers but it is quite overwhelming.

A: There's an example on GitHub that uses rest to get Speed Limits via Here + PDE. I've tried it and it works well.
https://github.com/seaBass3/here-pde-speed-limit


text:
Q: How to assign 0 to whole array I have an array. int[] array = new int[10];. I want to assign '0' to whole array without using loop means that 0 is to be stored in all of the indexes. How would i do it.

A: After creation all items of array will have default values, which is 0 for int. So, you don't need to do anything here.
From Arrays (C# Programming Guide):

The default values of numeric array elements are set to zero, and
  reference elements are set to null.

Also from C# Specification 12.2 Array creation

Elements of arrays created by array-creation-expressions are always
  initialized to their default value.

5.2 Default values

For a variable of a value-type, the default value is the same as the
  value computed by the value-type's default constructor

4.1.2 Default constructors

For sbyte, byte, short, ushort, int, uint, long, and ulong, the
  default value is 0.

but after assigning other values i want all the indexes to be 0 again
  so then how would i do it?

UPDATE: You can use Array.Clear:

Sets a range of elements in the Array to zero, to false, or to null,
  depending on the element type.

In your case:
Array.Clear(array, 0, array.Length);

Consider also to use List<int> instead of array - it allows to add/remove items dynamically.

A: You don't need to do anything at all.
Since int is a value type, all elements are initilialized to 0 as a default.
From Arrays (C# Programming Guide)

The default values of numeric array elements are set to zero, and
  reference elements are set to null.

ok if i want it to be assigned to 3 then how would i do it?

You can use for loop to assign them like;
int[] array = new int[10];
for(int i = 0; i < array.Length; i++)
    array[i] = 3;

If you want to give back their default values (which is 0 in this case), you can create a new array or you can use Array.Clear method like;
Array.Clear(array, 0, array.Length);

If you really don't want to use any loop, you might need to use List<int> instead an array. It has more functionality and it creates a clean list (without any default value).


text:
Q: How to design an optocoupler circuit for raspberry pi I want to give sensor pulse to raspberry pi. The sensor signal comes from a running conveyor . The sensor gives 24v signal hence I used a optocoupler to convert the 24v to 3.3v . How should I design a best optocoupler suitable for PI.

A: It seems your problem is that you have a 24 V signal that you want to get into a 3.3 V digital input.
Since the signal is coming from some industrial equipment, I agree that opto-isolating it is a good idea.  So here is what you do:
*

*Pick a opto-coupler.  Just about any will do since you seem to have plenty of input voltage and presumably current available.  Use whatever your company already has in stock.  If you don't already have something available, check out the FOD817 family.  They are cheap, widely available, and have good CTR.  They aren't for high speed applications, but should be instantaneous for a signal from a conveyor belt.

*Read the datasheet.

*Look at what kind of digital input is available.  The best would be one that has a internal pullup, because then you need not other parts than the opto itself on the digital side.  If all you have is a regular digital input, then you have to supply your own pullup resistor.  10 kΩ is usually a good value for such things.
Either way, find how much current the opto has to sink to pull the digital input low.

*Divide the minimum required pulldown current by the minimum guaranteed CTR (current transfer ratio).  Now at least double that.  This is current you want to drive the input of the opto with.

*Check the specs for the 24 V signal and verify it can source the current computed in the previous step, with some margin.  I'll assume it can.  If it can't, you'll have to get more clever and the solution isn't as simple as hooking up a opto-isolator.

*Look at the minimum guaranteed signal voltage (24 V nominal might only be 22 V min guaranteed, for example), and subtract off the maximum LED voltage from the opto datasheet.  This is the minimum voltage that will be across the resistor.

*Use Ohm's law to calculate the maximum allowed resistor in series with the LED on the opto's input side.  Go one or two standard values down from that, or some value you already stock that is a bit lower than the calculated value.

*Connect everything up.  Put the opto physically close to the digital input it drives.  In other words, the long pair of wires should be between the conveyor and the opto, not the opto and the digital board.

A: Does your sensor toggle between 0V and 24V with each impulse? Are the GNDs connected? You don't need an optocoupler then but can use a much simpler circuit:

simulate this circuit – Schematic created using CircuitLab
How does this work? Easy, the +24V from the input don't ever reach the Raspberry Pi GPIO port. Only the 0V do. Your impulses toggle between 0V and 24V, remember? When the sensor outputs 24V, the diode is non-conducting and thus, the GPIO is pulled to 3.3V by the resistor. When the sensor outputs 0V, the diode is conducting and the GPIO is pulled to 0.4V by the sensor.
Depending on your Raspberry Pi GPIO pullup setup, you may even leave out R1.

A: if the sensor generate high speed pulses use high speed optocouplers 6N137


text:
Q: nested conditionals in pgfmath The following code throws a division by 0 error when \dx==0 is true:
\pgfmathsetmacro{\rot}{(
  \dx==0 ? (\dy > 0 ? 90 : -90) : (\dx>0 ? atan(\dy/\dx) : 180+atan(\dy/\dx))
)}

The code sets \rot correctly, even when \dx==0 is true but it seems that the parser is continuing to analyze the false clause even though the condition was true. Anyone know what I'm doing wrong? Full code below:
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{calc}
\usepgfmodule{oo}
%http://tex.stackexchange.com/questions/33703/extract-x-y-coordinate-of-an-arbitrary-point-in-tikz
\makeatletter
\newcommand{\gettikzxy}[3]{%
  \tikz@scan@one@point\pgfutil@firstofone#1\relax
  \edef#2{\the\pgf@x}%
  \edef#3{\the\pgf@y}%
}
\makeatother

\pgfooclass{rr}{
  \method rr(#1,#2) { % The constructor; everything is done in here
    % Here I can get named x and y coordinates
    \gettikzxy{(#1)}{\spx}{\spy}
    \gettikzxy{(#2)}{\epx}{\epy}
    % I'd like named points to work with
    \coordinate (Start) at (\spx, \spy) node[right]{start};
    \coordinate (End) at (\epx, \epy);
    % Find the length between start and end. Then the angle between x axis and Diff will be the rotation to apply.
    \coordinate (Diff) at ($ (End)-(Start) $);
    \gettikzxy{(Diff)}{\dx}{\dy}
    \pgfmathparse{veclen(\dx, \dy)} \pgfmathresult
    \let\length\pgfmathresult
    \node[right] at (End) {\length};
    \pgfmathsetmacro{\rot}{(
      \dx==0 ? (\dy > 0 ? 90 : -90): (\dx>0 ? atan(\dy/\dx) : 180+atan(\dy/\dx))
    )}
    \begin{scope}   [rotate around = {\rot:(\spx, \spy )}]
      \draw ($ (Start)+(0,\hi) $) arc(90:270:\hi) -- +(\length pt, 0) arc(-90:90:\hi) -- cycle;
    \end{scope}
  }
}

\begin{document}
\begin{tikzpicture}
  \coordinate (A) at (0,0);
  \coordinate (B) at (0,16);
  \def\hi{0.25}
  \pgfoonew \AB=new rr(A,B);
  \fill (A) circle (3pt);
  \fill (B) circle (3pt);
\end{tikzpicture}
\end{document}

A: Yes, all components of the shorthand notation are evaluated, even though only one of the branches will be following. The following simple formula provides the same error:
\pgfmathparse{1==2 ? 3/0 : 4}\pgfmathresult

Since 1 is not 2, the result should be 4, but the compiler still evaluates 3/0.
One easy way around this is to use TeX conditionals which doesn't evaluate unless necessary. So, we first evaluate whether \dx==0 using \pgfmathparse and then condition (using TeX primitives) on \pgfmathresult.
That is,
\pgfmathsetmacro{\rot}{(
  \dx == 0 ? (\dy > 0 ? 90 : -90) : (\dx > 0 ? atan(\dy / \dx) : 180 + atan(\dy / \dx))
)}

becomes
\pgfmathparse{\dx == 0}%
\ifnum\pgfmathresult=1 % \dx == 0
  \pgfmathsetmacro{\rot}{\dy > 0 ? 90 : -90}
\else% \dx != 0
  \pgfmathsetmacro{\rot}{\dx > 0 ? atan(\dy / \dx) : 180 + atan(\dy / \dx)}
\fi


text:
Q: Angularjs routing to # causing problems Fairly new to angularjs, trying to make a single page application.
The default page to load should be a home page, and I also want a home button to route to this page.
Nav bar in HTML:

...

Home

About

Contact

...

in app.module.js:
var app = angular.module('app', ['ngRoute']);

app.config(function ($routeProvider) {
    $routeProvider
        .when('/', {
            templateUrl: 'pages/home.html',
            controller: 'main',
            controllerAs: 'vm'
        })
        .when('/about', {
            templateUrl: 'pages/about.html',
            controller: 'about',
            controllerAs: 'vm'
        })
        .when('/contact', {
            templateUrl: 'pages/contact.html',
            controller: 'contact',
            controllerAs: 'vm'
        });
});

app.controller('main', main);
app.controller('about', about);
app.controller('contact', contact);

function main() {
    var vm = this;
    vm.message = "Home page";
}

function about() { //stuff }

function contact() { //stuff }

When the page loads, everything displays correctly, and the url is http://localhost:8007/#/
My problem is that when I click Home, the url becomes http://localhost:8007/# and nothing displays. About and Contact both work as intended.
I know I can just change my Home button to have href="#/" but that feels like I am targeting the symptoms, not the problem. I feel like I really shouldn't have to do that.
I have tried adding .when('', { to app.module.js, but this does nothing.

A: Your home href will be Home which then translates to the path "/" you defined in $routeProvider.
Dont use href="#" anywhere in the app


text:
Q: uninstall custom actions After which custom action should my C# custom actions execute? And what condition should I use so my custom action could run only on uninstall?

A:
After which custom action should my C#
  custom actions execute?

It depends on what they do.

And what condition should I use so my
  custom action could run only on
  uninstall?

REMOVE = "ALL"

A: You need to provide the condition in custom action call as to when they should be called.
Example :
<Custom Action="UpdateConfig" After="InstallFinalize">INSTALL_APPLICATION = "1"</Custom>

Here, as you can see the custom action UpdateConfig will be called after everything is installed and if Application was selected as feature while installing.


text:
Q: PhantomJS require() a relative path In a PhantomJS script I would like to load a custom module but it seems relative paths do not works in PhantomJS ?
script.js:
var foo = require('./script/lib/foo.js');
foo.bar('hello world');
phantom.exit();

foo.js:
exports.bar = function(text){
  console.log(text);
}

*

*According to fs.workingDirectory I am in the good directory

*foo.js is not in the lookup path of phantomjs

Am I missing something ?
EDIT:
inject() is not revelant because I do not need to inject a JS to an HTML page but instead load my own module like require('fs') but with a relative path.

A: To load your own module, the right way to do it is to use module.exports, like this: foo.js

function bar(text) {
   console.log(text);
}

exports.bar = bar

And in script.js (which is executed with phantomjs script.js):
var foo = require('./script/lib/foo');
foo.bar('hello world');
phantom.exit();

A: My solution to load a resource file (like let's say a json file) within a phantomjs subfolder from a outer folder like in this structure:
├── consumer.js
├── assets
    ├── data.json
    ├── loader.js

Supposed that data.json must be load by the consumer module and that this module is called by somewhere else on this machine, outside the project root folder, the fs.workingDirectory will not work, since it will be the path of the caller file.
So to solve this, I did a simple loader module within the assets folder, where the files I want to load are:
(function() {

var loader = {
    load : function(fileName) {
        var res=require('./'+fileName);
        return res;
    }
}
module.exports=loader;

}).call(this);

I therefore call the loader module from the consumer module like
var loader=require('./data/loader');
var assets=loader.load('data.json');

and that's it.
NOTE. The require here is the phantomjs require not the node version, so it works a bit differently. In this case the data.json was a json array with no module.exports declaration. The array will be backed in the assets variable directly when calling the loader.load(fileName) method.

A: After a lot of time searching for the same thing, here is what I understood, though I might be wrong :

*

*PhantomJS doesn't use Node's require, but its own require, so things are different

*when providing a relative path to phantomjs's require, it is always interpreted as relative to the current working directory

*PhantomJS doesn't implement node's __dirname, and as such there is no direct way to have the directory of your script

The solution I found least annoying :

*

*if using phantomjs pure, without casperjs :
require(phantom.libraryPath + '/script/lib/foo.js')

*if using casperjs :
var scriptName = fs.absolute( require("system").args[3] );
var scriptDirectory = scriptName.substring(0, scriptName.lastIndexOf('/'));
require(scriptDirectory + '/script/lib/foo.js')

A: have you tried to use injectJs(filename)
excerpt form PhantomJS documentation:

Injects external script code from the specified file. If the file can
  not be found in the current directory, libraryPath is used for
  additional look up.
This function returns true if injection is successful, otherwise it
  returns false.

A: Which PhantomJS version are you running? Support for user provided modules was added in 1.7.


text:
Q: Flash Air to windows tablet i'm making an application in Flash Air(Flash cc 2014). It's an application where you can swipe between pages. But the application needs to be working on a windows tablet.
So I've tried to do: AIR 16.0 for Desktop => AIR 16.0 Desktop Settings
http://downloads.unides.be/Screen%20Shot%202015-03-25%20at%2014.02.16.png
When I publish this, I only see this in the structure:
http://downloads.unides.be/Screen%20Shot%202015-03-25%20at%2014.03.23.png
But I think I need to have an .exe -file? Can someone help me? What am I doing wrong? (I've opened all the folders, but none of these have an exe-file)

A: When you publish an application using MAC, the exported file will be .app or .dmg
Or you export your application using a PC, or you can try exporting projector files using Flash CC/2014.
You can also export a .AIR file and will be hybrid.
To export Projector files from Flash Pro CC, do the following:
1) In Flash Pro CC, select Commands > Export as Projector.
2) On the Export as Projector dialog, click Browse to navigate to and specify a location where you want to save the Projector file.
3) Select any of the following options:

*

*Windows to create a .exe file that can be run on Windows PC.

*MAC to create a .app file that can be run on MAC.
4) Click Export to export the Projector file.

Export As Projector dialog accessed from Commands > Export as Projector.


text:
Q: Which is the best way or method to prevent session fixation and highjacking in php ? I browsed various method to prevent session fixation and highjacking in php but I am finding it difficult to figure out which is the best way on which I can rely on . Like to prevent sql injection most of the developer suggest use of prepare statement .It is effective in preventing most of the sql injection attacks . Is there any such code , function or snippet availble best,quick and simple in regard to prevent attack on session . Please share it .
Thank you all .

A: There is a few things you can do to help such as, when setting cookies set them to httponly so they are not able to be read from javascript, keep track of a users ip address and only allow access to the session if the users ip is within a certain range of the ip they started the session with, when starting a new session regenerate session id instead of reusing a previous one , keep track of the users browser and if that changes during a session do not allow access to the session. I am sure there are more but thats just off the top pf my head.

A: Do not allow http protocol, only https.
That's it, it prevents SESSID hijackings...
RewriteEngine On
RewriteCond %{SERVER_PORT} !443
RewriteRule (.*) https://yourdomain.com/ [R]


text:
Q: Unattended installation prompting for password I'll start by posting this question here, and expand to other exchanges if the response rate is low.  But I think the excellent Ubuntu community is the right place to begin.
I am trying to accomplish an unattended installation of Ubuntu 18.04 LTS using the minimal ISO net installer.  I am orchestrating this installation with Hashicorp packer.
I have followed all guides, tips, tricks and setup techniques to great success. However, I am at a stuck place, so I am asking here for how to get beyond this very annoying issue I am having.
TL;DR: The installation is stopping and asking for a password.
The boot line I am using is:
linux initrd=initrd.gz file=/floppy/preseed.cfg priority=critical \
auto-install/enable=true oem-config/enable=true  \
debian-installer/locale=en_US netcfg/choose_interface=auto  \
quiet splash noprompt noshell  \
--

Maybe I've got extra useless stuff here, I am not 100% on this line.
Then the relevant sections of the kickstart preseed which should have (I thought) gotten me over the hump of the user/password dialogs.
# Users
# Root password, either in clear text
d-i passwd/root-login boolean true
d-i passwd/root-password-crypted password $6$mz7Yiq85Dk3uVc$L9D5BHr8QbC4PM/.5iq5kloKRxN4uRMmIyWanNFCTkuWGBEVFBC.sU.1ulfXdIh3amUdvnwY/PJ5FSDI.qxYQ0
# non root user
d-i passwd/user-fullname string ubuntu
d-i passwd/username string ubuntu
d-i passwd/user-password-crypted password $6$aEVY19fh9gXxlnD$rwfMtBhQLkTAz5wJzfJZtsNvIx1Sop1kFFpDzmffhcgXwVexJRzclQXZB5pw4.UqUhy3SvwX98zqyugiqWPJA0
d-i passwd/user-default-groups string wheel adm sudo
d-i user-setup/allow-password-weak boolean true

What obvious mistakes have I made here?
What not-so-obvious assumptions might I have made which are causing a failure for me?


text:
Q: How to extract an Id from URL in angular e2e testing I am writing e2e test cases for my angular application using protractor.
Here is my code
it('Select Dashboard.....', function(){
             element.all(by.css('.caption p a')).get(0).click();
             browser.getLocationAbsUrl().then(function(url) {
               expect(url.split('#')[1]).toBe('/patientDashboard/encounters/1');
             });
         });

How to extract ID from the URL(/patientDashboard/encounters/1)?
Because I am using the same URL in multiple places with different ID.


text:
Q: How to change language dropdown button image in react after dropdown menu link is clicked? I'm trying to learn react so as an exercise I'm trying to convert a static html website I built a while ago into react.
The website has content in two languages: English and German.
I created a custom dropdown element that contains a button with an image of US flag that toggles the dropdown menu, and a dropdown menu which itself contains two links: first one for the English and the other for German version of the website, each containing image of a flag and a span which names the language.
I'm using react router inside my Layout component to navigate to English and German and routing works fine, however I'm having trouble with switching the dropdown button flag image after I switch the language.
This is how my Dropdown component looks like:
import React, { Component } from 'react';
import DropdownLink from './DropdownLink/DropdownLink';

import FlagEn from '../../../assets/images/lang/flag-en.svg';
import FlagDe from '../../../assets/images/lang/flag-de.svg';

class Dropdown extends Component {
    constructor() {
        super();

        this.state = {
            showMenu: false,
        };

        this.showMenu = this.showMenu.bind(this);
        this.closeMenu = this.closeMenu.bind(this);
    }

    showMenu(event) {
        event.preventDefault();

        this.setState({ showMenu: true }, () => {
            document.addEventListener('click', this.closeMenu);

        });
    }

    closeMenu(event) {
        if (!this.dropdownMenu.contains(event.target) || this.dropdownMenu.contains(event.target)) {

            this.setState({ showMenu: false }, () => {
                document.removeEventListener('click', this.closeMenu);
            });

        }
    }

    render() {
        const dropdownLinks = [
            { href: '../en', linkText: 'English', linkImg: FlagEn, imgAlt: 'English' },
            { href: '../de', linkText: 'Deutsch', linkImg: FlagDe, imgAlt: 'Deutsch' }
        ];
        let dropdownMenuShow = null;
        if (this.state.showMenu) {
            dropdownMenuShow =
 {
                    this.dropdownMenu = element;
                }}>
                {dropdownLinks.map(dropdownLink => (
                    <DropdownLink
                        onClick={this.showMenu}
                        href={dropdownLink.href}
                        linkText={dropdownLink.linkText}
                        key={dropdownLink.linkText}
                        linkImg={dropdownLink.linkImg}
                        imgAlt={dropdownLink.imgAlt} />
                ))}

        }
        return (

                <button className="dropdown-toggle" type="button" id="dropdownMenuButton" onClick={this.showMenu}>

                </button>
                {dropdownMenuShow}

        );
    }
}

export default Dropdown;

and this is my DropdownLink component:
import React from 'react';
import { NavLink } from 'react-router-dom';

const dropdownLink = (props) => (
    <NavLink className="dropdown-item" to={props.href} exact>

        {props.linkText}
    </NavLink>
);

export default dropdownLink;

Is there a way to switch the dropdown button's flag image so that US flag is there when English language is selected and German flag for the German language?
Links are routing to "/en" and "/de".

A: here is a rough revision of your class that uses the local state to store the selected language (since you didn't specify how you're storing it)
import React, { Component } from 'react';
import DropdownLink from './DropdownLink/DropdownLink';

import FlagEn from '../../../assets/images/lang/flag-en.svg';
import FlagDe from '../../../assets/images/lang/flag-de.svg';

class Dropdown extends Component {
    constructor() {
        super();

        this.dropdownLinks = [
            { href: '../en', linkText: 'English', linkImg: FlagEn, imgAlt: 'English' },
            { href: '../de', linkText: 'Deutsch', linkImg: FlagDe, imgAlt: 'Deutsch' }
        ];

        this.state = {
            showMenu: false,
            selectedLanguage: this.dropdownLinks[0]
        };

        this.showMenu = this.showMenu.bind(this);
        this.setLanguage = this.setLanguage.bind(this);
        this.closeMenu = this.closeMenu.bind(this);
    }

    showMenu(event) {
        event.preventDefault();

        this.setState({ showMenu: true }, () => {
            document.addEventListener('click', this.closeMenu);

        });
    }

    setLanguage(language) {
        this.setState({selectedLanguage: language})
    }

    closeMenu(event) {
        if (!this.dropdownMenu.contains(event.target) || this.dropdownMenu.contains(event.target)) {

            this.setState({ showMenu: false }, () => {
                document.removeEventListener('click', this.closeMenu);
            });

        }
    }

    render() {
        let dropdownMenuShow = null;
        if (this.state.showMenu) {
            dropdownMenuShow =
 {
                    this.dropdownMenu = element;
                }}>
                {this.dropdownLinks.map(dropdownLink => (
                    <DropdownLink
                        onClick={() => this.setLanguage(dropdownLink)}
                        href={dropdownLink.href}
                        linkText={dropdownLink.linkText}
                        key={dropdownLink.linkText}
                        linkImg={dropdownLink.linkImg}
                        imgAlt={dropdownLink.imgAlt} />
                ))}

        }
        return (

                <button className="dropdown-toggle" type="button" id="dropdownMenuButton" onClick={this.showMenu}>

                </button>
                {dropdownMenuShow}

        );
    }
}

export default Dropdown;

A: You can add a function to update the image your showing in the button and pass that down into the  component.
    import React from 'react';
    import ReactDOM from 'react-dom';
    import DropdownLink from './DrowdownLink';

    export default class Test extends React.Component {
        constructor() {
            super();

            this.state = {
                showMenu: false,
                buttonFlag: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQb9JntXqHxGA9U_q4nJYzi1f5lzHWKReT3OwYNyydpNuFd9B0e'
            };

            this.showMenu = this.showMenu.bind(this);
            this.closeMenu = this.closeMenu.bind(this);
            this.updateFlag = this.updateFlag.bind(this);
        }

        showMenu(event) {
            event.preventDefault();

            this.setState({ showMenu: true }, () => {
                document.addEventListener('click', this.closeMenu);

            });
        }

        closeMenu(event) {
            if (!this.dropdownMenu.contains(event.target) || this.dropdownMenu.contains(event.target)) {

                this.setState({ showMenu: false }, () => {
                    document.removeEventListener('click', this.closeMenu);
                });

            }
        }

        updateFlag(link) {
            console.log(link);
            this.setState({ buttonFlag: link })
        }

        render() {
            const dropdownLinks = [
                { href: '../en', linkText: 'English', linkImg: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQb9JntXqHxGA9U_q4nJYzi1f5lzHWKReT3OwYNyydpNuFd9B0e', imgAlt: 'English' },
                { href: '../de', linkText: 'Deutsch', linkImg: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRDqHreeGXhpRqWg8YwpjAPfv6_HXy7nEatEU8ec2KWxtI0LnBRLQ', imgAlt: 'Deutsch' }
            ];
            let dropdownMenuShow = null;
            if (this.state.showMenu) {
                dropdownMenuShow =
 {
                        this.dropdownMenu = element;
                    }}>
                    {dropdownLinks.map(dropdownLink => (
                        <DropdownLink
                            onClick={this.showMenu}
                            href={dropdownLink.href}
                            linkText={dropdownLink.linkText}
                            key={dropdownLink.linkText}
                            linkImg={dropdownLink.linkImg}
                            updateFlag={this.updateFlag}
                            imgAlt={dropdownLink.imgAlt} />
                    ))}

            }
            return (

                    <button className="dropdown-toggle" type="button" id="dropdownMenuButton" onClick={this.showMenu}>

                    </button>
                    {dropdownMenuShow}

            );
        }
    }

The src for the button is now pulling from state and the state is updated from inside the DropdownLink component with a function we pass in as a prop called updateFlag. Also I don't have those resources so I just used two links to flag pictures online.
Here is the DropdownLink component
    import React from 'react';
    import { NavLink } from 'react-router-dom';

    const dropdownLink = (props) => (

             props.updateFlag(props.linkImg)} src={props.linkImg} alt={props.imgAlt} />
            {props.linkText}

    );

    export default dropdownLink;

Hope that helps!


text:
Q: Delegate not working when selecting row on UITableView I have a UITableView, which when I select a row, I want to segue to another view, where the details of the tank are displayed... The segue happens, but the delegate does not send the object etc over... I think I have my knickers in a twist over where the delegate is declared/synthesized and implemented etc...
Here is where I declare the delegate in the header file of the UITableViewController:
@class iTanksV2ListViewController;
@protocol iTanksV2ListViewControllerDelegate
- (void) iTanksListViewController:(iTanksV2ListViewController *) sender choseTank:(tank *)tank;
@end
@interface iTanksV2ListViewController : UITableViewController
@property (weak, nonatomic) id <iTanksV2ListViewControllerDelegate> delegate;
@end

and this is what I have in the UITableViewControllers m file:
@implementation iTanksV2ListViewController
@synthesize delegate = _delegate;

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.tankTableView.delegate = self;
    self.tankTableView.dataSource = self;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    self.selectedTank = [self.tanks objectAtIndex:indexPath.row];
    [self.delegate iTanksListViewController:self choseTank:self.selectedTank];
}

...and then here is the code I have for the delegate in the DetailViewController implementation file...
@interface tankDetailViewController () <iTanksV2ListViewControllerDelegate>
@end

-(void)iTanksListViewController:(iTanksV2ListViewController *)sender choseTank:(id)tank
{
    self.tankToShow = tank;
}

All the other variables etc are declared, I have left them out in the hope it makes things clearer - the code compiles, and the segue happens but the delegate doesn't seem to do anything!!!

A: You mention segues so I'm assuming you're using a storyboard.  If that's true, forget about delegates for this purpose. A delegate is supposed to be an object that performs some action for another but all you need is data transfer.
I suggest using the prepareForSeque: method instead in your iTanksV2ListViewController class.  Keep the line that sets self.selectedTank when a row is tapped but then put something like this in prepareForSegue:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    tankDetailViewController *next = (tankDetailViewController *)[segue destinationViewController];
    next.tankToShow = self.selectedTank;
}


text:
Q: Wrong db name in mongo URI- created a new db So in my MongoURI variable - i have mistakenly added a wrong db name for example it should be 'trepdb' but it was written as 'tpredb'.

*

*First I tried running the following script to import some dummy data

Seeder script/import script
const importData =async() =>{
 try{
   await Student.deleteMany()

     await Student.insertMany(students)
     console.log("Data imported".green.inverse)
     process.exit()

    }
    catch(error){
        console.error(`${error}`.red.inverse)
        process.exit(1)
    }
}

dummy data & SCHEMA

And I tried running it atleast 5 times but the students collection didnt have any data as I intended

*So i thought I may have made a mistake in adding the schema type. 'classesEnrolled:Array' So i deleted that from both studentSchema and dummy data and ran the seeder script (ie. import Students) and then i refreshed my cluster it showed me a new database with the mistaken name and the students collection in it with the data imported..

Is this the expected behavior-if so why so ? thanks for the help here - I would have expected an error saying that database doesnt exist or something but instead it created a database and added a brand new collection with the data in it,


text:
Q: dependence list with two conditions Hello everyone I need help with my php code
I need to use a dependency list , I have three select fields (filiere,Semestre,module)
the first list is filiere select which takes all the the filieres we have in the data base and we can select one of them
the secend list is semestre which has 6 options (S1,S2,S3,S4,S5,S6)
the last one is module which depends on the both previous ones (filiere & semestre )
we have in the database this tables
filiere ( Nom_filiere )
module ( Num_module,Nom_module,Nom_filiere,Nom_semestre)
I succeeded to make the last list depends on the first (filiere) but I still have a problem to add a condition on the second one (semestre)
this is my code :
// select.php
$query = "SELECT  * FROM filiere";
$result1 = mysqli_query($dbc, $query);

Filieres
<select onChange="getID(this.value);"  id="Nom_filiere"  name="Nom_filiere">

<?php while($row1 = mysqli_fetch_array($result1)):;?>

    <option value="<?php echo $row1[0];?>"><?php echo $row1[0];?></option>

<?php endwhile;?>
</select>

Semestre

<select id="NOM_semestre" name="NOM_semestre" >
    <option value="S1"> S1</option>
    <option value="S1"> S2</option>
    <option value="S1"> S3</option>
    <option value="S1"> S4</option>
    <option value="S1"> S5</option>
    <option value="S1"> S6</option>
</select>

 Module

    <select class="mdb-select md-form"  id="NOM_MODULE" name="NOM_MODULE[]" multiple>
        <option selected="" disabled="">selest module</option>
    </select>

// get_module.php :

if(isset($_POST['get_filiere'])) {

    $fid = $_POST['get_filiere'];

    $query2 = "SELECT * from module where NOM_Filiere ='$fid'";

    if($result2 = mysqli_query($dbc, $query2)) {

            while($row = mysqli_fetch_array($result2)){
                echo "<option value=".$row['NUM_Module'].">".$row['Nom_module']."</option>";
            }
    } else {
        echo "Something went wrong while executing query :: $query";
    }
    exit;
}

this code works fine with the first condition I just need to add a condition on Semestre

A: There are at least two libraries I know that could help you achieve this ...

*

*Form-Field-Dependency: http://emranahmed.github.io/Form-Field-Dependency/

*DependsOn: https://dstreet.github.io/dependsOn/
They will help you control the dependencies between fields by configuring in a declarative way.


text:
Q: Jquery typing effect on scroll bug Hi I have some js code that do typing effect on my web page it start typing when you scroll down end of page. For first it work normally  but when you start scroll faster down to up the typing effect goes crazy how can I fix that
demo page
code
$(window).scroll(function (e) {
    var elem = $(".hello-page");
    var scrollTop = $(window).scrollTop();
    var blockTop = elem.offset().top;
    var docHeight = $(document).height();
    var windowH = $(window).height();

    if (scrollTop >= blockTop) {
        var helloPageA = $(".hello-page").find("a");
        var text = helloPageA.attr("data-text");
        helloPageA.text('');
        $.each(text.split(''), function (i, letter) {
            setTimeout(function () {
                helloPageA.html(helloPageA.html() + letter);
            }, 150 * i);
        });
    } else {
        elem.find("a").text('');
    }
});

jsfiddle example
Thanks for your help

A: So, here is the solution - http://jsfiddle.net/u3ojjx8r/1/
I borrowed initial structure of the code from previous answer here and it was removed unfortunately, therefore I can't mention one of the co-authors. Though the code looked quite similar to topic-starter's one.
The idea of the code below is to separate the queuing of characters to render and the actual rendering. Another important improvement is always have control over timeouts, i.e. never schedule more than one timeout. That allows you to cancel them any time without unpredicted/uncontrolled behavior.
var timeoutVar;
var queue = [];
var drawQueueTimeout = -1;
var helloPageA = $(".hello-page").find("a");

function pushQueue (element) {
    console.log('pushQUeue', element.char);
    queue.push(element);
    checkQueue();
}

function flushQueue () {
    console.log('flushQueue');
    queue = [];

    clearTimeout(drawQueueTimeout);
    drawQueueTimeout = -1;
}

function checkQueue () {
    console.log('checkQueue', queue.length, drawQueueTimeout);
    if (queue.length > 0 && drawQueueTimeout < 0) {
        console.log('schedule drawQueue');
        drawQueueTimeout = setTimeout(drawQueue, 150);
    }
}

function drawQueue () {
    drawQueueTimeout = -1;

    console.log('draw queue');
    if (queue.length > 0) {
        var element = queue.shift();
        console.log('drawQueue', element.char);
        helloPageA.html(helloPageA.html() + element.char);
    }

    checkQueue();
}

$(window).scroll(function (e) {
    var elem = $(".hello-page");
    var scrollTop = $(window).scrollTop();
    var blockTop = elem.offset().top;
    var docHeight = $(document).height();
    var windowH = $(window).height();

    if (scrollTop + windowH == docHeight) {
        // Empty anything typed so far
        helloPageA.empty();
        flushQueue();

        var text = helloPageA.attr("data-text");
        helloPageA.text('');
        $.each(text.split(''), function (i, letter) {
            pushQueue({
                char: letter,
                index: i
            });
        });

    } else {
        helloPageA.empty();
        flushQueue();
    }
});


text:
Q: Keep gif animation I'm using the following script to generate animated GIFs: http://www.jeroenvanwissen.nl/weblog/php/howto-generate-animated-gif-with-php
if (!getimagesize($_FILES['myfile']['tmp_name']))
{
    array_push($errors, 'Invalid image file');
}
else
{
    $uploaded_type = exif_imagetype($_FILES["myfile"]["tmp_name"]);

    switch($uploaded_type)
    {
        case '1':
            $uploaded_type = 'gif';

            if(is_ani($_FILES['myfile']['tmp_name']))
                $is_animated = true;

            $image = imagecreatefromgif($_FILES['myfile']['tmp_name']);

        break;
        case '2':
            $uploaded_type = 'jpg';
            $image = imagecreatefromjpeg($_FILES['myfile']['tmp_name']);
        break;
        case '3':
            $uploaded_type = 'png';
            $image = imagecreatefrompng($_FILES['myfile']['tmp_name']);
        break;
    }

    list($width, $height, $type, $attr) = getimagesize($_FILES['myfile']['tmp_name']);
    $originalWidth = $width;
    $originalHeight = $height;
}

$new_image = imagecreatetruecolor($newWidth, $newHeight);

imagecopyresampled($new_image, $image, 0, 0, 0, 0, $newWidth, $newHeight, $originalWidth, $originalHeight);

ob_start();
imagegif($new_image);
$frames[]=ob_get_contents();
$framed[]=40;
ob_end_clean();

ob_start();
imagegif($new_image);
$frames[]=ob_get_contents();
$framed[]=40;
ob_end_clean();

$gif = new GIFEncoder($frames,$framed,0,2,0,0,0,'bin');

$fp = fopen($baseUrl . $filename, 'w');
fwrite($fp, $gif->GetAnimation());
fclose($fp);

Is there any way to keep a gif animation, if it already exists? My check for animated gifs seem to work, but i cant manage to maintain it. Any help is much appreciated.


text:
Q: Adding GCM to android eclipse project I am trying to add push notifications to my android application and I found this tutorial on the topic.
But eclipse does not recognize GoogleCoundMessaging, even though I added google_play_service_lib to my project.
Here is my captured screen

A: I have fixed my problem.
*I added "google_play service.jar" to my project "libs" folder and add it to project build path.
*Then eclipse recognized "GoogleCloudMessaging"
*But application stop working when try to get GCM RegID.
*I run my application without debugging. All problems fixed!


text:
Q: Switching 12 V with an active low 5 V signal I'm trying to switch 12 V (max 30 mA) with a signal from a MCU that I'd prefer to be active low (so the output voltage is 12V when the control signal is 0 V, and 0 V when the control signal is 5 V).
Since I have plenty of bipolar transistors at hand, I'm looking for a solution using bipolar transistors. For an active high signal, I found an answer on this site which seems to work perfectly, and it seems this can be adapted to an active low signal by adding yet another PNP transistor:

simulate this circuit – Schematic created using CircuitLab
However, 3 transistors for what seems to be a fairly simple problem seems a bit excessive. Is there a better solution?

A: You can achieve this with two NPN transistors as shown below. As you can see, whenever a 0V signal is given, 12V is seen in the output, and whenever a 5V is given in the input, 0V is seen on the output.
Let's see how it works. First of all, let's start with the scenario where the input is 5V, or in other words, HIGH. This will turn Q1 ON and the voltage on the collector of Q1 will be almost equal to the voltage on its emitter, which is GND. Q2's base is connected to Q1's collector, so when there is 0V on Q1's collector, or in other words when Q1 is ON, Q2 is OFF. That is because Q2's base will be shorted to ground.
When the input is 0V, or LOW, Q1 will not turn ON and can be imagined as being not connected at all. So, the current passing through R1 will turn ON Q2.
The current of Q2 is limitied with its base current and hFE, as it can bee seen in the below equation;
\$I_{CQ2}=I_{BQ2}*hFE_{Q2} = \dfrac{12-0.6}{10*10^3}*300=350 mA \$
As it can be seen, maximum current that can pass through Q2 is about 350mA. But this highly depends on hFE of the transistor, which can vary anywhere from about 50 to 300. With a hFE of 50, the current can be maximum of about 60 mA, which is enough for your specs. Lowering R1 will increase the current that Q2 will pass.

A: How about this for an idea.
With the input at 5V no current can flow through the zener (5 + 9 > 12). The output PNP transistor of held OFF by the base emitter resistors (= 4k7 + 2k2) and the output is 0. When the input is pulled down to 0V a small current will flow through the base  and the 2k2 resistor. The junction of the two resistors will be a 9V (the zener voltage) and the base will be at 11.4V (assuming a 0.6V Vbe drop).
The total current flowing through the base and zener (sink current) will be added (Kirchoff's current law). With values shown the base current will be 0.5mA and the resistor current 1.4mA giving a sink current of just under 2mA.

A: Here's an idea: -

Two NPNs and a PNP for the output stage. Resistor R is optional but some folk like to see one there. Make it 4k7.
With a logic 1 drive from the MCU, the middle transistor's base is shorted to ground and so collector current won't flow and therefore the output transistor will be off.


text:
Q: Angular logic chaining in ng-class I'm trying to chain logic in angular's ng-class directive. My code within ng-class looks like this:
'class-name': (x && y) || (z && !y)

It was working all fine when I only had (x && y) but the other expression broke it. This:
'class-name': x && y, 'class-name': z && !y

also doesn't work. Does anybody know the correct syntax for chaining expressions here? Thanks a lot for your help!


text:
Q: Is the following approximate functional equation for Riemann zeta function continuous at $t=8\pi$? Let $s=\sigma+it$, then the approximate functional equation for Riemann zeta function can be given by
$$\zeta(s) = \sum_{n\leqslant \sqrt{|t|/(2\pi)}}\frac{1}{n^s} \ + \chi(s) \ \sum_{n\leqslant \sqrt{|t|/(2\pi)}}\frac{1}{n^{1-s}} \ + \ O(x^{-\sigma}+ \ |t|^{\frac{1}{2}-\sigma}y^{\sigma - 1})\tag{1}$$
where $\chi(s)=\frac{\pi^{-(1-s)/2}\Gamma((1-s)/2)}{\pi^{-s/2}\Gamma(s/2)}$.
Question
Because the number of summation terms jumped by one when $t$ varies from $8\pi+0^-$ $8\pi+0^+$, is $\zeta(\sigma+it)$ still continuous at $t=8\pi$? There must be a proof somewhere.