text:
Q: How do you display Ruby ActiveAdmin attributes_table rows in 2 or more columns? With ActiveAdmin, you can have an attributes_table, eg
show do
    attributes_table do
        row :name
        row :gender
        row :email
        row :phone_number
    end
end

You would have a table with a bunch of rows, like the following:
Name              Joe Smith
Gender            Male
Email             joe.smith@joesmith.com
Phone Number      07722123456

The generated html looks like

            Name
            Joe Smith

            Gender
            Male

            Email
            joe.smith@joesmith.com

            Phone Number
            07722123456

I would like to display these attributes in 2 columns, like
Name      Joe Smith                  Gender         Male
Email     joe.smith@joesmith.com     Phone Number   07722123456

How do I achieve this easily with ActiveAdmin?
Thanks

A: There is an Arbre componenet to help with this, take a look at the documentation at https://activeadmin.info/12-arbre-components.html#columns


text:
Q: How to bind control's properties to variables in C#? I have form with lot's of TextBoxes and also there is a lot of threads in my program that need to read content's of those TextBoxes (settings).
Since I can't access controls from other threads, I decided to make special class that will hold all the settings, and if user changes some, control will invoke OnTextChanged event and change corresponding value in class. But if I use that approach there will be a lot of similar handlers tike this
private void txtCrap1_TextChanged(object sender, EventArgs e)
{
    Settings.Crap1 = txtCrap1.Text;
}

What I want is to do something like this
private void SetUpControlBindings()
{
    AddBinding(txtCrap1, Settings.Crap1);
    AddBinding(txtCrap2, Settings.Crap2);
}
private void AddBinding(object control, object value)
{
    //Add entry to some kind of dictionary
}
private void UpdateValue(object sender, EventArgs e)
{
    if (sender is TextBox)
    {
    //Search it in dictionary and change appropriate value
    }
}

But I can't find any pointers to variables in C#
Any ideas how to do this?
P.S. I can't use reflection since my code will be obfuscated after compilation
upd:
Actually my program is a bit more complicated. I have not only textboxes, but CheckBoxes, NumericUpDowns etc. also I want my Settings class to hold some additional objects like Lists.

A: The way I normally would solve something like this is by using data bindings.
txtCrap1.DataBindings.Add("Text", Settings, "Crap1");
chkCrap2.DataBindings.Add("Checked", Settings, "Crap2");

The problem is of course the obfuscation. But when obfuscating you can exclude things, like entire classes, methods or properties. If possible you could exclude the properties of the Settings class from the obfuscation and then be able to use normal data bindings. How you would exclude a property depends on the obfuscation framework you use.

A: Make your Settings object backed by a Dictionary<string, string> that maps the names of the textboxes to their values.
For example:
readonly Dictionary<string, string> values = new Dictionary<string, string>();
public void AddBinding(TextBox box) {
    box.Change += TextBox_Change;
    values.Add(box.Name, box.Value);
}

void TextBox_Change(object sender, EventArgs e) {
    var box = (TextBox)sender;
    values[box.Name] = box.Value;
}

//Properties:
public string Prop1 { get { return values["textBox1"]; } }
//Where textBox1 is the name of the textbox

Note
To use this on multiple threads, you'll need to use a ReaderWriterLockSlim.

A: Create a DataTable with a column for each TextBox, add a single row to it, and use normal Windows Forms data-binding. Then just treat the DataRow like a dictionary.

redpajama_set_name: RedPajamaStackExchange


text:
Q: exercise in quadratic reciprocity law This is exercise 22 in chapter 6 of Ireland and Rosen's A classical intorduction to Modern number theory, which is a modified argument of Kronecker about the sign of Gauss sum:
Let $\chi$ be the quadratic character mod p given by the Legendre symbol, let $$g(\chi)=\varepsilon\prod_{k=1}^{(p-1)/2}(\zeta^{2k-1}-\zeta^{-(2k-1)})$$ we want to show that $\varepsilon=+1$. Let $$f(x)=\sum_{j=1}^{p-1}\chi(j)x^j-\varepsilon\prod_{k=1}^{(p-1)/2}(x^{2k-1}-x^{-(2k-1)})$$.
Then $f(\zeta)=0$ and $f(1)=0$, we have $x^p-1|f(x)$. Write $f(x)=(x^p-1)h(x)$ for some $h(x)\in\mathbb{Z} [x]$. Now let $x=1+t$ then compare coefficients of  $t^{\frac{p-1}{2}}$ mod p of both sides.  To obtain that $\varepsilon =+1$ I need to show that $\sum_{j=\frac{p-1}{2}}^{p-1}\chi(j)\frac{j!}{(j-\frac{p-1}{2})!}\equiv -1$ mod $p$. Thanks


text:
Q: Запись таблицы в текстовый файл Пытаюсь записать таблицу в текстовый файл, но запись происходит только для первой  строки, а остальная часть таблицы не записывается. Как исправить код, чтобы писалась вся таблица? Главное в консоль выводится вся таблица верно.
 class Program
{
    static void Main(string[] args)
    {
        // строка подключения к БД
        string connStr = "server = localhost; port = 3306; username = root; password =; database = blacklist999";
        // создаём объект для подключения к БД
        MySqlConnection conn = new MySqlConnection(connStr);
        // устанавливаем соединение с БД
        conn.Open();
        // запрос
        string sql = "SELECT steamID, type, why FROM toxics";
        // объект для выполнения SQL-запроса
        MySqlCommand command = new MySqlCommand(sql, conn);
        // объект для чтения ответа сервера
        MySqlDataReader reader = command.ExecuteReader();
        // читаем результат
        while (reader.Read())
        {
            // элементы массива [] - это значения столбцов из запроса SELECT
            Console.WriteLine(reader[0].ToString() + "|" + reader[1].ToString() + "@" + reader[2].ToString());
        }

        StreamWriter sw = new StreamWriter(@"D:\1.txt");
        sw.Write(reader[0].ToString() + "|" + reader[1].ToString() + "@" + reader[2].ToString());
        sw.Close();

        reader.Close(); // закрываем reader
        // закрываем соединение с БД
        conn.Close();
        Console.ReadLine();

    }
}

