text:
Q: Three,js get mesh outside the loader I am working on a project using Three.js.
And, I am trying get mesh(gltf.scene) in the GLTF load from outside, but it says it is undefined if I console.log outside of the loader. I spent hours to figure this out but haven't able to solve this problem. I am guessing this is happening because it is asynchronous, but I am not so sure.
This is my first attempt to use javascript class format, so I am little bit confused. Usually it worked if I declare variable on the higher scope and assign the mesh to it but does not work this time.
class mainCharacter {
  constructor(game) {
...
...
...
this.character;
this.loader = new GLTFLoader();
this.loader.load("./c.glb",(gltf)=>{
this.character= gltf.scene;
});
console.log(this.character);

}

I also tried to do async function but did not work.
class mainCharacter {
  constructor(game) {
...
...
...
this.character;
this.loadMain();
console.log(this.character);
})

async loadMain(){
    const loader = new GLTFLoader();
    this.character = await loader.loadAsync("./c.glb");
    this.character.scene.scale.set(13, 13, 13);
    this.scene.add(this.character.scene);
}

Seems like it works if I use await in front of the loadMain() and console.log(this.character), but I cannot use await in the constructor function, since it is not async function.
If anyone have any idea, please help me out :'(
Thank you!

A: According to ThreeJS documentation (https://threejs.org/docs/#api/en/loaders/Loader.loadAsync), the method loadAsync does not return the loaded mesh, instead, it return a Promise event.
.loadAsync ( url : String, onProgress : Function ) : Promise

Therefore, you would need to declare a onLoad callback function like below:
this.character = await loader.loadAsync("./c.glb").then(function(value) {
  console.log(value); // "Success"
});

A: Define another static method (like load shown below) in your class and pass this as a parameter
class mainCharacter {
  constructor(game) {
    ...
    this.character;
    this.loader;
    mainCharacter.load(this);
    ...
  }
  static load(self) {
    self.loader = new GLTFLoader();
    self.loader.load(
      "./c.glb",
      (gltf) => self.character = gltf.scene
    );
  }
}

in arrow functions, this points to the owner of that function, or the object in which that particular arrow function is defined.
in your case, this inside the arrow function does not point to the mainCharacter object because its actually defined in and passed on to the loader.load() function.
See https://www.w3schools.com/js/js_arrow_function.asp for more details.


text:
Q: Callback function Jquery/javascript returning an array I dont know if i'm doing this the wrong way but I can't think of another way to do it.
I have a function in php that i'm calling with $.post and I want it to return an array.  It sounds like I need to use a callback function and i'm trying but it just wont work.
Here is the code:
Jquery:
$("#e_del_date_btn").click(function(){
    var new_date = $("#edited_del_date").val();
    if (new_date == '') {new_date = $("#edited_del_date").attr("placeholder");}
    var new_time = $("#edited_del_time").val();
    var non = $("#non").html();
    function getarray(new_date, new_time, non, callback) {
        $.post('http://localhost:8080/wsad2/post.php',{'new_date':new_date,'new_time':new_time,'non':non}, function(data) {
            callback(data);
        });
    }
    getarray(new_date,new_time,non, function(data) {
        alert(data[0]);
        $("#odi_span").html(data[0]);
        $("#e_del_date_pencil").attr("value",data[1]);
        $("#e_del_date_pencil").attr("value2",data[2]);
    });
    $("#e_del_date").hide();
    $("#e_del_date").css("z-index","0");
    $("#po_main_div_test").css({ opacity : 1.0 });
});

PHP Code:
$returndata = array();
$returndate = $returntime = $returntext = '';

if ($fail == "false") {if ($row['complete'] == "no") {$returntext .= '(When Completed) ';}}
$returntext .= 'This order is scheduled to be delivered on
';
if ($fail == "false") {$returntext .= $new_date_2;$returndate = $new_date_2;} else {$returntext .= $orig_deldate;$returndate = $orig_deldate;}
$returntext .= ' between ';
if ($fail == "false") {$returntext .= $new_time_2;$returntime = $new_time_2;} else {$returntext .= $orig_time;$returntime = $orig_time;}
if ($fail == "true") {$returntext .= '
The New Delivery Date must be tomorrow or later.';}

$returndata[0] = $returntext;
$returndata[1] = $returndate;
$returndata[2] = $returntime;

//echo ($returntext);

return $returndata;

from some of the things I've read I might be trying to use $.post improperly, but basically I need to pass the date/time variables and then have the php return the value but they can be changed in the PHP code (which is the point of this, to edit a delivery date/time) so i need the value sent from the php back to the JavaScript in case it was changed, so i can update the attribute in case they decide to change it again w/out refreshing the page.
My problem is, the alert is always blank (the alert is for testing purposes) and basically it SEEMS to be working, but the 3 jquery calls in the getarray() function do not seem to be firing, or if they are they aren't working.  right now the HTML field i'm updating doesn't change no matter what I do.
am I using the callback function improperly?  I really need $.post to return an array, not just echo data so that I can update multiple fields instead of just one.
Also, i've left out some of the php code as I didn't think it was relevant.  i just wanted to show the creation of the array and it being filled with data.

A: You can echo an array with PHP with JSON:
PHP:
http://php.net/manual/en/function.json-encode.php
Javascript:
http://api.jquery.com/jquery.parsejson/
Furthermore: How to send a proper POST request with JQuery:
$.ajax({
   url: "test.php",
   data: {my_$_Post1: "value"}
}).done(function() {
   //whatever you want to do
});

Or(NOT RECOMMANDED):
Answer = $.ajax({
   url: "test.php",
   async: false
   data: {my_$_Post1: "value"}
});
alert(Answer);

http://api.jquery.com/jquery.ajax/

A: One option is to print the data from your PHP code as a JSON (JavaScript) array. Then use JSON.parse() in your JavaScript code to parse the text and turn it into an array.

redpajama_set_name: RedPajamaStackExchange


text:
Q: C++ primer 5 ed. Virtual destructor and move semantics In C++ primer 5 ed. it is said:

"The fact that a base class needs a virtual destructor has an important indirect impact on the definition of base and derived classes: If a class defines a destructor—even if it uses = default to use the synthesized version—the compiler will not synthesize a move operator for that class (§13.6.2, p. 537)."

So for more understanding I've tried this:
class A
{
public:
    A(){cout << "A::A()\n";}
    virtual ~A(){cout << "A::~A()\n";}
    A& operator = (const A&) {cout << "A::=\n"; return *this;};
    A& operator = (A&&) = default;
};

int main()
{

    A a;
    A a2;
    a2 = std::move(a); // why copy-assignment operator is not called here. Normally a will be "moved" through copy-ctor (moving through working copy-ctor)

    std::cout << std::endl;
}

*

*So according to the text above in the book class A has a virtual destructor thus the compiler won't synthesize a move-ctor/assignment operations But in main I've tried to move an object of type class A so normally move here uses copy-assignment instead of move-assignment but copy-assignment is not called here?!

*So when a vairtual dtor causes a default operation be not synthesized? Thank you!

A: Your textbook is right, the compiler won't automatically synthesize a move operator. In the code sample you force the compiler to generate one by setting it to default, this can only fail if the move operator is implicitly deleted. Which is something else than it being implicitly declared.
Criteria for implicit deletion:

*

*A has a non-static data member that is const

*A has a non-static data member of a reference type

*A has a non-static data member that cannot be move-assigned (has deleted, inaccessible, or ambiguous move assignment operator)

*A has direct or virtual base class that cannot be move-assigned (has deleted, inaccessible, or ambiguous move assignment operator)

*A has a non-static data member or a direct or virtual base without a move assignment operator that is not trivially copyable

*A has a direct or indirect virtual base class

Criteria for implicit declaration:

*

*there are no user-declared copy constructors;

*there are no user-declared move constructors;

*there are no user-declared copy assignment operators;

*there are no user-declared destructors;

*the implicitly-declared move assignment operator would not be defined as deleted

source


text:
Q: Agrupar objetos e somar valores Tenho uma classe ListaBid com vários objetos, nesta classe existe os atributos Partnumber(Chave), Quantidade e SaldoPartnumber.
Posso ter X objetos com o partnumber Y e outros X objetos com Partnumber Z
Gostaria de fazer a soma do atributo SaldoPartnumber de todos os itens que tem o valor do Partnumber igual.

var itensPedido = (from l in listaBID
                   select new Pedido.sItemPedido
                   {
                       CodigoProduto = l.Partnumber,
                       SaldoPartnumberSap = l.SaldoPartnumberSap,
                       Saldo = l.Saldo,
                   }).ToList();

A: É só fazer um GroupBy simples
var groupped = itensPedido.GroupBy(x => x.CodigoProduto)
                          .Select(g => new
                          {
                              Chave = g.Key,
                              Itens = g.ToList(),
                              Total = g.Count(),
                              Soma = g.Sum(x => x.SaldoPartnumberSap),
                          });

Um exemplo completo - veja funcionando no .NET Fiddle:
using static System.Console;
using System.Linq;
using System.Collections.Generic;

public class Program
{
    private static List<ListaBid> _lista = new List<ListaBid>
    {
        new ListaBid { Partnumber = "A01", SaldoPartnumberSap = 10 },
        new ListaBid { Partnumber = "A02", SaldoPartnumberSap = 05 },
        new ListaBid { Partnumber = "A01", SaldoPartnumberSap = 11 },
        new ListaBid { Partnumber = "A02", SaldoPartnumberSap = 15 }
    };

    public static void Main()
    {
        var itensPedido = (from l in _lista
                           select new
                           {
                               CodigoProduto = l.Partnumber,
                               SaldoPartnumberSap = l.SaldoPartnumberSap,
                               Saldo = l.Saldo,
                           }).ToList();

        var groupped = itensPedido.GroupBy(x => x.CodigoProduto)
                                  .Select(g => new
                                          {
                                              Chave = g.Key,
                                              Itens = g.ToList(),
                                              Total = g.Count(),
                                              Soma = g.Sum(x => x.SaldoPartnumberSap),
                                          });

        foreach(var g in groupped)
        {
            WriteLine($"{g.Chave} - Total: {g.Total} - Soma: {g.Soma}");
        }
    }
}

class ListaBid
{
    public string Partnumber { get; set; }
    public int SaldoPartnumberSap { get; set; }
    public int Saldo { get; set; }
}


text:
Q: How does an old 32bit linux program end up calling a 64bit library? I have an old 32bit C++ app I need to run under RedHatEL7. RHEL7 has both 32 and 64 bit versions of libthread_db.so.1 installed. But then somehow the app ends up loading /lib64/libthread_db.so.1. How can I stop this happening? A console log shows this:
mybox:/home/worknet$ which corbanames
~/bin/corbanames
mybox:/home/worknet$ file ~/bin/corbanames
/home/worknet/bin/corbanames: **ELF 32-bit** LSB executable, Intel 80386, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.9, not stripped
mybox:/home/worknet$ locate libthread_db.so.1
**/usr/lib/libthread_db.so.1**
/usr/lib/i686/nosegneg/libthread_db.so.1
**/usr/lib64/libthread_db.so.1**
mybox:/home/myuser$ gdb corbanames
GNU gdb (GDB) Red Hat Enterprise Linux 7.6.1-100.el7_4.1
Copyright (C) 2013 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-redhat-linux-gnu".
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>...
Reading symbols from /home/myuser/bin/corbanames...done.
(gdb) r
Starting program: /home/myuser/bin/corbanames
[Thread debugging using libthread_db enabled]
Using host libthread_db library "**/lib64/libthread_db.so.1**".

Program received signal SIGSEGV, Segmentation fault.
0x080544a1 in getStackFrame<5> (this=<optimized out>) at StackCache.hpp:89
89  StackCache.hpp: No such file or directory.
Missing separate debuginfos, use: debuginfo-install glibc-2.17-196.el7_4.2.i686 libgcc-4.8.5-16.el7_4.2.i686 libstdc++-4.8.5-16.el7_4.2.i686
(gdb) bt
#0  0x080544a1 in getStackFrame<5> (this=<optimized out>) at StackCache.hpp:89
#1  fetchFrameData<5> (this=<optimized out>) at StackCache.hpp:76
#2  ECONZ::Leak::Impl::StackCache::StackCache (this=0xffffd01c)
    at StackCache.cpp:66
#3  0x08050c00 in ECONZ::Leak::Impl::HeaderList::doNew (size=32,
    throwFlag=false) at leakTracker.cpp:138
#4  0x08050d83 in operator new (size=32) at leakTracker.cpp:284
#5  0xf79762ac in ACE_OS_Object_Manager::instance ()
    at Object_Manager_Base.cpp:185
#6  0xf7976357 in ACE_OS_Object_Manager_Manager::ACE_OS_Object_Manager_Manager
    (this=0xf7a2318c <ACE_OS_Object_Manager_Manager_instance>)
    at Object_Manager_Base.cpp:488
#7  0xf7976393 in __static_initialization_and_destruction_0 (__initialize_p=1,
    __priority=65535) at Object_Manager_Base.cpp:504
#8  0xf79763cf in global constructors keyed to ACE_Object_Manager_Base::ACE_Object_Manager_Base() () at Object_Manager_Base.cpp:505
#9  0xf79c9816 in __do_global_ctors_aux ()
   from /usr/local/ACE_wrappers_32/lib/libACE.so.5.7.9
#10 0xf78ce475 in _init () from /usr/local/ACE_wrappers_32/lib/libACE.so.5.7.9
#11 0xf7fe9b5d in _dl_init_internal () from /lib/ld-linux.so.2
#12 0xf7fdb04f in _dl_start_user () from /lib/ld-linux.so.2
(gdb)

A: It seems I was mistaken, as @hgminh and @PeterCordes pointed out - the 64bit library was an artefact of debugging.
The actual SIGSEGV turned out to be calls to __builtin_[frame|return]_address not being binary compatible. They have been refactored.


text:
Q: Python passenger for simple asyncio application on host without any flask, django or FastApi apps I would like to create a mqtt broker helping of hbmqtt library and publish it on the server (web host). While publishing it the host server requires a passenger.py file, but I do not know what write, I have that kind of passenger file for Django, how can I change the the passenger file of Django to properly run my python script.
import logging
import asyncio
from hbmqtt.broker import Broker
from settings import config

broker = Broker(config)

@asyncio.coroutine
def broker_coro():
    yield from broker.start()

formatter = "[%(asctime)s] :: %(levelname)s :: %(name)s :: %(message)s"
logging.basicConfig(level=logging.INFO, format=formatter)
asyncio.get_event_loop().run_until_complete(broker_coro())
asyncio.get_event_loop().run_forever()


text:
Q: jQuery: Anchor scrolling jumpy I am using some code from www.css-tricks.com that can be used to animate local scrolling to a page anchor.  Here is the code snippet:
$("class-name-here").on("click", function() {
    var $target = $(this.hash);
    $target = $target.length && $target
    || $('[name=' + this.hash.slice(1) +']');
    if ($target.length) {
        var targetOffset = $target.offset().top;
        $('html,body')
        .animate({scrollTop: targetOffset}, 1500, "easeOutQuint");
     return false;
    }
});

I have tried using a variety of times for the animation duration, but when I click the link, the page does scroll correctly, but after the scroll reaches the destination, the animation continues.  In other words, it scrolls, but after the animation seems complete, if you try to scroll away manually, the page animates itself to that location again for about half a second.
Is there something wrong with the snippet / has anyone seen this before?

A: I found an example where we stop the scroll-event on different kind of events. I made an example for you without using jquery-ui. The scroll-timer is set to 2.5 sec so that you can stop it anytime before it reaches its target: JS-FIDDLE
function goTo(sectionID) {

   var page = $("html, body");
   page.on("scroll mousedown wheel DOMMouseScroll mousewheel keyup touchmove", function(){
       page.stop();
   });

   page.animate({ scrollTop: $("#section" + sectionID).offset().top }, 2500, 'swing', function(){
       page.off("scroll mousedown wheel DOMMouseScroll mousewheel keyup touchmove");
   });

   return false;
};

A: Can you try this :
$('.your-class-name-here').click(function(event) {
        var id = $(this).attr("href");
        var offset = 10;
        var target = $(id).offset().top - offset;
        $('html, body').animate({scrollTop:target}, 1000);
        event.preventDefault();
    });

});


