text:
Q: In IE7 how do I set a global variable or element value using an ajax call during a jquery .click event? In IE7, when this code is called in the .submittable click event, I have to click the submit button twice to get the orderCount global variable to be set.  Or if I set an attribute value on a hidden tag, I get the same experience. For the element value to be set I have to click the button twice.  It's like I need to give the browser more time to process.  Any suggetions ?  Thank You, Nate
var orderCount = 0;
$(document).ready(function(){
$('.submittable').click(function(){
        setOrderCount()
        if ( orderCount == 0 ){
            if (validateAcknowledment($(this).attr('id'))){
                acknowledgeDay($(this).attr('id'));
            }
        }
    });
});
function setOrderCount(){

    // move this up to validate and do a setAtr
    var school = $("#school").val();
    var orderDate = $("#orderDate").val();
    $.ajax({
        url: "/fos/inventory/getPreviousWeeklyMenuOrders",
        type: "GET",
        dataType: 'json',
        cache:false,
        data: {school: school,
            startWeekMonth: Date.parse(orderDate).getMonth(),
            startWeekDay: Date.parse(orderDate).getDate(),
            startWeekYear: Date.parse(orderDate).getFullYear()
        },
        success: function(data) {

            orderCount = data.orderCount;
            if(orderCount > 0){
                showErrorMessage("You must Acknowledge prior Weekly Menu Order(s) before acknowledging this week's order", 200, 300);
            }

        }
});

A: it's amazing how many of these questions come up.
By default the AJAX call is asnychronous. You initiate the call on your 4th line and then check orderCount on the 5th, before your asynchronous call has completed. On your second click your async call has now completed and the code is doing what you think it should be doing on the first click.
You need to move your orderCount checking logic inside your anonymous 'success' callback function, so that it will only be executed when the call is complete. Or make the ajax call synchronous (jquery options)

A: First of all, you need to realize that setOrderCount is an asynchronous function.  It will launch the ajax call and that ajax call may take awhile to process.  The setOrderCount function will return right away, long before the ajax call has completed and thus long before the orderCount variable has been set.
Then, in your click handler, you immediately check the orderCount variable, but it is not set yet.  What you need to do is move this code to the success function from the ajax call:
   if ( orderCount == 0 ){
        if (validateAcknowledment($(this).attr('id'))){
            acknowledgeDay($(this).attr('id'));
        }
    }

because that's when the orderCount variable is actually set.


text:
Q: Declrative transaction management with spring boot and spring data JPA repository I recently created spring boot REST application with spring data JPA repository.
I want  to define some rest services in read only mode and some other non read only.
Could you please help me how to implement this using @Transactional or AOP in declarative approach.
Also please share me any spring documentation where i can understand the transaction management using Spring boot application.

A: The implementation of @Transactional in Spring is mainly for a reason of transactions, and do every Insert, Update, Delete, etc in the same transaction and if any of them would fail it would rollback the whole transaction and none of them will be executed.
You may se more information in here jhades explains it perfectly well in his post on that blog and if you also need a complete documentation of the Transaction management you may see the Spring docs in here

redpajama_set_name: RedPajamaStackExchange


text:
Q: Lectura de archivo de texto Estaba haciendo un programa para administrar una tienda, decidi que los datos de los productos se guardaran en un archivo .txt y que estos se puediese imprimir en pantalla y al mismo tiempo, cuando el usuario presione una tecla, cada tecla corresponda a un producto y después hacer la suma del total de todos los productos ingresados. El problema es que no encuentro la manera de almacenar solo los valores numéricos en variables diferentes ¿ alguna idea ?
He intentado que el programa lea línea por línea el texto y guarde los datos en dichas variables diferentes, solo que me suelta error diciendo que la variable tiene que ser forzosamente char, y si es char no puedo hacer ninguna operación
#include<iostream>
#include<fstream>
#include<cstdlib>
#include<string>
#include<conio.h>
using namespace std;

fstream archivo;
void leerarchivo1(){
    archivo.open("DatosUsuario.txt",ios::in);
    if(archivo.is_open()){
        string linea;
        while(getline(archivo,linea))
        {
            cout<<"Bienvenid@"<<" "<<linea<<" "<<":D"<<endl<<endl;
        }
        archivo.close();
    }
    else
    {
        cout<<"algo ha salido mal o.O \n Esto pordia deberse a que el programa de configuracion no ha sido corrido aun";
    }
}

void leerarchivo2(){
    archivo.open("nomredeTiendita.txt",ios::in);
    if(archivo.is_open()){
        string linea;
        while(getline(archivo,linea))
        {
            cout<<"Operando desde"<<" "<<linea<<endl<<endl;
            cout<<"> = = = = = = = = = = = = = = = = = = = = = >INVENTARIO< = = = = = = = = = = = = = = = = = = = = = <"<<endl;
        }
        archivo.close();
    }
    else
    {
        cout<<"algo ha salido mal o.O \n Esto pordia deberse a que el programa de configuracion no ha sido corrido aun";
    }
}

void leerarchivo3(){
    archivo.open("Inventario.txt",ios::in);
    cout<<"inventario\n";

    if(archivo.is_open()){
    char c;
    while(!archivo.eof()){
        c = archivo.get();
        cout<<c;
    }
    }
    else
    {
        cout<<"No se encontro ningun registro de inventarios\n Vuelva a el programa de configuracion, ingrese los productos e intentelo de nuevo... u-u";
    }
    archivo.close();

}

void leerarchivo4(){
    archivo.open("Inventario.txt",ios::in);
    if(archivo.is_open()){
        int nproducto;
        char producto[50];;
        int precio;
        int num1;
        num1 = nproducto;
        while( !archivo.eof() ){
            archivo>>nproducto>>producto>>precio;
            cout<<"= + + + + + + + + + + + + + + + + + + + + + + + +>o<+ + + + + + + + + + + + + + + + + + + + + + + =\n";
            cout<<"["<<"Numero del producto: "<<nproducto<<" "<<" ][ "<<"Nombre del producto: "<<producto<<" "<<" ][ "<<"Precio: "<<precio<<" "<<" ] "<<endl;
            cout<<"= + + + + + + + + + + + + + + + + + + + + + + + +>v<+ + + + + + + + + + + + + + + + + + + + + + + =\n\n";
        }
        archivo.close();

    }
}

void leerarchivo5(){
    archivo.open("Inventario.txt",ios::in);
    if(archivo.is_open()){
        while(!archivo.eof()) {
        int numero1;
        fscanf(archivo,"%d\32",&numero1);
        cout<<numero1;
         }
        }
        archivo.close();

    }

int main(){
    leerarchivo1();
    leerarchivo2();
    leerarchivo4();
    leerarchivo5();
    system ("pause");
    return 0;
}

El contenido de cada txt es este:
DatosUsuario

Nahomy

nomredeTiendita
EVE

Inventario
1 Jabon 15
2 Papel 25
3 Escudo-Cokiri 13
4 Galletas-chokis 12
5 Helado 14

A:
El problema es que no encuentro la manera de almacenar solo los valores numéricos en variables diferentes ¿ alguna idea ?

Basta con mirar la gran cantidad de sobrecargas del operador de extracción de fstream (heredados gracias a ifstream) para ver que hay luz al final del tunel. Por otro lado nota que no hay ninguna necesidad de tener archivo como variable global.
El problema de leer en un char[]  es que no existe una sobrecarga para dicho tipo y, en consecuencia, el compilador no sabe cómo realizar la operación que le pides. Sin embargo sí que existe la sobrecarga para std::string:
std::ifstream archivo;
archivo.open("Inventario");
if(archivo.is_open()){
  int id, precio;
  std::string producto;

  while( !archivo.eof() )
  {
    archivo >> id >> precio >> producto;
  }
}


text:
Q: Webm vs Opus - Quality? - youtube-dl context When I download audio from youtube via youtube-dl:
A) if I type -f bestaudio I get webm files which can't contain musical metadata and can't be played by most apps.
B) if I type -f bestaudio --extract-audio --add-metadata I get opus files which contain musical metadata and can be play by most apps.
I conclude Opus is more useful. However webm and opus files often appear to be slightly different on Spek and so I get doubtful since I don't know how to read such subtle difference.
Questions

*

*Is someone able to explain me in casual language what is occurring in the process within youtube-dl when doing it with option A and when doing it with option B?

*Which one is finer? Quality as when played online full on is a must, not simply to have fun listening to.

*Is there any other info that could help me assure to download best unprocessed audio with youtube-dl?
I wish someone is able to help me, I thank you very much in advance! :)

A: If you're getting webm files (with .webm extension) with the bestaudio parameter that means, you're downloading Opus audio files in webm (matroska) containers:
$ youtube-dl -f bestaudio 'https://www.youtube.com/watch?v=LXb3EKWsInQ'
[youtube] LXb3EKWsInQ: Downloading webpage
[download] Destination: COSTA RICA IN 4K 60fps HDR (ULTRA HD)-LXb3EKWsInQ.webm
[download] 100% of 4.96MiB in 00:00
$ mediainfo 'COSTA RICA IN 4K 60fps HDR (ULTRA HD)-LXb3EKWsInQ.webm'
General
Complete name                            : COSTA RICA IN 4K 60fps HDR (ULTRA HD)-LXb3EKWsInQ.webm
Format                                   : WebM
Format version                           : Version 4
File size                                : 4.96 MiB
Duration                                 : 5 min 13 s
Overall bit rate                         : 133 kb/s
Writing application                      : google/video-file
Writing library                          : google/video-file

Audio
ID                                       : 1
Format                                   : Opus
Codec ID                                 : A_OPUS
Duration                                 : 5 min 13 s
Channel(s)                               : 2 channels
Channel layout                           : L R
Sampling rate                            : 48.0 kHz
Bit depth                                : 16 bits
Compression mode                         : Lossy
Language                                 : English
Default                                  : Yes
Forced                                   : No

So, it's not correct to say that there's no audio metadata. You can't play the audio in audio players because they consider it to be a video file, but most video players support playing it. For example, it works with vlc, mpv, totem, Google Chrome and Firefox.
When you add the extract audio parameter, an extra step is done: the webm container is replaced by the Ogg container (and the extension is renamed to .opus). The Opus audio contained in the file stays the same:
$ youtube-dl -f bestaudio --extract-audio 'https://www.youtube.com/watch?v=LXb3EKWsInQ'
[youtube] LXb3EKWsInQ: Downloading webpage
[download] COSTA RICA IN 4K 60fps HDR (ULTRA HD)-LXb3EKWsInQ.webm has already been downloaded
[download] 100% of 4.96MiB
[ffmpeg] Destination: COSTA RICA IN 4K 60fps HDR (ULTRA HD)-LXb3EKWsInQ.opus
Deleting original file COSTA RICA IN 4K 60fps HDR (ULTRA HD)-LXb3EKWsInQ.webm (pass -k to keep)
$ mediainfo 'COSTA RICA IN 4K 60fps HDR (ULTRA HD)-LXb3EKWsInQ.opus'
General
Complete name                            : COSTA RICA IN 4K 60fps HDR (ULTRA HD)-LXb3EKWsInQ.opus
Format                                   : Ogg
File size                                : 4.89 MiB
Duration                                 : 5 min 13 s
Overall bit rate                         : 131 kb/s
Writing application                      : Lavf58.76.100