Если поместить в sw.Write в while (reader.Read()) ничего не меняется :(
class Program
{
    static void Main(string[] args)
    {
        // строка подключения к БД
        string connStr = "server = localhost; port = 3306; username = root; password =; database = blacklist999";
        // создаём объект для подключения к БД
        MySqlConnection conn = new MySqlConnection(connStr);
        // устанавливаем соединение с БД
        conn.Open();
        // запрос
        string sql = "SELECT steamID, type, why FROM toxics";
        // объект для выполнения SQL-запроса
        MySqlCommand command = new MySqlCommand(sql, conn);
        // объект для чтения ответа сервера
        MySqlDataReader reader = command.ExecuteReader();
        // читаем результат
        while (reader.Read())
        {
            // элементы массива [] - это значения столбцов из запроса SELECT
            Console.WriteLine(reader[0].ToString() + "|" + reader[1].ToString() + "@" + reader[2].ToString());
            StreamWriter sw = new StreamWriter(@"D:\1.txt");
            sw.Write(reader[0].ToString() + "|" + reader[1].ToString() + "@" + reader[2].ToString());
            sw.Close();
        }

        reader.Close(); // закрываем reader
        // закрываем соединение с БД
        conn.Close();
        Console.ReadLine();

    }
}

A: Поместите
sw.Write(reader[0].ToString() + "|" + reader[1].ToString() + "@" + reader[2].ToString());

В цикл while, туда, где вы выводите в информацию о записи в консоль

A: static void Main(string[] args)
    {
        // строка подключения к БД
        string connStr = "server = localhost; port = 3306; username = root; password =; database = blacklist999";

        using (var con = new MySqlConnection(connStr))
        using(var cmd = con.CreateCommand())
        {
            cmd.CommandText = "SELECT steamID, type, why FROM toxics";
            con.Open();
            using (var reader = cmd.ExecuteReader())
            using (var writer = new StreamWriter(@"D:\1.txt"))
            {
                while (reader.Read())
                {
                    writer.WriteLine(reader[0].ToString() + "|" + reader[1].ToString() + "@" + reader[2].ToString());
                }
            }
        }
    }


text:
Q: Comparison Test Question (Theory based?)
Consider the series $$S = \sum_{n=1}^\infty \frac{1}{n!}$$
$(a.)$ Use ratio test to prove that this series is convergent.
  $(b.)$ Use comparison test to show that $S<2.$
$(c.)$ Write down the exact value of $S$.

I have a problem answering b and c.
I do not know how to approach this question. I would appreciate it if someone could explain to me how to attempt this kind of question.
Thank you!

A: Note that $n! \ge 2^{n-1}$ , $\forall n \ge 1$ and in particular $n! > 2^{n-1}$ , $\forall n \ge 3$
Prove by induction!
Then note that $\frac{1}{n!} \le \frac{1}{2^{n-1}}$ $\forall n\ge 1$ and in particular, $\frac{1}{n!} < \frac{1}{2^{n-1}}$ $\forall n\ge 3$
Thus $S = \sum_{n=1}^\infty\frac{1}{n!} < \sum_{n=1}^\infty  \frac{1}{2^{n-1}} = \frac{1}{1-\frac{1}{2}}=2 $
For part (c), recall $e^x=\sum_{n=0}^\infty \frac{x^n}{n!}$
Thus, $e=1+\frac{1}{1!}+\frac{1}{2!}+\dots=1+S \implies S=e-1$

A: Consider another infinite series
$$S' = 1 + \frac12 + \frac14 +\frac18 +....$$
It is easy to see that each element of $S'$ is $\ge$ than each element in $S$
We know that the sum of $S'$ is $2 \space($ Using sum of a G.P $).$
Hence we can claim that $S < S'$ or $S < 2$.
For the last part  , recall the value of the constant $e$.
We know that
$$e = \sum_{n=0}^\infty \frac1{n!}$$
Again it is easy to observe that $$S + 1 =e$$
Or $$S = e-1 \iff \boxed{\color{blue}{S = 1.71828...}}$$


text:
Q: how to manage/organize layouts in android studio when number of layouts in the project are too large? Normally when I create an android project I try to separate android java or kotlin files in packages as per their functions like activity, fragments, adapters, etc.
Image for package distribution of kotlin files
Now as my project size is increasing thus the number of layouts files. At present I have around 20 layout files and it is difficult to know which file is linked to what when I refer project again after few weeks. I want to know if there is a better way to organize layout files just like as I did for kotlin files in the structure of cards, activities, fragments, etc.
I found the package option to organize the kotlin files clicking right clicking, so I tried the same and there I found the option folder, But when I place file in that folder android studio isn't detecting it.
So is there a better way to organize these layout files?

A: I found just one way of doing it and that is by appending the particular layout name by type name.
For example, if we have a card layout file and dialog layout file, then it helps if we name them as card_(File name) and dialog_(File name).


text:
Q: How to know has a product an image In which table i can understand has a product an image or not. This is need to do with mysql queryes, not magento models.

A: In catalog_product_entity_media_gallery table you get information about product image
Please check image

Simple mysql query for getting image from databse is
$connection = Mage::getSingleton('core/resource')->getConnection('core_read');
    $sql= "Select value from catalog_product_entity_media_gallery WHERE entity_id=1";
    $rows       = $connection->fetchAll($sql);

Where entity_id is a propductId
Let me know if you have any query

A: Also with magento
<!--
<?php
$products123321 = Mage::getModel('catalog/product')
->getCollection()
->addAttributeToSelect('*')
->addAttributeToFilter('image', 'no_selection');

foreach($products123321 as $product123321)
{
    echo  $product123321->getSku() . " has no image \n<br />\n";
    //var_dump($product->getData()); //uncomment to see all product attributes
                                     //remove ->addAttributeToFilter('image', 'no_selection');
                                     //from above to see all images and get an idea of
                                     //the things you may query for
}
?>
-->


text:
Q: Why my jQuery ajax call is not successful I am developing my web app and run it on localhost:8080, in my js file, I have an ajax call to get xml data from server:
$.ajax({
        url: 'http://COMPANY_DOMAIN.com/company-interface/the-id',
        type: 'GET',
        async: false,
        dataType: 'application/xml',
        data: {id: 43},
        success: function(data) {

            alert(data);

        },
        error: function(xhr, status, error){
            alert('error happens');
        }
     })

I can access the url http://COMPANY_DOMAIN.com/company-interface/the-id/?id=43 which will show the xml result on browswer, but my above ajax call always go to error function.
I checked in firebug, the 'xml' tab shows "XML Parsing Error: no element found Location: moz-nullprincipal:{9fd0dca8-cf07-4401-b1de-ab04e8aa00bc} Line Number 1, Column 1:" and firebug shows the URL GET is http://COMPANY_DOMAIN.com/company-interface/the-id/?id=43& =1302610001570.
Why firebug GET shows the "...& =1302610001570"? what does it means? why my ajax call is failed, though I can access that URL?
----------------EDIT---------------
Hi, I changed to use localhost request like:
$.ajax({
            url: 'http://localhost:8080/company-interface/the-id',
            type: 'GET',
            async: false,
            dataType: 'xml',
            data: {id: 43},
            success: function(data) {

                alert(data);

            },
            error: function(xhr, status, error){
                alert('error happens');
            }
         })

But I got the same error... more suggestions please... thank you.

A: This is possibly due to cross domain access control. You are accessing the site which is on your machine which tries to connect to another website. This is not allowed unless you define Access-Control-Allow-Origin headers.
Also as @Craig said, content type as xml is needs to be changed.

A: Javascript is subject to the same origin policy. Your script running on localhost can't access COMPANY_DOMAIN.com.

A: Try Below code :
 $.ajax({
            url: 'http://localhost:8080/company-interface/the-id',
            type: 'GET',
            async: false,
            dataType: 'text',
            data: {id: 43},
            success: function(data) {

            // Assume response like..
            // <note>
            //    <from>Jani</from>
            //    <to>Tove</to>
            //    <message>Remember me this weekend</message>
            //  </note>

            xmlDoc = $.parseXML( data ),
            $xml = $( xmlDoc ),
            $message = $xml.find("message")
            alert($message.text());
            $("#xmlResonse").html($message.text());

        },
        error: function(xhr, status, error){
            alert('error happens');
        }
     })

A: change your datatype to application/xml or text/xml
As the other comment suggests, is your URL on another domain? If not then try using relative URL's instead.

A: 1302610001570 is for measuring response,
did you checked if the response create valid xml?


text:
Q: how to avoid xml caching plain javascript I'm trying to avoid xml caching. I read about this solution: How to force browser to reload updated XML file?
But no example is provided for a newbie! I think this is the part of my code for requesting XML where something has to be changed
xmlhttp.open("GET",link_xml,false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;

Can someon provide help? Thank you!

A: Before doing xmlhttp.send(); you can use:
xmlhttp.setRequestHeader("Cache-Control", "no-cache");

or
xmlhttp.setRequestHeader("Pragma", "no-cache");


text:
Q: mapnik stylesheet is not working with mapnilk v2.1.0 I installed mapnik using command line
sudo apt-get install -y python-software-properties
echo 'yes' | sudo add-apt-repository ppa:mapnik/v2.1.0
sudo apt-get update
# install core mapnik
sudo apt-get install -y libmapnik mapnik-utils python-mapnik
# install the python binding
sudo apt-get install -y python-mapnik
# confirm mapnik-config returns 2.1.0
mapnik-config -v

When i run python code doing import mapnik it worked fine. When i tried to generate a image using shape file it output the result. But when i tried the same using osm file and used the style sheet osm.xml given in this link http://wiki.openstreetmap.org/wiki/Mapnik_Example it then gives me error
Traceback (most recent call last):
  File "render.py", line 6, in <module>
    mapnik.load_map(m, stylesheet)
RuntimeError: Failed to parse expression: "NAME" in style 'CountryLabels' in TextSymbolizer at line 33 of 'mapnik_style2.xml'
Here i am using TextSymbolizer to display the country name.
Am i doing something wrong here. Any help will be grateful.
Thanks in Advance.

A: The example that you refer to is not up to date.
It was used for mapnik 0.7

(NOTE: The code used in this example is not current and was used for mapnik 0.7. Attempts to reproduce this image using mapnik 2.0+ using the following workflow will not work.]

The version 2.1 got a lot of change even for the style fomat. The parsing error about "NAME" of the xml style file comes from this. Starting with Mapnik 2.0 the new syntax for TextSymbolizer is used:
<TextSymbolizer name="[label]" />

becomes
<TextSymbolizer>[label]</TextSymbolizer>

This change was made to be forward compatible with changes to text formatting being introduced in later versions.
And your xml style file is probably even older (This is in the page that you indiquate):
<TextSymbolizer name="name" face_name="DejaVu Sans Bold" size="10" fill="#734a08" dy="18" halo_radius="1" wrap_width="0"/>

Attention: The attribute 'name' of node TextSymbolizer has NO square brackets.
So if you want to change your XML style file, you need to add [] to name -> name="[name]".  If you need more information about the TextSymbolizer, you can reference to: https://github.com/mapnik/mapnik/wiki/TextSymbolizer
If you need another example style file to test, perhaps this osm.xml could help:
https://trac.openstreetmap.org/browser/subversion/applications/rendering/mapnik/osm.xml?order=name


text:
Q: Spring Boot tries to connect to Mongo localhost I have a Spring Boot 2.x project using Mongo.  I am running this via Docker (using compose locally) and Kubernetes.  I am trying to connect my service to a Mongo server.  This is confusing to me, but for development I am using a local instance of Mongo, but deployed in GCP I have named mongo services.
here is my application.properties file:
#mongodb
spring.data.mongodb.uri= mongodb://mongo-serviceone:27017/serviceone

#logging
logging.level.org.springframework.data=trace
logging.level.=trace

And my Docker-compose:
version: '3'

# Define the services/containers to be run
services:
  service: #name of your service
    build: ./ # specify the directory of the Dockerfile
    ports:
      - "3009:3009" #specify ports forwarding
    links:
      - mongo-serviceone # link this service to the database service
    volumes:
      - .:/usr/src/app
    depends_on:
      - mongo-serviceone

  mongo-serviceone: # name of the service
    image: mongo
    volumes:
        - ./data:/data/db
    ports:
        - "27017:27017"

When I try docker-compose up . I get the following error:

mongo-serviceone_1          | 2018-08-22T13:50:33.454+0000 I NETWORK
  [initandlisten] waiting for connections on port 27017 service_1
  | 2018-08-22 13:50:33.526  INFO 1 --- [localhost:27017]
  org.mongodb.driver.cluster               : Exception in monitor thread
  while connecting to server localhost:27017 service_1
  |  service_1                   | com.mongodb.MongoSocketOpenException:
  Exception opening socket service_1                   |   at
  com.mongodb.connection.SocketStream.open(SocketStream.java:62)
  ~[mongodb-driver-core-3.6.3.jar!/:na]

running docker ps shows me:
692ebb72cf30        serviceone_service        "java -Djava.securit…"   About an hour ago   Up 9 minutes        0.0.0.0:3009->3009/tcp, 8080/tcp   serviceone_service_1
6cd55ae7bb77        mongo                      "docker-entrypoint.s…"   About an hour ago   Up 9 minutes        0.0.0.0:27017->27017/tcp           serviceone_mongo-serviceone_1

While I am trying to connect to a local mongo, I thought that by using the name "mongo-serviceone"

A: Hard to tell what the exact issue is, but maybe this is just an issue because of the space " " after "spring.data.mongodb.uri=" and before "mongodb://mongo-serviceone:27017/serviceone"?
If not, maybe exec into the "service" container and try to ping the mongodb with: ping mongo-serviceone:27017
Let me know the output of this, so I can help you analyze and fix this issue.
Alternatively, you could switch from using docker compose to a Kubernetes native dev tool, as you are planning to run your application on Kubernetes anyways. Here is a list of possible tools:
Allow hot reloading:

*

*DevSpace: https://github.com/covexo/devspace

*ksync: https://github.com/vapor-ware/ksync
Pure CI/CD tools for dev:

*

*Skaffold: https://github.com/GoogleContainerTools/skaffold

*Draft: https://github.com/Azure/draft
For most of them, you will only need minikube or a dev namespace inside your existing cluster on GCP.

A: Looks like another application was running on port 27017 on your localhost Similar reported issue
quick way to check on linux/mac:
telnet 127.0.01 27017

check logs files:
docker logs serviceone_service


text:
Q: How to break out of an else statement in node js in a discord bot I'm creating a discord bot in Node JS using discord.js module and I want to send a predefined message only if the user sends a particular text command in a particular predefined channel on the discord server else if the user sends the command in any other channel then send a message to the same channel notifying the user to use the predefined channel for the commands. eg.
According to me the code with the bug is :
client.on('message', message => {

    //Check message channel
    if (message.channel === 'aim-reception') {

        if (message.content.startsWith(`${prefix}hi`)) {
            console.log(`${message.author} used the "!hi" command in channel ${message.channel}`);
            message.channel.send(`Hello ${message.author}!`);
        }
    } else return message.channel.send('Please Use the channel #aim-reception');
});

And here is the full code for index.js file :
const Discord = require('discord.js');
const { prefix, token } = require('./config.json');
const client = new Discord.Client();

// Create an event listener for new guild members
client.on('guildMemberAdd', member => {
    // Send the message to a designated channel on a server:
    const channel = member.guild.channels.find(ch => ch.name === 'member-log');
    // Do nothing if the channel wasn't found on this server
    if (!channel) return;
    // Send the message, mentioning the member
    channel.send(`Welcome to the server, ${member}`);
});

client.on('message', message => {

    //Check message channel
    if (message.channel === 'aim-reception') {

        if (message.content.startsWith(`${prefix}hi`)) {
            console.log(`${message.author} used the "!hi" command in channel ${message.channel}`);
            message.channel.send(`Hello ${message.author}!`);
        }
    } else return message.channel.send('Please Use the channel #aim-reception');
});

/**
 * The ready event is vital, it means that only _after_ this
 * will your bot start reacting to information
 * received from Discord
 */
client.once('ready', () => {
    console.log('Bot is now connected');

});

client.login(token);

Even when the channel used is correct still it is skipping the if condition and is looping the else statement indefinitely.
A Snapshot of the error in a discord server

A: You need to ignore bots, you're creating an infinite loop where:
You send a message -> your bot receives it -> your bot sends a message -> your bot receives its own message -> sends a message -> ...
At the start of your message handler put:
if (message.author.bot) {
  return;
}

Or if you only want to ignore your own bot:
if (message.client.user.id === message.author.id) {
  return;
}

A: 1. Use the channel properties
In the docs, you'll see that the TextChannel object has the TextChannel.name property.
When you compare message.channel === 'aim-reception', you're comparing an object with a string, which will always return false. Use message.channel.name === 'aim-reception' instead.
2. Ignore bot messages, or at least ignore your bot's own messages
The message event will trigger for any message, including your bot's own messages, so try to ignore bot messages all together or at least just their own. Otherwise the bot will get stuck repeatedly replying to their own messages.
client.on('message', message => {
  // ignore bot messages
  if (message.author.bot) return;
  // ...
});

// or

client.on('message', message => {
  // ignore own messages
  if (message.author.id === client.user.id) return;
  // ...
});


text:
Q: access referenced projects at runtime I have a rather strange project where I need to check the assemblies of the projects included as references in my project to see if they contain a certain Type. As far as I can tell the only way to see which projects are in my solution is to parse the solution file - which I can't do at runtime since I don't have it.
Does anyone know a way to see, at runtime, which assemblies are in the project file?

A: To check the referenced assemblies in your project assembly at runtime, you need to use Reflection.this.GetType().Assembly.GetReferencedAssemblies()


text:
Q: Converting float to 32-bit hexadecimal C++ Could anyone please tell me if there is any code to convert floating point number to hexadecimal format?
For Ex: float num = 70.482 and hexadecimal function should return 428CF6C9.
If there are any codes already done before on this, kindly link me.
Cheers.

A: something like this is the floattohex conversion i use.. (it also performs a bit swap, if you dont need this take it out)
CString Class::FloatToHex(float* yourfloat)
{
unsigned char ch[4];
Cstring output;

memcpy(ch,yourfloat,sizeof(float));
output.Format("%X%X%X%X",ch[3],ch[2],ch[1],ch[0]);

return output;
}

A: Consider:
union float_bits {
    unsigned int i;
    float f;
} bits;

Assign the floating point number into bits.f, and then interpret the whole number as an unsigned integer and read it with bits.i. By doing this the floating point representation bytes will stay intact, and no implicit type conversion will be done as it would be when assigning a float to an int type variable. In this case we assume that the size of integer is same as the size of float.
Or you can do:
float f;
char *c = (char *) &f;

And then access the individual bytes of f through c[index].

A: You can just trivially write that yourself:
float x;
const unsigned char * pf = reinterpret_cast<const unsigned char*>(&x);

for (size_t i = 0; i != sizeof(float); ++i)
{
  // ith byte is pf[i]
  // e.g. printf("0x02X ", pf[i]);
}

In fact, you can do that to obtain the binary representation of any (standard-layout*) variable.
*) thanks, @R. Martinho Fernandes!
If you decide to try this on a long double (or rather, an 80-bit extended precision float), beware that that has only 10 bytes, but is padded to 12 or 16 on x86/x64, respectively.

A: float f = 70.482f;
int i = *(reinterpret_cast<int*>(&f));
printf("%08x\n", i);

A: you could use a union:
union FloatToChar {
    float f;
    char  c[sizeof(float)];
};

FloatToChar x;
x.f = 10.42f;
for (size_t i=0; i<sizeof(float); i++)
    printf( "%X", x.c[i] );

you could do this vice-versa, too.

A: Simply use sprintf() : http://www.cplusplus.com/reference/clibrary/cstdio/sprintf/
For example,
char out[8];
float myFloat = 70.482;
sprintf(out,"%X",myFloat);


text:
Q: Whats the trick behind getting the physical IP address? How can I get the same IP Address I get when I go to "http://www.whatsmyip.org/" using C++ and winsock library?
I know how to get the "127.0.0.1" and the router IP "192.168.1.103"...
But when I got to "http://www.whatsmyip.org/" I get "65.55.105.132"...
How can I accomplish this?

A: You can't.
http://www.whatsmyip.org is telling you the IP address it sees when you talk to it. It could be seeing yours, or a proxy server, or a NAT box, or anything else. There's no way for you to know.
What are you trying to accomplish?

A: In a general way - you can't.  You could open an http connection to whatmyip and parse the result.  Or as Justin suggests in the comments, use http://www.whatismyip.com/automation/n09230945.asp and save on parsing and bandwidth.  But in the end, that's only going to give you the IP of the NAT / proxy / whatever that's between you and whatsmyip.  That address is only connected to your computer through forwarding.
There isn't a general way to retrieve your router's internet facing IP address (that's the 65.55.105.132 IP you are seeing.)  Even if you could, there's no reason that there couldn't be more layers of NATing getting in the way.

A: There is no way to accomplish this without using something that is outside of your network.
The address returned is the first public ip address between your computer and the outside world.  10., 192.168., 172.[16-31].* ip address are "private" and should not be forwarded intact to any non-private ip address.
At some point, private ip addresses must be linked to a public ip address.  The first public ip address in the path from your computer to the whatsmyip.com site is what is displayed on that page.  The trick is that your computer might have a public ip, or there might be some number of hops to computers/switches/routers that have private ip's until there is eventually a public ip.  There is no way to know what that number of hops is, and depending on the network the route can change from one request to another and there migth be a different number of hops each time (unlikely for a home network, but more likely in a corporate network).
The only way to get the first public ip address is to send a packet to an address that is public, and trace the route that it took.  Again...that route can (and does) change on a complex network.
If you have a specific problem that you are trying to solve, there might be a better answer.

A: As others have said, you need a third party on the network such as whatismyip.com to tell you your IP address. I just wanted to add, you shouldn't depend on whatismyip.com, instead you should consider setting up your own, as services like this tend to come and go or change who may connect to them (see this example for why that may happen).
You can easily set up a service to do this just for your application for free, say, based on Google AppEngine. The requisite request handler might look something like:
from google.appengine.ext import webapp

class RemoteAddressHandler(webapp.RequestHandler):
    def get(self):
        self.response.out.write(self.request.remote_addr)

A: Well, there is no trick really. The reason www.whatsmyip.com can tell your "outside" IP address is because they receive a request that has been NATed (Network Address Translated) by your router and so they see your public IP address. That is something that you can't really get at an arbitrary internal host on your network - not unless you have a server on the outside that you could query or have a mechanism to ask your router what IP address it uses when making public internet requests..

A: As others have said, there may not be an easy / great solution.  An (albeit hacky) solution might be to shell out to the 'tracert' system call.  Ex:
tracert google.com

This call will return a list of all routers in between your PC and google.com (or whatever external site.)  You can then iterate through the results, taking the first node that isn't a private IP address range.  (I.e., not 192.168.., etc.)
Granted, this is by no means an elegant solution.  However, it might give you the info you need.  As a test, you can simply run the above from a command line and see if it's helpful.

A: Wow that was a very quick reply. Thanks guys for the answers now I know better.
I am currently building a C++ HTTP server for learning purpose. I accomplish to forward the IP address I get when I got to "whatismyip.org" to my private ip "192.168.1.3" making any external call to be handle by my server. So pretty much I created a simple C++ server. However I am using something called No-IP DUC to translate "yellowyackets.no-ip.org" to my public IP so that people don't have to memorize my public IP. But because the IP changes I have to keep track to whats is my new IP so that people can keep connecting to me... so I have to go to "whatsmyip.org" to know my new IP. Then I wanted to create a program that would actually tell me thats my new IP.
I dunno if what I just said make sense but... I am brand new to servers... Like I said this is for learning purpose.
Thanks again.
and good luck to everyone.

A:
One c/c++ way of getting the external ip is to use a web based IP address API tool, download the webpage containing your IP address into a char array and extract the IP address from the HTML source. Here is some winsock code to demonstrate it. it uses http://api.ipify.org/ 's online web api.
//
// Winsock get external ip address from website api at   api.ipify.org
// api.ipify.org
//

#include <string.h>
#include <stdio.h>

#include <winsock2.h>
#include <windows.h>
#include <iostream>
#include <vector>

#include <algorithm>
#include <cctype>
#include <locale>
#include <fstream>
#include <ctime>
#include <cstdlib>

using namespace std;
#pragma comment(lib,"ws2_32.lib")

string website_HTML;
locale local;
char ipaddress[16];
int ic=0;
void get_Website(char *url );
char mystring[] = " ";
char seps[]   = " ,\t\n";
char *token;
char lineBuffer[200][80] ={' '};
char buffer[10000];
char ip_address[16];
int i = 0, bufLen=0, j=0,lineCount=0;
int lineIndex=0, posIndex=0;

int main( void ){

    SYSTEMTIME st;
    GetLocalTime(&st);
    char *today = new char[32];
    memset(today,' ', sizeof(today) );
    sprintf(today,"%d-%d-%d", st.wYear , st.wMonth , st.wDay);
    memset(buffer,'\0',sizeof(buffer));

    get_Website("api.ipify.org" );
    for (size_t i=0; i<website_HTML.length(); ++i) website_HTML[i]= tolower(website_HTML[i],local);

    token = strtok( buffer , seps );
    while( token != NULL ){

      strcpy(lineBuffer[lineIndex],token);
      int dot=0;
      for (int ii=0; ii< strlen( lineBuffer[lineIndex] ); ii++ ){

          if (lineBuffer[lineIndex][ii] == '.') dot++;
          if (dot>=3){
              dot=0;
              strcpy(ip_address,lineBuffer[lineIndex]);
          }
      }

      token = strtok( NULL, seps );
      lineIndex++;
   }
     cout<<"Your IP Address is  "<< ip_address<<" \n\n";

 return 0;
}

void get_Website(char *url ){
    WSADATA wsaData;
    SOCKET Socket;
    SOCKADDR_IN SockAddr;
    int lineCount=0;
    int rowCount=0;
    struct hostent *host;
    char *get_http= new char[256];

    memset(get_http,' ', sizeof(get_http) );
    strcpy(get_http,"GET / HTTP/1.1\r\nHost: ");
    strcat(get_http,url);
    strcat(get_http,"\r\nConnection: close\r\n\r\n");

    if (WSAStartup(MAKEWORD(2,2), &wsaData) != 0){
        cout << "WSAStartup failed.\n";
        system("pause");
        //return 1;
    }

    Socket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
    host = gethostbyname(url);

    SockAddr.sin_port=htons(80);
    SockAddr.sin_family=AF_INET;
    SockAddr.sin_addr.s_addr = *((unsigned long*)host->h_addr);

    if(connect(Socket,(SOCKADDR*)(&SockAddr),sizeof(SockAddr)) != 0){
        cout << "Could not connect";
        system("pause");
        //return 1;
    }
    send(Socket,get_http, strlen(get_http),0 );

    int nDataLength;
    while ((nDataLength = recv(Socket,buffer,10000,0)) > 0){
        int i = 0;
        while (buffer[i] >= 32 || buffer[i] == '\n' || buffer[i] == '\r'){

            website_HTML+=buffer[i];
            i += 1;
        }
    }

    closesocket(Socket);
    WSACleanup();
    delete[] get_http;
}


text:
Q: Select a href in WordPress Primary Navigation to open modal I am creating WordPress theme and trying to open modal by clicking on li element containing a href inside navigation menu
My code is working in static html:

// Get the modal
var modal1 = document.getElementById("myModal-registration");

// Get the button that opens the modal
var btn1 = document.getElementById("sign-up");

// Get the  element that closes the modal
var span1 = document.getElementsByClassName("close")[0];

// When the user clicks the button, open the modal
btn1.onclick = function() {
    modal1.style.display = "block";
};

// When the user clicks on  (x), close the modal
span1.onclick = function() {
    modal1.style.display = "none";
};

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
    if (event.target == modal1) {
        modal1.style.display = "none";
    }
};
.modal {
    display: none; /* Hidden by default */
    position: fixed; /* Stay in place */
    z-index: 1; /* Sit on top */
    padding-top: 100px; /* Location of the box */
    left: 0;
    top: 0;
    width: 100%; /* Full width */
    height: 100%; /* Full height */
    overflow: auto; /* Enable scroll if needed */
    background-color: rgb(0,0,0); /* Fallback color */
    background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
    z-index: 1000;
}

/* Modal Content */
.modal-content {
    background-color: #fefefe;
    margin: 0 auto;
    padding: 20px;
    border: 1px solid #888;
    width: 60%;
    @media screen and (max-width: 420px) {
        width: 100%;
    }
    .container {
        font-family: 'Open Sans', sans-serif;
        display: block;
        font-size: 18px;
        line-height: 20px;
      //  margin: 0 auto;
    }
}

/* The Close Button */
.close {
    color: #aaaaaa;
    float: right;
    font-size: 28px;
    font-weight: bold;
}

.close:hover,
.close:focus {
    color: #000;
    text-decoration: none;
    cursor: pointer;
}

SIGN UP

    ×
      <form class="modal-content-animate" action="/action_page.php">

      <input type="text" placeholder="Enter Email" name="email" required>

      <input type="password" placeholder="Enter Password" name="psw" required>

      <input type="password" placeholder="Repeat Password" name="psw-repeat" required>

        <button type="submit" class="signupbtn">Sign Up</button>
        <button type="button" onclick="document.getElementById('myModal-registration').style.display='none'" class="cancelbtn">Cancel</button>

  </form>

But in WordPress a menu is registered in functions.php :
function register_theme_menus() {

    register_nav_menus(array(
        'primary-navigation' => __( 'Primary Navigation' ),
    ));
}

and is called using PHP in header.php:
   wp_nav_menu(array(
                'container' => 'ul',
                'menu_class' => '',
                'theme_location' => 'primary-navigation',
                'menu' => 'primary-navigation'
           ));

after all, generated HTML code have no id for a href:

SIGN UP

A custom URL with # was set in WordPress Menu options:

and was attempted to be selected as a href by using JS:
var btn1 = document.querySelectorAll("a[href^='#sign-up']");

but without any decent results. Am I missing a point here and using only JS is not an valid option in this case?
Let me know if you have any additional questions.
Many thanks for all possible help, will be looking forward.

A: The menu-item (li) in wp menus usually have a unique class. In your case its  menu-item-20
You can target the link you are asking with  .menu-item-20 a
so use
// Get the button that opens the modal
var btn1= document.querySelector(".menu-item-20>a")


text:
Q: "Unmerge" upstream branch by resetting origin and then merging I am having a problem reverting a merge I made into an upstream branch, to which I do not have direct write access.
I made some changes locally, pushed them to origin, and had them merged by a fellow team member into our upstream repository. Now I want to revert those changes, essentially "unmerge" the merge. So far, I have:

*

*Reverted my local repository to the correct commit using git reset --hard *commit number*

*Force push this reset to origin using git push --force origin *branch name*
Currently, my remote repository is updated to show none of the commits that I have reverted, which is correct. However, when I try to merge these changes into upstream, essentially "unmerging" my previous merge, GitHub shows that there are no differences between the specified branch of my remote repository and the same branch of the upstream respository. Am I doing something incorrectly?
Note: I tried adding a new line to a file, thus showing that there is some change between the branches, and then merging, but this did not work.


text:
Q: AttributeError: 'dict' object has no attribute 'translate' I'm having a problem with this piece of code, it's an exercise where I need to set up a word cloud by catching the frequency of words in a text.
I was able to strip off the punctuations using map and translate, then I turned them all into lower strings and checked the frequency of them with a for loop.
When I try to pass them to the wordcloud generator I get an error: AttributeError: 'dict' object has no attribute 'translate'

    import string

    def calculate_frequencies(file_contents):
        # Here is a list of punctuations and uninteresting words you can use to process your

    text
            punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''
            uninteresting_words = ["the", "a", "to", "if", "is", "it", "of", "and", "or", "an",

    "as", "i", "me", "my", \
                "we", "our", "ours", "you", "your", "yours", "he", "she", "him", "his", "her", "hers", "its", "they", "them", \
                "their", "what", "which", "who", "whom", "this", "that", "am", "are", "was", "were", "be", "been", "being", \
                "have", "has", "had", "do", "does", "did", "but", "at", "by", "with", "from", "here", "when", "where", "how", \
                "all", "any", "both", "each", "few", "more", "some", "such", "no", "nor", "too", "very", "can", "will", "just"]

    # LEARNER CODE START HERE
        word_listing=[]
        container = {}

        table = str.maketrans(dict.fromkeys(string.punctuation)) #Removing punctuation first
        file_contents = file_contents.translate(table)
        #-------------------------------------------------------------------------------
        file_contents=file_contents.split()
        file_contents=map(str.lower,file_contents) #making lower string
        file_contents=list(file_contents)
        #-------------------------------------------------------------------------------
        for item in file_contents:
            if item not in (uninteresting_words): #removing uninteresting words

                container[item]=item
                word_listing.append(item)
                #setting up frequency count

                for i in word_listing:
                    container[i] = 0
                for i in word_listing:
                    container[i] += 1

        #wordcloud
        cloud = wordcloud.WordCloud()
        cloud.generate_from_frequencies(container)
        return cloud.to_array()

That works all right, the problem comes up when I set this one up:

    myimage = calculate_frequencies(container)
    plt.imshow(myimage, interpolation = 'nearest')
    plt.axis('off')
    plt.show()

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-15-cacedc8fdb8f> in <module>
      1 # Display your wordcloud image
      2
----> 3 myimage = calculate_frequencies(container)
      4 plt.imshow(myimage, interpolation = 'nearest')
      5 plt.axis('off')

<ipython-input-13-0620c3cd20f5> in calculate_frequencies(file_contents)
     15
     16     table = str.maketrans(dict.fromkeys(string.punctuation)) #Removing punctuation first
---> 17     file_contents = file_contents.translate(table)
     18     #-------------------------------------------------------------------------------
     19     file_contents=file_contents.split()

AttributeError: 'dict' object has no attribute 'translate'

I need help on understanding why that happens and how to fix it.
Thank you all!


text:
Q: Is there an Amazon.com API to retrieve Amazon Keyword volume data Hello all I am looking for an Amazon API that can be used to pull volume of a keyword from Amazon? Is there is any API available?
This website is doing the same but not sure what services or APIs they will be using: https://www.merchantwords.com/

A: As Amazon does not publish these numbers, my guess it's just applied statistics, based on search/Amazon ranking click through distributions and the way the products Amazon rankings fluctuate.


text:
Q: WARNING: Exception encountered during context initialization - cancelling refresh attempt Error is as shown below. The problem is, occurring as below, this XmlWebApplicationContext need not occur, since it's injecting the bean again. How to avoid it?
org.springframework.web.context.support.XmlWebApplicationContext prepareRefresh

INFO: Initializing Spring root WebApplicationContext
Sep 08, 2015 12:40:44 PM org.springframework.web.context.ContextLoader initWebApplicationContext
INFO: Root WebApplicationContext: initialization started
Sep 08, 2015 12:40:44 PM org.springframework.web.context.support.XmlWebApplicationContext prepareRefresh
INFO: Refreshing Root WebApplicationContext: startup date [Tue Sep 08 12:40:44 IST 2015]; root of context hierarchy
Sep 08, 2015 12:40:44 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from ServletContext resource [/WEB-INF/context/PersistenceManagerContext.xml]
Sep 08, 2015 12:40:44 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from ServletContext resource [/WEB-INF/context/ServiceApiContext.xml]
Sep 08, 2015 12:40:44 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from ServletContext resource [/WEB-INF/context/RuleEngineContext.xml]
Sep 08, 2015 12:40:44 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from ServletContext resource [/WEB-INF/context/applicationContext.xml]
Sep 08, 2015 12:40:44 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from ServletContext resource [/WEB-INF/context/CacheContext.xml]
Sep 08, 2015 12:40:45 PM org.springframework.web.context.support.XmlWebApplicationContext refresh
WARNING: Exception encountered during context initialization - cancelling refresh attempt
org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [com.rakuten.points.persistence.manager.MemberPointSummaryDAOImpl] for bean with name 'MemberPointSummaryDAOImpl' defined in ServletContext resource [/WEB-INF/context/PersistenceManagerContext.xml]; nested exception is java.lang.ClassNotFoundException: com.rakuten.points.persistence.manager.MemberPointSummaryDAOImpl
    at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1351)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.determineTargetType(AbstractAutowireCapableBeanFactory.java:628)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.predictBeanType(AbstractAutowireCapableBeanFactory.java:597)
    at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:1444)
    at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:974)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:752)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:834)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:537)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:446)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:328)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4729)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5167)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1408)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1398)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.ClassNotFoundException: com.rakuten.points.persistence.manager.MemberPointSummaryDAOImpl
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1313)
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1164)
    at org.springframework.util.ClassUtils.forName(ClassUtils.java:250)
    at org.springframework.beans.factory.support.AbstractBeanDefinition.resolveBeanClass(AbstractBeanDefinition.java:394)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doResolveBeanClass(AbstractBeanFactory.java:1396)
    at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1343)
    ... 19 more