text:
Q: Retrieve File from Location on Windows, Mac and Linux Currently, I have a Java application that needs to copy a file from a directory and place it on the Desktop. I have this method
public static void copyFileUsingFileStreams(File source, File dest) throws IOException {

    InputStream input = null;
    OutputStream output = null;

    try {
        input = new FileInputStream(source);
        output = new FileOutputStream(dest);
        byte[] buf = new byte[1024];
        int bytesRead;
        while ((bytesRead = input.read(buf)) > 0) { output.write(buf, 0, bytesRead); }
    }
    finally {
        input.close();
        output.close();
    }
}

and I call it like below.
copyFileUsingFileStreams(new File("C:/Program Files (x86)/MyProgram/App_Data/Session.db"), new File(System.getProperty("user.home") + "/Desktop/Session.db"));

This works perfectly on Windows. However, I want to be able to do the exact same thing on Mac and Linux machines as well (location is /opt/myprogram/App_Data/Session.db). How can I assess whether the machine running is Windows or Mac/Linux, and how do I restructure my code accordingly?

A: You can get the OS info using System.getProperty like
String property = System.getProperty("os.name");

Moreover you can use Files.copy() to simplify your code(and if you want more control then use StandardCopyOption). e.g.
Files.copy(src, Paths.get("/opt/myprogram/App_Data/Session.db"));

so your updated code can look something like this
public static void copyFileUsingFileStreams(File source, File dest) throws IOException {
    String property = System.getProperty("os.name");

    if (property.equals("Linux")) {
        dest = Paths.get("/opt/myprogram/App_Data/Session.db").toFile();
    }
    //add code to adjust dest for other os.
    Files.copy(source.toPath(), dest.toPath());
}

A: You can determine the OS name using
System.getProperty("os.name")


text:
Q: Discord py - How to check if creating date is below 10 minutes? how can I check if a created server invite is below 10 minutes? I tried to make a list that prints every invite that's created below 10 minutes ago, but it doesn't print anything.
I tried:
invites = await ctx.guild.invites()
for invite in invites:
    if (time.time() - invite.created_at.timestamp()) < 600:
        print(invite)

I added:
@bot.event
async def on_invite_create(invite):
    print(invite.created_at.timestamp())
    print(time.time())
    print(time.time() - invite.created_at.timestamp())

and that was the results from the prints (fresh created invite):
1619006499.447825
1619013699.5136192
7200.065812826157

A: The discord.Guild.invites() method returns a list of discord.Invite objects. Each discord.Invite object has an attribute created_at, which returns the time which the invite was created at as a datetime.datetime object. This is different than time.time(), which is simply a float. So, you should use datetime.datetime.now() to get the current time as a datetime.datetime object.
import datetime

invites = await ctx.guild.invites()
for invite in invites:
    if (datetime.datetime.now() - invite.created_at).total_seconds() < 600:
        print(invite)

Alternatively, you could use datetime.timedelta() to compare the differences in time.
for invite in await ctx.guild.invites():
    if datetime.datetime.now() - invite.created_at < datetime.timedelta(minutes=10):
        print(invite)


text:
Q: Convert string to int after reading data from CSV file I'm trying to read data from a csv file into a vector of structs each containing various values from a football game (offensive team, quarter, down, yards to go, play desc, etc). I'm trying to use stringstream to convert strings to ints but i'm returning junk data.
Data d;  //structs
vector<Data> TeamData;  //vector of structs
string s;
istringstream iss( s );

ifstream myfile;
myfile.open("CSV file here");  //open CSV file