Audio
ID                                       : 2697462219 (0xA0C801CB)
Format                                   : Opus
Duration                                 : 5 min 13 s
Channel(s)                               : 2 channels
Channel layout                           : L R
Sampling rate                            : 48.0 kHz
Compression mode                         : Lossy
Writing library                          : Lavf58.76.100
Language                                 : English

So, both commands download exactly the same audio contents. The difference is that the latter is wrapped in a container that audio players understand.

A: webm is a media container similar to mkv, opus is a audio format which can be included in the webm among with video, other audio tracks and subtitles etc..
opus seems to have higher bitrate (better quality) than offered by youtube-dl/newpipe but not so great hardware support, that does not matter for your pc and phone though.
youtube does not offer uncompressed audio/video


text:
Q: Insert primary key in a class I'm having difficulty changing this class to include a primary key field with auto-increment. this schema I get the data from an industrial equipment through third-party libraries, this scheme was provided by the own company that provided these libraries, we should add a primary key field for this data layer will need to put another layer of data access other application to retrieve this data through the linked reports.
const string connectionString =
    "Data Source=(local);Initial Catalog=MyDB;Integrated Security=true";

using (var connection = new SqlConnection(connectionString))
{
    connection.Open();

    // Create all necessary ADO.NET objects.
    var adapter = new SqlDataAdapter("SELECT * FROM MyTable", connection);
    var dataSet = new DataSet();
    adapter.FillSchema(dataSet, SchemaType.Source, "MyTable");
    adapter.InsertCommand = new SqlCommandBuilder(adapter).GetInsertCommand();
    DataTable table = dataSet.Tables["MyTable"];

    int[] handles = EasyDAClient.DefaultInstance.SubscribeMultipleItems(
        new[]
            {
                new DAItemGroupArguments("", "MyOPCServer.1", "OPCItem01", 1000, null),
                new DAItemGroupArguments("", "MyOPCServer.1", "OPCItem02", 1000, null),
                new DAItemGroupArguments("", "MyOPCServer.1", "OPCItem03", 1000, null),
                new DAItemGroupArguments("", "MyOPCServer.1", "OPCItem04", 1000, null)
            },
        (_, eventArgs) =>
            {
                if (eventArgs.Vtq != null)
                {
                    // Fill a DataRow with the OPC data, and add it to a DataTable.
                    table.Rows.Clear();
                    DataRow row = table.NewRow();
                    row["ItemID"] = eventArgs.ItemDescriptor.ItemId;
                    row["Value"] = eventArgs.Vtq.Value; // The DataRow will make the conversion to a string.
                    row["Timestamp"] = (eventArgs.Vtq.Timestamp < (DateTime) SqlDateTime.MinValue)
                                           ? (DateTime)SqlDateTime.MinValue
                                           : eventArgs.Vtq.Timestamp;
                    row["Quality"] = (short)eventArgs.Vtq.Quality;
                    table.Rows.Add(row);

                    // Update the underlying DataSet using an insert command.
                    adapter.Update(dataSet, "MyTable");
                }
            }
        );

Any suggestion to include a primary key field in the current scheme?

A: Hello, you can try with this code:
DataColumn idColumn = new  DataColumn();
idColumn.DataType = System.Type.GetType("System.Int32");
idColumn.ColumnName = "id";
table.Columns.Add(idColumn);

//Just if you want define AutoIncrement
//idColumn.AutoIncrement = true;

DataColumn [] keys = new DataColumn [1];
keys[0] = idColumn;
table .PrimaryKey = keys;

Insert this code after this line:
DataTable table = dataSet.Tables["MyTable"];

A: const string connectionString =
            "Data Source=(local);Initial Catalog=MyDB;Integrated Security=true";

using (var connection = new SqlConnection(connectionString))
{
    connection.Open();

    // Create all necessary ADO.NET objects.
    var adapter = new SqlDataAdapter("SELECT * FROM MyTable", connection);
    var dataSet = new DataSet();
    adapter.FillSchema(dataSet, SchemaType.Source, "MyTable");
    adapter.InsertCommand = new SqlCommandBuilder(adapter).GetInsertCommand();
    DataTable table = dataSet.Tables["MyTable"];
        DataColumn[0] key1 = dataSet.Tables["MyTable"].Columns["ItemID"];
        key1[0].AutoIncrement = true;
        key1[0].AutoIncrementSeed = 1;
        key1[0].AutoIncrementStep = 1;
        dataSet.Tables["MyTable"].PrimaryKey = key1;

        key1 = null;

    int[] handles = EasyDAClient.DefaultInstance.SubscribeMultipleItems(
        new[]
            {
                new DAItemGroupArguments("", "MyOPCServer.1", "OPCItem01", 1000, null),
                new DAItemGroupArguments("", "MyOPCServer.1", "OPCItem02", 1000, null),
                new DAItemGroupArguments("", "MyOPCServer.1", "OPCItem03", 1000, null),
                new DAItemGroupArguments("", "MyOPCServer.1", "OPCItem04", 1000, null)
            },
        (_, eventArgs) =>
            {
                if (eventArgs.Vtq != null)
                {
                    // Fill a DataRow with the OPC data, and add it to a DataTable.
                    table.Rows.Clear();
                    DataRow row = table.NewRow();
                    row["ItemID"] = eventArgs.ItemDescriptor.ItemId;
                    row["Value"] = eventArgs.Vtq.Value; // The DataRow will make the conversion to a string.
                    row["Timestamp"] = (eventArgs.Vtq.Timestamp < (DateTime) SqlDateTime.MinValue)
                                           ? (DateTime)SqlDateTime.MinValue
                                           : eventArgs.Vtq.Timestamp;
                    row["Quality"] = (short)eventArgs.Vtq.Quality;
                    table.Rows.Add(row);

                    // Update the underlying DataSet using an insert command.
                    adapter.Update(dataSet, "MyTable");
                }
            }
        );
}


text:
Q: How can I configure Installer for 32Bit and 64Bit JRE as well? Is there a possibility to configure an Installer (Install4J 8.0.4) which runs under 32bit and 64bit JRE as well?
At the moment, I have configured two media files in the Install4J project, so
that I get two Installer one for 32bit und another one for 64 bit JRE Support.
And the second question is, how can I configure that two different installers can access the same named data files? That doesn't work for me even though I use different compiler variables for naming the installer and the directory for the data files?
Install4J Editor - Installer data files
Install4J Editor - Media file name

A: 32-bit executables work on 64-bit Windows installations as well, so you can choose to distribute 32-bit media files only.
For dedicated 32-bit and 64-bit support, you need to separate media files, one for 32 bit and one for 64 bit, there is no way to combine them into a single one.
As for the media file names (please ask separate question on stackoverflow), you have to use the same URL for all media files, and not include the media file name in it.


text:
Q: Laravel get collection who comply with condition on different model I have two models:
Class Survey{
    public function steps(){
        return $this->hasMany( Step::class );
    }
}

Class Step{
    public function survey(){
        return $this->belongsTo( Survey::class );
    }

    public function isFinished( Survey $survey ){
        // Check some things
        return ( /* Chech if that step of the survey is finished */ ) ? true : false;
    }
}

In my controller, I want to retrieve all the surveys that have a specific step finished.
public function getFinished( Step $step ){
    $finished = collect();
    $surveys = Survey::all();
    foreach( $surveys as $survey ){
        if( $step->isFinished( $survey ) ){
            $finished->push( $survey );
        }
    }
    return $finished;
}

I know this is not an efficient way to do it. I would like to do it from the model with a static function, so I could do something like:
public function getFinished( Step $step ){
    return Survey::getFinished( $step );
}

A: You can use whereHas():
public function getFinished(Step $step) {
    return Survey::whereHas('steps', function($query) use($step) {
        $query->where('id', $step->id)->where('isFinished', 1);
    })->get();
}


text:
Q: How do I attach an instance-specific queryset to a model in Django? I am making a very minimal user-to-user messaging app using Django 1.4. I want to fetch unread messages that a user received in a straightforward way from my templates. My model looks something like this:
from django.contrib.auth.models import User

class Message(models.Model):
    sender = models.ForeignKey(User, related_name='messages_sent')
    receiver = models.ForeignKey(User, related_name='messages_received')
    read = models.BooleanField(default=False)

Now I can easily access the messages that a user has received from user.messages_received. I'd like to filter this queryset, though, to quickly access the unread messages in an easy way. I know that I can always filter the queryset user.messages_received.filter(read=False), but I'd like to get at them directly in templates, possibly like this:
 Inbox ({{ user.unread_messages.count }})

I suspect I want to make a Manager, but I'm not sure how to write it or where to attach it.
Thanks in advance.

A: There are two ways to accomplish this that come to my mind.
First, you could extend the user model with a custom function.
from django.contrib.auth.models import User

def unread_messages(self):
    return self.messages_received.filter(read=False)
User.add_to_class('unread_messages', unread_messages)

But that is slightly hacky. The "clean" way would be not to extend the User model directly, but to create a UserProfile for your users and add the function there. The docs describe this quite well.
In your case:
models.py
from django.db import models
from django.contrib.auth.models import User

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    def unread_messages(self):
        return self.user.messages_received.filter(read=False)

settings.py
AUTH_PROFILE_MODULE = 'appname.UserProfile'

template
{{ user.get_profile.unread_messages.count }}

The code is untested, but should work :)


text:
Q: Files built with Delphi 2010 report virus/trojan I tried to email a DLL-file built with Delphi but received an rejection email reporting:
"Your email was rejected because it contains the Trojan.Delf-9364"
So I uploaded the file to http://scanner.novirusthanks.org and sure enough it reports a positive in one of the virus scanners:
"F-PROT6 20100630  4.5.1.85  W32/Swizzor-based.2!Maximus"
I then built a empty exe-file (File - New - VCL Forms Application) and uploaded again, this time I get another positive:
"VBA32 01/07/2010  3.12.12.2 Trojan.Win32.Swisyn.acyl"
More details here: http://scanner.novirusthanks.org/analysis/e59033c40f1a6e37c210cb1c4f40f059/UHJvamVjdDEuZXhl/
So I'm not sure how to interpret these results. Are all the above false positives, are my computer infected with a virus that infects all binaries, or is my copy of Delphi infected with a Delphi-specific virus? I use AVG antivirus and it reports no problems on my computer. Perhaps someone else with Delphi 2010 can try uploading a project1.exe and see if they receive different results?

A: I think it is a false positive. There have been more questions here about Delphi applications detected as virus, but those were all false positives.
Report this as a false positive.
There is a virus that infects your Delphi installation (4,5,6,7) by modifying SysConst.pas and compiling it, leaving a SysConst.bak in your lib directory. You can check for this. Follow this link for more information: http://www.securelist.com/en/weblog?weblogid=208187826
But you are on Delphi 2010, so you are not affected by that virus.

A: Yeah, I just uploaded a blank project from D2010 and got "VBA32 01/07/2010 3.12.12.2 Trojan.Win32.Swisyn.acyl" too.  Looks like a false positive to me.
This has happened a few times in the past.  Delphi's very good at creating software that works well very quickly.  But unfortunately, that holds true even when the "software" in question is evil.  It's been so widely used for nefarious purposes that there have been a few incidents of antivirus makers inserting a "virus signature" in their definitions that was actually part of the VCL or RTL.  Looks like something similar's happened again.  You ought to report this as a false positive.