Sep 08, 2015 12:40:45 PM org.springframework.web.context.ContextLoader initWebApplicationContext
SEVERE: Context initialization failed
org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [com.rakuten.points.persistence.manager.MemberPointSummaryDAOImpl] for bean with name 'MemberPointSummaryDAOImpl' defined in ServletContext resource [/WEB-INF/context/PersistenceManagerContext.xml]; nested exception is java.lang.ClassNotFoundException: com.rakuten.points.persistence.manager.MemberPointSummaryDAOImpl
    at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1351)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.determineTargetType(AbstractAutowireCapableBeanFactory.java:628)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.predictBeanType(AbstractAutowireCapableBeanFactory.java:597)
    at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:1444)
    at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:974)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:752)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:834)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:537)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:446)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:328)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4729)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5167)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1408)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1398)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.ClassNotFoundException: com.rakuten.points.persistence.manager.MemberPointSummaryDAOImpl
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1313)
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1164)
    at org.springframework.util.ClassUtils.forName(ClassUtils.java:250)
    at org.springframework.beans.factory.support.AbstractBeanDefinition.resolveBeanClass(AbstractBeanDefinition.java:394)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doResolveBeanClass(AbstractBeanFactory.java:1396)
    at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1343)
    ... 19 more

Sep 08, 2015 12:40:45 PM org.apache.catalina.core.StandardContext listenerStart
SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [com.rakuten.points.persistence.manager.MemberPointSummaryDAOImpl] for bean with name 'MemberPointSummaryDAOImpl' defined in ServletContext resource [/WEB-INF/context/PersistenceManagerContext.xml]; nested exception is java.lang.ClassNotFoundException: com.rakuten.points.persistence.manager.MemberPointSummaryDAOImpl
    at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1351)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.determineTargetType(AbstractAutowireCapableBeanFactory.java:628)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.predictBeanType(AbstractAutowireCapableBeanFactory.java:597)
    at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:1444)
    at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:974)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:752)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:834)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:537)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:446)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:328)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4729)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5167)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1408)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1398)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.ClassNotFoundException: com.rakuten.points.persistence.manager.MemberPointSummaryDAOImpl
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1313)
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1164)
    at org.springframework.util.ClassUtils.forName(ClassUtils.java:250)
    at org.springframework.beans.factory.support.AbstractBeanDefinition.resolveBeanClass(AbstractBeanDefinition.java:394)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doResolveBeanClass(AbstractBeanFactory.java:1396)
    at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1343)
    ... 19 more