while (  !myfile.eof()  )
{
getline (myfile, d.gameid, ',');  //read to comma, store in d.gameid

getline (myfile, s, ',');  //read to comma
iss >> d.qtr;             //use stringstream to store into d.qtr

repeat for remaining values . . .

The cvs file looks similar to this if you're wondering:
20070906_NO@IND,1,47,25,IND,NO,1,10,31,(2:25) J.Addai up the middle to NO 27 for 4 yards (S.Fujita).,0,0,2007
20070906_NO@IND,1,46,42,IND,NO,2,6,27,(1:42) P.Manning pass deep left to M.Harrison for 27 yards TOUCHDOWN.,0,0,2007

My program returns data like this when i try to output everything of relevance:
Game ID: 20070906_NO@IND
Offensive team: IND
Quarter: 7077994
Down: 4696320
To go: 4670480
Play: (2:25) J.Addai up the middle to NO 27 for 4 yards (S.Fujita).

Game ID: 20070906_NO@IND
Offensive team: IND
Quarter: 7077994
Down: 4696320
To go: 4670480
Play: (1:42) P.Manning pass deep left to M.Harrison for 27 yards TOUCHDOWN.

A: I think you should look at my answer for 'reading floats'
Instead of parsing on whitespace parse on commas.
Using ifsstream to read floats

A: istringstream copies the string you pass it in the constructor, so changes you make to the string following that won't have any effect on the stream. You should construct a new stream, or call the istringstream:str() method to supply a new string, every time the string changes.
getline (myfile, s, ',');  //read to comma
iss.str(s);                // supply new string to stream
iss >> d.qtr;              //use stringstream to store into d.qtr


text:
Q: Invisible JButton in JPanel Here's my JPanel. The first button is always visible, but the secound is visible only when you place a cursour on it. Where the problem can be?
P.S. Please use simple english, if u can, because I don't speak english well
public class GamePanel extends JPanel implements KeyListener{

GamePanel(){
    setLayout(null);
}

public void paint(Graphics g){

    JButton buttonShip1 = new JButton();
    buttonShip1.setLocation(10, 45);
    buttonShip1.setSize(40, 40);
    buttonShip1.setVisible(true);
    add(buttonShip1);

    JButton buttonShip2 = new JButton();
    buttonShip2.setLocation(110, 145);
    buttonShip2.setSize(440, 440);
    buttonShip2.setVisible(true);
    add(buttonShip2);
    }
}

A: *

*Don't use a null layout

*Don't create components in a painting method. The paint() method is for custom painting only. There is no need for you to override the paint() method.

Read the section from the Swing tutorial How to Use FlowLayout for a simple example that uses buttons and a layout manager.

A: If you want to avoid problems and learn Java Swing correctly, go check out their tutorials here.
There are too many problems to discuss here, so I'll try to keep it simple.

*

*You're using a null layout. null layouts are avoided for the most part because there is usually a layout that does exactly what you want. It takes some time to get it working, but there are some defaults in this tutorial that are fairly simple to use. There are some nice pictures there that show you what you can do with each layout, too. If you use a layout manager, you generally don't need to use setLocation, setSize or setVisible on most components like JButtons.

*You're calling the paint method in a Swing application. You want to call paintComponent because you're using Swing and not Awt. You also need to call the super.paintComponent(g) method on the first line of the paintComponent method in order to correctly override the other paintComponent method.

*The paint/paintComponent related methods are called very often. You don't want to create/initialize objects in them. The paint/paintComponent methods aren't a one time method like they may sound. They're continuously called and you should design your GUI around this. Design your paint-related methods to be event-driven rather than sequential. In other words, program the paintComponent method with the mindset that your GUI is reacting to things continuously rather than running in sequential order like a normal program. That's a very basic approach to it and hopefully doesn't confuse you, but if you go check out that tutorial you'll see what I mean eventually.
There are two basic types of GUIs in Java. One is Swing and the
    other is Awt. Check out this answer on stackoverflow for a
    nice description of the two.
Here is an example of what two buttons on a JPanel look like.
public class Test
{
    public static void main(String[] args)
    {
        JFrame jframe = new JFrame();
        GamePanel gp = new GamePanel();

        jframe.setContentPane(gp);
        jframe.setVisible(true);
        jframe.setSize(500,500);
        jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }

    public static class GamePanel extends JPanel{

    GamePanel() {
        JButton buttonShip1 = new JButton("Button number 1");
        JButton buttonShip2 = new JButton("Button number 2");
        add(buttonShip1);
        add(buttonShip2);

        //setLayout(null);
        //if you don't use a layout manager and don't set it to null
        //it will automatically set it to a FlowLayout.
    }

    public void paintComponent(Graphics g){
        super.paintComponent(g);

        // ... add stuff here later
            // when you've read more about Swing and
            // painting in Swing applications

        }
    }

}


text: Q: How to scrape the text from this data?


text:
Q: Designing template for Ruby on Rails view. What and where to learn? I have a project going on, and I am in charge of the front-end design, whereas my developers will work on the back-end with Ruby on Rails.
I do not know Ruby on Rails, and am designing front-end using XHTML, CSS, jQuery, 960.gs CSS Framework. My developer is supposed to take my design and connect the elements of back-end to it, with Ajax too.
What are the things that I should know while designing the template/view so that I won't kick my developers' asses with my design? How to help the connecting of elements painless? I understand I must avoid . Some Ruby on Rails developers also prefer Blueprint CSS Framework over 960.gs.
Any guidance? Thanks.

A: Generally the Rails templating system is quite flexible and will enable developers to create even complex designs. The CSS framework should not make such a difference. However if they are using Rails 2.x it is markedly easier to use Prototype instead of jQuery. However Rails 3.x is also agnostic to javascript library.
A relatively good overview is the official guide. You might also try out this tool for cutting up your views and layouts.

A: I can speak from the developer point of view.
The things that piss me off are too complicated css structures, keep it simple and abstract as you can.
The other things is naming classes and ids, in general try to find out what models the developer is using and name your classes and ids accordingly. E.g. for a blog with posts:
#posts .post for a post in the index view  and #post for a post in the show view.
I never care what css framework the designer uses, as long as it works.
And lastely, if you design different html pages, be aware that we often have only one or two layouts, that's eg. /views/layouts/application.html.erb and we usually try to keep that number low as possible.
jQuery is find, ever been my preferred choice over rails' own prototype.


text:
Q: spark partitionBy with partitioned column in json output im reading below json in spark
{"bucket": "B01", "actionType": "A1", "preaction": "NULL", "postaction": "NULL"}
{"bucket": "B02", "actionType": "A2", "preaction": "NULL", "postaction": "NULL"}
{"bucket": "B03", "actionType": "A3", "preaction": "NULL", "postaction": "NULL"}

val df=spark.read.json("actions.json").toDF()

Now im writing the same to a json output as below
df.write. format("json"). mode("append"). partitionBy("bucket","actionType"). save("output.json")

and the output.json is as below
{"preaction":"NULL","postaction":"NULL"}

bucket,actionType columns are missing in the json output, i need partitionby columns as well in the output

A: You can try a workaround by creating duplicate columns to be used in partitionBy as
import org.apache.spark.sql.functions._
df.select(Seq(col("bucket").as("bucketCopy"), col("actionType").as("actionTypeCopy")) ++ df.columns.map(col): _*)
  .write.format("json").mode("append").partitionBy("bucketCopy","actionTypeCopy"). save("output.json")


text:
Q: convert deprecated opengl function to modern opengl (3.3) i need help to convert the render function of IQM model (void renderiqm()) to modern OpenGL (without the deprecated functions like enableClientState(), etc).
The code of renderiqm() function is here:
https://github.com/lsalzman/iqm/blob/master/demo/gpu-demo.cpp
and these are the shaders:
Vertex Shaders:
"#version 120\n"
"#ifdef GL_ARB_uniform_buffer_object\n"
"  #extension GL_ARB_uniform_buffer_object : enable\n"
"  layout(std140) uniform animdata\n"
"  {\n"
"     uniform mat3x4 bonemats[80];\n"
"  };\n"
"#else\n"
"  uniform mat3x4 bonemats[80];\n"
"#endif\n"
"attribute vec4 vweights;\n"
"attribute vec4 vbones;\n"
"attribute vec4 vtangent;\n"
"void main(void)\n"
"{\n"
"   mat3x4 m = bonemats[int(vbones.x)] * vweights.x;\n"
"   m += bonemats[int(vbones.y)] * vweights.y;\n"
"   m += bonemats[int(vbones.z)] * vweights.z;\n"
"   m += bonemats[int(vbones.w)] * vweights.w;\n"
"   vec4 mpos = vec4(gl_Vertex * m, gl_Vertex.w);\n"
"   gl_Position = gl_ModelViewProjectionMatrix * mpos;\n"
"   gl_TexCoord[0] = gl_MultiTexCoord0;\n"
"   mat3 madjtrans = mat3(cross(m[1].xyz, m[2].xyz), cross(m[2].xyz, m[0].xyz), cross(m[0].xyz, m[1].xyz));\n"
"   vec3 mnormal = gl_Normal * madjtrans;\n"
"   vec3 mtangent = vtangent.xyz * madjtrans; // tangent not used, just here as an example\n"
"   vec3 mbitangent = cross(mnormal, mtangent) * vtangent.w; // bitangent not used, just here as an example\n"
"   gl_FrontColor = gl_Color * (clamp(dot(normalize(gl_NormalMatrix * mnormal), gl_LightSource[0].position.xyz), 0.0, 1.0) * gl_LightSource[0].diffuse + gl_LightSource[0].ambient);\n"
"}\n",

Fragment Shader:
"uniform sampler2D tex;\n"
"void main(void)\n"
"{\n"
"   gl_FragColor = gl_Color * texture2D(tex, gl_TexCoord[0].xy);\n"
"}\n",

i tried to convert this to modern opengl (vbo, vao, shader version 330, etc), but i dont know which is the fail. Can you show me the correct form to convert it to modern opengl?
PD: im using opengl version 3.3.
Add Important information:
Ok, here is my  renderiqm() modified function  :
void renderiqm(GLSLProgram& mainShader)
{
    m_matrix->loadIdentity();
    matrixTransformations();

    mainShader.sendUniform("modelYAxisDiff",getYAxisDiff());
    mainShader.sendUniform4x4("modelMatrix", m_matrix->getModelMatrix());
    //envía la matriz de normales
//  mainShader.sendUniform4x4("normalMatrix", m_matrix->getNormalMatrix());
    mainShader.sendUniform3x3("normalMatrix", glm::value_ptr(m_matrix->getNormalMatrix()));
    //envía la matriz de transformación  (modelview)
    mainShader.sendUniform4x4("modelViewMatrix", glm::value_ptr(m_matrix->getModelViewMatrix()));
    mainShader.sendUniform("objColor", m_color);

    m_matrix->pushMatrix(MODEL_MATRIX);

    glBindBuffer(GL_UNIFORM_BUFFER, ubo);
    glBufferData(GL_UNIFORM_BUFFER, ubosize, NULL, GL_STREAM_DRAW);
    glBufferSubData(GL_UNIFORM_BUFFER, bonematsoffset, numjoints*sizeof(Matrix3x4), outframe[0].a.v);
    glBindBuffer(GL_UNIFORM_BUFFER, 0);

    glBindBufferBase(GL_UNIFORM_BUFFER, 0, ubo);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
    glBindBuffer(GL_ARRAY_BUFFER, vbo);

    vertex *vert = NULL;

    GLsizei stride = sizeof(vert->position)+sizeof(vert->normal)+sizeof(vert->tangent)+sizeof(vert->texcoord);
    if(numframes > 0)
    {
        stride+= sizeof(vert->blendindex)+sizeof(vert->blendweight);
    }

    //vertices
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0,3, GL_FLOAT, GL_FALSE, stride, 0);

     //normales
    glEnableVertexAttribArray(1);
    glVertexAttribPointer(1,3,GL_FLOAT, GL_FALSE, stride, (void*)sizeof(vert->position));

    //tangente
    glEnableVertexAttribArray(2);
    glVertexAttribPointer(2, 4, GL_FLOAT, GL_FALSE, stride, (void*)sizeof(vert->position)+sizeof(vert->normal));

    //texturas
    glEnableVertexAttribArray(3);
    glVertexAttribPointer(3, 2, GL_FLOAT, GL_FALSE, stride, (void*)sizeof(vert->position)+sizeof(vert->normal)+sizeof(vert->tangent));

    if(numframes > 0)
    {
        //blendweight
        glEnableVertexAttribArray(4);
        glVertexAttribPointer(4, 4, GL_UNSIGNED_BYTE, GL_TRUE, stride, (void*)sizeof(vert->position)+sizeof(vert->normal)+sizeof(vert->tangent)+sizeof(vert->texcoord));

        //blendindex
        glEnableVertexAttribArray(5);
        glVertexAttribPointer(5, 4, GL_UNSIGNED_BYTE, GL_FALSE, stride, (void*)sizeof(vert->position)+sizeof(vert->normal)+sizeof(vert->tangent)+sizeof(vert->texcoord)+sizeof(vert->blendindex));
    }

    iqmtriangle *tris = NULL;

    //DEBUG
    int i=0;
    for(i = 0; i < m_textureIndices.size(); i++)
    {

        iqmmesh &m = meshes[i];
        glBindTexture(GL_TEXTURE_2D, textures[i] ? textures[i] : notexture);
        tTextures[i].bindTexture(0);

        glDrawElements(GL_TRIANGLES, 3*m.num_triangles, GL_UNSIGNED_INT, &tris[m.first_triangle]);
    }

    glDisableVertexAttribArray(0);
    glDisableVertexAttribArray(1);
    glDisableVertexAttribArray(2);
    glDisableVertexAttribArray(3);
    if(numframes > 0)
    {
        glDisableVertexAttribArray(4);
        glDisableVertexAttribArray(5);
    }

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
    glBindBuffer(GL_ARRAY_BUFFER, 0);

    //glPopMatrix();
    m_matrix->popMatrix(MODEL_MATRIX);
}