A: @VilleK try giving the Assembly information to the Delphi Project like Name , Version etc . I too faced the similar situation sometimes back .
Check  Delphi 7 , MCafee and Virus to know more . I feel this applies to Delphi 2010 too .


text:
Q: Openshot .svg titles no longer appear OpenShot in Arch Linux does not seem to allow me to add titles to a project. The titles are created fine (and if you search using a file browser, they appear in the relevant thumbnail folder) but they do not get added to the project (i.e. they won't show in the list of files for the project).
What would be causing this issue and how would I fix it? Or even diagnose what is going on.
I tried this with both old projects (from a Ubuntu 14.04 install) and new projects, with the same issue. Trying to import the .svg files manually using the "Import Files" option results in OpenShot showing an error "OpenShot does not support this file type". Interestingly, it won't allow me to import png images either, and jpg images show up as a white square.
Note: this was working fine in Ubuntu 14.04.

A: Okay, for some reason, I couldn't open OpenShot at all (got locked). I removed the .openshot folder in my home folder.
And now OpenShot is properly saving titles! I have no idea whether the titles were working before it crashed or only after I removed the .openshot folder, but I thought I would let people know that the issue is no longer there.
I will keep the question without an accepted answer, as I don't remember exactly whether this fixed the issue or whether it just started working by itself.


text:
Q: iOS app does not run properly I'm newbie in iOS development and I've got an issue with my app. I'm developing my first iOS app, everything is fine either when I deploy my app from mac on my devices. But the problem occurs when I wanted to start my app for example after week. I click on app icon and there is just launchscreen showing and app is closed. What should be wrong? It happened on many devices I've tried. My first view after launchscreen contain in viewDidLoad() function just these rows :
    super.viewDidLoad()
    loader.stopAnimating()
    NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)

Now I don't know if I've got bug in my app or if there is some kind of restriction from apple. Thanks a lot.

A: Please check you have added self.keyboardWillShow & self.keyboardWillHide in your ViewController.swift file. Instead of self.keyboardWillShow & self.keyboardWillHide you should use ViewController.keyboardWillShow & ViewController.keyboardWillHide with #selector.


text:
Q: Open Source alternative to Windows Identity Foundation I was wondering what alternatives exists for seting up a federated token based security service.
And also how does it compare with a regular OpenId server.
Any literature on the subject would be more than welcome (I'm just getting into the subject)

A: WIF deals mostly with SAML tokens and WS-Federation (websites) based identity federation. For other alternatives (OAuth, OpenId) there are various frameworks. One of them is DotNetOpenAuth.
If your solution will be SAML based, I wouldn't bother too much with anything but WIF, unless you have a good reason (e.g. you are not running on Windows).


text:
Q: Can I still get a key to the hotel room after Boone joins me? Already found out who the culprit was and donned the special hat during a stroll out in front of the dinosaur, now after a dialogue with Boone he has joined me.
Question remains, how can I get a key to the hotel room at this point if possible?

A: Go talk to Cliff Briscoe inside the dinosaur. Once your rep with Novac is 'Accepted', you'll get a permanent key from him.


text:
Q: select an xml element, ignore element name, print newline I'd like to select the first element, but ignore its name in the output.
This is what I'm getting, after requesting the first url element from each input xml file:
% xmllint \
 --xpath '(//yandexsearch/response/results/grouping/group/doc/url)[1]' \
 *.response.ya.xml
<url>https://example.com/</url><url>https://example.net/</url><url>https://example.org/</url>

But this is what I want instead:
https://example.com/
https://example.net/
https://example.org/

Note that the idea is to select the value of the first <url> element from each input Yandex.XML (Я Feel Lucky).
How do I do that with xpath?

A: I ended up using awk to remove <url> and </url>, and print the text from each element on a separate line, ignoring all the empty lines:
xmllint \
--xpath '(//yandexsearch/response/results/grouping/group/doc/url)[1]' \
| awk -F'</?url>' '{for(i=2;i<=NF;i++) if ($i != "") print $i}'

A: Try instead:
//yandexsearch/response/results/grouping/group/doc[1])/url/text()

XPath normally only selects nodes, and you would do concatenation in the code surrounding the xpath extraction.
That being said, XPath 2.0 can, if that's available to you:
string-join(//yandexsearch/response/results/grouping/group/doc[1])/url/text(), ' \n')

Also, this answer provides a couple of XSLT-based solutions.


text:
Q: Weird closure behavior in PHP Given this code in JavaScript:
function getFunc(){
    var myVar = 1;
    function inc(var1) {
        myVar = myVar + 1;
        return var1 + myVar;
    }
    return inc;
}
var inc = getFunc();
console.log(inc(5));
console.log(inc(6));

If you run this code in your browser console it gives you 7 and 9 as the result. I wrote the same code in C# and it gave me the same result:
static void Main(string[] args)
{
    var inc = GetAFunc();
    Console.WriteLine(inc(5));
    Console.WriteLine(inc(6));

    Console.ReadKey();
}

public static Func<int, int> GetAFunc()
{
    var myVar = 1;
    Func<int, int> inc = delegate(int var1)
    {
        myVar = myVar + 1;
        return var1 + myVar;
    };
    return inc;
}

But why doesn't it give the same result in PHP?
function getFunc() {
    $myVar = 1;

    $inc = function($var1) use ($myVar) {
        $myVar = $myVar + 1;
        return $var1 + $myVar;
    };

    return $inc;
}

$inc = getFunc();
echo $inc(5);
echo $inc(6);

It gave me 7 and 8!
Why they don't work the same way? Is something wrong with the code?

A: This is due to the fact you need to be explicit in PHP if you'd like to modify a variable in another scope. You can do this by defining $var as a reference with &. For example: use (&$var).
The following code will give you your expected behaviour:
function test() {
  $var = 1;

  $inc = function($num) use (&$var) {
      var_dump($var);
    $var = $var + 1;
    return $num + $var;
  };

  return $inc;
}

$test = test();
echo $test(5);
echo $test(6);

Hope this helps :) x

A: By default, PHP passes the function arguments by value and so the original variable will not be changed.
You can change this behaviour by prepending an ampersand to the variable name in the function:
function test() {
  $var = 1;

  $inc = function($num) use (&$var) {
    ++$var;
    return $num + $var;
  };

  return $inc;
}

$test = test();
echo $test(5);
echo $test(6);

A: You have to pass $var as reference to your subfunction, using the ampersand
  $inc = function($num) use (&$var) {

A: You can also make a static variable inside your closure instead of the creator.
This gives the expected results 7 and 9.
<?php

function test() {
    $inc = function($num) {
        static $var = 1;
        $var = $var + 1;
        return $num + $var;
    };

    return $inc;
}

$test = test();
echo $test(5);
echo $test(6);

A: All the other answers are right: PHP will pass-by-value the variable in use unless you make it a pass-by-reference.
Here are some authoritative examples from the PHP documentation:
http://php.net/manual/en/functions.anonymous.php
Example 3:
$message = 'hello';

// Inherit by-reference
$example = function () use (&$message) {
    var_dump($message);
};
echo $example();

It doesn't do very much though.
Example 4:
public function getTotal($tax)
{
    $total = 0.00;

    $callback =
        function ($quantity, $product) use ($tax, &$total)
        {
            $pricePerItem = constant(__CLASS__ . "::PRICE_" .
                strtoupper($product));
            $total += ($pricePerItem * $quantity) * ($tax + 1.0);
        };

    array_walk($this->products, $callback);
    return round($total, 2);
}

The top voted comment on this page also mentions that people will forget the pass-by-value behavior: http://php.net/manual/en/functions.anonymous.php#99287


text:
Q: Вызов метода объекта по ссылке родительского класса в C# Всем привет! У меня имеется код на C#, в котором объявлены класс Point и его производные, в том числе класс RightTriangle:Point. Я создал ссылку, которую необходимо при определённых условиях приравнивать к разным классам (все они произведены от Point), и по этой ссылке нужно вызывать методы (простые Get/Set) и также проводить сравнение (Equals, GetHashCode, ==, != переопределены для каждого производного класса). Проблема в том, что это банально не работает. Среда пишет, что никаких методов дочерних классов по этой ссылке нет, сравнение, очевидно, тоже не проходит, выдавая false на все случаи.
Point obj1;
obj1 = rtr1; // rtr1 имеет класс RightTriangle:Point
obj1.GetSideA(); // не работает, но у RightTriangle есть метод GetSideA

RightTriangle obj2;
obj2 = rtr1;
obj2.GetSideA(); // теперь работает, но я не знаю класс obj2 заранее

upd: почитал MSDN, по своей проблеме ничего не нашёл. Пока что реализовал алгоритм с помощью тонны отвратительных конструкций на if-ах, но очень бы не хотелось так оставлять, потому что смысл всего ООП в моей работе тогда вообще теряется.

A: class Point
{
    public int X;
    public int Y;
    override bool Equals(object obj)
    {
      var p2 = obj as Point;
      return p2 != null && p2.X == X && p2.Y == Y;
    }
}
class Circle: Point
{
    public int R;
    override bool Equals(object obj)
    {
      var c2 = obj as Circle;
      return c2 != null && c2.X == X && c2.Y == Y && c2.R == R;
    }
}
class Triangle: Point
{
    public int X2;
    public int Y2;
    public int X3;
    public int Y3;
    override bool Equals(object obj)
    {
      var t2 = obj as Triangle;
      return t2 != null && t2.X == X && t2.Y == Y
                        && t2.X2 == X2 && t2.Y2 == Y2
                        && t2.X3 == X3 && t2.Y3 == Y3;
    }
}

Point p = new Circle();

var circle = p as Circle;
if (circle != null)
  circle.R = 10;


text:
Q: bats - how can i write errors to a log file instead of the general output + run tests in parralel?
*

*I run a lot of Bats tests in an automated test suite -
is there a way to write the failures messages to a separate file??
when multiple tests fail it is very unclear because of the massive logs.
I want the general output to only show "pass/fail" for the tests and the log should contain the errors for each test.

*Is there a way to run the tests in parallel to save time?

A: Example code, comments inside:
check() {
     #this function emulates your automated test, it has return code, std out, and error out
     echo $1 some error log >&2
     echo $1 some normal log
     return $1
}

#This two tests are running in parallel in background.
#Replace 'check 1' with your command to implement.
{ check 1 >> log1 2>>errorlog1 ;
  RC=$?;
  [ "$RC" -eq 0 ] \
      && echo Test1 Succeed \
      || echo Test1 Fail
} >>mainlog &

#Replace 'check 0' with your command to implement.
{ check 0 >> log2 2>>errorlog2 ;
  RC=$?;
  [ "$RC" -eq 0 ] \
      && echo Test2 Succeed \
      || echo Test2 Fail
} >> mainlog &

This code will produce 5 files on disk.
Output from commands:
$ cat log1
1 some normal log

$ cat log2
0 some normal log

Errors from commands:
$ cat errorlog1
1 some error log

$ cat errorlog2
0 some error log

Main Log file with results:
$ cat mainlog
Test1 Fail
Test2 Succeed


text:
Q: How to list a post under an author's archive page in WordPress? I am creating a WordPress plugin which lists the author and its contributors in custom post meta-box. So what happens so far is when a user clicks the author name, it gives authors archive page which lists all the posts by author. So how can I list that same post in contributor's archive page?

A: What you are asking for is a meta_query.
I am assuming on contributor archive page you can able to get contributor ID.
Now suppose you store your post meta like
meta_key = 'contributor_id'; and
meta_value = '2' //ID of contributor
So now
$args = array(
   'meta_query' => array(
       array(
           'key' => 'contributor_id',
           'value' => '2',
           'compare' => '=',
       )
   )
);
$query = new WP_Query($args);
print_r($query);

above code will return all the posts which belongs to that specific contributor.

A: I don't think this is possible automatically.
On WordPress every post has one and only author, so in the archive page of that author you'll have only his/her posts.
Maybe you could implement a widget/plugin to show "related posts"


text:
Q: Python return statement, frequent issue The below program finds words like code/cope/coje etc. and returns the count of matches. However my return function is not giving me an output. print(len(matches)) gives the right output but I need to use return. I see in this question that 'findall' is a more straightforward method, but I want to use finditer for now. Why isn't this return statement correct? I'm actually facing this problem in frequently as I write programs to learn python. I was unable to pick the answer from these references one,two
import re
mystr = "codexxxcmkkaicopemkmaskdmcone"

def count_code (char):
  pattern = re.compile (r'co\we')
  matches = pattern.finditer(char)
  result = tuple (matches)
  return len(result)

count_code(mystr)

count_code (mystr) didn't return anything, and did not return an error. See here : repl.it

A: Your function seems to work fine. This is what I get when I run it in a local repl:
>>> import re
>>> mystr = "codexxxcmkkaicopemkmaskdmcone"
>>>
>>> def count_code (char):
...   pattern = re.compile (r'co\we')
...   matches = pattern.finditer(char)
...   result = tuple (matches)
...   return len(result)
...
>>> count_code(mystr)
3

It isn't outputting anything in repl.it because you're not sending anything to output. Replace that last line with print count_code(mystr) and see the results:
Python 2.7.10 (default, Jul 14 2015, 19:46:27)
[GCC 4.8.2] on linux
>
3
>

And here's my repl.it.
import re
mystr = "codexxxcmkkaicopemkmaskdmcone"

def count_code (mystr):

    pattern = re.compile (r'co\we')

    matches = pattern.finditer(mystr)
    matches = tuple (matches)

    return len(matches)

print count_code(mystr)


text:
Q: Android SQLiteDatabase WHERE selection I used an online note taking tutorial to make notes. It works, but I want to make notes based on selection. I thought I did it right, but can someone explain to me what I am doing wrong? I am passing in the course code and I thought I set it up to select correctly. Just tell me what I need to do.
This code seems to be the problem. If selectionargs and where are null it works by returning all notes. I want to return all notes with the where statement to be WHERE courseCode = thisCourse.getCourseID() How do I do this?
(DBOpenHelper.NOTE_COURSE is courseCode)
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
    String whereClause = DBOpenHelper.NOTE_COURSE+"=?";
    String[] selectionArgs = { thisCourse.getCourseID().trim() };
    return new CursorLoader(this, NotesProvider.CONTENT_URI, null, whereClause, selectionArgs, null);
}

A:
If selectionargs and where are null it works by returning all notes

If you want to select rows from your table where NOTE_COURSE is null you must use IS NULL:
String whereClause = DBOpenHelper.NOTE_COURSE + " IS NULL";

NOTE: it is NOT an argument value!
EDIT
Where clause is used to limit returned data and as such it is optional and if no special where clause is specified then all rows match the query. This is what happen when you pass null because you simply tell "I do not want rows filered", so all rows are returned.
Also your code looks fine, however I am not sure what you call trim() for setting up selectionArgs.

A: The answer is simple and it makes me feel so very silly. You need to make your parameters SQL ready by adding single quotes around them as seen in this example.
 @Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
    String whereClause = DBOpenHelper.NOTE_COURSE+" LIKE " + "'"+thisCourse.getCourseID()+"'";
    return new CursorLoader(this, NotesProvider.CONTENT_URI, null, whereClause, null, null);
}