Web.xml
<!-- USing the dispatcher servlet -->
<servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

<!-- The pattern is /* -->
<servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/*</url-pattern>
</servlet-mapping>

<!-- Looking for beans in *Context.xml files -->
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/context/*Context.xml</param-value>
</context-param>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

Dispatcher-Servlet.xml

<!-- <import resource="/WEB-INF/context/*Context.xml"></import> -->

<bean
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix">
        <value>/</value>
    </property>
    <property name="suffix">
        <value>.jsp</value>
    </property>
</bean>

Then we have a bunch of context xmls available in the folder "CONTEXT".
Pom:
PersistenceManager has that class:
[![PersistenceManager is in the war][2]][2]

A: The important part is this:
Cannot find class [com.rakuten.points.persistence.manager.MemberPointSummaryDAOImpl] for bean with name 'MemberPointSummaryDAOImpl' defined in ServletContext resource [/WEB-INF/context/PersistenceManagerContext.xml];

due to:
nested exception is java.lang.ClassNotFoundException: com.rakuten.points.persistence.manager.MemberPointSummaryDAOImpl

According to this log, Spring could not find your MemberPointSummaryDAOImpl class.

A: Didn't really believe, but maven clean helped me

A: This was my stupidity, but a stupidity that was not easy to identify :).
Problem:

*

*My code is compiled on Jdk 1.8.

*My eclipse, had JDK 1.8 as the compiler.

*My tomcat in eclipse was using Java 1.7 for its container, hence it was not able to understand the .class files which were compiled using 1.8.

*To avoid the problem, ensure in your eclipse, double click on your server -> Open Launch configuration -> Classpath -> JRE System Library -> Give the JDK/JRE of the compiled version of java class, in my case, it had to be JDK 1.8

*Post this, clean the server, build and redeploy, start the tomcat.

If you are deploying manually into your server, ensure your JAVA_HOME, JDK_HOME points to the correct JDK which you used to compile the project and build the war.
If you do not like to change JAVA_HOME, JDK_HOME, you can always change the JAVA_HOME and JDK_HOME in catalina.bat(for tomcat server) and that'll enable your life to be easy!

A: In my case, I'm using j-hipster and I had to do ./mvnw clean to overcome this warning.

A: *

*To closed ideas,

*To remove all folder and file C:/Users/UserName/.m2/org/*,

*Open ideas and update Maven project,(right click on project -> maven->update maven project)

*After that update the project.


text:
Q: Qt-Signal not connecting in virtual machine I develop and compile on RedHat 7.4 with GCC 4.8.5 and Qt 4.8.5. The code has to be statically linked. Then executed on a virtual machine running Scientific Linux release 6.7. memcpy-Wrap is used in order to prevent dependencies on newer GLIBC  >= 2.4
I have the following MWE:
#include <iostream>
#include <unistd.h>
#include <QtCore>
#include <QThread>

__asm__(".symver memcpy, memcpy@GLIBC_2.2.5");
extern "C" {
void *__wrap_memcpy(void *dest, const void *src, size_t n) { return memcpy(dest, src, n); }
}

class Worker : public QThread {
    void run() {
        std::cout << "WORKER: Started." << std::endl;
        QObject::connect(this, SIGNAL(finished()), QCoreApplication::instance(), SLOT(quit()));
        int i=0;
        while(i++<3) {
            std::cout << "WORKER: I am running." << std::endl;
            usleep(1e6);
        }
        std::cout << "WORKER: Finished." << std::endl;
    }
};

int main(int argc, char** argv) {

    std::cout << "MAIN: Init QCoreApplication" << std::endl;
    QCoreApplication qtApplication(argc, argv);

    std::cout << "MAIN: Init Worker" << std::endl;
    Worker myWorker;
    myWorker.start();

    std::cout << "MAIN: Start Event-Loop." << std::endl;
    qtApplication.exec();

    std::cout << "MAIN: Event-Loop finished." << std::endl;
    return 0;
}

This code is compiled on the RedHat-System with
g++ -I$QTD/mkspecs/linux-g++ -I$QTD/include -I$QTD/include/QtCore -o mwe mwe.cpp  -Wl,--wrap=memcpy -L$QTD/lib/ -lQtCore -lQtNetwork -lglib-2.0 -lrt -lpthread -ldl -lz

where $QTD holds my installation of my Qt-4.8.5.
The following behavior is expected and observed on the Red-Hat-System:
MAIN: Init QCoreApplication
MAIN: Init Worker
MAIN: Start Event-Loop.
WORKER: Started.
WORKER: I am running.
WORKER: I am running.
WORKER: I am running.
WORKER: Finished.
MAIN: Event-Loop finished.

The following behavior is observed on the Scientific-Linux-System:
MAIN: Init QCoreApplication
MAIN: Init Worker
MAIN: Start Event-Loop.
WORKER: Started.
WORKER: I am running.
WORKER: I am running.
WORKER: I am running.
WORKER: Finished.

And then the application never finishes.
It seems that in the Red-Hat-System, the finished-signal from the worker-thread is connected to the quit-slot in the core application. This doesn't seem to happen in the Scientific-Linux-System. Does anyone have any advice why this happens and how I can debug it?

A: You have to use QThread in proper way.
overloading run() function is not safe and Nokia accept it before and show how to use QThread.
Look at this documentation.

A: As it was mentioned - it is not recommended way to work with threads in Qt. But it is fine for your case. Anyway, I recommend you to try the next approach:
class Worker : public QThread {
    Q_OBJECT // Don't forget this macro
    void run() {
        std::cout << "WORKER: Started." << std::endl;
        // QObject::connect(this, SIGNAL(finished()), QCoreApplication::instance(), SLOT(quit()));
        int i=0;
        while(i++<3) {
            std::cout << "WORKER: I am running." << std::endl;
            usleep(1e6);
        }
        std::cout << "WORKER: Finished." << std::endl;
        this->deleteLater();
    }
};

int main(int argc, char** argv) {

    std::cout << "MAIN: Init QCoreApplication" << std::endl;
    QCoreApplication qtApplication(argc, argv);

    std::cout << "MAIN: Init Worker" << std::endl;
    Worker *myWorker = new Worker();
    QObject::connect( myWorker, SIGNAL(destroyed()), &qtApplication, SLOT(quit());
    myWorker->start();

    std::cout << "MAIN: Start Event-Loop." << std::endl;
    qtApplication.exec();

    std::cout << "MAIN: Event-Loop finished." << std::endl;
    return 0;
}


text:
Q: Configure fails to detect proper ld on a 64-bit system with 32-bit userland I have an i386 debian system running in an lxc container. The userland is 32 bit, the kernel is 64 bit. Thus configure detects this:
checking build system type... x86_64-unknown-linux-gnu
checking host system type... x86_64-unknown-linux-gnu
checking target system type... x86_64-unknown-linux-gnu

Probably this is taken from the output of uname -m
I have a package which builds fine with gcc and the result is a proper 32 bit binary. Unfortunately in another c++ project I get this:
configure:8595: checking whether the gcc linker (/usr/bin/ld -m elf_x86_64) supports shared libraries

From here on the linker is using this switch and thus will try to link 64 bit libs instead of 32 bit and it fails:
/usr/bin/ld: skipping incompatible /usr/lib/libboost_program_options.so when searching for -lboost_program_options
/usr/bin/ld: skipping incompatible /usr/lib/libboost_program_options.a when searching for -lboost_program_options
/usr/bin/ld: cannot find -lboost_program_options
collect2: ld returned 1 exit status

Though the library .so file is the proper 32 bit ELF:
file /usr/lib/libboost_program_options.so.*
/usr/lib/libboost_program_options.so.1.42.0: ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV), dynamically linked, stripped

What's odd is that configure works fine for the other project and the linker is detected correctly to use the proper arch (elf_i386):
checking whether the gcc linker (/usr/bin/ld -m elf_i386) supports shared libraries... yes

Any hints?

A: I just remove unknown for the syntax of command.
The problem is the target: /usr/local/libexec/gcc/x86_64-unknown-linux-gnu/
An idea to reconfigure target in a conf flie?
This works for me:
Replace:
./configure --host=x86_64-unknown-linux-gnu --build=x86_64-unknown-linux-gnu \
  --target=x86_64-unknown-linux-gnu --options...
By:
./configure --host=x86_64-linux-gnu --build=x86_64-linux-gnu --options...

A:
Probably this is taken from the output of uname -m

This configure script is clearly confused.
To un-confuse it, tell it exactly what you want it to do:
./configure --host=i686-unknown-linux-gnu --build=i686-unknown-linux-gnu \
  --target=i686-unknown-linux-gnu


text:
Q: Constant Current LED Driver Output Control using PWM I want to control the brightness of a led which is powered by a constant current driver.
On utilizing a MOSFET and pwm signal from an arduino uno the led starts to fade in as the duty cycle increases. But the problem is that the led "blinks" at lower duty cycle and stabilizes only at about the full brightness. (The constant current driver that came with led is used here).
Please suggest me a new circuit in which I am able to avoid the blinking issue while utilizing the driver that came with the led.
Also, take a look at this : how to control constant current led driver output with pwm?

simulate this circuit – Schematic created using CircuitLab


text:
Q: WP8 DataBound app shows "runtime one", "runtime two" I am testing the DataboundApp template for my app. I've changed the records in the SampleData file. The Designer shows the records correctly (on MainPage.xaml), but when i'm running it on device, it only shows "runtime one" "runtime two" "runtime three" etc. instead of my edited datas. What's the problem here?
I'm talking about the raw DataboundApp template, i've just edited the database file.

A: The designer data is not same in this application. Look LoadData() methode in mainViewModel.


text:
Q: I have no icons or even launcher in ubuntu desktop I'm new in ubuntu. I have installed ubuntu for one month, but during this time I encountered this problem (removing icons or even launcher from ubuntu desktop) for two times. this problem comes to me after running make command in terminal. in fact in the middle of make process I got error that was different in each times. when I closed terminal after getting error, I turned off computer then I turned it on but there was nothing on my desktop, neither icons nor launcher.
what is my problem?
This problem forced me to reinstall ubuntu several times and this bothered me.
thank you for your attention.
Thank you Lorenzo
Now I reinstalled Ubuntu again. Unfortunately I didn't save those errors but I guess it will repeat again.
Infact, I wanted to install special software that I got the error. in it's installation guide had been said I must separate binary and source files from each other. I didn't know the difference between binary and source file therefore simply entered to software directory and ran ccmake comand then called make and got the error that I said before.
May be this explanation have a clue for solving my problem.
Thank you

A: Be sure to have dependencies for the packages you are about to compile & install.
Now, try to reinstall your Graphic User Interface by writing this on a virtual terminal (press CTRL+ALT+F1 and login):
sudo apt-get purge gnome
(confirm)

...and after it has finished:
sudo apt-get install gnome

If it still can't work, issue from a virtual terminal (the same):
sudo apt-get dist-upgrade

The password asked is always your account password.
You will need a working internet connection. This is a really generic answer because your question has very few details. If you need more help comment under here and I will answer soon.
Good evening.
Edit: let's make some controls to solve your problem:

*

*Open a terminal (Gnome terminal or xterminal are OK) and execute whoami. It should output your current user and NOT root or any other user. If the user is different, login as Your user to the graphic interface.

*Execute sudo apt-get check gnome and verify the absence of errors. If there are errors correct them with aptitude.

*Be sure to be prompted for login at the system startup, otherwise install a login manager.

*If you still have troubles, logout and in the login panel select a different session type and then login. Continue until you find the right session type.

*Use less /var/log/syslog from a terminal to check for errors.

*Last hope, run cat /var/log/Xorg.0.log|grep WW and report here any error.

Last note, in the mid time you solve, the "source files" are the text files used to compile a program (are the source code written by a programmer), and the binary files are the executables. Use the file command to see the file type or run ls -lh to have a colored output dependent on the file type. Never install untrusted software from exeternal repositories.


text:
Q: TypeScript output file doesn't get updated after transpilation I downloaded this seed for an Angular & TypeScript project. I updated the ts files and then transpiled it with no errors, but the output file doesn't get updated.
tsconfig:
{
    "compilerOptions": {
        "module": "commonjs",
        "target": "es5",
        "noImplicitAny": true,
        "sourceMap": true,
         "outFile": "dist/app.js"
    },
    "exclude": [
        "node_modules"
    ],
    "files": [
        "app/initialize.ts",
        "app/welcome/welcome.ts"
    ]
}

Please let me know if you need any other information.


text:
Q: PHP: Custom Liking Function for my Comics Site I'm building a comics website and have recently been working on and testing a liking function. The reason I'm building my own is because

*

*I wanted to allow users to like and dislike a comic. FB liking doesn't offer that

*I wanted a custom liking graphic

*I want the like counts to be stored in my database so I can sort
comics by popularity... I don't think I can get the total likes from
FB for such a thing.
Based on the information below, should I continue on with my approach or not?
Each time a unique person likes a comic id, it will first insert that user's ip and that specific comic id that they liked.
Since their IP is now in the database, if they try to vote on the same comic id again, it won't let them. But their IP can still vote on any other comic id.
If they are in fact liking a unique comic id, it will increment the like or dislike count of the associated comic id in the comics table. I can then use this to rank and sort comics by popularity.
As I was testing, I realized that a user with a unique IP can potentially like all comics (ex: 127.0.0.1 liked comicid  30, 127.0.0.1 liked comicid 31, 127.0.0.1 liked comicid  32, etc... and there's 60 unique comics)... so that's 60 database entries. That's just one user... Now what happens if my site starts becoming popular... that could result in n voters * x comics that they've liked... which could be a ton of database entries... which could be a huge burden on my hosting server, and a mess to manage.
That being said, should I just use facebook's liking function? If I do that, can I use those likes to rank my own comics by popularity in the database? Should I continue on with my custom liking function, but change my approach?
If it'd be helpful, I can post my current liking function code...
Any tips appreciated... Thanks!

A: I'd stick with the facebook like button. As you can see from the comments it can get tricky to think of all the cases if you're trying to do it yourself, but FB has already taken care of that.
The FB API definitely allows for getting the number of likes, take a look at this related post: How to get number of likes from facebook like button?


text:
Q: Convert Minutes to Milliseconds The Timer class in Winforms has a property called, Interval and it

Gets or sets the time, in milliseconds, before the Tick event is raised relative to the last occurrence of the Tick event.

On my form I have a text box where the user can input in minutes how long they want to set the timer for.
However I am unable to use the function I made to convert minutes to milliseconds:
public static double ConvertMinutesToMilliseconds(double minutes)
{
  return TimeSpan.FromMinutes(minutes).TotalMilliseconds;
}

My code looks like this:
if (result1 == DialogResult.Yes)
{
    Timer tm;
    tm = new Timer();

    tm.Interval = int.Parse(textBox2.Text);
    tm.Interval = ConvertMinutesToMilliseconds(tm.Interval);
    tm.Tick += new EventHandler(button1_Click);

    string pastebuffer = DateTime.Now.ToString();
    pastebuffer = "### Edited on " + pastebuffer + " by " + txtUsername.Text + " ###";
    Clipboard.SetText(pastebuffer);

    tm.Start();
}

My error is: Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?)

A: Your function accepts a double but you're inputting an int (this conversion can happen implicitly), then you're transforming this time to milliseconds (probably an int as well) and returning it as a double. Then you're assigning the double to an int (tm.Interval).
This last conversion cannot happen implicitly (which means the compiler won't do it for you) because you're converting a a type that can represent fractions (double) to one that can't (int), so information may be lost.
To fix this you can change the line
tm.Interval = ConvertMinutesToMilliseconds(tm.Interval);

to
tm.Interval = (int) ConvertMinutesToMilliseconds(tm.Interval);

or, more conveniently, the line
public static double ConvertMinutesToMilliseconds(double minutes)

to
public static int ConvertMinutesToMilliseconds(int minutes)

Since it's not anything complicated you may also want to use
minutes*60000

instead of
TimeSpan.FromMinutes(minutes).TotalMilliseconds.

A: The convenient way for you to go would be:
public static int ConvertMinutesToMilliseconds(int minutes)
{
    return (int) TimeSpan.FromMinutes(minutes).TotalMilliseconds;
}

A: System.Windows.Forms.Timer.Interval is of type int - it's slightly confusing because System.Timers.Timer.Interval is of type double. So you're trying to assign the result of your method (a double) to a property of type int. That isn't going to work. You can just cast, of course:
timer.Interval = (int) ConvertMinutesToMilliseconds(...);

However, I'd take this opportunity to refactor your code a bit too. Initially you're assigning the minutes value to timer.Interval, which is simply wrong in terms of units. You're just using it as a temporary variable, effectively - so make that clearer, and try to use "assign at point of declaration" for clarity too:
if (result1 == DialogResult.Yes)
{
    // TODO: Use int.TryParse to handle invalid input
    int minutes = int.Parse(textBox2.Text);
    Timer timer = new Timer
    {
        // I don't actually think it's worth having a method for this...
        Interval = (int) TimeSpan.FromMinutes(minutes).TotalMilliseconds
    }
    // Use method group conversion instead of new EventHandler(...)
    // TODO: Rename button1_Click to a name which says what it actually does
    timer.Tick += button1_Click;

    // Interpolated strings make life simpler
    Clipboard.SetText($"### Edited on {DateTime.Now} by {txtUsername.Text} ###");

    timer.Start();
}

Then you just need to worry (if I remember correctly) about keeping a reference to the timer instance so it doesn't get garbage collected. So you may want some sort of "list of active timers". It's possible that I've misremembered this, but you may well want to keep that list anyway, so that you can stop all the active timers at an appropriate time.


text:
Q: onPeriodicNotification is not working for every 20ms I need a fetch a new audio frame every 20ms, therefore i create a AudioTrack which has buffer size of 7528 bytes(Maximum of 2 Audio Buffers of 3764 byes each)
int minBufferSize = 7528;

mAudioTrack = new AudioTrack(
AudioManager.STREAM_MUSIC, 44100, AudioFormat.CHANNEL_OUT_STEREO, AudioFormat.ENCODING_PCM_16BIT, minBufferSize , AudioTrack.MODE_STREAM);

mAudioTrack.setPlaybackPositionUpdateListener(CarMediaPlayer.this ,mMainThreadHandler );

mAudioTrack.setPositionNotificationPeriod(914); //Set a notification for every 20ms to get an Audio frame. This is got by Dividing 3764/4(framesize)

The problem i see is that the callback
@Override
public void onPeriodicNotification(AudioTrack track)
{
    Log.i(TAG, "onPeriodicNotification ");
    getAudioFrame();
}

Is not getting called for every 20ms. Sometimes it gets called very early and sometimes too late. It is not consistent but get called for every playback of frame of 3764 bytes.
Any idea how to make it consistent so that it get called for every 20ms?


text:
Q: Secure WebSocket Connection through nginx 1.10.3 and LetsEncrypt Been ripping hair out because I cannot find out why I cannot connect to my WebSocket server through HTTPS.
So, I have an Express 4 server running a vue app. It uses the ws library from npm to connect to the WebSocket server. The nginx is 1.10.3. I use LetsEncrypt to secure it.
When I go online, I get (in the console):

main.js:12 WebSocket connection to 'wss://play.mysite.com:8443/' failed: Error in connection establishment: net::ERR_CONNECTION_CLOSED

Line 12:

window.ws = new WebSocket(${tls}://${window.location.hostname}:${port});`

That is wss://play.mysite.com:8443. It is indeed on a subdomain.
Here is my nginx block:
update: I got it!
upstream websocket {
    server 127.0.0.1:8443;
}

server {
    root /var/www/play.mysite.com/dist;
    index index.html;

    access_log /var/log/wss-access-ssl.log;
    error_log /var/log/wss-error-ssl.log;

    server_name play.mysite.com www.play.mysite.com;

    location /ws {
        proxy_pass http://websocket;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;
    }

    listen [::]:443 ssl ipv6only=on default_server; # managed by Certbot
    listen 443 ssl http2 default_server; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/play.mysite.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/play.mysite.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}

As you see, we have the subdomain on https://play.mysite.com. My Express server always listen on port 4000 and my WebSocket server listens to wss / port 8443 on production.
When I view the /var/log/wss-error-ssl.log, I get:

2018/03/01 04:45:17 [error] 30343#30343: *1 connect() failed (111: Connection refused) while connecting to upstream, client: 68.117.172.118, server: play.mysite.com, request: "GET /static/css/app.67b8cb3fda61e1e2deaa067e29b52040.css HTTP/1.1", upstream: "http://[::1]:4000/static/css/app.67b8cb3fda61e1e2deaa067e29b52040.css", host: "play.mysite.com", referrer: "https://play.mysite.com/"

So, what exactly am I doing wrong?
The proxy_pass was set right. Listening to port 8443 for WebSocket on both client/server. What is the meaning? Thank you.
edit: and yes, I know the port 8443 is running:
root@MySITE:/var/www/play.mysite.com# netstat -l
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State
tcp        0      0 *:https                 *:*                     LISTEN
tcp        0      0 localhost:4000          *:*                     LISTEN
tcp        0      0 localhost:mysql         *:*                     LISTEN
tcp        0      0 *:http                  *:*                     LISTEN
tcp        0      0 *:ssh                   *:*                     LISTEN
tcp6       0      0 [::]:8443               [::]:*                  LISTEN
tcp6       0      0 [::]:https              [::]:*                  LISTEN
tcp6       0      0 [::]:http               [::]:*                  LISTEN
tcp6       0      0 [::]:ssh                [::]:*                  LISTEN
udp        0      0 *:bootpc                *:*
udp        0      0 45.76.1.234.vultr.c:ntp *:*
udp        0      0 localhost:ntp           *:*
udp        0      0 *:ntp                   *:*
udp6       0      0 2001:19f0:5:2b9c:54:ntp [::]:*
udp6       0      0 fe80::5400:1ff:fe61:ntp [::]:*
udp6       0      0 localhost:ntp           [::]:*
udp6       0      0 [::]:ntp                [::]:*

A: TL'DR Add a second location block for /websocket and have the javascript client hit wss://play.mysite.com/websocket
I see a couple of issues with your nginx server conf.

*

*Nginx is not listening on port 8443 yet your javascript is hitting wss://play.mysite.com:8443.  So while nginx is serving up ports 443 and 80 for the play.mysite.com domain, you javascript is trying to bypass nginx using wss (TLS) and hit NodeJS directly -- though I suppose you meant to offload the SSL onto Nginx.  The wss call must go through nginx in order for the SSL handshake to be successful.

*You are passing all calls to localhost:4000.  Instead I suggest that you have two location blocks location / { ... } and location /websocket { ... }.  This way in the second websocket location block you can proxy pass the calls to localhost:8443.  This would require the client to connect to wss://play.mysite.com/websocket.


text:
Q: How to confirm the working of Remote Storage with Magento Cloud? I have successfully configured and synced the media files to the Amazon S3 bucket(as mentioned in https://devdocs.magento.com/guides/v2.4/config-guide/remote-storage/config-remote-storage-aws-s3.html) but still, the product images are getting loaded from the media cache folder. How to confirm whether Remote storage is successfully installed or not.Any idea?

A: Magento recently added this documentation, https://experienceleague.adobe.com/docs/commerce-operations/configuration-guide/storage/remote-storage/cloud-support.html?lang=en


text:
Q: hash function confusion
Anyone know how to start this problem? I mean, I understand what a hash does, but I have no idea what this quesiton is talking about.
Any ideas on how to go about this?
Given:

*

*the hash function: h(x) = | 2x + 5 | mod M

*a bucket array of capacity N

*a set of objects with keys: 12, 44, 13, 88, 23, 94, 11, 39, 20, 16, 5 (to input from left to right)

4.a *[5 pts]***** Write the hash table where M=N=11 and collisions are handled using separate chaining.
4.b *[5 pts]***** Write the hash table where M=N=11 and collisions are handled using linear probing.
4.c *[5 pts]***** If M=11 can you find a value of N that generates no collisions hashing those keys?

A: Use the equation h(x) to find the hash value of each key. This is the location in the array where the value is stored. Since, this is clearly homework, I won't explain linear probing or separate chaining or 4c.
M is the size of the array that you put the values in.
N is the number of objects that you're hashing.

A: *

*You have a function which given a number (x) determines where that should go in a table.

*The table has a given size, N.  In the case of parts a and b of this question N is 11.

*M is 11 for questions a, b and c.  M is just a value which is plugged into the given formula h(x) = (2x + 5) mod M

*So given the number 12, h(12) = (2 * 12 + 5) mod 11 => 7.  So the first result goes into bucket 7.

*You then work your way through the rest of the numbers in turn, working out what h(x) is for each.

*However, when you come to a collision (i.e. a scenario where the bucket which the number should go in has already been filled by a previous number) you need to select a different bucket for it.  Which bucked you select will depend on your overflow strategy.

*in question A your overflow strategy is separate chaining

*in question B your overflow strategy is linear probing

*if you're unfamiliar with these methods, watch these:

*

*Separate Chaining: http://www.youtube.com/watch?v=IDqTof09ufg

*Linear Probing: http://www.youtube.com/watch?v=g0n0Ep18DJc

*If C is taken as read I assume it means that take the numbers from the start of the list until you hit the first collision; however many numbers you already have in your bucket is the value for N.

*However, I believe question C I believe is a misprint.  I think it wants you to find a value for M which would allow the given list of numbers to all be assigned to a unique bucket (i.e. no collisions / no overflow strategy).

A: Start by computing the hash of each key.


text:
Q: UIWebview crashes when I load certain webpages I have been hitting my head against the wall trying to figure this out for two days with no luck. I have a basic UIWebview that is navigating to a page.  That page has a JavaScript function that seems to crash the UIWebView but works just fine in safari.  I am at a loss.  I get the following crash error:
2010-02-03 08:30:16.559 Wasp[11380:207] *** -[DOMElement structuralComplexityContribution]: unrecognized selector sent to instance 0xf53e60
2010-02-03 08:30:16.561 Wasp[11380:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[DOMElement structuralComplexityContribution]: unrecognized selector sent to instance 0xf53e60'

Thanks for any help or direction.
The problematic JavaScript file is the new gordon flash runtime.  An example can be seen at
http://davididas.com/gordon/test1.html.

A: File a bug with Apple, with a reference to that page. The UIWebView should not crash. Even if the html, css or JavaScript is faulty.


text:
Q: Do we need a random number generator to decipher (decrypt)? I'm by far an expert on encryption and therefor am seeking out software deciphering advice.  My example bellow deals with hardware, but my question is to seek software advice on whether a software solution is feasible, doable and reasonable.
Background:
On our product, we are considering adding encryption on our RFID keys.  Our current firmware does not support this and our hardware guy now wants to upgrade the hardware to add a random number generator chip.
As mentioned above, I'm no expert on encryption, but I always though that a random number generator was required for the ciphering, but not for the decipher?
Additional info: We are using a low power ARM processor (don't know the model at this time).
So my questions are as follows:

*

*Do you really need random numbers to decipher data?

*If so, why wouldn't a standard C language library be sufficient?

And lastly,

*

*If we do need random numbers to decipher, can anyone with experience comment of the benefits/disadvantages of having hardware vs. software random numbers?  Example: Is the random number portion of a decipher only 1% of the total processing and thus I would not     necessarily speed things up?

Thank you in advance!

A: Your confusion is because in this case the random numbers are not being used for randomness. Many cryptographic algorithms such as RC4 are based on XORing the plaintext with a cryptographically secure pseudorandom random number generator (CSPRNG) initialized with the key as a seed. (pseudorandom means the random number generator uses a algorithm to generate values) The data is then decrypted by again using the CSPRNG with the key and XORing it against the ciphertext.

*

*If so, why wouldn't a standard C language library be sufficient?

No, as almost all rand() implementations use an LCG, which is insecure and not suited for cryptographic purposes.

If we do need random numbers to decipher, can anyone with experience
  comment of the benefits/disadvantages of having hardware vs. software
  random numbers? Example: Is the random number portion of a decipher
  only 1% of the total processing and thus I would not necessarily speed
  things up?

As is explained, generating values using the CSPRNG takes up virtually all the computing power required for encryption; the only other step is XORing the CSPRNG with the plaintext/ciphertext. However, I don't think you need a hardware accelerated pseudorandom generator as RC4 only requires 7 cycles a byte on a Pentium and most practical cryptographic algorithms less than 100 cycles per byte. If it needs to encrypt faster than hundreds of megabytes a second, then a hardware accelerated pseudorandom generator would accelerate the encryption significantly.


text:
Q: Rails migrations on the fly I am wondering if Rails is capable of doing migration on the fly without locking table.
For example, there are too many tools that can do this pt-online-schema-change and oak-online-alter-table. Therefore it's reasonable to assume that it's already done, are you familiar with something like this?

A: Funny, I just answered another similar question. You should look into https://github.com/DAddYE/mini_record
It works very similar to Datamapper. Just define or modify your column names/types right in your model and the schema gets updated automagically. Pretty cool.
I'm not sure about the locking, but you can submit an issue on that github page. The developers are very responsive and helpful.


text:
Q: Modifying an array through a ref to one of its elements - Will it work? It is safe to modify value types in an array through a method which uses a ref to the element in the array, as shown below? If so, what kinds of value types can be modified this way? Is it limited to simple value types or will struct also work?
// Method that sets an integer to x.
void SetToX(ref int element, int x) {
    element = x;
}

// Int array with one element set to 0.
int[] myIntArray = new int[1] {0};

// (Try to) set element 0 of the int array to 1.
SetToX(ref myIntArray[0], 1);

// Will this log "0" or "1"?
Log(myIntArray[0].ToString());

Answer courtesy of Reed Copsey and Alexei Levenkov
This works fine - the sample code will print "1". This also works with any value type including struct.
However, this is ONLY the case with arrays. If you attempt to modify another kind of collection this way, you will be prompted with:
A property, indexer or dynamic member access may not be passed as an out or ref parameter
This is because only arrays actually return a reference to the value type in the element. All other collections will return a copy of the element, and using ref will modify the copy, leaving the original untouched.

A: Yes, this works fine.
Your sample code will print:
1

If so, what kinds of value types can be modified this way? Is it limited to simple value types or will structs also work?

Any value types.  A custom struct will have the same behavior.


text:
Q: Azure PIM PowerShell Script On Azure Portal we can grant Contributor role to Subscription using PIM for limited period of time.
Like 1 - 2 - 3 hours.
Those are called eligible assignments.
Anyone has tried assigning eligible assignments using powershell ?
As per my research  -- AZureADPreview module is present.
(https://learn.microsoft.com/en-us/azure/active-directory/privileged-identity-management/powershell-for-azure-ad-roles )
But it is still under preview and doens't have full functionality.

A: I think the functionality has already been mentioned in the doc, give a sample here to elaborate on the specific usage.
For example, you want to assign the Application Administrator role to a user, then the script should be:
Note: The -ResourceId parameter uses your AAD tenant id <tenant-id>.
$role = Get-AzureADMSPrivilegedRoleDefinition -ProviderId aadRoles -ResourceId "<tenant-id>" | Where-Object {$_.DisplayName -eq 'Application Administrator'}

$schedule = New-Object Microsoft.Open.MSGraph.Model.AzureADMSPrivilegedSchedule
$schedule.Type = "Once"
$schedule.StartDateTime = (Get-Date).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffZ")
$schedule.endDateTime = "2021-07-25T20:49:11.770Z"
Open-AzureADMSPrivilegedRoleAssignmentRequest -ProviderId aadRoles -Schedule $schedule -ResourceId "<tenant-id>" -RoleDefinitionId $role.Id -SubjectId "<object-id of user or group>" -AssignmentState "Eligible" -Type "AdminAdd"

Check in the portal:


text:
Q: flutter: why the hintText doesn't appear unless I click the textField? I set the property hintText of textField, which is placed in a Container, but the content of the hintText doesn't appear(as the first picture shows). When I click the textField, the hintText appears(as the second picture shows). So what's the problem?

Container(
                      width: 330,
                      height: 40,
                      alignment: Alignment.centerLeft,
                      child: TextField(
                        controller: inputController,
                        focusNode: focusNode,
                        style: MyTextStyle.level4,
                        keyboardType: TextInputType.number,
                        decoration: InputDecoration(
                          filled: true,
                          hintText: 'hint text here',
                          hintStyle: MyTextStyle.grey,
                          prefixIcon: MyIcon.SearchGreyIcon,
                          border: InputBorder.none,
                          suffixIcon: focusNode.hasFocus ? IconButton(
                            icon: MyIcon.CloseIcon,
                            onPressed: () {
                              inputController.clear();
                            }
                          ) : Container(),
                        ),
                      ),
                      decoration: BoxDecoration(
                        color: MyColor.MidGray,
                        borderRadius: MyStyle.CIRCULAR_BORDER_RADIUS,
                      ),
                    ),

A: You seem missing labelText ,
hintText -Text that suggests what sort of input the field accepts.
labelText - Text that describes the input field.
TextField(
      obscureText: true,
      decoration: InputDecoration(
        border: OutlineInputBorder(),
        labelText: 'Password',
      ),
    )


text:
Q: Imap Select Folder Which's Name Contains Turkish Character using MailSystem.NET I'm using MailSystem.Net to receive my mails. When I try to select a folder which contains turkish character it returns me an error.
My code is here:
string folderName = "[Gmail]/Yıldızlı";
Mailbox inbox = imap.SelectMailbox(folderName);

And the Imap4Exception is here:

Command "select "[Gmail]/Yıldızlı"" failed : 150721051043320 NO [NONEXISTENT] Unknown Mailbox: [Gmail]/Y?ld?zl? (now in authenticated state) (Failure)

How can I fix this issue?
Thanks.


text:
Q: Python serial write doesn't work FIRST run I have 2 programs to test serial communication, an simple arduino program that echoes whatever is on the serial port and a python program that writes to the serial port and prints the reply.
I'm having an issue where whenever I upload the arduino program and try to run the python the first time after I uploaded, it would be stuck on print ser.readline() which I'm assuming means for some reason python is not writing to the serial port.  I would have to quit the python program and run it again to get it to get a reply from arduino.  The program would continue to work until I re-upload the arduino then once again python wouldn't work on first run.  Also if I open and close the serial monitor before I run the python program it will work the first run.  Does anyone know what is the issue?  This is on Ubuntu.
arduino
String str;

void setup() {
// Turn the Serial Protocol ON
  Serial.begin(115200);
}

void loop() {
  if (Serial.available()) {
      str = Serial.readStringUntil('\n');     // Read the serial input
      Serial.println(str);             // sends ascii code

  }
}

Python
import serial

ser = serial.Serial('/dev/ttyACM1', 115200)

for i in range(0,4):
    str = "test string\n"
    ser.write(str)
    print ser.readline()

A: The issue is likely related to many Arduinos resetting when a new serial connection is made.
The solution is to either add a delay (about 2 seconds works) to the python program between the serial connection being created and the first data being sent or modifying the hardware to prevent a reset on serial connect.

A: By default python Serial might be blocking by default try removing the timeout:
ser = serial.Serial('/dev/ttyACM1', 115200,timeout=0)

additionally have a peek at the serial.threaded in the docs

A: I added
time.sleep(1)
ser.setDTR(level=0)
time.sleep(1)

after opening the serial port and the issue was fixed.