Clarification:
mainShader is a tested shader interface that works fine (no errors here),
m_matrix is a GLM interfaces and also works fine.
the vertexShader would be this one:
string vAnimationShader = "\n\
#version 330                                                                \n\
                                                                            \n\
uniform mat4 projectionMatrix;                                              \n\
uniform mat4 modelViewMatrix;                                               \n\
uniform mat4 normalMatrix;                                                  \n\
uniform mat4 modelMatrix;                                                   \n\
uniform vec3 objColor;                                                      \n\
\n\
uniform mat4 DepthBiasMVP;                          \n\
smooth out vec4 ShadowCoord;\n\
\n\
smooth out vec2 texCoord;                                                   \n\
smooth out vec3 vNormal;                                                    \n\
smooth out vec3 vEyeSpacePos;                                               \n\
smooth out vec3 vWorldPos;                                                  \n\
smooth out vec3 vObjColor;                                                  \n\
\n\
layout (location = 0) in vec3 inPosition;                                   \n\
layout (location = 3) in vec2 inCoord;                                      \n\
layout (location = 1) in vec3 inNormal;                                     \n\
                                                                            \n\
uniform mat3x4 bonemats[80];\n\
\n\
layout (location = 4) in vec4 vweights;\n\
layout (location = 5) in vec4 vbones;\n\
layout (location = 2) in vec4 vtangent;\n\
void main(void)\n\
{\n\
    vObjColor = objColor;                                               \n\
   mat3x4 m = bonemats[int(vbones.x)] * vweights.x;\n\
   m += bonemats[int(vbones.y)] * vweights.y;\n\
  m += bonemats[int(vbones.z)] * vweights.z;\n\
   m += bonemats[int(vbones.w)] * vweights.w;\n\
    vec4 vEyeSpacePosVertex = modelViewMatrix*vec4(inPosition, 1.0);        \n\
    gl_Position = projectionMatrix*vEyeSpacePosVertex;                      \n\
   mat3 madjtrans = mat3(cross(m[1].xyz, m[2].xyz), cross(m[2].xyz, m[0].xyz), cross(m[0].xyz, m[1].xyz));\n\
   vec3 mnormal = inNormal * madjtrans;\n\
   vec3 mtangent = vtangent.xyz * madjtrans; // tangent not used, just here as an example\n\
   vec3 mbitangent = cross(mnormal, mtangent) * vtangent.w; // bitangent not used, just here as an example\n\
   texCoord = inCoord;      \n\
    vec4 vRes = normalMatrix*vec4(inNormal, 0.0);                           \n\
    vNormal = vRes.xyz;                                                     \n\
    vEyeSpacePos = vEyeSpacePosVertex.xyz;                                  \n\
    vec4 vWorldPosVertex = modelMatrix*vec4(inPosition, 1.0);               \n\
    vWorldPos = vWorldPosVertex.xyz;                                        \n\
    ShadowCoord = DepthBiasMVP * vWorldPosVertex;   \n\
}\n\
";

i didn't find the error... in the screen i dont see the iqm model.. all the other things draw perfectly, but iqm model doesn't appear.
IMPORTANT DISCOVERING:
recently, i have discovered that the problem occurs when the Opengl Context is 3.2+ . if I switch to the 3.1 Version of the opengl context , it works perfectly with my modified function.
i didn't find what the problem is... i associate that with a deprecated function but i cant findit. Please, can you help me? Thanks a lot.

A: The problem was the initialization of vbo without a vao, i fixed it and now the model is rendering correctly.


text:
Q: Is there a way to create Google Maps KML layer in high resolution for retina display? So I try to use KML Layer with custom icons for my Google Maps V3 mobile webapp (using jQuery Mobile). The base layer of the map is displayed correctly with sharp resolution and the zoom control is styled in compact mode automatically by the API, so I guess the API has detected the mobile device alright.
However, the custom icons on the KmlLayer appear to be blurry, as a common symptom of displaying low-res marker image on high density mobile display (retina and such), despite the fact that I've already used the double-sized images. I tried to adjust the <scale> tag in the kml file to no avail, since it seems to only affect the icons after being downsampled to 32*32 by Google's server.
So the question is: is there a way to request the Google KmlLayer server to serve high-res tile images? I didn't see any such option in the documentation. Maybe some trick on the KML generation side?
Thank you in advance.
UPDATE: as Chad stated below this is not currently supported. So while I open my photoshop and design the new marker image so that it won't be so much ugly when blurred out, here's the link for the feature request on Google's page.

A: I am sorry I but I don't think it is available. All you can do is in your KML where you write
  <IconStyle id="mystyle">
  <Icon>
    <href>http://maps.google.com/mapfiles/kml/pushpin/ylw-pushpin.png</href>
    <scale>1.0</scale>
  </Icon>
</IconStyle>

Make sure you use high resolution icon. I hope it helps.


text:
Q: Deploying a Python Library with C Dependencies to Heroku I am having some frustration deploying my project to Heroku. It depends upon a few python libraries for astrological software, which work fine on my local machine. But one of these libraries requires you to download some files and set the path to the downloaded files in order to run, and I think it is failing at this moment in the build process. The library is a Python extension to another library originally written in C. The python library is here. I've been looking at some documentation here and here and here, but I've never built a docker image, and I'm not even sure it would be a solution to my problems. I also thought of adding a new buildpack, but also not sure it would solve the problem. My error is below, hopefully someone can point me in the right direction. I'm mostly looking for someone to tell me whether my problem could be solved with Docker or otherwise so that I don't waste time going down that path if it won't help. Thank you.
Installing collected packages: pyswisseph
2020-05-20T00:01:48.839661+00:00 app[web.1]: Running setup.py install for pyswisseph: started
2020-05-20T00:01:48.839662+00:00 app[web.1]: Running setup.py install for pyswisseph: finished with status 'error'
2020-05-20T00:01:48.839662+00:00 app[web.1]:
2020-05-20T00:01:48.839801+00:00 app[web.1]: ERROR: Command errored out with exit status 1:
2020-05-20T00:01:48.839814+00:00 app[web.1]: command: /app/.local/share/virtualenvs/app-4PlAip0Q
/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-djfmycyt
/pyswisseph/setup.py'"'"'; __file__='"'"'/tmp/pip-install-djfmycyt/pyswisseph/setup.py'"'"';
f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"',
'"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-
wheel-vuz1lu7j
2020-05-20T00:01:48.839815+00:00 app[web.1]: cwd: /tmp/pip-install-djfmycyt/pyswisseph/
2020-05-20T00:01:48.839815+00:00 app[web.1]: Complete output (23 lines):
2020-05-20T00:01:48.839816+00:00 app[web.1]: Searching system libswe...
2020-05-20T00:01:48.839816+00:00 app[web.1]: pkg-config not found
2020-05-20T00:01:48.839816+00:00 app[web.1]: Using internal libswe
2020-05-20T00:01:48.839817+00:00 app[web.1]: /app/.local/share/virtualenvs/app-4PlAip0Q
/lib/python3.7/site-packages/setuptools/dist.py:454: UserWarning: Normalizing '2.08.00-1' to
'2.8.0.post1'

2020-05-20T00:01:48.839817+00:00 app[web.1]: warnings.warn(tmpl.format(**locals()))
2020-05-20T00:01:48.839818+00:00 app[web.1]: running bdist_wheel
2020-05-20T00:01:48.839818+00:00 app[web.1]: running build
2020-05-20T00:01:48.839818+00:00 app[web.1]: running build_ext
2020-05-20T00:01:48.839818+00:00 app[web.1]: building 'swisseph' extension
2020-05-20T00:01:48.839819+00:00 app[web.1]: creating build
2020-05-20T00:01:48.839819+00:00 app[web.1]: creating build/temp.linux-x86_64-3.7
2020-05-20T00:01:48.839819+00:00 app[web.1]: creating build/temp.linux-x86_64-3.7/libswe
2020-05-20T00:01:48.839820+00:00 app[web.1]: creating build/temp.linux-x86_64-3.7/swephelp
2020-05-20T00:01:48.839823+00:00 app[web.1]: gcc -pthread -Wno-unused-result -Wsign-compare
 -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -Ilibswe -Iswephelp -I/app/.local/share/virtualenvs
/app-4PlAip0Q/include -I/app/.heroku/python/include/python3.7m -c pyswisseph.c -o
build/temp.linux-x86_64-3.7/pyswisseph.o -std=gnu99
2020-05-20T00:01:48.839824+00:00 app[web.1]: In file included from /usr/lib/gcc/x86_64-linux-
gnu/7/include-fixed/syslimits.h:7:0,
2020-05-20T00:01:48.839824+00:00 app[web.1]: from /usr/lib/gcc/x86_64-linux-gnu/7/include-

fixed/limits.h:34,
2020-05-20T00:01:48.839825+00:00 app[web.1]: from /app/.heroku/python/include/python3.7m/Python.h:11,
2020-05-20T00:01:48.839825+00:00 app[web.1]: from pyswisseph.c:58:
2020-05-20T00:01:48.839828+00:00 app[web.1]: /usr/lib/gcc/x86_64-linux-gnu/7/include-fixed/limits.h:194:15: fatal error: limits.h: No such file or directory
2020-05-20T00:01:48.839829+00:00 app[web.1]: #include_next <limits.h>  /* recurse down to the
 real one */
2020-05-20T00:01:48.839829+00:00 app[web.1]: ^~~~~~~~~~
2020-05-20T00:01:48.839829+00:00 app[web.1]: compilation terminated.
2020-05-20T00:01:48.839846+00:00 app[web.1]: error: command 'gcc' failed with exit status 1
2020-05-20T00:01:48.839847+00:00 app[web.1]: ----------------------------------------
2020-05-20T00:01:48.839847+00:00 app[web.1]: ERROR: Failed building wheel for pyswisseph

EDIT - Here is the example setup.py code that is failing for reference :
# Test for pkg-config
has_pkgconfig = False
if swe_detection:
    print('Searching system libswe...')
    try:
        import subprocess
        try:
            subprocess.check_output(['pkg-config'], stderr=subprocess.STDOUT)
        except AttributeError: # < Python 2.7
            # detection without pkg-config (or use popen)
            pass
    except subprocess.CalledProcessError:
        has_pkgconfig = True
        print('Found pkg-config')
    except OSError:
        print('pkg-config not found')
        pass
    except ImportError: # Python < 2.4
        pass
    #

# Find libswe-dev
libswe_found = False
if has_pkgconfig:
    try:
        swe_includes = subprocess.check_output(
            ['pkg-config', '--cflags', 'libswe-'+swe_version],
            stderr=subprocess.STDOUT)
        swe_libs = subprocess.check_output(
            ['pkg-config', '--libs', 'libswe-'+swe_version],
            stderr=subprocess.STDOUT)
        swe_sources = []
        swe_depends = []
        swe_defines = [('PYSWE_DEFAULT_EPHE_PATH',
            '"/usr/share/libswe/ephe2:/usr/share/libswe/ephe"')]
        libswe_found = True
        print('pkg-config found libswe-'+swe_version)
    except subprocess.CalledProcessError:
        pass
    #

# Another attempt at finding libswe-dev -- without pkg-config
# (pkg-config may be uninstalled but pc file should be in place)
# (and assuming there is only one version installed...)
if ( swe_detection and not libswe_found
    and os.path.isfile( '/usr/lib/pkgconfig/libswe-'+swe_version+'.pc' )):
    swe_includes = ['/usr/include']
    swe_sources = []
    swe_depends = []
    swe_libs = ['swe']
    swe_defines = [('PYSWE_DEFAULT_EPHE_PATH',
        '"/usr/share/libswe/ephe2:/usr/share/libswe/ephe"')]
    print('Found system libswe')