text:
Q: How to write valid XPath expression using AND condition On multiple environments of the app which we are testing, the ID of one element is different. I have this div ID
CoredataForm:sec2_natural:grid1:left_section_natural:profession:selectProfession_auto_complete_force:ajax
Bold marked parts of the id, is the part which is same for all the environments.
How should I write xpath expression which would fit to all of them?
I used this
xpath="//div[starts-with(@id,'CoredataForm:sec2_natural:grid1:left_section_natural:profession:selectProfession') and ends-with(@id,'ajax')]"

but it doesn't work. Maybe another question: how can I use contains() function with multiple wildcards?

A: Your XPath might not work if your tool supports XPath1.0 only cause fn:ends-with is not available in XPath1.0
You can try to replace ends-with with contains in your XPath as
"//div[starts-with(@id,'CoredataForm:sec2_natural:grid1:left_section_natural:profession:selectProfession') and contains(@id,'ajax')]"

A: Selenium supports only XPath 1, but as JaSON says, ends-with is only available in XPath 2 and later versions.
However, it's possible to check that a string ends with another string using just the XPath 1 functions substring and string-length. The substring function returns a substring starting at a particular character location. The first character in the string has position 0, so substring('abc', 1)='bc'
If a string $s1 ends with another string$s2, then the following is true:
substring($s1, string-length($s1) - string-length($s2)) = $s2
So this expression should work for you (broken into multiple lines, for readability):
//div[
   starts-with(
      @id,
      'CoredataForm:sec2_natural:grid1:left_section_natural:profession:selectProfession'
   )
   and
   substring(
      @id,
      string-length(@id) - string-length('ajax')
   ) = 'ajax'
]


text:
Q: Handling single level routes in asp.net core I am working on a small SPA with asp.net core + angular2.
Naturally, I would like all my routes to return Home/Index page, which hosts the app.
Howeever, I am having some trouble with this.
In my startUp.cs file
    app.UseMvc(routes =>
        {
            routes.MapRoute(
                     "default",                                               // Route name
                    "{*any}",                                           // URL with parameters (matching anything)
                    new { controller = "Home", action = "Index" }  // Parameter defaults to Error/404
                );
        });

I am using this code.
But the issue I am having
if the url is http://localhost:43515/ - everything works fine
http://localhost:43515/NonExistingController/NonExistingAction - works fine
http://localhost:43515/singleLevelRoute - {"id":["The value 'singleLevelRoute' is not valid for Int32."]}
What is the cause for this?
I am very puzzled.
Please advise.


text:
Q: Business Logic in SQL Server 2008 If there are any DBAs out there, I'm making a fairly large piece of software and one of the biggest issues presently is where to put the business logic. While Stored Procedures would be easier to fix on the fly, the processing requirements would probably slow the DB down tremendously. I also don't want to have all of the business logic handled by the application because I want it to be a "self-sustaining entity" that doesn't require the user-front end to operate.
My idea, is to create a service to run on a central server somewhere, and have the clients connect through that. The service would maintain all the business logic and serve as a front-end for all the database operations.
Ideas? Yes? No?
I'm willing to accept that I'm also missing some key concepts and need to read some literature.

A: i would suggest that you keep a keen eye on the difference between what you think of as business logic, and what are the referential integrity constraints.
Make sure all constraints that keep the data meaningfully related are in place at the database layer.  i.e. if you need to cascade some deletes, or inserts - and when you need to validate some basic data values in order to have everything make sense... these should all be in the database.
Then decide if the Client, or the middle layer server, or the database is appropriate for any additional business logic.

A: What do you mean by "business logic"?
I've seen cases where aggregations and other set-based operations have been done in client code, as well as horrible RBAR operations in SQL that should be somewhere else.
SQL is one tool that has it's place: if you're working through large datasets, JOINs, aggregations etc then SQL is the place to do it. Anything else is slavish obedience to an SOA ideal.
My approach is to consider what the stored proc or SQL is doing: is it part of the middle tier to avoid set based operations in procedural code, or is it lower as pure data integrity/persistence?
If your business logic is 100% set based then you don't need a middle tier (edit: client code based) arguably, unless it's very thin.

A: Over the years, I've seen client applications come and go, but the database is still there.
So nowadays I use stored procedures for most of the business logic.  Three big advantages:

*

*Bug fix deployment takes an instant, with no downtime

*Multi-user by default

*Far less plumbing code (no data access layer)

A: Having all business logic on the server side is fine.
Not having it on the server side is fine, too.
In fact, it's up to you.
If a stored procedure tends to look not sql-ish, you can make a CLR stored procedure.
Here's a similar question.

A: I'd highly recommend a traditional n-layer approach, where you have at least UI layer, business layer (like a C# assembly or Java equivolent), and data access.  See:  http://en.wikipedia.org/wiki/Multitier_architecture.
I worked for a company where all the business logic was in the procs, and maintence costs are much higher than they had to be, it limited us to a specific version of sql server, it wasn't scalable, etc.  In short, unless your application is a simple throw away kind of thing, I'd not put any business logic in the database.


text:
Q: Alternatives of Google App Engine + Java If I develop my web application on GAE using Java, in future would I have easy migration opportunities, or will I stuck to GAE?
What can be other alternatives of Google App Engine + Java?
Not:

A: An GAE you are pretty much developing inside a Google managed Container - against restricted Java and other APIs. This is the PaaS - Platform As A Service approach to cloud computing. This would be similar to the Salesforce, Facebook etc approach.
However for most flexibility you should look at IaaS - Infrastructure As A Service Cloud platforms (like Amazon/Rackspace/etc..) where you have most flexibility.
We currently use both Rackspace and Amazon and have machines as our elastic containers on top of which we can deploy anything we want (custom Ubuntu image etc..)

A: With some care, you can write a Java app such that it will work both on and off App Engine. A better option, though, would be to use AppScale if you choose to leave App Engine. AppScale provides an App Engine compatible environment on your own hardware.

A: right now most viable competitor of GAE is Windows Azure.  You can easily build a site/application in Azure without getting dependent on Azure framework. There is /very/ little from Azure APIs that you have to deal with(mostly for diagnostics). If you decide to use other Azure services, like table storage services, you'll want to get real good at abstracting yourself away from the table storage to make your code portable.  Dealing with SQL Azure (at least from utilization perspective) is no different then using SQL Server and you would need to make a simple abstraction from actual rdbms implementation (most data access libraries do that anyway) to later utilize MySQL or Oracle, etc.

A: You will probably be stuck to GAE (or a very similar platform you could replicate on your own).
Alternatives: Amazon EC2? Windows Azure?

A: Using GAE requires you to design the app around their system so migration could require a rewrite. Certainly their NoSQL db at the least. Some people are saying Amazon EC2 is a better bet, but I haven't tried it yet. Also I prefer python-based stuff like Django, rather than Java stuff. Try the pyjamas client-side toolkit also.


text:
Q: Altering the value of k in kNN algorithm - Java I have applied the KNN algorithm for classifying handwritten digits. the digits are in vector format initially 8*8, and stretched to form a vector 1*64..
As it stands my code applies the kNN algorithm but only using k = 1. I'm not entirely sure how to alter the value k after attempting a couple of things I kept getting thrown errors. If anyone could help push me in the right direction it would be really appreciated. The training dataset can be found here and the validation set here.
ImageMatrix.java
import java.util.*;

public class ImageMatrix {
    private int[] data;
    private int classCode;
    private int curData;
public ImageMatrix(int[] data, int classCode) {
    assert data.length == 64; //maximum array length of 64
    this.data = data;
    this.classCode = classCode;
}

    public String toString() {
        return "Class Code: " + classCode + " Data :" + Arrays.toString(data) + "\n"; //outputs readable
    }

    public int[] getData() {
        return data;
    }

    public int getClassCode() {
        return classCode;
    }
    public int getCurData() {
        return curData;
    }

}

ImageMatrixDB.java
import java.util.*;
import java.io.*;
import java.util.ArrayList;
public class ImageMatrixDB implements Iterable<ImageMatrix> {
    private List<ImageMatrix> list = new ArrayList<ImageMatrix>();

    public ImageMatrixDB load(String f) throws IOException {
        try (
            FileReader fr = new FileReader(f);
            BufferedReader br = new BufferedReader(fr)) {
            String line = null;

            while((line = br.readLine()) != null) {
                int lastComma = line.lastIndexOf(',');
                int classCode = Integer.parseInt(line.substring(1 + lastComma));
                int[] data = Arrays.stream(line.substring(0, lastComma).split(","))
                                   .mapToInt(Integer::parseInt)
                                   .toArray();
                ImageMatrix matrix = new ImageMatrix(data, classCode); // Classcode->100% when 0 -> 0% when 1 - 9..
                list.add(matrix);
            }
        }
        return this;
    }

    public void printResults(){ //output results
        for(ImageMatrix matrix: list){
            System.out.println(matrix);
        }
    }

    public Iterator<ImageMatrix> iterator() {
        return this.list.iterator();
    }

    /// kNN implementation ///
    public static int distance(int[] a, int[] b) {
        int sum = 0;
        for(int i = 0; i < a.length; i++) {
            sum += (a[i] - b[i]) * (a[i] - b[i]);
        }
        return (int)Math.sqrt(sum);
    }

    public static int classify(ImageMatrixDB trainingSet, int[] curData) {
        int label = 0, bestDistance = Integer.MAX_VALUE;
        for(ImageMatrix matrix: trainingSet) {
            int dist = distance(matrix.getData(), curData);
            if(dist < bestDistance) {
                bestDistance = dist;
                label = matrix.getClassCode();
            }
        }
        return label;
    }

    public int size() {

        return list.size(); //returns size of the list

        }

    public static void main(String[] argv) throws IOException {
        ImageMatrixDB trainingSet = new ImageMatrixDB();
        ImageMatrixDB validationSet = new ImageMatrixDB();
        trainingSet.load("cw2DataSet1.csv");
        validationSet.load("cw2DataSet2.csv");
        int numCorrect = 0;
        for(ImageMatrix matrix:validationSet) {
            if(classify(trainingSet, matrix.getData()) == matrix.getClassCode()) numCorrect++;
        } //285 correct
        System.out.println("Accuracy: " + (double)numCorrect / validationSet.size() * 100 + "%");
        System.out.println();
    }

A: In the for loop of classify you are trying to find the training example that is closest to a test point. You need to switch that with a code that finds K of the training points that is the closest to the test data. Then you should call getClassCode for each of those K points and find the majority(i.e. the most frequent) of the class codes among them. classify will then return the major class code you found.
You may break the ties (i.e. having 2+ most frequent class codes assigned to equal number of training data) in any way that suits your need.
I am really inexperienced in Java, but just by looking around the language reference, I came up with the implementation below.
public static int classify(ImageMatrixDB trainingSet, int[] curData, int k) {
    int label = 0, bestDistance = Integer.MAX_VALUE;
    int[][] distances = new int[trainingSet.size()][2];
    int i=0;

    // Place distances in an array to be sorted
    for(ImageMatrix matrix: trainingSet) {
        distances[i][0] = distance(matrix.getData(), curData);
        distances[i][1] = matrix.getClassCode();
        i++;
    }

    Arrays.sort(distances, (int[] lhs, int[] rhs) -> lhs[0]-rhs[0]);

    // Find frequencies of each class code
    i = 0;
    Map<Integer,Integer> majorityMap;
    majorityMap = new HashMap<Integer,Integer>();
    while(i < k) {
        if( majorityMap.containsKey( distances[i][1] ) ) {
            int currentValue = majorityMap.get(distances[i][1]);
            majorityMap.put(distances[i][1], currentValue + 1);
        }
        else {
            majorityMap.put(distances[i][1], 1);
        }
        ++i;
    }

    // Find the class code with the highest frequency
    int maxVal = -1;
    for (Entry<Integer, Integer> entry: majorityMap.entrySet()) {
        int entryVal = entry.getValue();
        if(entryVal > maxVal) {
            maxVal = entryVal;
            label = entry.getKey();
        }
    }

    return label;
}

All you need to do is adding K as a parameter. Keep in mind, however, that the code above does not handle ties in a particular way.


text:
Q: Following Followers in Spring I am trying to develop a Following Followers functionality in a Spring Boot application. i search for example and I saw this one, which made perfect sense at the beginning:
https://github.com/SoichiSumi/Twitter-Clone/blob/master/src/main/java/yoyoyousei/twitter/clone/domain/model/User.java
My User had a ManyToMany relation of following, like this....
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "relation",
            joinColumns = @JoinColumn(name = "user_id"),
            inverseJoinColumns = @JoinColumn(name = "following_id"))
private List<User> following;

I developed my controllers, JSPs and tables and it works great to see which user your are following, but the problem came when I tried to  develop the Followers.
User_id  Following_id
1       2
1       3
1       4
1       6
2       4
2       6

*

*User_ID=1 is following user: 2,3,4&6

*User_ID=4 has followers: 1&2

How could I ask that table for the followers of user_id=4?
I thought that I should use a FollowerService and DAO, but I realized that I do not have a bean to use it.
The only way I think I can do it is to fetch all the table and start searching for all the appearances of a certain following_id to see with user_id is the follower.
I can not find an easy way to do it. Do you think I should create a bean? How? Thanks

A: Create the opposite relation like this:
@ManyToMany(mappedBy = "following")
private List<User> followers;

And you can get the followers of the user with id = 4 with its followers field.

A: This was my solution for your problem. The user class:
@Entity
public class User {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private long id;

    private String name;

    @OneToMany(mappedBy="to")
    private List<Followers> followers;

    @OneToMany(mappedBy="from")
    private List<Followers> following;

    public User() {}

    public User(String name) {
        this.name = name;
    }

}

As you can see the user class has a reference to the users who is following and those who he follows.
@Entity
public class Followers {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private long id;

    @ManyToOne
    @JoinColumn(name="from_user_fk")
    private User from;

    @ManyToOne
    @JoinColumn(name="to_user_fk")
    private User to;

    public Followers() {};

    public Followers(User from, User to) {
        this.from = from;
        this.to = to;
    }
}

The followers class contain the relationship between the two users, of course you might need to add more information to that class like when 'from' started following 'to'.
If you want to get the followers/following of a user you just call the respective getter.


text:
Q: How to send document paramaters to Docusign envelope Can we, using the PHP API, send extra parameters that, otherwise are needed to be filled in by the user? So for example, we have a field 'address' in the PDF. We already know the address in the application so we want to prefill that. Is this possible?
    $config = array(
        'integrator_key' => 'asdf',
        'email' => 'asdf',
        'password' => 'asdf',
        // The version of DocuSign API (Ex: v1, v2)
        'version' => 'v2',
        // The DocuSign Environment (Ex: demo, test, www)
        'environment' => 'www',

    );

    $client = new DocuSign_Client($config);

    echo $current_user->user_email;

    $role = new DocuSign_TemplateRole('Bulk Recipient', $current_user->user_firstname.' '.$current_user->user_lastname, $current_user->user_email);
    $roles = array( $role );

    $signatureService = new DocuSign_RequestSignatureService($client);
    $result = $signatureService->signature->createEnvelopeFromTemplate('asdf', 'asdf',  'sent', $roles);

Update:
I added tabs to the data and a field to the template in docusign, labelled Adres. In send the following data to to docusign and got a file to sign without the added data. Guess I'm still doing 'something' wrong here.
Bellow the data array.
 ["templateId"]=>
  string(36) "1e9517bf-51c3-4e40-8bd0-600fe3a35bdf"
  ["status"]=>
  string(4) "sent"
  ["templateRoles"]=>
  array(1) {
    [0]=>
    array(4) {
      ["roleName"]=>
      string(14) "Bulk Recipient"
      ["name"]=>
      string(15) "Roel Veldhuizen"
      ["email"]=>
      string(27) "someemail@gmail.com"
      ["tabs"]=>
      array(1) {
        ["textTabs"]=>
        array(1) {
          [0]=>
          array(2) {
            ["tabLabel"]=>
            string(5) "Adres"
            ["value"]=>
            string(18) "Some example adres"
          }
        }
      }
    }
  }

A: Yes. Note there are two issues:

*

*Supplying your data to DocuSign for future use in a "tab" on the document.

*Placing the tab on the document where you want the information to appear.
The simplest is if you already know where the tab should appear on the doc. In that case, include the tab, with the data and location information in your Envelope.Create call. See the tabs section of the Request Body. Eg, you'd use a text tab for the address line.
You can also have either the human or DocuSign locate the tab in the right place on the document, then use an API call to populate it with the data. Look at anchoring and templates if this is of interest.


text:
Q: ath9k driver suddenly doesn't see channel 13 anymore Suddenly, after upgrade to Linux kernel 3.11.0-19, my wireless card with the ath9k driver is no longer seeing the 13th channel, even though it worked fine for the last year and half. It also still works fine on another Ubuntu laptop and an Android phone.
How can I re-enable the 13th channel? It is very necessary as most of the channels are taken here.

A: I installed the wireless-crda and the iw packages which automatically seem to have fixed things, before I saw these replies. Thank you for the answers, however!

A: I seem to be having the same problem with Ubuntu 20.04, switching from Kernel 5.4.x to 5.13.x. Installing wireless-crda did not help at all.
On an Arch Linux forum I found the remark that crda is actually deprecated over wireless-regdb.
Anyway. What solved it for me, was to force the regdomain when loading the cfg80211 module:
Add a file /etc/modprobe.d/cfg80211.conf with the content
options cfg80211 ieee80211_regdom=DE # or your country's 2-char ISO code.

A: You need to set your regulatory domain
Edit your /etc/default/crda and set your country code.
There is more info by running dmesg.
See. regulatory domain


text:
Q: In Jersey, how do I specify a minimal application.wadl that only shows resources? For example, I want something of the form:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<application xmlns="http://wadl.dev.java.net/2009/02">
    <doc xmlns:jersey="http://jersey.java.net/" jersey:generatedBy="Jersey: 1.18 11/22/2013 01:21 AM" />
    <grammars />
    <resources base="https://localhost/plugh/">
    ....
    </resources>
/application>