A: I fixed my issue. I think the build process was getting convoluted because I had a Rails app that was trying to run Python scripts, and I had two different buildpacks that were probably conflicting. I rewrote my app using just Python/Flask (it's just one page so far for testing deployment), and this seems to work (at least I've had no import/build errors). So, for anyone looking at this question, that was my fix. I used pipenv / a Pipfile instead of venv or virtualenv and gunicorn to deploy.


text:
Q: How do i disable the ctrl+click on an Apple Mouse I'm finding it hard playing my games because of the ctrl+click that apple made for 1 button mouses. Can anybody help me because it's not doing what i want it do, it just does a right-click.

A: If your mouse really has two buttons, like the Mighty Mouse or Magic Mouse, just configure it as a two-button mouse under System Settings -> Mouse. Then, CTRL-Left click should be sent as such to applications.


text:
Q: Talib indicators not working on .resample()'d dataframes; returns all NaN's To reproduce, download my 15 second SPY stock OHLCV dataset from here, and place in the same folder as this script. Should have Talib and pandas installed. Running Python 3.7.9, Windows 10.
Talib indicators don't seem to work after a df is upsampled to a higher timeframe, even though the dataframe remains numeric. I'm trying to upsample this 15 second dataset to a 5 minute timeframe. I attempt to add a moving average both before and after the resampling, before works fine, after returns all NaN's. Any idea why? (Will be back online tomorrow to review answers)
from pandas import read_csv, to_numeric, to_datetime
import talib

# Import the 15 second dataframe
df = read_csv("./SPY_15_Second.csv")
df['time'] = to_datetime(df['time'], format="%Y-%m-%d %H:%M:%S")
df = df.set_index('time')

# Apply an SMA now and it works
df['SMA1'] = talib.SMA(df['close'], timeperiod=15)
print("First DF")
print(df)

# Upsample it to 5 minute dataset
ohlc_dict = {
    'open': 'first',
    'high': 'max',
    'low': 'min',
    'close': 'last',
    'volume': 'sum',
}

df = df.resample('5min', closed='left', label='left').apply(ohlc_dict).apply(to_numeric)
print("Upsampled DF")
print(df)

# Try to apply a second simple moving average after resampling, see nans
df['SMA2'] = talib.SMA(df['close'], timeperiod=15)
print("Problem DF")
print(df)

# Why entire column nan? Attempted to apply to_numeric. Something
# to do with the resample function.

A: It works if you use the .ohlc() method on it, and not reassign it to a variable, so in other words, use this:
Change this:
df = df.resample('5min', closed='left', label='left').apply(ohlc_dict).apply(to_numeric)

...to this:
df.resample('5min', closed='left', label='left').ohlc()


text:
Q: Refresh access token on mod_auth_openidc when submitting a form I am successfully using mod_auth_openidc to authenticate my website and get an access_token. I can use the access_token to authenticate my server-side code to a third-party resource hosted elsewhere as the logged-in user.
If the access token expires, I need to refresh it, and mod_auth_openidc seems to require me to make a redirect call to a specific url to do so.
If the page I'm in is a GET request, that's fine. The page notices the token has expired, and the redirect comes back to the same page. But if it's a POST, PUT or DELETE request, the eventual refresh is still a GET.
So unless I write some really dirty code to stash the original page and its full details, I seem to be stuck.
By contrast, I can easily make a server-side call to refresh the token, without involving the module, but then the module doesn't know the token has been updated and the updated token will be lost.
The particular use case is one in which I present a form to the user, ask them to fill it in, and send it off. The resulting post data is used to call the third-party API. But if the user spends too long filling in the form, the POST call has an expired access token and can't refresh it.
Is there a way round this, or will I need to revert to using a language-specific library to do all my openid and oauth stuff?

A: You should be able to have your server side code not redirect the user's browser to the module's handler URL, but actually perform a direct backchannel call to it to refresh the access token. You will have to pickup and present the session cookie to be able to make that call though.


text:
Q: Error connecting to SQL Server using PDO in PHP These are the few lines of code that I used to try to connect to a SQL Server.
$servername = "";
$username = "";
$password = "";
$database = "";
$port = "1433";
try {
    $conn = new PDO("sqlsrv:server=$servername,$port;Database=$database;ConnectionPooling=0", $username, $password,
        array(
            PDO::ATTR_PERSISTENT => true,
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
        )
    );
} catch (PDOException $e) {
    echo ("Error connecting to SQL Server: " . $e->getMessage());
}

After running it, this error came out.

Error connecting to SQL Server: SQLSTATE[IMSSP]: An unsupported attribute was designated on the PDO object.

May I know what does this mean and any suggestions on how to solve it?


text:
Q: After button clicked, change to different page and show hidden content I have some "Learn More" links on my Home page, all of which correspond to different sections of content that is on the More Info page. These different sections of content are all hidden using display: none.
What I'm wondering is if there's a way to make it so that when I click a particular "Learn More" link, the user will be sent to the More Info page, and the section of content corresponding to the Learn More link they clicked will be shown.
I can't think of a way to achieve this, but I'm hoping it will be possible, perhaps using JavaScript.
EDIT:
The code I currently have is nothing special. Four  links on the Home page, then on the More Info page, four divs that are all initially hidden using display: none.

A: The solution ended up being fairly simple, I did what is described in the top answer of this question: Getting URL hash location, and using it in jQuery

A:  Learn more

A: I think it is possible.You can take the information on a div,and then you click "Learn more",show the div.
In this way,you even needn't a hyperlink,just a click event,like the code upstairs.Of course,this div was hidden before.

A: One way you can achieve this would be to add a hash to that link with the id of the section you want to show, like this: Learn More. Then just check for it in window.location.hash on the /moreinfo page and show the div.

A: You have to do it this way: try to use named anchors.
first:
Learn More

when use clicks this link user will navigate to particular page with different sections.
second:
on this page suppose you want to show the 3rd section:
 .....

Your section-3

In your case divs are hidden then use js or jQuery for this:
As you will get a hash in the location url then use  .substr()' and.indexOf()` javascript methods.
try to put this script on those page where you are having your hidden divs
$(function(){
   var url = window.location.href;
   var obj = url.substr(url.indexOf('#'));
   $(obj).show();
});


text:
Q: Linux/RHEL Server Down with "xinetd" Alerts? Suddenly one of my RHEL 6 Server [VM] (serving Apache on it also) went down and when i rebooted it, i saw several of following /var/log/messages as latest before it went down:
May  4 08:16:37 localhost xinetd[1928]: START: nrpe pid=19307 from=10.xx.xx.xx
May  4 08:16:37 localhost xinetd[1928]: EXIT: nrpe status=0 pid=19307 duration=0(sec)
May  4 08:17:08 localhost xinetd[1928]: START: nrpe pid=19363 from=10.xx.xx.xx
May  4 08:17:08 localhost xinetd[1928]: EXIT: nrpe status=0 pid=19363 duration=0(sec)
May  4 08:18:38 localhost xinetd[1928]: START: nrpe pid=19417 from=10.xx.xx.xx
May  4 08:18:38 localhost xinetd[1928]: EXIT: nrpe status=0 pid=19417 duration=0(sec)
May  4 08:18:40 localhost xinetd[1928]: START: nrpe pid=19420 from=10.xx.xx.xx
May  4 08:18:42 localhost xinetd[1928]: EXIT: nrpe status=0 pid=19420 duration=2(sec)
May  4 08:21:37 localhost xinetd[1928]: START: nrpe pid=19574 from=10.xx.xx.xx
May  4 08:21:37 localhost xinetd[1928]: EXIT: nrpe status=0 pid=19574 duration=0(sec)
May  4 08:21:38 localhost xinetd[1928]: START: nrpe pid=19577 from=10.xx.xx.xx
May  4 08:21:38 localhost xinetd[1928]: EXIT: nrpe status=0 pid=19577 duration=0(sec)
May  4 08:21:38 localhost xinetd[1928]: START: nrpe pid=19580 from=10.xx.xx.xx
May  4 08:21:38 localhost xinetd[1928]: START: nrpe pid=19581 from=10.xx.xx.xx
May  4 08:21:38 localhost xinetd[1928]: EXIT: nrpe status=0 pid=19580 duration=0(sec)
May  4 08:21:38 localhost xinetd[1928]: EXIT: nrpe status=0 pid=19581 duration=0(sec)
May  4 08:24:31 localhost xinetd[1928]: START: nrpe pid=19701 from=10.xx.xx.xx
May  4 08:24:31 localhost xinetd[1928]: EXIT: nrpe status=0 pid=19701 duration=0(sec)
May  4 08:24:49 localhost xinetd[1928]: START: nrpe pid=19713 from=10.xx.xx.xx
May  4 08:24:49 localhost xinetd[1928]: EXIT: nrpe status=0 pid=19713 duration=0(sec)
May  4 08:25:17 localhost xinetd[1928]: START: nrpe pid=19745 from=10.xx.xx.xx
May  4 08:25:17 localhost xinetd[1928]: EXIT: nrpe status=0 pid=19745 duration=0(sec)

*

*What does it mean please?

A: It is connections from Nagios server with Nagios NRPE(Nagios Remote Plugin Executor) which executes checks on other hosts remotely, obviously in collaboration with xinetd. So I do not think it has anything to do with your machine been down, it is not a symptom.


text:
Q: Can I use Paging3 library for APIs without 'page=number' query? I was wondering can I use paging3 library for API's that does not support 'page=RANDOM_NUMBER' in their queries? For example I have an API in which I can add custom query like 'number=50' and it will display 50 items as a result. I'm confused that I wouldn't be able to use that library for my API without page=RANDOM_NUMBER query. Can someone give me an answer?

A: Paging3 supports arbitrary key types (you define both the key and how it is used). In order to load data incrementally, you need to be able specify "load after ___", otherwise it's not possible to continue loading data after the initial load. If this is something that is tracked independently, say a cookie or session token, then you can try keeping maxSize set to unbounded, and just use any non-null value for nextKey.
Edit: Since you mentioned you are in the item-keyed scenario, where your next load is based on the last item you loaded, you might do something like this:
class MyPagingSource : PagingSource<String, Item>(
  val api: NetworkApi,
) {
  override suspend fun load(params: LoadParams): LoadResult<String, Item> {
    try {
      val result = withContext(Dispatchers.IO) {
         api.loadPage(after_id = params.key)
      }

      return LoadResult.Page(
        data = result.items,
        nextKey = result.items.lastOrNull().id,
      )
    } catch (exception: IOException) {
      return LoadResult.Error(exception)
    }
  }
}

Basically whatever value you pass to nextKey will get passed to LoadParams.key when user near the bottom of the loaded data, and in the case where there are no more items or you get an empty response from network (Due to being at the end of the list), you can return null for nextKey to tell Paging there is no more to load in that direction.
Note that I haven't covered prepend / prevKey, but if it is unsupported in your case you can just pass null.
If you don't support prepend, you won't be able to resume loading from the middle of the list, so you need to return null in getRefreshKey() which tells Paging what key to use to resume loading from a scroll position in case of config change, etc.