A: I am answering my own question to share what I learned.
Define a subclass of WadlGeneratorConfig,
where you define a WadlGenerator grammar that does nothing.
  package com.try1234;

  import java.util.List;

  import com.sun.jersey.api.wadl.config.WadlGeneratorConfig;
  import com.sun.jersey.api.wadl.config.WadlGeneratorDescription;
  import com.sun.jersey.server.wadl.generators.WadlGeneratorGrammarsSupport;

  public class PlughWadlGeneratorConfig extends WadlGeneratorConfig
  {
      @Override
      public List<WadlGeneratorDescription> configure()
      {
          return
           generator(WadlGeneratorGrammarsSupport.class)
               .prop("grammarsStream", "application-grammars.xml")
               .prop("overrideGrammars", true)
           .descriptions();
      }
  }

Define an empty application-grammars.xml
<grammars xmlns="http://wadl.dev.java.net/2009/02"
   xmlns:xsd="http://www.w3.org/2001/XMLSchema"
   xmlns:xi="http://www.w3.org/1999/XML/xinclude">
</grammars>

Make sure it is on the classpath for the webapp, e.g., in a Maven-style directory structure, the file resides in target/classes.
Modify your web.xml to use the subclass of WadlGeneratorConfig. Add these lines:
<init-param>
    <param-name>com.sun.jersey.config.property.WadlGeneratorConfig</param-name>
    <param-value>com.try1234.PlughWadlGeneratorConfig</param-value>
</init-param>

Load your web application, the following GET on this URL should work:
https://localhost/plugh/application.wadl
This solution works for Jersey 1.18.
Note: The rationale for the empty grammars element is that
I had run into https://java.net/jira/browse/JAXB-411 ; by not producing any , I was able to avoid the IllegalArgumentException.
References:
http://razvancaraghin.blogspot.com/2014/01/html-documentation-for-your-rest.html
Troubles with WADL / generated XSD using Jersey with a contract-first approach


text: Q: Where can I obtain an exhaustive list of Google's Schema.org type values? Google's Query Patterns documentation refers to use of Schema.org types, but I cannot find a way to obtain the comprehensive list of values that can be returned for enumerated types such as $SchemaOrg_Color, $SchemaOrg_servesCusine and $SchemaOrg_Product. I've checked the schema.org website and still cannot find values, only types. I've also checked schema.org's github project (of course, Google's values are likely different).


text: Q: Android: Check which app is open on the screen Hi everyone I am trying to make an app that will check which screen is open at the client and accordingly check: if an open app X will do ... and so on.  I would be happy for help on how to check which app is open to the customer on the screen.  And enslavement throughout Android


text:
Q: Gradle IntelliJ Idea JavaFX Runtime Error I wanted to use JavaFX to start doing an interface to my app but I get error:
java.lang.UnsupportedClassVersionError: org/openjfx/gradle/JavaFXPlugin has been compiled by a more recent version of the Java Runtime (class file version 55.0), this version of the Java Runtime only recognizes class file versions up to 52.0
> org/openjfx/gradle/JavaFXPlugin has been compiled by a more recent version of the Java Runtime (class file version 55.0), this version of the Java Runtime only recognizes class file versions up to 52.0

Can someone please explain me how to fix it for IntelliJ Idea?
Thank you!

A: It says that your current version of Java only recognises class file version up to 52.0. This means you have Java 1.8 (version 8) installed on your system.
Simply install Java version 11 to remove the error. Or if you already have Java 11 installed, then check your project's JDK path and make sure that you've configured JDK 11.
 Check this out for step by step solution on Eclipse IDE


text:
Q: How to fix late binding for datarow in datacollection where datarow variable defined in range I'm in the process of converting VB to C#.Net for my company. In order to do this more easily, I have option strict ON. I am trying to resolve a late binding on the following code. Row is considered an OBJECT by the compiler. I've never written code in this fashion (someone else's work). Here is the code.
        Dim items As List(Of Contact) = ContactsTable.GetChanges.DataTableToList(Of Contact)
    'Dim row As DataRow = Nothing
    Dim modifiedRows As DataRowCollection = From row In ContactsTable.Rows
                       Where row.RowState = DataRowState.Modified Or row.RowState = DataRowState.Added

A: There was no way to modify the existing code. The next best option was to recode it using a "For each" loop.
        Dim modifiedRows As DataRowCollection = Nothing
    For each row As DataRow In ContactsTable.Rows
        If row.RowState = DataRowState.Modified Or row.RowState = DataRowState.Added Then
            modifiedRows.Add(row)
        End If
    Next


text:
Q: Uploading video using Facebook SDK and iOS9, what am I doing wrong? I'm not sure what I'm doing wrong here and hope someone can point me in the right direction as the code is failing silently without any error output...I've checked every thread here and have tried all suggested solutions to no avail.
I'm trying to upload a video to facebook using the latest SDK for ios and the code below--I've checked the permissions--they are correct, I can upload images, post messages, etc
I've also tried the parameter @"video.mov" as well as the graphPath @"{userID}/video}"
It looks like the FBSDKGraphRequest never starts. I've checked the NSData by writing it to a local mov file and playing it with no problems.
Any help is appreciated, thanks
     NSMutableData * movieData=[[NSMutableData alloc]init];
    [manager requestDataForAssetResource:asset[1] options:nil dataReceivedHandler:^(NSData * _Nonnull data) {
        [movieData appendData:data];
    } completionHandler:^(NSError * _Nullable error) {

        if (error == nil) {

            NSDictionary *stuff = @{
                                     @"source": movieData,
                                     @"description":@"testing",
                                      @"contentType":@"video/quicktime",
                                     };

            /* make the API call */

       if ([[FBSDKAccessToken currentAccessToken] hasGranted:@"publish_actions"]) {

           NSLog(@"starting connection");
            FBSDKGraphRequest *connection = [[FBSDKGraphRequest alloc] initWithGraphPath:@"me/videos" parameters:stuff HTTPMethod:@"POST"];

            [connection startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {

                if (!error) {

                    NSLog(@"Video uploaded %@",result);

                } else {

                    NSLog(@"Video uploaded failed %@",error.userInfo);

                }

            }];

A: I got it to work by pulling the post function out of the completionHandler..for some reason the request doesn't execute there.


text:
Q: i'm Trying to make react paypal button that change the billing amount on props change i'm Trying to make react paypal button that changes the billing amount on props change.
I call the following component with props price and everytime the price change i would like to rerender the button to update the actual price.
const PaypalForm = props => {
  let paypalRef = useRef();

  useEffect(() => {
    window.paypal
      .Buttons({
        createOrder: (data, actions) => {
          return actions.order.create({
            purchase_units: [
              {
                description: "test",
                amount: {
                  currency_code: "USD",
                  value: props.price
                }
              }
            ]
          });
        },
        onApprove: async (data, actions) => {
          const order = await actions.order.capture();
          console.log(order);
        },
        onError: err => {
          setError(err);
          console.error(err);
        }
      })
      .render(paypalRef.current);
  }, [props.price]);

  return (
    <Row className="justify-content-center">
      {error &&
Uh oh, an error occurred! {error.message}
}

    </Row>
  );
};

Everything is working except that a new button is created and added in the bottom of old one at each props change. I would like my new button to replace the old one.

A: You can pass the amount to the forceRerender property of the button and the button will rerender each whenever the amount is updated.

A: You should really just use react-paypal-button-v2
It updates with props, works as a stateless function and works with SSR such as next.js.
It even allows bypassing actions.order.create() so that you can call your own API's.

import { PayPalButton } from "react-paypal-button-v2";

const PaypalButton = ({total, cart}) => {
  return (
    <PayPalButton
    createOrder={(data, actions) => {
      return fetch('/api/paypal/create-transaction', {
        method: 'POST',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            total: total,
            cart: cart,
        })
      })
      .then((response) => {return response.json()})
      .then((data) => {return data.orderID})
      .catch(error => console.log(error))
    }}
    onApprove={(data) => {
      // Capture the funds from the transaction
      return fetch('/api/paypal/capture-transaction', {
        method: 'POST',
        headers: {
          'content-type': 'application/json'
        },
        body: JSON.stringify({ orderID: data.orderID })
      })
        .then((res) => { return res.json() })
        .then((details) => {
          if(details === 200){
            console.log('success');
          } else {
            console.log('failure');
          }
        })
        .catch(error => {
          console.log(error)
        })
    }}
    options={{
      clientId: process.env.PAYPAL_CLIENT_ID
    }}
  />
  );
}

export default PaypalButton;


text:
Q: Flood-fill fails to fill whole shape when reaching boundary color? I would like to draw some shape and then fill those shape with chosen color. At this time, I have just completed in drawing some basic shapes, but I'm still stuck at coloring them with flood-fill algorithm.
In details, I can not coloring the whole shape after clicking on it. All it could do is just drawing a line to the edge of the screen, leaking the chosen color outside the edge of the shape (ignoring the boundary color of the shape).

Here is all my work, can anyone help me???
#include <GL/glut.h>
#include <math.h>
#include <iostream>
using namespace std;

static int window;
static int value = 0;
GLsizei width, height;
int flag = 0;
bool up = false, down = false;

struct Point {
    GLint x;
    GLint y;
};
struct RGBColor
{
    GLfloat r;
    GLfloat g;
    GLfloat b;
};
struct Position
{
    Position() : x(0), y(0) {}
    float x;
    float y;
};
Position start;
Position finish;
void init()
{
    glClearColor(0, 0, 0, 0);
    glPointSize(2.0);
    glLineWidth(2.0);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluOrtho2D(0.0, 500.0, 500.0, 0.0);
}
void menu(int num) {
    if (num == 0) {
        glutDestroyWindow(window);
        exit(0);
    }
    else {
        value = num;
    }
    glutPostRedisplay();
}
void createMenu(void)
{
    int sub_Triangle = glutCreateMenu(menu);
    glutAddMenuEntry("Isoceles right", 2);
    glutAddMenuEntry("Equilateral", 3);
    int menu_Triangle = glutCreateMenu(menu);
    int sub_Quadrilateral = glutCreateMenu(menu);
    glutAddMenuEntry("Rectangle", 4);
    glutAddMenuEntry("Square", 5);
    int menu__Quadrilateral = glutCreateMenu(menu);
    int sub_Oval = glutCreateMenu(menu);
    glutAddMenuEntry("Circle", 6);
    glutAddMenuEntry("Ellipse", 7);
    int menu_Oval = glutCreateMenu(menu);
    int sub_RegularPolygon = glutCreateMenu(menu);
    glutAddMenuEntry("Pentagon", 8);
    glutAddMenuEntry("Hexagon", 9);
    int menu_RegularPolygon = glutCreateMenu(menu);
    int sub_OtherShape = glutCreateMenu(menu);
    glutAddMenuEntry("Arrow", 10);
    glutAddMenuEntry("Star", 11);
    int menu_OtherShape = glutCreateMenu(menu);
    int sub_Operation = glutCreateMenu(menu);
    glutAddMenuEntry("Add", 12);
    glutAddMenuEntry("Subtract", 13);
    glutAddMenuEntry("Multiply", 14);
    glutAddMenuEntry("Divide", 15);
    int menu_Operation = glutCreateMenu(menu);
    int sub_ColorFill = glutCreateMenu(menu);
    glutAddMenuEntry("Red", 16);
    glutAddMenuEntry("Green", 17);
    glutAddMenuEntry("Blue", 18);
    int menu_ColorFill = glutCreateMenu(menu);
    glutAddMenuEntry("Line", 1);
    glutAddSubMenu("Triangle", sub_Triangle);
    glutAddSubMenu("Quadrilateral", sub_Quadrilateral);
    glutAddSubMenu("Oval", sub_Oval);
    glutAddSubMenu("Regular Polygon", sub_RegularPolygon);
    glutAddSubMenu("Other Shape", sub_OtherShape);
    glutAddSubMenu("Operation", sub_Operation);
    glutAddSubMenu("Color Fill", sub_ColorFill);
    glutAddMenuEntry("Shape Choice", 19);
    glutAttachMenu(GLUT_RIGHT_BUTTON);
}
void draw_Line()
{
    glColor3f(1.0, 1.0, 1.0);
    glBegin(GL_LINE_LOOP);
    glVertex2f(start.x, start.y);
    glVertex2f(finish.x, finish.y);
    glEnd();
    glutSwapBuffers();
}
void draw_IsocelesRight()
{
    glColor3f(1.0, 1.0, 1.0);
    glBegin(GL_LINE_LOOP);
    int a = finish.y - start.y;
    glVertex2f(start.x, start.y);
    glVertex2f(start.x, start.y + a);
    glVertex2f(start.x + a, start.y + a);
}
void draw_Equilateral()
{
    glColor3f(1.0, 1.0, 1.0);
    glBegin(GL_LINE_LOOP);
    int midx = (finish.x + start.x) / 2;
    int midbotx = (start.y - finish.y)*(1 / sqrt(3));
    int midboty = finish.y;
    glVertex2f(midx, start.y);
    glVertex2f(midx - midbotx, finish.y);
    glVertex2f(midx + midbotx, finish.y);
}
void draw_Rectangle()
{
    glColor3f(1.0, 1.0, 1.0);
    glBegin(GL_LINE_LOOP);
    glVertex2f(start.x, start.y);
    glVertex2f(finish.x, start.y);
    glVertex2f(finish.x, finish.y);
    glVertex2f(start.x, finish.y);
}
void draw_Square()
{
    glColor3f(1.0, 1.0, 1.0);
    glBegin(GL_LINE_LOOP);

    int a = finish.y - start.y;
    glVertex2f(start.x, start.y);
    glVertex2f(start.x, start.y + a);
    glVertex2f(start.x + a, start.y + a);
    glVertex2f(start.x + a, start.y);
}
void draw_Circle()
{
    float PI = 3.14;
    glColor3f(1.0, 1.0, 1.0);
    glBegin(GL_LINE_LOOP);
    int size = sqrt(pow(finish.x - start.x, 2) + pow(finish.y - start.y, 2));
    for (int i = 0; i <= 360; i++)
    {
        float theta = (2 * 3.14 * i) / 360;
        glVertex2f((size / 2) * cos(theta) + finish.x, (size / 2) * sin(theta) + finish.y);
    }
}
void draw_Ellipse()
{
    float PI = 3.14;
    glColor3f(1.0, 1.0, 1.0);
    glBegin(GL_LINE_LOOP);
    int size1 = sqrt(pow(finish.x - start.x, 2) + pow(finish.x - start.x, 2));
    int size2 = sqrt(pow(finish.y - start.y, 2) + pow(finish.y - start.y, 2));

    for (int i = 0; i <= 360; i++)
    {
        float theta = (2 * 3.14 * i) / 360;
        glVertex2f((size1 / 2) * cos(theta) + finish.x, (size2 / 2) * sin(theta) + finish.y);
    }
}
void draw_Pentagon()
{
    const double PI = 3.14159265358979323846;
    double r = sqrt(pow(finish.x - start.x, 2));
    int sides = 5;
    int center_x = start.x + (finish.x - start.x) / 2;
    int center_y = start.y + (finish.y - start.y) / 2;

    glBegin(GL_LINE_LOOP);
    for (int i = 0; i < sides; i++) {
        double angle = i * 2 * PI / sides;
        glVertex2d(center_x + r*cos(angle), center_y + r*sin(angle));
    }
}
void draw_Hexagon()
{
    const double PI = 3.14159265358979323846;
    double r = sqrt(pow(finish.x - start.x, 2));
    int sides = 6;
    int center_x = start.x + (finish.x - start.x) / 2;
    int center_y = start.y + (finish.y - start.y) / 2;
    glBegin(GL_LINE_LOOP);
    for (int i = 0; i < sides; i++) {
        double angle = i * 2 * PI / sides;
        glVertex2d(center_x + r*cos(angle), center_y + r*sin(angle));
    }
}
void draw_Arrow()
{
    glColor3f(1.0, 1.0, 1.0);
    glBegin(GL_LINES);
    const double PI = 3.14159265358979323846;
    double length = finish.x - start.x;
    double e = length / 3;
    double x1 = finish.x - e *  (1/tan(45 * PI /180));
    double y1 = start.y - e * tan(45 * PI / 180);
    double x2 = finish.x - e *  (1 / tan(45 * PI / 180));
    double y2 = start.y + e * tan(45 * PI / 180);
    glVertex2f(start.x, start.y);
    glVertex2f(finish.x, start.y);
    glVertex2f(finish.x, start.y);
    glVertex2f(x1, y1);
    glVertex2f(finish.x, start.y);
    glVertex2f(x2, y2);
}
void draw_Star()
{
    glColor3f(1.0, 1.0, 1.0);
    glBegin(GL_LINE_LOOP);
    glVertex2f(100, 225);
    glVertex2f(210, 225);
    glVertex2f(250, 100);
    glVertex2f(290, 225);
    glVertex2f(400, 225);
    glVertex2f(315, 290);
    glVertex2f(350, 400);
    glVertex2f(250, 330);
    glVertex2f(150, 400);
    glVertex2f(185, 290);
}
void draw_Add()
{
    glColor3f(1.0, 1.0, 1.0);
    glBegin(GL_LINES);
    double length = finish.x - start.x;
    double half_length = length / 2;
    glVertex2f(start.x + half_length, start.y);
    glVertex2f(start.x + half_length, start.y + length);
    glVertex2f(start.x, start.y + half_length);
    glVertex2f(start.x + length, start.y + half_length);
}
void draw_Subtract()
{
    glColor3f(1.0, 1.0, 1.0);
    glBegin(GL_LINES);
    double length = finish.x - start.x;
    glVertex2f(start.x, start.y);
    glVertex2f(start.x + length, start.y);
}
void draw_Multiply()
{
    glColor3f(1.0, 1.0, 1.0);
    glBegin(GL_LINES);
    double length = finish.x - start.x;
    glVertex2f(start.x, start.y);
    glVertex2f(start.x + length, start.y + length);
    glVertex2f(start.x + length , start.y);
    glVertex2f(start.x, start.y + length);
}

RGBColor getPixelColor(GLint x, GLint y)
{
    RGBColor color;
    glReadPixels(x, y, 1, 1, GL_RGB, GL_FLOAT, &color);
    return color;
}
void setPixelColor(GLint x, GLint y, RGBColor color)
{
    glColor3f(color.r, color.g, color.b);
    glBegin(GL_POINTS);
    glVertex2i(x, y);
    glEnd();
    glFlush();
}
void floodFill(GLint x, GLint y, RGBColor oldColor, RGBColor newColor)
{
    RGBColor color;
    color = getPixelColor(x, y);
    if (color.r == oldColor.r && color.g == oldColor.g && color.b == oldColor.b)
    {
        setPixelColor(x, y, newColor);
        floodFill(x + 1, y, oldColor, newColor);
        floodFill(x, y + 1, oldColor, newColor);
        floodFill(x - 1, y, oldColor, newColor);
        floodFill(x, y - 1, oldColor, newColor);
    }
    return;
}

bool IsSameColor(RGBColor x, RGBColor y) {
    if (x.r == y.r && x.b == y.b && x.g == y.g) {
        cout << "is same color true" << endl;
        return true;
    }
    else {
        cout << "is same color false" << endl;
        return false;
    }
}
void BoundaryFill(int x, int y, RGBColor F_Color, RGBColor B_Color) {
    cout << "bound fill" << endl;
    RGBColor currentColor;

    currentColor = getPixelColor(x, y);

    if (!IsSameColor(currentColor, B_Color) && !IsSameColor(currentColor, F_Color)) {
        cout << "bound" << endl;
        setPixelColor(x, y, F_Color);
        BoundaryFill(x - 1, y, F_Color, B_Color);
        BoundaryFill(x, y + 1, F_Color, B_Color);
        BoundaryFill(x + 1, y, F_Color, B_Color);
        BoundaryFill(x, y - 1, F_Color, B_Color);
    }
}

void display()
{
    if (flag == 1)
    {
        if (value == 1) {
            draw_Line();
        }
        else if (value == 2) {
            draw_IsocelesRight();
        }
        else if (value == 3) {
            draw_Equilateral();
        }
        else if (value == 4) {
            draw_Rectangle();
        }
        else if (value == 5) {
            draw_Square();
        }
        else if (value == 6) {
            draw_Circle();
        }
        else if (value == 7) {
            draw_Ellipse();
        }
        else if (value == 8) {
            draw_Pentagon();
        }
        else if (value == 9) {
            draw_Hexagon();
        }
        else if (value == 10) {
            draw_Arrow();
        }
        else if (value == 11) {
            draw_Star();
        }
        else if (value == 12) {
            draw_Add();
        }
        else if (value == 13) {
            draw_Subtract();
        }
        else if (value == 14) {
            draw_Multiply();
        }
        else if (value == 16)
        {
            RGBColor newColor = { 1.0f, 0.0f, 0.0f }; // red
            RGBColor oldColor = { 0.0f, 0.0f, 0.0f }; // black
            floodFill(start.x, start.y, oldColor, newColor);
        }
        glEnd();
        glutSwapBuffers();
        glFlush();
    }
    flag = 0;
}
void reshape(int w, int h)
{
    glViewport(0, 0, (GLsizei)w, (GLsizei)h);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluOrtho2D(0, w, h, 0);

    width = w;
    height = h;

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
}
void mouse(int button, int state, int x, int y)
{
    if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN)
    {
        down = true;
        start.x = x; //x1
        start.y = y; //y1
    }
    if (button == GLUT_LEFT_BUTTON && state == GLUT_UP)
    {
        if (down == true) {
            up = true;
            flag = 1;
            finish.x = x;
            finish.y = y;
        }

        down = false;
        up = false;
    }
    glutPostRedisplay();
}

int main(int argc, char** argv)
{
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
    glutInitWindowSize(500, 500);
    glutInitWindowPosition(450, 100);
    window = glutCreateWindow("Coloring Shapes");

    init();
    createMenu();
    glutDisplayFunc(display);
    glutReshapeFunc(reshape);
    glutMouseFunc(mouse);
    glutMainLoop();
    return 0;
}

A: The major issue is, that the coordinates which you pass to glReadPixels are wrong.
When a point is drawn, by glVertex then the coordinates are transformed by the modelview  and projection matrix.
So the orthographic projection is applied

gluOrtho2D(0.0, 500.0, 500.0, 0.0);

But glReadPixels directly read the fragment of the framebuffer. The coordinates are the x and y coordinate of the fragment in the framebuffer, where the bottom left is always (0, 0) and the top right is (widht, height).
You've to flip the y coordinate when you read the the fragment:
RGBColor getPixelColor(GLint x, GLint y)
{
    RGBColor color;
    glReadPixels(x, height-y, 1, 1, GL_RGB, GL_FLOAT, &color);
    return color;
}

In order not to sit rounding errors when calling glVertex2i, I recommend to use glRasterPos2i and glDrawPixels instead. The coordinates to glRasterPos2i are transformed by the current modelview and projection matrix:
void setPixelColor(GLint x, GLint y, RGBColor color)
{
    glRasterPos2i( x, y );
    glDrawPixels( 1, 1, GL_RGB, GL_FLOAT, &color );
    glFlush();
}

Since the color values are floating point values, you've to consider in inaccuracy when reading the color back from the GPU. Consider this when you compare the colors:
e.g.
color1.r == color2.r
fabs(color1.r - color2.r)  < 0.001f
Write a function which compares colors and use it in floodFill:
bool isEqual( const RGBColor &c1, const RGBColor &c2 )
{
    return fabs(c1.r - c2.r) < 0.001f && fabs(c1.g - c2.g) < 0.001f && fabs(c1.b - c2.b) < 0.001f;
}

void floodFill(GLint x, GLint y, RGBColor oldColor, RGBColor newColor)
{
    RGBColor color;
    color = getPixelColor(x, y);
    if ( isEqual(color, oldColor) )
    {
        setPixelColor(x, y, newColor);
        floodFill(x + 1, y, oldColor, newColor);
        floodFill(x, y + 1, oldColor, newColor);
        floodFill(x - 1, y, oldColor, newColor);
        floodFill(x, y - 1, oldColor, newColor);
    }
    return;
}

Anyway your code will only work for small areas, because the algorithm is recursive. The stack usage increased rapidly and causes a stack overflow immediately.
But it works for tine areas.

A: Make sure your glReadBuffer() points to the right buffer. For double buffered rendering, glDrawBuffer and glReadBuffer point to GL_BACK per default.
Also there are some issues in your code. It seems to me you use double buffered rendering in an incorrect way. Single frame rendering procedure usually looks like this:
void display(){
    // user sees front buffer at the moment
    ClearScreen(); // glClear() or something, done on back buffer
    RenderAllYouHaveOnTheScene(); // rendered to back buffer
    SwapBuffers(); // glutSwapBuffers() does this in glut
    // Now back buffer becomes front buffer and user sees rendered scene.
    // Contents of current back buffer (which was front buffer
    // before glutSwapBuffers()) is undefined and you should
    // clear it and redraw everything on next iteration.
}

And I don't see any point in swaping buffers in your draw_Line() procedure.
It is not a good thing to do float comparison with == operator. Read here. Use unsigned char pixel format or do float comparison with precision as described in the link.
Also check if your (x, y) coordinates do not overflow your screen boundaries (0 <= x < Width, 0 <= y < Height).
Edit: Also, as I noticed later, you specify GLUT_SINGLE in glutInitDisplayMode which means single buffered rendering, but use glutSwapBuffers, which should only be used in case of double buffered rendering. Read here to learn the difference.


text:
Q: Python multithreading radial basis function So i need to make an Radial Basis Function run a bit quicker
    while(error):
        epoch += 1
        error = 0
        for i in xrange(self.numPoints):
            dp = self.dotProduct(g[i], self.weights)
            signum = self.sig(dp)
            if dp < 0 and g[i].classification == 1:
                self.updateWeights(signum, g[i])
                error += 1
            elif dp > 0 and g[i].classification == -1:
                self.updateWeights(signum, g[i])
                error += 1
            elif dp == 0:
                self.updateWeights(signum, g[i])
                error += 1
        if epoch > 10000:
            return 0
    print "Epochs %i, %i Dimensions" % (epoch, self.numWeights - 1)
    return 1

def dotProduct(self, x, y):
    ret = 0.0
    for i in xrange(len(y)):
        ret += x.points[i]*y[i]
    return ret

def sig(self, x):
    if x < 0:
        return 1
    if x > 0:
        return -1
    else:
        return 0

def updateWeights(self, s, g):
    for i in xrange(self.numWeights):
        self.weights[i] = self.weights[i] + self.learningRate * s * g.points[i]

I was wanting to use concurrent threads but python threading locks threads until the previous thread has finished so it will not make it any faster that running a single main thread.
I need to find a way to run threads concurrently, a single thread for every:
   for i in xrange(self.numPoints):
But locking the values for self.weights, meaning that only one thread can change them at a time.
Anyone got any ideas how this can be done?
This works great on a small data set but when using real data gets a little hairy

A: You could use numpy arrays to improve performance e.g.:
import numpy as np

def dotProduct(self, x, y):
    return np.dot(x.point, y)

def updateWeights(self, s, g):
    self.weights += self.learningRate * s * g.points

where x.point, y, self.weights, g.points are 1d numpy arrays.

A: Python multihreading run all threads in a singe process on one CPU core.
To run truly parallel thread you should use the multiprocessing library.


text:
Q: Vulkan vkResetCommandPool vs vkResetCommandBuffer The description of vkResetCommandPool just says

Resetting a command pool recycles all of the resources from all of the command buffers allocated from the command pool back to the command pool. All command buffers that have been allocated from the command pool are put in the initial state.

Is it the same as resetting all the existing command buffers allocated from the command pool, which is the same as calling vkResetCommandBuffer for each single buffer assuming that the command pool was created with VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT.
I am wondering whether the additional control brought by VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT will impact the performance. If I have a few swapchain images and want to reset my command buffer when drawing each frame. Is it better to create a separate command pool for each swapchain image and reset the corresponding command pool when drawing every frame, or just create a single command pool with VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT and reset the corresponding command buffer when drawing each frame?

A: The answer is mostly going to be "it depends". How many command buffers do you have per frame?
If you have many command buffers per frame, it's probably less expensive to have one pool per frame and reset the pool.
If you have few command buffers per frame then it's probably cheaper to reset individual command buffers.
That said, it's entirely implementation-defined behaviour, so if you have a concern about it write a small benchmark and test your hypothesis.


text:
Q: In React, what is the proper way to await looking up a value in sessionStorage? I'm using React 16.  I have a hook where I determine if a session token has been stored in session storage ...
import { useEffect } from 'react';
import { useAuthenticationState, useAuthenticationDispatch } from '../context';

const useAuthentication = () => {
  const authenticationState = useAuthenticationState();
  const updateAuthenticationState = useAuthenticationDispatch();

  useEffect(() => {
    const auth_token = sessionStorage.getItem('token');
    console.log("auth token: " + auth_token);
    updateAuthenticationState({
      type: 'field',
      fieldName: 'isAuthenticated',
      payload: !!auth_token,
    });
  }, [updateAuthenticationState]);

  const isAuthenticated = authenticationState.isAuthenticated;

  return {
    isAuthenticated,
  };
};

export default useAuthentication;

I would like to pass the value of what is stored in session storage to a component that will either render another component or redirect based on the value of the my hook ...
const DirectoryApp = () => {
  console.log("starting get hook value ...");
  const { isAuthenticated } = useAuthentication();
  console.log("is auth:" + isAuthenticated);

  return (
      <Router>
        ...
                  <PrivateRoute
                  authed={isAuthenticated} path="/unapproved-list/"
                  component={UnapprovedList}
                  />

But this line
const { isAuthenticated } = useAuthentication();

isn't properly getting the value of what is in sessionStorage -- it is always initialy returning false.  I think this is because I'm not awaiting the result of what the hook returns, but if I do this
const { isAuthenticated } = await useAuthentication();

I get the error
Syntax error: Unexpected reserved word 'await'. (24:31)

How do I properly await the value of what the hook returns?

A: Effect is being called after the initial render of the DirectoryApp component. It means your useAuthentication hooks gets whatever is stored in the authenticationState and returns it without any dependency on the code inside of the useEffect hook at that point ant returns the the DirectoryApp component, DirectoryApp renders with this initial value and only after that the effect is being executed.
There's nothing to await as there's no async code in the code you provided.
Based on your imports and code structure I assume you are trying to use React.Context with reducer inside to manage authentication state. In this case you have your AuthenticationProvider component of some sort sowhere wrapping the DirectoryApp so you can solve the issue there by moving the session storage read to the reducer's third initializer parameter:
const reducer = (state, action) => {
    // reducer logic
};

const StateContext = createContext();
const DispatchContext = createContext();
const useAuthenticationState = () => useContext(StateContext);
const useAuthenticationDispatch = () => useContext(DispatchContext);

const AuthenticationProvider = ({ children }) => {
    const [state, dispatch] = useReducer(reducer, { isAuthenticated: false }, (arg) => {
        const auth_token = sessionStorage.getItem('token');

        return { ...arg, isAuthenticated: !!auth_token };
    });

    return (
        <DispatchContext.Provider value={dispatch}>
            <StateContext.Provider value={state}>
                {children}
            </StateContext.Provider>
        </DispatchContext.Provider>
    );
};

const App = () => (
    <AuthenticationProvider>
      <DirectoryApp />
    </AuthenticationProvider>
);

sessionStorage.getItem is a synchronous function so you will get properly initialized state before the first render of the DirectoryApp.


text:
Q: передать значение из str в hex Стоит задача на входе у скрипта 16ричный код ("7200F40004226301"). Этот код в переменную считывается в формате list, и каждый символ имеет расширение как str, И необходимо что-бы скрипт мог с символом работать,как с числом.
for item in content:
  for symbol in item:
      k = int(''.join("%02X " % ord( symbol )))

результат:
>> symbol
7
>>> type(symbol)
<class 'str'>
>>> type(k)
<class 'int'>
>>> k
37
>>> hex(k)
'0x25'

Но я хочу сделать чтобы hex(k) = 0x07, а не 0x25.
Возможно я изначально неправильно выбрал путь решения задачи, так как профан в программировании.

A: Если открыв файл как текст (к примеру, в notepad), вы видите в нём строку 7200F40004226301 (шестнадцатеричные цифры в тексте—Unicode символы: 7 (U+0037 DIGIT SEVEN), 2 (U+0032 DIGIT TWO), 0 (U+0030 DIGIT ZERO), итд) так называемый hexdump (bytes -> hex), то чтобы выполнить обратное преобразование (hex -> bytes) и получить исходную последовательность байт: 0x72, 0x00, 0xF4, ... как тип bytes в Питоне:
>>> import binascii
>>> binascii.unhexlify("7200F40004226301")  # из hex-строки в bytes
b'r\x00\xf4\x00\x04"c\x01'
>>> list(_)
[114, 0, 244, 0, 4, 34, 99, 1]
>>> b'r'[0]  # индексация bytes возвращает индивидуальные байты (int)
114
>>> int("72", 16)  # из hex-строки в int
114
>>> 0x72 == 114 == 0b1110010  # одно и то же число в разных системах исчисления
True

В тексте Питон программы, байты, которые соответствуют печатаемым ASCII символам, могут быть представлены как эти символы, поэтому байт 114 печатается в виде текста как b'r', а не b'\x72' как другие байты. См. Байты - перевод из строки.

A: Если я правильно понял вопрос, то на входе вы получаете кодированные в hex бинарные данные.
Для получения байтового массива из такого представления есть функция binascii.unhexlify


text:
Q: Is there a way to observe superlayer? I have a class inherited from CALayer. In this class I need to catch an adding to superlayer event. How can I do it?

A: As formulated, the answer is: You can't. There is no event sent to a layer on the occasion when it acquires a superlayer.