text:
Q: Have a each() with if statement not working Problem
I only want the commands in the if logic to happen if the 3rd default button is visible, but it throws an error saying its parent has the css class of visibility: hidden. When you need to remove that state the 3rd default button becomes visible so I'm not sure why it isn't passing.
Desired Behaviour
I want it so for each state that is underlined to click on them to unselect them. Then the if statement is to take care of those who need to be actually removed, because they have info filled out for them, and so if the 3rd default button is visible, which is the remove button, then to execute the code inside the if statement which is to make sure the other default buttons are hidden and click the remove button.
Code
it('deletes all selected states', () => {
  cy.get('span[class*="css-ddft8r-StateText"]').each($el => {
    cy.wrap($el)
      .filter(':has(span[class*="css-1qkbmzm-Underline css-1x6iasc4"])')
      .click({ multiple: true });
    if (cy.get('[data-cy=default-buttons]').eq(3).should('be.visible')) {
      cy.get('[data-cy=default-buttons]')
        .eq(0)
        .should('be.hidden');
      cy.get('[data-cy=default-buttons]')
        .eq(2)
        .should('be.visible');
      cy.get('[data-cy=default-buttons]')
        .eq(3)
        .click();
    }
  });
});

A: *

*Cypress commands return Chainer object - it is inner Cypress entity which can't be used with conditionals as object is always recognized as true within if statement.
So please give a chance for jquery:
if(Cypress.$('[data-cy=default-buttons]:contains("remove")').is(':visible')){
// do assertions
cy.get('[data-cy=default-buttons]:contains("remove")').click({force: true})
// as parent is hidden, we can ommit click visibility check by passing force: true
}

**= is checking that attribute contains part of passed string, so your selector could be simplified to:
[class*="StateText"]

*Whole test seems as overengineered and not working properly with these each cycle and conditional inside. Maybe you dont even need to check buttons for each element and move assertions out of loop. Example repository would be helpful.

A: So the solution I ended up using was actually just using .each() instead of the if statement within it. We figured out we could utilize a ternary inside of a data-cy due to those css classes being unstable/unreliable and this took care of not having to write an if statement.
We did roughly this:
cy.get('[data-cy=example_data_cy]').each($el => {
//click on the state if it was selected to unselect it


text:
Q: iOS Firebase + Fabric Beta Crashylitics Not Reporting Issue I've just recently installed Fabric to a project which already had Firebase installed and suddenly Crashyltics has stopped working. It's not included within the 'Fabric.with([])' call on AppDelegate.swift but I wondered if Fabric and Firebase were cancelling out Crashyltics. I'm using Fabric for it's Beta option and everything else is inside Firebase.

*

*I can force a crash inside the app - But not getting anything reported in either Dashboard.

*My run Script Phase is also correct.

*My Debug is DWARF with DYSIM.

*Cleared derived data etc.

*Firebase is called after Fabric inside AppDelegate.

Thanks

A: I think that you have to link your firebase and fabric apps.
Go to https://fabric.io/firebase_migration/status, click on link apps and select the apps to link (the one on fabric and the corresponding app on firebase)

A: Do you upload your dSYM to Firebase/Crashlytics? If not it can be the issue.


text:
Q: Docker compose disabling my login to Azure Linux VM I am trying to deploy the airflow docker compose to my azure linux vm.
when i run (apache airflow) docker compose on azure VM.
docker-compose up

It tries to create a network and kicks me out of SSH. Thereafter , I am not able to login to the VM.
Can someone plz help?


text:
Q: UIScrollView does not scroll I got a problem about UIScrollView. I am making a custom view which inherits UIView. The view has a UIScrollView on which there are lots of buttons which should scroll left and right. The UIScrollView and buttons can show normally. But I cannot scroll the buttons. Could someone give me some suggestions? Thanks a lot!
MZMPhotoCalenderSwitcher.h
#import <UIKit/UIKit.h>

@interface MZMPhotoCalenderSwitcher : UIView <UIScrollViewDelegate>

@property (strong, nonatomic) UIScrollView *topSwitcher;

@end

MZMPhotoCalenderSwitcher.m
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.topSwitcher = [[UIScrollView alloc] initWithFrame:CGRectMake(0, LABEL_HEIGHT + VIEW_Y, self.view.bounds.size.width, TOP_SWITCHER_HEIGHT)];
    self.topSwitcher.backgroundColor = [UIColor greenColor];
    self.topSwitcher.pagingEnabled = YES;
    self.topSwitcher.showsHorizontalScrollIndicator = NO;
    self.topSwitcher.showsVerticalScrollIndicator = NO;

    [self add:3 ButtonsOnView:self.topSwitcher withButtonWidth:44.8f andHeight:20.0f];
}

- (void)add:(int)num ButtonsOnView:(UIScrollView *)view withButtonWidth:(CGFloat)width andHeight:(CGFloat)height
{
    CGFloat totalTopSwitcherWidth = num * width;
    [view setContentSize:CGSizeMake(totalTopSwitcherWidth, view.bounds.size.height)];
    CGFloat xOffset = 0.0f;

    for (int i=1; i<=num; i++)
    {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [button setFrame:CGRectMake(xOffset, 0, width, height)];
        xOffset += width;
        [button setTitle:[NSString stringWithFormat:@"%d", i] forState:UIControlStateNormal];

        button.titleLabel.font = [UIFont systemFontOfSize:10];
        [button setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateSelected];
        [button setTag:i];
        [button addTarget:self action:@selector(buttonEvent) forControlEvents:UIControlEventTouchUpInside];

        if (i % 2 == 0)
            [button setBackgroundColor:[UIColor yellowColor]];
        else
            [button setBackgroundColor:[UIColor redColor]];

        [view addSubview:button];
    }
}

A: Below following line
[view addSubview:button];

add
view.contentSize = CGSizeMake(view.contentSize.width, button.frame.origin.y + button.frame.size.height);

This will set content size of scroll view to the bottom of your button.

A: It should be issue of content size, also check that scrollEnabled property of UIScrollView object is set to TRUE,
Check solution of UIScrollView won't scroll!

A: Just disable "Auto Layout" in your project and it will start working!

A: I'm using Xcode 6/iOS 8+ now with auto-layout turned on, and I had the same problem in the first place, removing auto-layout doesn't work at all, so in order to make scroll view scrollable vertically, I made sure the following:

*

*The scroll view content size height MUST be bigger than the screen
height, this almost goes without saying...

*The top/bottom/left/right constraint of the scroll view HAS TO BE
    pinned, I did this using storyboard so no code showing up here
If you want to make the scroll view scrollable horizontally, then make sure its content size width is bigger than the screen width, the other rule applies the same.
This worked for me, hope it can help someone.

A: Combining all of this advise into one simple answer:
// In viewDidLoad
// set the size of the scrollview (in this case I made it the size of its container
self.scrollView.frame = self.view.frame;
// now set the size of the content to be scrolled within the scrollview
// the content to be displayed must be bigger than the scrollView
// in this case I added 100 to make the content size, so that it is taller than the height of the scrollView
// now it scrolls
    self.scrollView.contentSize = CGSizeMake(self.scrollView.frame.size.width, self.scrollView.frame.size.height + 100);

A: Where are you add ScrollView on SuperVIew? And where are you recalculate Content size property of scrollView?
[view setContentSize:CGSizeMake(<summYourViews.width>,<summYourViews.height>)];

A: Your problem is that you haven't set your contentSize, therefore, the contentSize is the same than the frame view.
You need to do this in your viewDidLoad
- (void)viewDidLoad {
    ........
    self.scrollView.contentSize = CGSizeMake(/*yourWidth*/, /*yourHeight/*);
    ........
}

Try do adjust your contentSize to the last position of your object plus its size plus a padding.

A: You have to set scrollview frame size and content size.

A: try this . . . .
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.topSwitcher = [[UIScrollView alloc] initWithFrame:CGRectMake(0, LABEL_HEIGHT + VIEW_Y, self.view.bounds.size.width, TOP_SWITCHER_HEIGHT)];
    self.topSwitcher.backgroundColor = [UIColor greenColor];
    self.topSwitcher.pagingEnabled = YES;
    self.topSwitcher.showsHorizontalScrollIndicator = NO;
    self.topSwitcher.showsVerticalScrollIndicator = NO;
    [topSwitcher setContentSize:CGPointMake(self.view.bounds.size.width,TOP_SWITCHER_HEIGHT+400)];

    [self add:3 ButtonsOnView:self.topSwitcher withButtonWidth:44.8f andHeight:20.0f];
}

A: It's amazing.
I just move the codes which was in viewDidLoad to initWithFrame:, then it works. I do not know why it is?


text:
Q: How to add elements into one div until it's width almost equal to another div? I have 2 containers, one inside the other, and I'm trying to fill the inner container with elements on document.ready so it's width is almost equal to the outer's div width.
It works perfectly with "if" statement on window.resize, but since I need to fill the div on document.ready I'm trying to use "while" and it doesn't work. Why?
Here is the HTML:

...and JS:
function width_check() {
    var ddd = $("#outer").width() - $("#inner").width();
    var sss = 0;

    if (ddd > 100) {
        sss = 1;
    } else { sss = 0 };}

$(document).ready function() {
    width_check();

    while (sss = 1) {
        $("#inner").append('

');
        width_check();
                    }        }

A: I think you have a scope problem here.
You have a function that defines var sss = 0. But the check of $(document).ready has its own sss. sss is undefined in this function. Try something like:
function width_check()
{
    var ddd = $("#outer").width() - $("#inner").width();
    return ddd > 100;
}

$(document).ready( function() // check the extra brackets around the function.
{
    while(width_check()) // check the width every time
    {
        $("#inner").append('

');
    }
});

A: Do like marnix says, and add display: block; to your lis


text:
Q: Get frame as file from video using FFMpeg on Android I'm trying to extract frame from video file and save it as an image on Android.
Currently using FFmpeg from this library:

implementation "com.writingminds:FFmpegAndroid:${FFmpeg}"

But also was experimenting with

implementation "nl.bravobit:android-ffmpeg:1.1.7"

Tryed to execute following commands:

*

*"-i", videoFile!!.path, "-vf", "select=1", "-vsync", "0", outputFilePath

*"-i", videoFile!!.path, "-vf", "select=eq(n\,34)", "-vframes", "1", outputFilePath

*"-y", "-i", videoFile!!.path, "-strict experimental", "-an", "-r", "1/2", "-ss", "00:00:00.000", "-t", "00:00:03", outputFilePath

Problem i currently facing is that file on outputFilePath created, but they are empty (0B).
I'm creating output file with this func:
    val timeStamp: String = SimpleDateFormat(OptiConstant.DATE_FORMAT, Locale.getDefault()).format(Date())
    val imageFileName: String = OptiConstant.APP_NAME + timeStamp + "_"
    val storageDir: File = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES)
    if (!storageDir.exists()) storageDir.mkdirs()
    return File.createTempFile(imageFileName, OptiConstant.PNG_FORMAT, storageDir)

I think problem with my FFMpeg usage becouse loading is starting with callback onStart from lib, but never ends. Log doesn't say much. it just stops loading and dont call onFinish(). Any suggestions?


text:
Q: Git fetch differences as local change Is there a way to fetch differences from a different branch or commit without introducing them to your local history? Just fetching all the changes as unstaged code?
For example
Branch1:
(HEAD) abc1 : added file A.txt

Branch2:
(HEAD) abc2 : added file B.txt
 |
abc1 : added file A.txt

so at Branch1 i want to fetch all the differences from Branch2 without adding them to Branch1 history. As a result I expect to have A.txt from commit abc1 and an unstaged file B.txt

A: git checkout command  is able to pick a single file (or many files) from specific version without changing a branch. Note that command git checkout is kind of Swiss army knife tool and is able to do many stuff.
In your case it should be:
git checkout branch2 -- B.txt

This should create file B.txt in staged state.


text:
Q: PHP Sort array in groups of two avoiding merge of items with same values I have a code to generate bracket sheets for a tournament. I have players and each player is associated with an school. I need to sort an array with the players so there no first matches of players of the same school (or the lower same-school matches possible).
Something like this:
$players = array(
             array('name' => 'juan', 'school' => 'ABC'),   // 0
             array('name' => 'leo', 'school' => 'ABC'),    // 1
             array('name' => 'arnold', 'school' => 'DEF'), // 2
             array('name' => 'simon', 'school' => 'DEF'),  // 3
             array('name' => 'luke', 'school' => 'ECD'),   // 4
             array('name' => 'ash', 'school' => 'ECD'),    // 5
           );
// code to sort here

array_chunk($players, 2); // this generate an array with groups of two for matches.

In the above example [0] and [1] cant go together because they are on the same school. [0] can go with 3, for example.
I'm trying with usort, but I'm not sure what's the right way to approach this.

A: Ok, a new answer having re-examined the issue. The algorithm, I think, should be thus:

*

*Iterate over unallocated players (noting that this list reduces 2 at a time).

*Find the school with the most available remaining players which is not the school the current iteration of player is in.

*If the above check does not find a school with any players, resort to using the same school as the current iteration of player is in. This has the effect that players in the same school can play eachother if no other players remain in the allocation pool.

*Allocate an arbitrary player from the school we just found

*Pair the currently iterated player and the arbitrary player

*Remove both players from the pool

Implementation-wise, I found it easier to maintain 2 indexes - one of schools and 1 of players. I bundled it into a couple of classes because the inherently referential nature of objects makes life easier. My code is below... it works out of the box but may need some tweaking.
<?php

class School {
        protected $name;
        protected $players = [];

        public function __construct($name) {
                $this->name = $name;
        }

        public function get_name() {
                return $this->name;
        }

        public function add_player($name) {
                $this->players[] = $name;
        }

        public function del_player($name) {
                if (($index = array_search($name, $this->players)) !== false) {
                        unset($this->players[$index]);
                }
        }

        public function player_count() {
                return count($this->players);
        }

        public function get_player() {
                if (!reset($this->players)) {
                        return false;
                }

                return [
                        'school' => $this->name,
                        'name' => reset($this->players),
                ];
        }
}

class Players {
        protected $schools_index = [];
        protected $player_index = [];

        public function add_player($school, $player) {
                // Create school if not exists
                if (!isset($this->schools_index[$school])) {
                        $this->schools_index[$school] = new School($school);
                }

                // Add player to school and own index
                $this->schools_index[$school]->add_player($player);
                $this->player_index[$player] = $school;
        }

        public function del_player($school, $player) {
                // From school index
                $this->schools_index[$school]->del_player($player);

                // From own index
                if (isset($this->player_index[$player])) {
                        unset($this->player_index[$player]);
                }
        }

        public function biggest_school($exclude = null) {
                $rtn = null;

                // Find school excluding the exclude. Don't get schools with nobody left in them.
                foreach ($this->schools_index as $name=>$school) {
                        if ((!$exclude || $name != $exclude) && ($school->player_count()) && (!$rtn || $rtn->player_count() < $school->player_count())) {
                                $rtn = $school;
                        }
                }

                // If we didn't get a school, shitcan the exclude and try the excluded school
                if (!$rtn && $exclude) {
                        if ($this->schools_index[$exclude]->player_count()) {
                                $rtn = $this->schools_index[$exclude];
                        }
                }

                return $rtn;
        }

        public function get_player() {
                if (!reset($this->player_index)) {
                        return false;
                }

                return [
                        'school' => reset($this->player_index),
                        'name' => key($this->player_index),
                ];
        }

        public static function from_players_arr(array $players) {
                $obj = new static();

                foreach ($players as $player) {
                        // Add to indexes
                        $obj->add_player($player['school'], $player['name']);
                }

                return $obj;
        }
}

$players = array(
        array('name' => 'juan', 'school' => 'ABC'),
        array('name' => 'leo', 'school' => 'ABC'),
        array('name' => 'arnold', 'school' => 'ABC'),
        array('name' => 'simon', 'school' => 'ABC'),
        array('name' => 'luke', 'school' => 'ABC'),
        array('name' => 'alan', 'school' => 'JKL'),
        array('name' => 'jeff', 'school' => 'BAR'),
        array('name' => 'paul', 'school' => 'FOO'),
);

$players_obj = Players::from_players_arr($players);

$pairs = [];

while ($player = $players_obj->get_player()) {
        $players_obj->del_player($player['school'], $player['name']);

        $opponent = $players_obj->biggest_school($player['school'])->get_player();

        $pairs[] = [
                $player['name'],
                $opponent['name'],
        ];

        $players_obj->del_player($opponent['school'], $opponent['name']);
}

var_dump($pairs);

Output is below:
array(4) {
  [0] =>
  array(2) {
    [0] =>
    string(4) "juan"
    [1] =>
    string(4) "alan"
  }
  [1] =>
  array(2) {
    [0] =>
    string(3) "leo"
    [1] =>
    string(4) "jeff"
  }
  [2] =>
  array(2) {
    [0] =>
    string(6) "arnold"
    [1] =>
    string(4) "paul"
  }
  [3] =>
  array(2) {
    [0] =>
    string(5) "simon"
    [1] =>
    string(4) "luke"
  }
}

A: What we are going to do, is split the players in 2 groups: contenders 1 & contenders 2. We're going to fill contenders a with consecutive players of the same school:
If we name the schools a single letter for brevity, what we'll essentially have is:
 A A A A B B B C
 C C D D E E F F

Or, if we flip it, it becomes clearer:
 A C
 A C
 A D
 A D
 B E
 B E
 B F
 C F

What happens if one school has > the half of the total number of players? Well, let's see:
 A A A A A
 A B B C D

So:
 A A <= one A vs. A, which is unavoidable, but the method still works.
 A B
 A B
 A C
 A D

I cheated a bit here: I sorted out the players from the biggest school first. It however still works as long as we group schools together. Let's take my output of $a = range('A','F'); shuffle($a):, which here resulted in: FCADBE, which gives us:
 F A
 F D
 C D
 C B
 C B
 A B
 A E
 A E

.. which works, also for A > half:
 C A
 A A <= that one double again, unavoidable
 A D
 A B
 A B

Let's break this into parts. What we have to do is:

*

*sort the players by school

*break this sorted array into 2 groups.

*create pairs by adding on from the first group & one from the second group, in order.

The advantage of cutting it down is so you can find answers:

*

*hundreds of questions on SO

*this is a nice answer

*We could use a MultiIterator, which would be a logical (and working) choice, but I'll show you another short way of creating pairs of 2 arrays (or triplets if you have 3 arrays, etc.)

So, let's do that:
 //sort by school
 $players = ... your array ...
 usort($players,function($playerA, $playerB){
     return strcmp($playerA['school'], $playerB['school']);
 });
 //voila, sorted

 //break this into 2 groups:
 $size = ceil(count($players) / 2); // round UP
 $groupA = array_slice($players,0,$size);
 $groupB = array_slice($players,$size);

 //create our duels array:
 $duels = array_map(null, $groupA, $groupB);

$duels now has this content with your input:
[
    [
        {
            "name": "juan",
            "school": "ABC"
        },
        {
            "name": "arnold",
            "school": "DEF"
        }
    ],
    [
        {
            "name": "leo",
            "school": "ABC"
        },
        {
            "name": "ash",
            "school": "ECD"
        }
    ],
    [
        {
            "name": "simon",
            "school": "DEF"
        },
        {
            "name": "luke",
            "school": "ECD"
        }
    ]
]


text:
Q: Custom Textview in Android with height = fill_parent but having the background fill only wrap_content So, the title is a little confusing, I know, but what I want is basically a notification box that has a colored background and borders that appears on the center of the screen, but is not stretched.
I already have the custom view, making the background and borders, but if I make "width: fill_parent" and "height: wrap_content", it will appear on the top of the screen, and if I put height to fill_parent, the entire screen will be filled with the background (which I kinda knew it would happen).
I also tried a simpler approach, setting layout_gravity to center, but didn't help. The view is inside a vertical linear layout and it's the only visible view within it (all the other elements have visibility = View.GONE).
How should I code the onDraw() of the custom view to be able to put height: fill_parent and have the background to obey the wrap_content rule? A simpler, better solution is always welcome as well.

A: I think the problem is that it's nested in a LinearLayout.
Try it in a FrameLayout which

"is designed to block out an area on the screen to display a single
  item"

You should be able to then center your custom view over a transparent background FrameLayout
EDIT: To clarify why I think the LinearLayout is the problem. A LinearLayout fills up like a stack which is why when you tried to center by gravity the item was at the top. If you imagine a stack of plates... you can't start in the middle :-)


text:
Q: Why is it a bad idea to run as root?
Possible Duplicate:
Concern about logging in as root overrated?

I often hear that it's a bad idea to use root for general use.
Why is this a bad idea?

A: Summarizing from this Ask Ubuntu answer, it is a bad idea to run as root because:

*

*You are much more prone to mistakes or software bugs. That program which deleted files as a bug? If it ran as a limited user, at most it can damage stuff in your home directory and on a few other devices (e.g. USB disks).
If ran as root, it might have freedom to delete everything in the system. Besides, you might be the victim of a buggy script which accidentally deletes critical files.

*Similarly, a vulnerability or malicious software can cause much more harm, because you gave it full permissions. It can change programs in /bin and add backdoors, mess with files in /etc and make the system unbootable etc...

*You can be victim of your own stupidity. That rm -rf * you ran by mistake, or if you swapped input/output device in dd, would be stopped by your lack of permissions, but if you run as root, you are all powerful.

*You don't need it for most uses, except for administrative work.
sudo has similar dangers, but at least they will not (at least they should not) happen by accident - if you typed sudo destroy_my_machine you presumably knew well what would happen, it's very hard to believe one could do it by accident.
For an example of something quite nasty, assume a script that runs rm -rf $someDir/*; if $someDir isn't set, the end result is rm -rf /*.


text:
Q: Missing space when replacing with \regex_replace_all:nnN How can I make \regex_replace_all:nnN not remove the space between x y?

\documentclass{article}
\usepackage{l3regex}

\ExplSyntaxOn
\cs_new:Npn \replace #1#2#3
 {
  \tl_set:Nn \l_tmpa_tl  {#3}
  \regex_replace_all:nnN {#1} {#2} \l_tmpa_tl
  \tl_use:N \l_tmpa_tl
 }
\ExplSyntaxOff

\begin{document}
\replace{a}{x y}{abc}
\end{document}

A: The syntax rules for regex substitutions are rather bizarre under some respects; as the documentation specifies, significant spaces in the search or the replacement strings should always be escaped, because unescaped spaces are ignored.
Moreover you need to specify that you want a "real" space with the right category code; if you simply say x\ y in the replacement string, you'd get a category code 12 space, which would print whatever character is in slot 32 of the current font (which in OT1 encoding is a strange glyph and in T1 encoding, but also in T2A, is a "visible space").
So the most correct syntax would be
\replace{a}{\cLx\cS\ \cLy}{abc}

where you specify that you want x and y as normal letters: by default l3regex uses category code 12 characters. However this is being picky, as category code 12 and 11 characters are indistinguishable when printed.
For simple substitutions like that you could use
\tl_replace:Nnn

So, for example,
\documentclass{article}
\usepackage{xparse}

\ExplSyntaxOn
\NewDocumentCommand{\replace}{mmm}
 {
  \tl_set:Nn \l_tmpa_tl {#3}
  \tl_replace_all:Nnn \l_tmpa_tl {#1} {#2}
  \tl_use:N \l_tmpa_tl
 }
\ExplSyntaxOff

\begin{document}
\replace{a}{x y}{abc}
\end{document}


text:
Q: Trying to get number for each character in str I am doing a coding and question and I can't see where I am going wrong. I am asked to print out each number for every corresponding letter.
EG.
a = 1
b = 2
Also to remove any special characters and spaces.
Below is my code, greatly appreciated :)
 function alphabetPosition(str) {
   str.split('');
   var emptyArr = [];
   var letters = /^[A-Za-z]+$/;
   for(i=0; i <= str.length; i++){
    if(str[i].match(letters)){
     var num = str[i].charCodeAt(0) - 96
     emptyArr.push(num)
     var arrStr = emptyArr.toString();

     return arrStr

     }else{
      console.log('didnt match');
     }

   }
}

alphabetPosition('sunset')

so hello man should print out "19 21 14 19 5 20"

A: Your code has to return the value after the for loop.

 function alphabetPosition(str) {
   str = str.split('');
   var emptyArr = [];
   var letters = /^[A-Za-z]+$/;
   for(i=0; i < str.length; i++){
    if(str[i].match(letters)){
     var num = str[i].charCodeAt(0) - 96
     emptyArr.push(num)
     }else{
      console.log('didnt match');
     }
   }
   return emptyArr.toString()
}
console.log(alphabetPosition('sunset'))

Also another way to do it :

alphabetPosition=t=>t.match(/[a-z]/gi).map(i=>parseInt(i,36)-9).join(" ")
console.log(alphabetPosition('sunset'))

A: Your return is too early. Move it (and the toString() call) outside the loop and your code should work.

A: Don't return inside the for loop
function alphabetPosition(str) {
   str.split('');
   var res = [];
   var letters = /^[A-Za-z]+$/;

   for(i=0; i < str.length; i++){
    if(str[i].match(letters)){
     var num = str[i].charCodeAt(0) - 96
     res.push(num)

     }else{
      console.log('didnt match');
     }

   }
   return res.join(' ')
}

A: You could use parseInt for the character with radix 36 and use an offset of -9 for getting the values.

function alphabetPosition(string) {
    return Array
        .from(
            string,
            c => parseInt(c, 36) - 9
        )
        .join(' ');
}

console.log(alphabetPosition('sunset'))


text:
Q: Wifi Authorization using Curl session_start();

function sendAuthorization($id, $minutes)
{
$unifiServer = "https://xxx.xxx.xxx.xxx:xxxx";
$unifiUser = "xxxxx";
$unifiPass = "xxxxx";

// Start Curl for login
$ch = curl_init();
// We are posting data
curl_setopt($ch, CURLOPT_POST, TRUE);
// Set up cookies
$cookie_file = "/tmp/unifi_cookie";
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);
// Allow Self Signed Certs
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
// Force SSL3 only
curl_setopt($ch, CURLOPT_SSLVERSION, 3);
// Login to the UniFi controller
curl_setopt($ch, CURLOPT_URL, "$unifiServer/login");
curl_setopt($ch, CURLOPT_POSTFIELDS,
    "login=login&username=$unifiUser&password=$unifiPass");
// send login command
curl_exec ($ch);

// Send user to authorize and the time allowed
$data = json_encode(array(
    'cmd'=>'authorize-guest',
    'mac'=>$id,
    'minutes'=> $minutes));

// Send the command to the API
curl_setopt($ch, CURLOPT_URL, $unifiServer.'/api/cmd/stamgr');
curl_setopt($ch, CURLOPT_POSTFIELDS, 'json='.$data);
curl_exec ($ch);

// Logout of the UniFi Controller
curl_setopt($ch, CURLOPT_URL, $unifiServer.'/logout');
curl_exec ($ch);
curl_close ($ch);
unset($ch);
}

(thought I would add the code first)
would anyone out there know how to turn this around so that I could call the function so the user IS NOT authorized?
Im making a captive portal. this is a authorized.php page, but on this i would like to have a function which is unauthorize within this page, to call it if some information is missing.
Thanks,
Andrew


text:
Q: nested exception is org.hibernate.PersistentObjectException I am getting error when i am  clicking on post method in postman and getting blank response and error is
Employee not founddetached entity passed to persist: com.example.restapiexample.models.Employee; nested exception is org.hibernate.PersistentObjectException: detached entity passed to persist: com.example.restapiexample.models.Employee
Hibernate: select employee0_.id as id1_0_0_, employee0_.employee_age as employee2_0_0_, employee0_.employee_name as employee3_0_0_, employee0_.employee_salary as employee4_0_0_ from employee employee0_ where employee0_.id=?
Hibernate: delete from employee where id=?
Hibernate: select employee0_.id as id1_0_, employee0_.employee_age as employee2_0_, employee0_.employee_name as employee3_0_, employee0_.employee_salary as employee4_0_ from employee employee0_

@Entity

@Table(name = "employee")
public class Employee {

      // ------------------------
      // PRIVATE FIELDS
      // ------------------------

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

      @NotNull
      private String employee_name;

      @NotNull
      private int employee_salary;

      @NotNull
      private int employee_age;

      public Employee() { }

      public Employee(int id) {
        this.id = id;
      }

      public Employee(String employee_name, int employee_salary, int employee_age) {
        this.employee_name = employee_name;
        this.employee_salary = employee_salary;
        this.employee_age = employee_age;
      }
      public String getName() {
          return employee_name;
      }
      public int getSalary() {
          return employee_salary;
      }
      public int getAge() {
          return employee_age;
      }
      public void setAge(int age) {
          this.employee_age = age;
      }
      public void setName(String name) {
          this.employee_name = name;
      }
      public void setSalary(int salary) {
          this.employee_salary = salary;
      }
      public void setId(int value) {
        this.id = value;
      }
      public int getId() {
        return id;
      }

}
package com.example.restapiexample.controllers;

import com.example.restapiexample.models.Employee;
import com.example.restapiexample.models.EmployeeDao;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class EmployeeController {
    @Autowired
    EmployeeDao employeeDao;

    @RequestMapping("/getall")
    @ResponseBody
    public List<Employee> getAll() {
        return employeeDao.getAll();
    }

    @RequestMapping(value = "/get/{id}", method = RequestMethod.GET, consumes="application/json")
    @ResponseBody
    public ResponseEntity<Employee> getById(@PathVariable("id") int id) {
        Employee emp = null;
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json");
        headers.add("Responded", "EmployeeController");

        try {
            emp = employeeDao.getById(id);
        } catch(Exception ex) {
             System.out.println("Employee not found" + ex.getMessage());
             return ResponseEntity.accepted().headers(headers).body(emp);
        }

        return ResponseEntity.ok().headers(headers).body(emp);
    }

    @RequestMapping(value = "/create", method = RequestMethod.POST, consumes="application/json")
    @ResponseBody
    public ResponseEntity<Employee> create(@RequestBody Employee postdata) {
        Employee emp = null;
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json");
        headers.add("Responded", "EmployeeController");

        try {
            emp = employeeDao.create(postdata);
        } catch(Exception ex) {
             System.out.println("Employee not found" + ex.getMessage());
             return ResponseEntity.ok().headers(headers).body(emp);
        }

        return ResponseEntity.ok().headers(headers).body(emp);
    }

    @RequestMapping(value = "/delete/{id}", method = RequestMethod.DELETE, consumes="application/json")
    @ResponseBody
    public String delete(@PathVariable("id") int id) {
        boolean isDeleted = false;
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json");
        headers.add("Responded", "EmployeeController");

        try {
            Employee emp = new Employee(id);
            isDeleted = employeeDao.delete(emp);
        } catch(Exception ex) {
             System.out.println("Employee not found to delete" + ex.getMessage());
             return "Error deleting the Employee: " + ex.toString();
        }

        if(isDeleted) {
            return "Employee succesfully deleted!";
        }
        return "Error! Employee deleted!";
    }
}
package com.example.restapiexample.models;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;

import org.springframework.stereotype.Repository;

@Repository
@Transactional
public class EmployeeDao {
    @PersistenceContext
      private EntityManager entityManager;
      /**
       * Return all the employee stored in the database.
       */
      @SuppressWarnings("unchecked")
      public List<Employee> getAll() {
        return entityManager.createQuery("from Employee").getResultList();
      }

      public Employee getById(int id) {
          return entityManager.find(Employee.class, id);
      }

      /**
       * Save the employee in the database.
       */
      public Employee create(Employee emp) {
        entityManager.persist(emp);
        int id = emp.getId();
        return entityManager.find(Employee.class, id);
      }
      /**
       * delete the employee in the database.
       */
      public Boolean delete(Employee emp) {
          if (entityManager.contains(emp))
              entityManager.remove(emp);
          else
              entityManager.remove(entityManager.merge(emp));

          return true;
      }
}

A: You should do:
emp = entityManager.find(Employee.class, id);
then entityManager.delete(emp);


text:
Q: MOSFET driver circuit configuration for half bridge MOSFETs for power amplifier I am making a class D audio amplifier and I am using a MOSFET driver to control two MOSFETs in a half bridge configuration as shown in the circuit below

When I connected the circuit without the MOSFET half-bridge, I grounded Vs and I got a neat output according to my needs 15 V peak at HO & LO, The problems started when I connected the MOSFETs, The HO & LO terminals started sending out the same signal but with a max voltage of 3 V or  probably less, then the circuit drew around 1 AMP from my voltage source and burned the MOSFET driver chip, I knew for sure that it was burned because the resistance between the VDD terminal and the COM terminal was 26 Ohms instead of the high resistance a new chip had. An engineer in my uni suggested that the problem might be caused because I was providing the 15 volts to the MOSFETs from the same node that supplies the same voltage 15 V to my entire circuit, although my circuit was drawing only 40 milliamps from the power supply before connecting the MOSFETs.
I would like to note that the chip is FAN7390. I have fried two so far. I would guess that the common power supply might be the problem?, or it might be that the switching frequency of 125kHz the problem? The Hin and Lin signals are PWM signals with 15 V peak.

A: Several things wrong with that design!

*

*Where is the decoupling? That 15V line needs a whole pile of cap on it....

*C4???! 22uF for a boost cap, just insane, get rid of it, the 220n should be fine on its own.

*R13/14 1k, try more like 100k.

*Those mosfets, 140nC maximum gate charge?! Yea they are very, very butch fets, but you really want something much smaller and with a very much lower Qg.

*Layout? It really, really matters.

*Not the cause of the blowup, but R11/12 seem very high in value, especially given the Qg of those mosfets.


text:
Q: Responsive video resizing html/php I am currently trying to figure out a solution to resizing a video for a website I have created. This video is in a container which is responsive to a certain point but then stops resizing. This is annoying due to the fact i am forseeing most views of the website to be through mobile phones where the pixel resolution will be lower and a lot of the video will be cut off. Here is the website in question hosted on a free web host for now: Website in question
CSS:
.container{
  max-width:960px;
  padding-left:1rem;
  padding-right:1rem;
  margin:auto;
  text-align:center;

}

.fullscreen-video-wrap{
  position:absolute;
  top:0;
  left:0;
  width:101%;
  height:100vh;
  overflow:hidden;
}

.fullscreen-video-wrap video{
  min-height:100%;
  min-width:100%;
}

@media(max-width:960px){
  .container{
    padding-right:3rem;
    padding-left:3rem;
  }
}

Any help would be massively appreciated! Thanks :)