text:
Q: css selector for ul after div containing a checked checkbox Is there a way, using minimal css, to select an ul element, which is located directly after a div that contains a checked checkbox? I couldn't find an answer so I hope you guys can help me.
Original model I'm using is here: http://acidmartin.wordpress.com/2011/09/26/css3-treevew-no-javascript/
My goal is to make a div-treeview using minimal, standard css and avoid using js libraries etc.
Here's my setup:
the html:

            <input type="checkbox" id="mychk" />
            chktitle

and my css:
.css-treeview div.ou + ul  /* for hiding ul's after div with class 'ou' */
{
    display: none;
}

/* I tried something like this but this would select the ul if it was inside */
/* the div, which I don't want */
.css-treeview div.ou > input:checked + ul
{
    display: block;
}

Is there a simple, smart way to select the ul depending on the checkbox state?

A: Try This Demo

            chktitle
            <input type="checkbox" id="mychk" />

 some content

.css-treeview div.ou ul
{
    display: none;
}

.css-treeview div.ou > input:checked + ul
{
    display: block;
}

A: Thank you all for your comments, I accepted Pete's and Amit's answer, as it helped me a great deal. If anyone needs to accomplish the same as I do, here's some adaptations of what I'm going for:
This one is practically the answer given here:
Html:

                Title

                Other data etc

                Link

            <input type="checkbox" id="item-0-0-1" />  V

                            Title

                            Other data

                            Link

                            Title

                            Other data

                            Link

And here is css for above:
(note I had to add the br to the selector)
body {
    text-align: center;
}

ul {
    display: inline-block;
    padding:0px;
    margin:0px;
    text-align:center;
}

li {
    display: inline-block;
    list-style: none;
    vertical-align:top;
    margin-top:20px;
    margin-right:10px;
    text-align:center;
}

div.ou {
    border:1px solid blue;
    margin:0px;
    margin-right:10px;
    padding-top:0px;
    padding-left:20px;
    padding-bottom:20px;
    padding-right:0px;
    border-radius:10px;
    text-align:left;
    min-width:100px;
}

div.ou_content {
    min-width:150px;
    padding:4px;
    border:0px solid green;
    margin-top:10px;
    margin-right:10px;
}

label {
    border: 1px solid navy;
    float:right;
    margin-right:0px;
    margin-left:10px;
    display:inline-block;
    cursor:pointer;
    background-color:lightblue;
}

#menutree li {
    list-style: none;
}

.css-treeview input + label + br + ul
{
    display: none;
}

.css-treeview input:checked + label + br + ul
{
    display: inline-block;
    text-align: center;
}

.css-treeview input
{
    opacity: 0;
    display:none;
}

Also I did another proof-of-concept:
Here's my own try-out:
Html:

 place for content

        Title1   V
        <input type="checkbox" id="c3" name="level2" value="1" />

 place for content

                Title2
                <input type="checkbox" id="c4" name="level3" value="1" />

 place for content

                Title3
                <input type="checkbox" id="c5" name="level3" value="1" />

And css for this:
#menutree li {
    list-style: none;
    text-align: center;
}

li .menu_label + input[type=checkbox] {
    opacity: 0;
    display:none;
}

li .menu_label {
    cursor: pointer;
}

li .menu_label + input[type=checkbox] + ol > li {
    display: none;
}

li .menu_label + input[type=checkbox]:checked + ol > li {
    display: inline-block;
    text-align: center;
}

li  :not(.menu_label + input[type=checkbox]:checked + ol > li) {
    display: none;
}

div.contentdiv {
    height:40px;
    padding-top:6px;
}

li {
    border-top:4px solid blue;
    border-right: 2px solid blue;
    border-left: 2px solid blue;
    border-bottom: 0px solid blue;

    border-radius:30px 30px 0px 0px;
    margin-top:20px;
    margin-left:6px;
    margin-right:6px;
    padding-right:10px;
    padding-left:10px;
    display: inline-block;
    vertical-align:top;
    text-align: center;
    height:50px;
    min-width:100px;
}

label {
    border: 1px solid navy;
    padding:0px;
    border-radius:0px;
    vertical-align:top;
    text-align: center;
    margin-left:4px;
    margin-right:4px;
}

body {
    text-align: center;
}

ol {
    display: block;
    padding:0px;
    margin:0px;
}


text:
Q: Error: No module named django I have an old CentOS machine, where a software app written for Django 1.4.x is running. The software requires Python2.7. So I upgraded the implementation to Python2.7 and installed the various necessary software.
on the python2.7 command prompt
>>> import django

Works perfectly. I am able to play around with everything fine. Even when I print sys.path it shows directories fine.
But running
python2.7 manage.py runserver

or any other command throws up an error
python2.7 manage.py runserver
Error: No module named django

This is the first time I have seen such an issue in last 10 years. The software works perfectly in the ubuntu version which has python2.7 installed.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Handle CSV data: Separate data with a comma I need to handle the data from a CSV list. I need to import this list, but for that, I need to join the data, separated by commas.
Currently the list looks something like this:
COMPANY;CITY;COUNTRY
Comp1;curitiba;brazil
Comp2;curitiba;brazil
Comp3;detroit;usa
Comp4;detroit;usa

What I need is to group the values, separator by comma, according to the city, exactly as follows:
COMPANY;CITY;COUNTRY
Comp1,Comp2;curitiba,curitiba;brazil,brazil
Comp3,Comp4;detroit,detroit;usa,usa

The list has thousands of lines, which makes it impossible to do it manually.
Would anyone know a way to do this with some tool?

A: You could use some SQL aggregation function.
In sqlite in example, starting from this kind of table, named "input"
+---+---+---+
| a | b | c |
+---+---+---+
| 2 | 3 | 3 |
| 1 | 3 | 4 |
| 2 | 5 | 7 |
+---+---+---+

and running
SELECT
    a,GROUP_CONCAT(b) b,GROUP_CONCAT(c) c
FROM
    input
group by a

you will have
+---+-----+-----+
| a | b   | c   |
+---+-----+-----+
| 1 | 3   | 4   |
| 2 | 3,5 | 3,7 |
+---+-----+-----+

The GROUP_CONCAT function is in a lot of db systems (not only sqlite).

A: If I'm understanding you correctly and you just want every two rows to be combined into a single row, then the following will get you where you need to go. Otherwise, it should be enough to introduce you to Power Query and you can adjust from what this is to what you need.
From within a new workbook in Excel...

*

*Do Data - New Query - From File - From CSV from the Microsoft Excel ribbon. This will open up the "Power Query Editor"

*Confirm/adjust to make sure it's importing your starting format correctly.

*Rename the query you create to "RawImport". (Look for the "Name" property on the right sidebar.)

*Create a new query that starts with the current one by, from the ribbon (in the Power Query editor), clicking Home - Manage - Reference

*Click View and ensure that "Formula Bar" in the ribbon is checked.

*Change the name of this query to "RawImportEvenOdd"

*Click Add Column - Index Column from the ribbon. This should create a new "Index" column that starts with 0 and increments by 1.

*Click Add Column - Custom Column from the ribbon. In the dialog box, give it a name of "IsEvenRowNum", and a formula of Number.Mod([Index], 2) = 0

*Click the little "ABC 123" icon in the left edge of your new "IsEvenRowNum" column's title. Change it to a type of "True/False". This isn't necessary, but trust me and start your habit of strongly typing your data today. It will save you from yourself one day.

*Create a new query that will be only the even rows by clicking Home - Manage - Reference

*Rename this third query to "RawImportEvenOnly"

*Click on the little filter button on the right edge of the "IsEvenRowNum" and filter your query to only show rows where IsEvenRowNum is true

*Click Add Column - Custom Column and in the dialog box, name it "NewRowNum" with a formula of [Index]/2

*Click Home - Choose Columns and change it so only COMPANY, CITY, COUNTRY, and NewRowNum are selected.

*Double-click on the "COMPANY" column title and add "_E" to the end (renaming it to "COMPANY_E")

*Repeat the same for CITY and COUNTRY

*Create a new query that will be only the odd rows by clicking Home - Manage - Duplicate (note: Duplicate, not Reference)

*Change the query name to "RawImportOddOnly"

*Click on the Filtered Rows step in the right side-bar and then edit the displayed formula in the formula bar to change true to false

*Click on the next step, "Added Column", and then edit the formula from = Table.AddColumn(#"Filtered Rows", "NewRowNum", each [Index]/2) to = Table.AddColumn(#"Filtered Rows", "NewRowNum", each ([Index]-1)/2)

*In the last step, "Renamed Columns", change it so that it appends "_O" instead of "_E" to COMPANY, CITY, and COUNTRY.

*If the left side-bar hasn't already expanded for you, you can expand it to see the queries you've made so far. Click the "RawImportEvenOnly" query to go back to editing it.

*Click Home - Manage - Reference to start making your final query.

*Change the name to whatever you like.

*Click Home - Merge Queries and, in the dialog box,

*

*Click on the "NewRowNum" column title to highlight it.

*Change the dropdown box for the second table to be "RawImportOddOnly"

*Click on the "NewRowNum" column title on this second table to highlight it.

*Click Okay.

*Okay, so now the value of our new column for any given row is a subtable of the corresponding row from RawImportOddOnly, and we need to expand it. Instead of a filter button, the button the right edge of the new "RawImportOnly" column is an expand button. Click it. In the dialog box, make sure only COMPANY_O, CITY_O, and COUNTRY_O are selected, deselect "Use original column name as prefix" at the bottom of the dialog box, then click "Ok"

*Click Add Column - Custom Column, name it "COMPANY" with a formula of [COMPANY_E]&","&[COMPANY_O]

*Click Add Column - Custom Column, name it "CITY" with a formula of [CITY_E]&","&[CITY_O]

*Click Add Column - Custom Column, name it "COUNTRY" with a formula of [COUNTRY_E]&","&[COUNTRY_O]

*Click Home - Choose Columns and change the dialog box so only COMPANY, CITY, AND COUNTRY are selected.

*In the Home ribbon, click, the tiny little down-arrow in the "Close & Load" button and choose "Close & Load To", and choose "Only Create Connection" and click Ok.
Now you're back at Excel and nothing's happened (except for your new queries appearing in a side-bar)! This is because we didn't load anything into Excel, we only made query definitions. We did this because we just created a whole lot of queries and we didn't want to store the results of each and every one; we only want the last one!  In the side-bar, right click on the last query you created, click "Load to..." and load it to a new worksheet. This will do all of the work we've set up, from the beginning... which is great because if you realize you want to change any part of how this was made, go ahead, then refresh! Maybe I misunderstood you and you needed to sort it first? Maybe you've changed your mind and want to separate by slashes instead of commas? Change the queries and refresh the resulting table, and your new set of steps are done.
Not described is how to get this into a the semi-colon delimited file you're looking for, but I assume you can take it from there?

A: Using Miller (https://github.com/johnkerl/miller) is very easy.
Running
mlr --csv --fs ";" nest --implode --values --across-records  --nested-fs "," -f COMPANY input.csv

you will have
COMPANY;CITY;COUNTRY
Comp1,Comp2;curitiba;brazil
Comp3,Comp4;detroit;usa

Some notes:

*

*--fs ";", to set the field separator of the file;

*nest --implode --values --across-records, to set the implode nesting across the records;

*--nested-fs ",", to set the nested field separator;

*-f COMPANY, to set the field to implode.


text:
Q: How to let a SmartWatch vibrate from an HTML5 page without intervention As I have developed a solution for people with Alzheimer's, Dementia and for instance an Autisme Spectrum Disorder, that normally is shown on tablets (see www.dontforgetit.eu), I have made also an Android APP to be installed on a SmartWatch.
This app is developed with Android Studio and has an HTML5 background (as for the tablets).
What I do is I start with a page that needs to be tapped. It vibrates and that goes to the actual HTML5 page showing upcoming appointments and other obligations. The maximum ages shown is three (a clock, the actual event and the upcoming event). The upcoming event is only shown 5 minutes before the actual event terminates. Three minutes before the actual event stops and the upcoming events starts, the SmartWatch needs to vibrate.
For that reason I start with the earlier mentioned start page. However I get the following message "Blocked call to navigator.vibrate because user hasn't tapped on the frame or any embedded frame yet: https://www.chromestatus.com/feature/5644273861001216." and the Watch doesn't vibrate.
How do I solve this problem, preventing the disabled person to continue tapping the Watch?


text:
Q: Como comparar la ultima posición de un String Tengo un pequeño problema, no sabría como comparar la última posición de un String con un carácter alfabético.
// El DNI me lo pasarían por pantalla
for(int i=0; i<DNI.lenght; i++){
  if ((DNI.lenght-1) != //letra (de todo el abecedario))
{
...
}

Un saludo y gracias.

A: Para comparar la ultima letra primero debes de obtenerla. Puedes hacerlo de la siguiente manera:
Con el método charAt, donde la posicion sera el length -1 (algo parecido a como lo tienes puesto):
char ultimaLetra = DNI.charAt(DNI.length()-1);
System.out.println(ultimaLetra);

O puedes hacerlo tambien con substring, que devolvera una cadena y no un caracter como hace charAt:
String ultimaLetra = DNI.substring(DNI.length() - 1);
System.out.println(ultimaLetra);

Ya con esto obtienes la ultima letra, solo te quedaría compararla con lo que desees.

A: Para obtener el ultimo carácter puedes usar chartAt() y luego usar Character y sus métodos para saber si es numero o letra
 String DNI = "cadena0";
    char mchar = DNI.charAt(DNI.length() - 1);
    if (Character.isAlphabetic(mchar)) {
        System.out.println("es letra");
    } else {
        System.out.println("es numero");
    }

A:
Para tratar una cadena de caracteres, se la puede tratar de a uno en uno utilizando el metodo de String cadena.charAt(indice).
  Como lo que queres es el último caracter de la cadena necesitas saber cuantos caracteres tiene la cadena, para lo que se usa el metodo de String, cadena.length().

//Acá usamos DNI.length()-1 porque el indice de charAt comienza desde 0.
char ultimoCaracter = DNI.charAt(DNI.length()-1);

Una vez que se tiene el último caracter guardado en la variable ultimoCaracter, te  fijas si es una letra del alfabeto, el tipo de dato char, tiene la posibilidad de recorrerlo cual si fueran enteros, ya que tienen siguiente y anterior por lo que 'a' < 'b' y 'a'+1 ='b'.
  Por ello sugiero preguntar si tu caracter esta entre ['a' y 'z'] o entre ['A' y 'Z'] o si es'ñ' o 'Ñ'

boolean esAlfabetico;
esAlfabetico=(ultimoCaracter >= 'A'&&ultimoCaracter<='Z')
||(ultimoCaracter >= 'a'&&ultimoCaracter<='z'||ultimoCaracter=='ñ'||ultimoCaracter=='Ñ');

Luego la variable booleana esAlfabetico se vuelve verdadera si el caracter esta entre  ['a' y 'z'] o entre ['A' y 'Z'] o si es'ñ' o 'Ñ' o falsa de lo contrario.

A: Si deseas simplemente obtener el último carácter de un DNI, puedes usar el método substring() :
  String DNI = "99323664G";
  System.out.println("último caracter: " + DNI.substring(DNI.length() - 1));

salida:
último caracter: G

Pero si lo que deseas es obtener el último carácter No numérico puedes usar un REGEX para eliminar los valores numéricos y obtener posteriormente el último carácter:
 String DNI = "99323664G12A38";

 //Elimina valores numericos.
 DNI = DNI.replaceAll("[\\d.]", "");

 //Obtiene último caracter
 System.out.println("último caracter: " + DNI.substring(DNI.length() - 1));

Salida:
último caracter: A


text:
Q: Fixating the horizontal major gridlines Im looking for a way of fixating the horizontal major gridlines. I need them to be positioned at 70 and 30. I am thinking of removing the major gridlines entirely and just add two striplines together with two textboxes indicating the level on the Y axis but I would prefer to do it with gridlines :)
an exaple with red lines below - disregard the existing gridlines.

A: Ended up using two striplines.


text:
Q: force line break in html table cell I'm trying to find a way to force line break in table cell after text inside of it will become longer than say 50% of max allowed size.
How can I do it without any JS function, using just pure HTML with CSS?

A: I think what you're trying to do is wrap loooooooooooooong words or URLs so they don't push the size of the table out.  (I've just been trying to do the same thing!)
You can do this easily with a DIV by giving it the style word-wrap: break-word (and you may need to set its width, too).
div {
    word-wrap: break-word;         /* All browsers since IE 5.5+ */
    overflow-wrap: break-word;     /* Renamed property in CSS3 draft spec */
    width: 100%;
}

However, for tables, you must either wrap the content in a DIV (or other block tag) or apply: table-layout: fixed.  This means the columns widths are no longer fluid, but are defined based on the widths of the columns in the first row only (or via specified widths). Read more here.
Sample code:
table {
    table-layout: fixed;
    width: 100%;
}

table td {
    word-wrap: break-word;         /* All browsers since IE 5.5+ */
    overflow-wrap: break-word;     /* Renamed property in CSS3 draft spec */
}

Hope that helps somebody.

A: You could put the text into a div (or other container) with a width of 50%.
http://jsfiddle.net/6gjsd/

A: this work for me, without using table-layout:fixed; so you still can freely set each column.
table td {
    word-break: break-all;
    word-break: break-word;
}

A: I suggest you use a wrapper div or paragraph:

Text only allowed to extend 50% of the cell.

And you can make a class out of it:

Text only allowed to extend 50% of the cell.

td.linebreak p {
    width: 50%;
}

All of this assuming that you meant 50% as in 50% of the cell.

A: It's hard to answer you without the HTML, but in general you can put:
style="width: 50%;"

On either the table cell, or place a div inside the table cell, and put the style on that.
But one problem is "50% of what?" It's 50% of the parent element which may not be what you want.
Post a copy of your HTML and maybe you'll get a better answer.

A: Try using

as table style along with
long text

for td
it works for normal/real scenario text with words, not for random typed letters without gaps


text:
Q: iOS - TableView + button layout (outside) I am new to iOS and the following question might be too basic. But not able to figure out.
I have a tableview which extends till the bottom of the view controller. I want to also put a button at the bottom of the view controller - (this will not be in the tableView). When I put the button in the storyboard (image 1)- it hides behind the tableview when i run the code(image 2). Not sure how to tackle this. I want both the button and tableView to be aligned to the the bottomViewController. Final view will be something like image 3

A: You've got two options:

*

*Put the button in the table footer view

*Or, in your storyboard, go to the left bar, where you've got all your objects, and move the table view above the button, that will make the button to be over the table.

A: Here, you can use Autoresizing property form the storyboard.
By using this property you don't need to put device specific framing code.


text:
Q: Decrypt aes-256-cbc openssl in C I have a file encrypted using the following openssl command line:
openssl enc -aes-256-cbc -pass pass:somepassword -p -in inputfile.txt -out outputfile.enc

The following Java code can decrypt this fine:
    byte[] encrypted = getBytesFromInputStream(in);

    String password = "somepassword";

    Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding", "BC");

    // Openssl puts SALTED__ then the 8 byte salt at the start of the
    // file. We simply copy it out.
    byte[] salt = new byte[8];
    System.arraycopy(encrypted, 8, salt, 0, 8);
    SecretKeyFactory fact = SecretKeyFactory.getInstance("PBEWITHMD5AND256BITAES-CBC-OPENSSL", "BC");
    c.init(Cipher.DECRYPT_MODE, fact.generateSecret(new PBEKeySpec(password.toCharArray(), salt, 100)));

    // Decrypt the rest of the byte array (after stripping off the salt)
    byte[] data = c.doFinal(encrypted, 16, encrypted.length - 16);

It reads the salt and derives the IV from the password as the openssl command line version does.
How would you decrypt this file on iOS using C or ObjC? Would Commoncrypto be a good option, or is it better to stick to the openssl EVP api? I couldn't find any functions for deriving the openssl keyspec in either API, although the API must be there in openssl somewhere as the command line utility is using it.
I'd guess using commoncrypto would be the preferred way? Is there a way to replicate the PBE Key Spec in commoncrypto?


text:
Q: Google App Engine, Task Queues How can I remove a task from a task queue? Is Google App Engine Task Queue removes the task from the queue after it is executed?

A: The task queue API only specifies a function for adding tasks.  It will remove them when they complete.
You can, however, manually remove them using the admin console.
Details: http://code.google.com/appengine/docs/python/taskqueue/overview.html#Managing_Task_Queues

A: A task is removed from the queue when it executes if and only if it returns an HTTP 200 response.  For any other response, it will be retried until it successfully executes.
As David's answer indicates, they can also be manually removed.

A: Tasks can be deleted via delete_tasks function.
Details:
https://developers.google.com/appengine/docs/python/taskqueue/queues#Queue_delete_tasks


text:
Q: creating nested Async tasks android I'm developing an android application where I connect to a server to get data
I'm using Volley library to perform my request in a separate class from the controller class, I put the data from the server in global list where I call it from the UI thread
my problem is when I call the function that initiates the call to the server it starts the Async task for the connection and doesn't wait for the data and calls the function that adds the data to the UI
so can I put the call of the function that initiates the call in an Async task and have nested Async tasks or it will do the same

A: new AsynctaskName().execute().get();

Try using get() to execute async task.
It will wait until the async task get executed.


text:
Q: Transparency collada file I need to change the transparency of a file. Dae (collada), by my code with the library Three.js with dat.gui. I'm using:
        $gui = new DAT.GUI();
                gui.add(opacity_pele, 'pele').onChange(function(){
                if ( opacity_pele.pele ) {
                    material[pele].transparency = 1.0;

                } else {
                    material[pele].transparency = 0.0;

                }

            });
           gui.close();

A: Have you tried seting the transparency right in your 3D editor program?
E.g. in Blender you can adjust the transparency of your object on the panels (please see below). I'm using this method for displaying transparent objects and this works perfectly for me.


text:
Q: Node express & pg-promise - db.any is not a function I have this error :
TypeError: db.any is not a function

I'm using node JS, with pg-promise and express.
Here is the queries.js file (db) :
const promise = require('bluebird');

var options = {
    promiseLib: promise
};

var pgp = require('pg-promise')(options);
var connectionString = 'postgres://localhost:5432/spendy';
var db = pgp(connectionString);

console.log('connexion ok');

The controller :
const db = require('../queries');

module.exports = {
    getAllUsers: function(req, res, next) {
        db.any('select * from users')
            .then((data) => {
                res.status(200)
                    .json({
                        status: 'success',
                        data: data,
                        message: 'Retrieve all users'
                    });
            })
            .catch((err) => {
                console.log(err);
                return next(err);
            });
    }
}

And the routes file :
var express = require('express');
var router = express.Router();
var db = require('../queries');
const UserController = require('../controller/UserController');

router.get('/users', UserController.getAllUsers);

module.exports = router;

I use pg-promise with version 6.7.1 and bluebird 3.5.0,
I don't understand where is the error, if someone could help me,
thank you !

A: You dont appear to be exporting your db in the queries file.
Try inluding this in queries
module.exports = db;

A: you don't export your module queries
http://openmymind.net/2012/2/3/Node-Require-and-Exports/


text:
Q: how to swtich extjs themes? I noticed that extjs comes with 3 to 4 default themes/skins . How can I select or swtich between the themes?
I want to change the blue to select the grey themes or something else.
Thanks

A: Ext.util.CSS.swapStyleSheet function can be used to switch between the different themes, this forums post shows an example.
Also   I implemented this at first in my app a while back, but I ultimately found that forcing a browser refresh was necessary instead of dynamically swapping the CSS as there would still be some weird sizing/positioning issues.  This was mainly when switching between the accessibility theme.

A: Though Ext.util.CSS.swapStyleSheet will work, It has few drawbacks:
1. It takes more time to render the page with new CSS theme.
2. While switching between themes, your page will be out of any css for a while. That will make the page look bad (broken and plain).
3. Unnecessary scrollbars will appear on the screen.
I overcame these using JavaScript:
Here,

*

*Include all the CSS files in your HTML file.
<link rel="stylesheet" id="theme1" type="text/css" href="../Theme1.css" />
<link rel="stylesheet" id="theme2" type="text/css" href="../Theme2.css" />

*Disable all the themes except one you want as default.
document.getElementById('theme1').disabled = true;
document.getElementById('theme2').disabled = false;

Now the page will be loaded with 'theme2'.

*If you want to switch the theme. Do the opposite of the above...
document.getElementById('theme1').disabled = false;
document.getElementById('theme2').disabled = true;

In this way, the switching will be real fast. Since we have loaded all the css files initially. It will not ask the server for new theme every time.
It worked very well for me.


text:
Q: Mudar a propriedade FormBorderStyle para None sem perder as funções Sizable em C# Olá, estou como um pequeno problema, pois preciso mudar o design do meu Form referente a sua borda, sendo que a forma que encontrei em fazer isso foi mudando a propriedade FormBorderStyle para None e fazendo as devidas alterações no design, porém ao fazer isso pego as principais funções de quando estar como Sizable, sendo que as funções Minimize, Restore e Close eu ainda consigo faze-la com o uso de imagens ou botões, porém a função de redimensionar o form com o mouse o "esticar" e "encolher" eu não a tenho mais. O que devo fazer para que o form volte a ter-las?

O que eu estou precisando é algo semelhante ao novo design do visual studio pro exemplo, onde ele mantem as mesmas funções, porém com o layout personalizado, como pode ser visto na imagem abaixo:

A: É possível fazer o redimensionamento do form usando o método WndProc. Faça um teste com o código abaixo:
public partial class Form1 :Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private int borderWidth = 5; //Exemplo apenas para teste
    private new Padding Padding = new Padding(50); //Exemplo apenas para teste (Pode ser especificado direto nas propriedades do Form)

    private WinApi.HitTest HitTestNCA(IntPtr lparam)
    {
        Point vPoint = new Point((Int16)lparam, (Int16)((int)lparam >> 16));
        int vPadding = Math.Max(Padding.Right, Padding.Bottom);

        if (RectangleToScreen(new Rectangle(ClientRectangle.Width - vPadding, ClientRectangle.Height - vPadding, vPadding, vPadding)).Contains(vPoint))
            return WinApi.HitTest.HTBOTTOMRIGHT;

        if (RectangleToScreen(new Rectangle(borderWidth, borderWidth, ClientRectangle.Width - 2 * borderWidth, 50)).Contains(vPoint))
            return WinApi.HitTest.HTCAPTION;

        return WinApi.HitTest.HTCLIENT;
    }

    protected override void WndProc(ref Message m)
    {
        if (DesignMode)
        {
            base.WndProc(ref m);
            return;
        }

        switch (m.Msg)
        {
            case (int) WinApi.Messages.WM_NCHITTEST:
                WinApi.HitTest ht = HitTestNCA(m.LParam);
                if (ht != WinApi.HitTest.HTCLIENT)
                {
                    m.Result = (IntPtr) ht;
                    return;
                }
                break;
        }

        base.WndProc(ref m);
    }

    [SuppressUnmanagedCodeSecurity]
    internal static class WinApi
    {
        public enum Messages : uint
        {
            WM_NCHITTEST = 0x84,
        }

        public enum HitTest
        {
            HTCLIENT = 1,
            HTBOTTOMRIGHT = 17,
            HTCAPTION = 2
        }

    }
}

*Observe que a propriedade Padding determinará a área em que o redimensionamento poderá ocorrer, neste caso, uma área quadrada de 50 pixels no canto inferior direito.
Este trecho de código foi retirado de um framework desenvolvido para criar aplicações no estilo Metro, usando o Windows Forms:
MetroFramework - Modern UI for WinForms (http://thielj.github.io/MetroFramework/)
Caso os forms e os controles que eles disponibilizam não atendam aos seus requisitos, é possível obter o código fonte e fazer as alterações necessárias.


text:
Q: undefined reference to `_WinMain@16' with cygwin and mingw in openssl I kind of am struggling with OpenSSL over here. I downloaded the current release 1.0.1 and the compilation itself works. I can even call ./apps/openssl.exe. But when I get to the linking process the linker complains:
/usr/i686-pc-mingw32/sys-root/mingw/lib/libmingw32.a(main.o): In function `main':
/usr/src/mingw-runtime/mingw-runtime-3.20-1/src/mingwrt-3.20-mingw32/main.c:73: undefined reference to `_WinMain@16'

(this is if I use mingw in cygwin, the same error occurs with cygwin itself)
This is the cygwin error:
/usr/lib/gcc/i686-pc-cygwin/3.4.4/../../../libcygwin.a(libcmain.o):(.text+0xba): undefined reference to `_WinMain@16'

Now I found out that this means that it doesn't find a main function, but this couldn't actually be, can it? I mean openssl HAS its main-function. And concerning mingw: I can't find that file it mentions so there could be cause of the error, but libcygwin.a does exist (though I have no idea how to figure out if it has a main function).
So basically I ask: Why does this error occur that only occurs if I don't add a main function. Did I miss something?
Edit: Sorry to have missed that: I am on Win 7 x64 Enterprise

A: See this for a solution.  Steps summarized below:

*

*unpack the .tar with the msys tools and NOT 7-zip.

*Use tar -xzf openssl-x.y.z.tar where x.y.z denotes your version.

*Then run the commands and it will work like a charm.


text:
Q: How to add a line of metadata above a dataframe My question is probably very simple, but I can't find an answer
I have the dataframe (where the first row are in fact colnames)
      a      b       c     d      e
   1
   2
   3
   4
   5

And I need to include some metadata:
      >this is metadata
      a      b       c     d      e
   1
   2
   3
   4
   5

How can I do that?

A: There are two things you could do if you want to retain some metadata:
1) If you want to manipulate data frames with metadata in your R session, you can create a new S3 class that inherits from data.frame and add a metadata attribute to it. You can find some relevant information here
2) If you want to save a data frame with metadata to disk, you can add a comment line at the top of your csv file (or any other format that you prefer). Something like this will work:
con <- file(paste0(base_path, file_name),'wt')

cat(paste0(comment_string,'\n'), file = con)
write.table(your_data_frame,
              con,
              append = TRUE,
              sep = ',',
              dec = '.',
              row.names = FALSE,
              col.names = FALSE)

close(con)

where comment_string is your metadata and your_data_frame is your data frame.

A: Easiest way is to use openxlsx.
https://cran.r-project.org/web/packages/openxlsx/vignettes/Introduction.html
as in:
header <- "this is metadata"
df <- my dataframe

wb <- createWorkbook()
#create an empty workbook
    addWorksheet(wb, sheetName = "df_name", gridLines = F)
#add one or more worksheets specifying the name you want for the worksheet
    writeData(wb, 1, x = header, startCol = 1, startRow = 1)
#write your header to the workbook
    writeDataTable(wb, sheet = 1, df, startCol = 1, startRow = 2)#)
#write your data to the workbook
    saveWorkbook(wb, "df_name.xlsx", overwrite = TRUE)
#export your workbook to excel file

#not run for this example


text:
Q: How to validate Extjs Editable Grid Cell I have an editable grid and for a particular column / field I have to implement validation. For example lets say I have a grid with 2 columns. Want to validate the symbol once enter a symbol and its quantity.
For validation there will be a service call and the response will have an indicator and based on that Will set the background of Invalid symbol to RED.

How can I send AJAX request and mark invalid symbol with Border color red / bgcolor red
Thanks in advance!!

A: For cell editing you can use Ext.grid.plugin.CellEditing grid plugin. This plugin have edit( editor, context, eOpts ) event which is fired after cell was edited.
In listener for this event, you can get information about edited record from context parameter and make AJAX request to server for validation.
For set background color of the grid cell you can use:
// get element object from HTML code
var rowEl = Ext.get(context.row);
var tdElIdx =  context.colIdx + 1;
// find element of edited cell
var celEl = rowEl.down('td:nth(' + tdElIdx + ')');
// set background color of the cell
celEl.setStyle('background-color','red');


text:
Q: Install some recommended packages Is it possible in apt/apt-get to install a package and only some of its recommendations?
For example: I want to install kde-plasma-desktop which recommends sddm, but I don't want to install sddm. What I do want is to install the rest of the recommended packages.
Is there any way of doing this with apt?

A: You could try appending a dash to the end of the package you don't want installed, as in apt-get install kde-plasma-desktop sddm-. From man apt-get:

If a hyphen is appended to the package name (with no intervening space), the identified package will be removed if it is installed. Similarly a plus sign can be used to designate a package to install. These latter features may be used to override decisions made by apt-get's conflict resolution system.


text:
Q: Optionally serialize a property based on its runtime value Fundamentally, I want to include or omit a property from the generated Json based on its value at the time of serialization.
More-specifically, I have a type that knows if a value has been assigned to it and I only want to serialize properties of that type if there has been something assigned to it (so I need to inspect the value at runtime).  I'm trying to make it easy for my API to detect the difference between "has the default value" and "wasn't specified at all".
A custom JsonConverter does not seem sufficient; I tried it and I believe the property name is already serialized before the converter is called.  In my case I want to omit even the property name.
I've looked at extending DefaultContractResolver but CreateProperty and CreateProperties (which return JsonProperty serialization metadata) take only the Type being serialized, so I can't inspect the instance itself.  In general, I don't see anything on the DefaultContractResolver allowing me to control if an instance is serialized; maybe I missed it.
I also thought maybe I needed to create a ContractResolver that returned a custom JsonObjectContract for my type.  But, again, I don't see anything on JsonObjectContract that makes decisions based on an instance.
Is there a good way to accomplish my goal?  Am I just missing something simple?  Any help you can provide is greatly appreciated.  Since Json.NET is so extensible, I thought this wouldn't be too hard.  But I'm starting to think I'm way off in the weeds here. :)

A: Because you are asking to do it based on the value of a property what you can do is put the data into a dictionary. You can exclude adding the value to the dictionary. Below is a simple example of how to get the data out of an object.
public class Class1
{
    public string Name { get; set; }
}

[TestFixture]
public class Tests
{
    [Test]
    public void ConvertTest()
    {
        var dictionary = new Dictionary<string, object>();
        var @class = new Class1 { Name = "Joe" };

        var propertyInfos = typeof (Class1).GetProperties();

        foreach (PropertyInfo propertyInfo in propertyInfos)
        {
            dictionary.Add(propertyInfo.Name, propertyInfo.GetValue(@class, BindingFlags.GetProperty, null, null, null));
        }

        var serializeObject = JsonConvert.SerializeObject(dictionary);
        var o = JsonConvert.SerializeObject(@class);

        Console.WriteLine(serializeObject);
        Console.WriteLine(o);

        var class1 = JsonConvert.DeserializeObject<Class1>(serializeObject);
        Console.WriteLine(class1.Name);
    }
}

A: Ok, after digging around in Json.NET source for a while, I finally got this working and it will even honor the ShouldSerialize* and *Specified members that Json.NET supports.  Be warned: this is definitely going off into the weeds.
So I realized that the JsonProperty class returned by DefaultContractResolver.CreateProperty has ShouldSerialize and Converter properties, which allow me to specify if the property instance should actually be serialized and, if so, how to do it.
Deserialization requires something a little different, though.  DefaultContractResolver.ResolveContract will, by default for a custom type, return a JsonObjectContract with a null Converter property.  In order to deserialize my type properly, I needed to set the Converter property when the contract is for my type.
Here's the code (with error handling / etc removed to keep things as small as possible).
First, the type that needs special handling:
public struct Optional<T>
{
    public readonly bool ValueProvided;
    public readonly T Value;

    private Optional( T value )
    {
        this.ValueProvided = true;
        this.Value = value;
    }

    public static implicit operator Optional<T>( T value )
    {
        return new Optional<T>( value );
    }
}

And there's the converter that will serialize it properly after we know it should be serialized:
public class OptionalJsonConverter<T> : JsonConverter
{
    public static OptionalJsonConverter<T> Instance = new OptionalJsonConverter<T>();

    public override void WriteJson( JsonWriter writer, object value, JsonSerializer serializer )
    {
        var optional = (Optional<T>)value; // Cast so we can access the Optional<T> members
        serializer.Serialize( writer, optional.Value );
    }

    public override object ReadJson( JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer )
    {
        var valueType = objectType.GetGenericArguments()[ 0 ];
        var innerValue = (T)serializer.Deserialize( reader, valueType );
        return (Optional<T>)innerValue; // Explicitly invoke the conversion from T to Optional<T>
    }

    public override bool CanConvert( Type objectType )
    {
        return objectType == typeof( Optional<T> );
    }
}

Finally, and most-verbosely, here's the ContractResolver that inserts the hooks:
public class CustomContractResolver : DefaultContractResolver
{
    // For deserialization. Detect when the type is being deserialized and set the converter for it.
    public override JsonContract ResolveContract( Type type )
    {
        var contract = base.ResolveContract( type );
        if( contract.Converter == null && type.IsGenericType && type.GetGenericTypeDefinition() == typeof( Optional<> ) )
        {
            // This may look fancy but it's just calling GetOptionalJsonConverter<T> with the correct T
            var optionalValueType = type.GetGenericArguments()[ 0 ];
            var genericMethod = this.GetAndMakeGenericMethod( "GetOptionalJsonConverter", optionalValueType );
            var converter = (JsonConverter)genericMethod.Invoke( null, null );
            // Set the converter for the type
            contract.Converter = converter;
        }
        return contract;
    }

    public static OptionalJsonConverter<T> GetOptionalJsonConverter<T>()
    {
        return OptionalJsonConverter<T>.Instance;
    }

    // For serialization. Detect when we're creating a JsonProperty for an Optional<T> member and modify it accordingly.
    protected override JsonProperty CreateProperty( MemberInfo member, MemberSerialization memberSerialization )
    {
        var jsonProperty = base.CreateProperty( member, memberSerialization );
        var type = jsonProperty.PropertyType;
        if( type.IsGenericType && type.GetGenericTypeDefinition() == typeof( Optional<> ) )
        {
            // This may look fancy but it's just calling SetJsonPropertyValuesForOptionalMember<T> with the correct T
            var optionalValueType = type.GetGenericArguments()[ 0 ];
            var genericMethod = this.GetAndMakeGenericMethod( "SetJsonPropertyValuesForOptionalMember", optionalValueType );
            genericMethod.Invoke( null, new object[]{ member.Name, jsonProperty } );
        }
        return jsonProperty;
    }

    public static void SetJsonPropertyValuesForOptionalMember<T>( string memberName, JsonProperty jsonProperty )
    {
        if( jsonProperty.ShouldSerialize == null ) // Honor ShouldSerialize*
        {
            jsonProperty.ShouldSerialize =
                ( declaringObject ) =>
                {
                    if( jsonProperty.GetIsSpecified != null && jsonProperty.GetIsSpecified( declaringObject ) ) // Honor *Specified
                    {
                        return true;
                    }
                    object optionalValue;
                    if( !TryGetPropertyValue( declaringObject, memberName, out optionalValue ) &&
                        !TryGetFieldValue( declaringObject, memberName, out optionalValue ) )
                    {
                        throw new InvalidOperationException( "Better error message here" );
                    }
                    return ( (Optional<T>)optionalValue ).ValueProvided;
                };
        }
        if( jsonProperty.Converter == null )
        {
            jsonProperty.Converter = CustomContractResolver.GetOptionalJsonConverter<T>();
        }
    }

    // Utility methods used in this class
    private MethodInfo GetAndMakeGenericMethod( string methodName, params Type[] typeArguments )
    {
        var method = this.GetType().GetMethod( methodName, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static );
        return method.MakeGenericMethod( typeArguments );
    }

    private static bool TryGetPropertyValue( object declaringObject, string propertyName, out object value )
    {
        var propertyInfo = declaringObject.GetType().GetProperty( propertyName, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance );
        if( propertyInfo == null )
        {
            value = null;
            return false;
        }
        value = propertyInfo.GetValue( declaringObject, BindingFlags.GetProperty, null, null, null );
        return true;
    }

    private static bool TryGetFieldValue( object declaringObject, string fieldName, out object value )
    {
        var fieldInfo = declaringObject.GetType().GetField( fieldName, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance );
        if( fieldInfo == null )
        {
            value = null;
            return false;
        }
        value = fieldInfo.GetValue( declaringObject );
        return true;
    }
}

I hope that helps somebody else. Feel free to ask questions if anything is unclear or if it looks like I missed something.


text:
Q: How to build an internal messenger in Laravel I am building an internal messenger for a site with Laravel 9.
I want to be able to send messages to my users. unilaterally
But how does this work?
If I have 4000 users, should a copy of the message be inserted in the database for each user?
Or connect a message with a pivot table to the user table?
If users delete the message, how do I know
which users I sent the message to?
How should this be done so that the server does not time out or crash?
Doesn't the capacity of the database run out with this?
What is the right way?

A: Create 2 tables, Rooms and Messages. Rooms to group who are the users in the chat (can be more than two in one room) then Messages with room_id as foreign key. You can also add read by recipients in your messages to view who read your messages. Just paginate your messages when they scroll up to load the next page.
rooms migration
Schema::create('chat_rooms', function (Blueprint $table) {
    $table->id();
    $table->string('_uuid', 50);
    $table->string('chat_initiator', 50);
    $table->json('user_ids');
    $table->timestamps();
});

messages migration
Schema::create('chat_messages', function (Blueprint $table) {
    $table->id();
    $table->string('_uuid', 50);
    $table->string('chat_room_id', 50);
    $table->string('posted_by_user', 50);
    $table->json('message');
    $table->json('read_by_recipients');
    $table->string('type', 10);
    $table->timestamps();
});

Since you are using json as field, add this in your models
protected $casts = [
    'column_here' => 'array',
];

Rooms table:

Messages table:


text:
Q: What HTTP method should I use if my endpoint will perform database CREATE and UPDATE operations? I'm new to backend development. I still wonder what the correct route method is if the controller has different types of database actions. the example below is not the "exact" code but it does explain of what I'm trying to do.
const purchase = async (req, res) => {
  await updateThisOneFromDatabase();
  await createThisOneFromDatabase();

   return res.status(200).json({});
}

A: for create or insert to database, POST method is most recomended
The HTTP POST method sends data to the server. The type of the body of the request is indicated by the Content-Type header.
The difference between PUT and POST is that PUT is idempotent: calling it once or several times successively has the same effect (that is no side effect), where successive identical POST may have additional effects, like passing an order several times.
A POST request is typically sent via an HTML form and results in a change on the server. In this case, the content type is selected by putting the adequate string in the enctype attribute of the  element or the formenctype attribute of the  or  elements:
When the POST request is sent via a method other than an HTML form — like via an XMLHttpRequest — the body can take any type. As described in the HTTP 1.1 specification, POST is designed to allow a uniform method to cover the following functions:
Annotation of existing resources
Posting a message to a bulletin board, newsgroup, mailing list, or similar group of articles;
Adding a new user through a signup modal;
Providing a block of data, such as the result of submitting a form, to a data-handling process;
Kindly refer below for more information
https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST
https://www.w3schools.com/tags/ref_httpmethods.asp


text:
Q: vue - interpolation html value there is a v-data-table with server side pagination, where I used a formatter for a specific column as described to this topic.
the need is to replace it with HTML and not plain text. For example my function is like :
    formatCurrency (value) {
        return '' + value + '';
        //'<v-icon dark small>tick-outline</v-icon>' + value;
    },

when I using this getting the pure HTML.... as :

A: Try to use v-html directive :

new Vue({
  el: '#demo',
  data() {
    return {
      price: 555.33
    }
  },
  methods: {
    formatCurrency (value) {
      return '' + value + '';
        //'<v-icon dark small>tick-outline</v-icon>' + value;
    },
  }
})

Vue.config.productionTip = false
Vue.config.devtools = false


text:
Q: How can I prevent redirecting to php file after submission? I have a problem with the submission of a form. The form data is sent to the server as it should do but after clicking on the send button I get redirected to the php file. After the submission I would like to keep being on the same page.
Here's the code:

window.addEventListener('load', function() {

  $(document).ready(function() {

    $("#send").click(function(e) {
      e.preventDefault();
      $.ajax({
        type: 'POST',
        url: 'submitmessage.php',
        data: $('form').serialize(),
        success: function() {
          console.log("Submission succeeded");
          document.getElementById("send").innerHTML = "Sent";
        },
        error: function() {
          console.log("Error");
        }
      });
    });
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="submitmessage.php" method="POST">
  <input id="name" name="name" placeholder="Name" type="text" ></input>
  <input id="email" name="email" placeholder="email" type="email" ></input>
  <textarea id="message" name="message" maxlength="100" placeholder="Write here"></textarea><br>
  <button id="send" name="send">Submit</button>
</form>

A: Instead of using a handler on a specific button, assign it to the Form:

$('form[action="submitmessage.php"]').on("submit", function(e) {

  // prevent default browser form submit
  e.preventDefault();

  // We'll use AJAX instead:
  $.ajax({
    type: 'POST',
    url: this.action,
    data: $(this).serialize(),
    success: function() {
      $("#send").text("Sent");
    },
    error: function() {
      $("#send").text("Error");
    }
  });
});

A: The problem is the button <button id="send" name="send">Submit</button>. This is a "random" button and the e.preventDefault(); prevents nothing. If you change it to <input type="submit" id="send" name="submit" /> now actually submits the form. To prevent this, listen for $('form').submit(function(e) {}); instead.


text:
Q: how to resume wget mirroring website? I use wget to download an entire website.
I used the follwing command (in windows 7):
wget ^
 --recursive ^
 -A "*thread*, *label*" ^
 --no-clobber ^
 --page-requisites ^
 --html-extension ^
 --domains example.com ^
 --random-wait ^
 --no-parent ^
 --background ^
 --header="Accept: text/html" --user-agent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:21.0) Gecko/20100101 Firefox/21.0" ^
     http://example.com/

After 2 days my little brother restarted the PC
so I tried to resume the stopped process
I added the following to the command
--continue ^

so the code looks like
wget ^
     --recursive ^
     -A "*thread*, *label*" ^
     --no-clobber ^
     --page-requisites ^
     --html-extension ^
     --domains example.com ^
     --random-wait ^
     --no-parent ^
     --background ^
     --continue ^
     --header="Accept: text/html" --user-agent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:21.0) Gecko/20100101 Firefox/21.0" ^
         http://example.com/

unfortunately it started a new job it downloads the same files again and write a new log file named
wget-log.1

Is there anyway to resume mirroring site with wget or do have I to start the whole thing over again?

A: Try -nc option.  It checks everything once again, but doesn't download it.
I'm using this code to download one website:
    wget -r -t1 domain.com -o log
I've stopped the process, I wanted to resume it, so I changed the code:
    wget -nc -r -t1 domain.com -o log
In the logs there is  something like this:
    File .... already there; not retrieving. etc.
I checked logs before this and it seems that after maybe 5 minutes of this kind of checking it begins to download new files.
I'm using this manual for wget: http://www.linux.net.pl/~wkotwica/doc/wget/wget_8.html


text:
Q: Autoclosing of brackets and quotes in Spyder IPython console? How do I configure the IPython console in Spyder to auto-close brackets/braces/parens and quotes?

A: (Spyder developer here) There's no option to do this, sorry.

A: Click to see what to do
Simply follow this:
Go to Tools > Preferences > Editor > Advanced settings and tick the "Automatic insertion of quotes" option and click apply.
It worked for me, hope it works for you too.

A: Please select the check boxes at
Tools > Preferences > Editor > Advanced Settings


text:
Q: Modern page: Show FILTER PANE in Library webpart. Possible? I am using this modern "filter pane" in my library, but when  I use a Document Library Webpart to show this library as part of  a page, the filter pane is not present. How can I show  the Filter Pane while using a library webpart?
The filter pane is a big plus for the end user to filter the library based on metadata. It is a bummer if this is only available in a Library it selves and not in Library webparts


text:
Q: StripeSignatureVerificationError when handling stripe webhooks I'm trying to handle a stripe webhook, I've used their examples for express, also tried everything found on github/stackoverflow, nothing seems to work.

After few days of trying different approaches proposed by others, I can't manage to make it working, I'm getting the same issue StripeSignatureVerificationError every-time, please let me know what I'm doing wrong.
Thanks!

A: Try once with this:
event = this.stripeClient.webhooks.constructEvent(
    request.body,
    request.headers["stripe-signature"],
    webhookSecret
);


text:
Q: Java class for AES encryption/decryption of files Is there a Java class for simply encrypting/decrypting files by only providing source and destination files and AES key without bothering about encryption and IO details?
Thanks

A: You can look at Jasypt library.


text:
Q: Is a model with xs squared a good fit for a parabola? It should be, but the fact that the xs and not the parameters is squared confuses me.

A: A parabola can be directly seen as a linear model. You do not need any activation function. Let a general parabola equation
$$y=ax^2+bx+c$$
If you use the features $x$ and $x^2$ then $y$ is linear with respect to $a,b,c$ and you can simply run a linear regression that will estimates $a,b,c$.
It can be surprising to see that a parabola is linear in some sense, but the trick is that the word "linear" in linear regression means linear with respect to the coefficients (here $a,b,c$) not the feature (here $x$).


text:
Q: Make JsonDeserializer global effect When deserialize json to Map<out Any, Any>, gson will use Double to fill the Map, even the field is int number, so I use a MapDeserializerDoubleAsIntFix to covert number to int if it is possible.
{
    "person":{
        "name":"jack",
        "age":24,
        "height":174.5
    }
}

class MapDeserializerDoubleAsIntFix: JsonDeserializer<Map<out Any, Any>> {
    override fun deserialize(
        json: JsonElement,
        typeOfT: Type,
        context: JsonDeserializationContext
    ): Map<out Any, Any>? {
        return deserialize(json) as Map<out Any, Any>
    }

    private fun deserialize(jsonElement: JsonElement): Any? {
        when {
            jsonElement.isJsonArray -> {
                val list: MutableList<Any?> = ArrayList()
                val arr = jsonElement.asJsonArray
                for (anArr in arr) {
                    list.add(deserialize(anArr))
                }
                return list
            }
            jsonElement.isJsonObject -> {
                val map: MutableMap<String, Any?> = LinkedTreeMap()
                val obj = jsonElement.asJsonObject
                val entitySet = obj.entrySet()
                for ((key, value) in entitySet) {
                    map[key] = deserialize(value)
                }
                return map
            }
            jsonElement.isJsonPrimitive -> {
                val prim = jsonElement.asJsonPrimitive
                when {
                    prim.isBoolean -> {
                        return prim.asBoolean
                    }
                    prim.isString -> {
                        return prim.asString
                    }
                    prim.isNumber -> {
                        // Here is what i do
                        // use int or long if it is possible
                        val numStr = prim.asString
                        return if (numStr.contains(".")) {
                            prim.asDouble
                        } else {
                            val num = prim.asNumber
                            val numLong = num.toLong()
                            return if (numLong < Int.MAX_VALUE && numLong > Int.MIN_VALUE) {
                                numLong.toInt()
                            } else {
                                numLong
                            }
                        }
                    }
                }
            }
        }
        return null
    }
}

object MapTypeToken: TypeToken<Map<out Any, Any>>()

private val GSON = GsonBuilder()
        .registerTypeAdapter(MapTypeToken.type, MapDeserializerDoubleAsIntFix())
        .create()

*

*And when I use GSON deserialize json as map, it works.

 val map: Map<out Any, Any> = GSON.fromJson(json, MapTypeToken.type)

*

*But when the map is in a data class as a field, the MapDeserializerDoubleAsIntFix not work.

data class Test(
    val person: Map<out Any, Any>
)

val test = GSON.fromJson(json, Test::class.java)

So is there any way to deserialize map or filed map ?

A: Now I use this to solve.
class TestJsonDeserializer: JsonDeserializer<Test> {
    override fun deserialize(
        json: JsonElement,
        typeOfT: Type,
        context: JsonDeserializationContext,
    ): Test {
        val jsonObject = json.asJsonObject
        val personElement = jsonObject.get("person")
        val person = context.deserialize<Map<out Any, Any>>(personElement, MapTypeToken.type)
        return Test(person)
    }
}

private val GSON = GsonBuilder()
        .registerTypeAdapter(MapTypeToken.type, MapDeserializerDoubleAsIntFix())
        .registerTypeAdapter(Test::class.java, TestJsonDeserializer())
        .create()

But if another data class has map, I have to write another JsonDeserializer and register it.
Hope there is a better way to make the MapDeserializerDoubleAsIntFix work as global.


text:
Q: C++ Visual Studio DLL File My objective is to create a dll and lib file so i'm following this guide
1) I created a new win32 Console Application project in VS, chose DLL as 'Application Type' and Emptied Project
2) I'm trying to create a database in C++. So I have 5 headers with ONLY function declarations.
3) Database.h is my top header, it looks like this:
#ifdef DBDLL_EXPORTS
#define DBDLL_API __declspec(dllexport)
#else
#define DBDLL_API __declspec(dllimport)
#endif
#ifndef __Database_H
#define __Database_H

#include "Table.h"

class DBDLL_API Database { ... };
#endif

4) Now with only headers, I tried compiling the project. It compiled but I don't see any DLLs or Libs anywhere in the project folder. How do I create them?

A: This is because headers are not compiled -- only CPP files are compiled (which pull in the headers -- a source file and all the headers it pulls in is called a "translation unit", which is the thing actually being compiled (independent of other TUs)).
So, in effect, the build system thinks you're building an empty project, and in this case generates nothing at all. Note that even if the headers are pulled in and compiled, unless an exported symbol is actually referenced somewhere, it may be optimized out. In such cases, you will get an (empty) DLL, but no .lib file (which can cause errors down the line if you have dependent projects looking for this .lib before there's anything in the DLL).
You'll need to create some CPP files that implement the functions declared in the headers. If you have everything in the headers and don't need any CPP files at all, then there's no point in having a DLL! (Since you could include the headers in any other project without needing any other dependency.)
Finally, your include guard (#ifndef ...) should encompass the entire header, including the DLL export macros, otherwise you'll eventually get macro redefinition warnings.
I would suggest using #pragma once instead of include guards since it's simpler and recognized by pretty much every compiler. I would also put the DLL macro goop into its own header (e.g. "dllmacros.h") and include that where it's needed (this will reduce duplication).


text:
Q: Angular + RxJS: repeat the request on status code 202 I have a simple request that I would like to repeat in case the response is with status 202. Currently, it looks like this:
this.http.get(endPoint, {
    withCredentials: true,
    headers: this.headers
})
.map((response: Response) => {
    return response.text() ? response.json() : '';
})
.catch((error) => this.handleError(error));

I have tried with .repeatWhen() but unfortunately, I don't receive the Response object and I cannot set a validation by the status code.
Any ideas how can I do that?

A: That's a misunderstanding of how repeatWhen() works. The callback to this operator receives a single parameter which is an Observable where it pushes an empty item when the source completes. So it's not ideal for you (because you don't have access to the Response object you need).
You could use retryWhen() instead:
this.http.get(endPoint, { withCredentials: true, headers: this.headers })
    .map((response: Response) => {
        if (response.code === 202) {
            throw response;
        }
        return response;
    })
    .map((response: Response) => {
        return response.text() ? response.json() : '';
    })
    .retryWhen(obs => {
        return obs; // always just resubscribe without any further logic
    });

This throws the response as an error which is then caught by retryWhen that just resubscribes. You could of course use more logic to control if you resubscribe, for example:
.retryWhen(obs => {
   return obs.filter(...);
});

A: Use this for Rx 6. This retries the 202 up to 3 times, and throws a timeout error at the end of the third try.
@Injectable()
export class ProgressInterceptor implements HttpInterceptor {
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        return next.handle(req).pipe(
            map(t => {
                if (t['status'] === 202) {
                    throw 202;
                }
                return t;
            }),
            retryWhen(t => {
                return t.pipe(
                    concatMap((e, i) => {
                        if (e !== 202) {
                            return throwError(e);
                        }
                        return iif(
                            () => i >= 2,
                            throwError(new Error('Operation Timed Out!')),
                            of(e).pipe(delay(1000))
                        )
                    })
                )
            }),
        );
    }
}

A: Seeing as retryWhen() is deprecated and will be removed in v9 or v10, below is an updated answer; reference: retryWhen
Use retry() with it's delay option.

Will be removed in v9 or v10, use retry's delay option instead. Will be removed in v9 or v10. Use retry's delay option instead. Instead of retryWhen(() => notify$), use: retry({ delay: () => notify$ }).

@Injectable()
export class RetryInterceptor implements HttpInterceptor {
  constructor() {}

  shouldRetry(error: HttpErrorResponse) {
    if (error.status >= 300) {
      throw error;
    }
    return timer(30);
  }

  intercept(
    request: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    return next.handle(request).pipe(
      map((response: HttpResponse<unknown>) => {
        if (response.status === 204) {
          throw 204;
        }
        return response;
      }),
      retry({ count: 1000, delay: this.shouldRetry })
    );
  }
}

Retry count and status code can be changed to suit scenario.

A: You can make http call again in the catch method
.catch(res => {
    return res.status === 202?
        this.http.get(endPoint):
        Observable.throw(res);
});

A: How about using flatMap:
.flatMap((response:Response) => {
    if (response.status === 200) {
        return Observable.of(this.mapResponse(response.json()));
    } else if (response.status === 202) {
        return this.http.get(endPoint, {
            withCredentials: true,
            headers: this.headers
        });
    }
})


text:
Q: CSS Container Class I am working through a web dev project on youtube building a JavaScript clock. I think I know that creating a container and a child element allows positioning with absolute and relative.
However I don't understand why .clock is in every line and for example where it says .clock .number1 its not just .number1. Does the container or parent element have to be specified?

.clock {
  background-color: red;
  width: 500px;
  height: 500px;
  border-radius: 50%;
  border: 2px solid black;
  position: relative;
}

.clock .number {
  position: absolute;
  height: 100%;
  width: 100%;
  text-align: center;
}

.clock .number1 {
  transform: rotate(30deg);
}

.clock .number2 {
  transform: rotate(60deg);
}

.clock .number3 {
  transform: rotate(90deg);
}

.clock .number4 {
  transform: rotate(120deg);
}

.clock .number5 {
  transform: rotate(150deg);
}

.clock .number6 {
  transform: rotate(180deg);
}

.clock .number7 {
  transform: rotate(210deg);
}

.clock .number8 {
  transform: rotate(240deg);
}

.clock .number9 {
  transform: rotate(270deg);
}

.clock .number10 {
  transform: rotate(300deg);
}

.clock .number11 {
  transform: rotate(330deg);
}

.hand .hour {
  width: 20px;
  height: 20px;
  position: relative;
  top: 20px;
  left: 5px;
}

1

2

3

4

5

6

7

8

9

10

11

12

A: The short answer: you do not need the .clock in every line.
In CSS, when there are two classes specified, it will only target an object that has all of these classes. For example, let's say we have two things that have different parent elements but the same class name.

If we wanted to target only one of the child elements, it would become tricky since they both have the class "thing". So in this case, we would want to use two classes to identify a specific element:
.parent1 .thing {
     //insert styles
}

However, in your case, it appears that each element has a unique name, so there is no need to specify two classes. This was likely written in this way so that if there ever was an element created with the same class name, it wouldn't interfere with the already existing element.


text:
Q: How to know if a thread is blocked by Reader.read()? In the document of Reader.read() it says

Reads a single character. This method will block until a character is available, an I/O error occurs, or the end of the stream is reached.

When read() doesn't get anything from the stream, it will block. However, this kind of "blocking" doesn't turn the thread into State.BLOCKED or State.WAITING -- the thread is still in State.RUNNABLE when read() waits for the first character, thus I can't know if the thread is blocked by a read().
So how can I know if Reader.read() is blocking in a thread from another thread?

A: You can get a stack trace for the Thread and see which method it is running at that point.
Or what I do is set a time when the read starts which is clearer when the read finishes. I have another thread which checks this time and issues a warning when it has been too long.

A: why don't you just check with Reader#ready() if your read is going to block?

A: Just set a read timeout with Socket.setSoTimeout() and catch SocketTimeoutException.


text:
Q: Tenda 1024g Screw Type? Does anybody know the type of screw/clip nut I should use for my Tenda 1024g? Thanks in advance!

A: You can contact the manufacturer for "rackmount ears", if you don't have them. Otherwise, you may need to place the switch on a shelf...

Edit:
Since you have the rack ears, you need a cage nut, which clips into the square hole and provides a threaded receptacle for a matching bolt.
See:


text:
Q: UE4 Dedicated Server with critical error EXCEPTION_ACCESS_VIOLATION I use UE4.26.2 and window10.
After i followed the UE4 guide : Setting up Dedicated Servers, i can get folders and files that are packaged by UE4 engine. And i make shortcut FPSServer.exe with "-log" tag as well. But the problem is happened when i run it. Many text lines appeared and suddenly were closed before i check what logs on the Prompt. Fortunately, i can stop scrolling it clicking Mouse1 on Prompt screen.
=== Critical error: ===
Fatal error!

Unhandled Exception: EXCEPTION_ACCESS_VIOLATION reading address 0x0000000000000200

0x00007ff7685fc444 FPSServer.exe!UnknownFunction []
0x00007ff76549663a FPSServer.exe!UnknownFunction []
0x00007ff76549c9cb FPSServer.exe!UnknownFunction []
0x00007ff765b3ac09 FPSServer.exe!UnknownFunction []
0x00007ff765d85627 FPSServer.exe!UnknownFunction []
0x00007ff76833ead5 FPSServer.exe!UnknownFunction []
0x00007ff7647917d1 FPSServer.exe!UnknownFunction []
0x00007ff768301f3e FPSServer.exe!UnknownFunction []
0x00007ff7683207c2 FPSServer.exe!UnknownFunction []
0x00007ff768d0bebc FPSServer.exe!UnknownFunction []
0x00007ff768d12403 FPSServer.exe!UnknownFunction []
0x00007ff76909a87d FPSServer.exe!UnknownFunction []
0x00007ff7690b722f FPSServer.exe!UnknownFunction []
0x00007ff7654efb4f FPSServer.exe!UnknownFunction []
0x00007ff7654eff4e FPSServer.exe!UnknownFunction []
0x00007ff765500e1b FPSServer.exe!UnknownFunction []
0x00007ff7691056f2 FPSServer.exe!UnknownFunction []
0x00007ff7691107d2 FPSServer.exe!UnknownFunction []
0x00007ff7689d22ef FPSServer.exe!UnknownFunction []
0x00007ff7689dbbd2 FPSServer.exe!UnknownFunction []
0x00007ff76883b2fe FPSServer.exe!UnknownFunction []
0x00007ff764652d9d FPSServer.exe!UnknownFunction []
0x00007ff76466630d FPSServer.exe!UnknownFunction []
0x00007ff7646663ca FPSServer.exe!UnknownFunction []
0x00007ff764676630 FPSServer.exe!UnknownFunction []
0x00007ff76a443fbe FPSServer.exe!UnknownFunction []
0x00007ffb8cc17034 KERNEL32.DLL!UnknownFunction []
0x00007ffb8ce82651 ntdll.dll!UnknownFunction []

It is only what i just have known about EXCEPTION_ACCESS_VIOLATION is for Pointer problem. But i don't understand why my game is working well on UE4 editor with using multiplayer option and why this problem is appeared after package my game. Could you please help me to solve this error and let me know why it is happened?


text:
Q: Annihilator Method Help I'm having trouble on some annihilator method problems for homework and was wondering if anyone would be able to point me in the right direction. The problem is:
$$y''-8y'+20y=5xe^{4x} \sin(2x)$$
I need to find the annihilator (I think it's actually the same as the left side, $(D^2-8D+20)^2$, though I could be wrong) and find the particular solution.
I understand how to do variation of parameters and undetermined coefficients but I need to learn how to do this problem the annihilator way. It's confusing me though. Thanks in advance for the help!

A: Note that the annihilator equation
$$ ((D-4)^2+4)^2(D^2-8D+20)y=0 $$
The corresponding characteristic equation is
$$ ((r-4)^2+4)^2(r^2-8r+20)=0 \text{ or }((r-4)^2+4)^3=0 $$
which has roots $r=4\pm 2i$
with multiplicity 3. Thus a general solution of the annihilator is
$$ y_a=(c_1+c_2x+c_3x^2)e^{(4+2i)x}+(c_4+c_5x+c_6x^2)e^{(4-2i)x}. $$
I think now you solve it.


text:
Q: Should I expect Sorbet to perform platform-dependently? I've run into some trouble when changing the image I've been using for my CI process on CircleCI. I changed the image when I upgraded my version of Ruby.
bundle exec srb tc is running fine locally however it's flipping out with thousands of errors in CircleCI. I've wiped all of my local gems and reinstalled to match production but it doesn't make any difference to the errors.
The only thing I can tell that is different between the two environments is that my local environment is OSX and the remote one is linux (as are the production servers).
Local
$ ruby -v
ruby 2.7.5p203 (2021-11-24 revision f69aeb8314) [x86_64-darwin20]

Circle CI
$ ruby -v
ruby 2.7.5p203 (2021-11-24 revision f69aeb8314) [x86_64-linux]

Is that enough to account for all of the errors in Sorbet? And if so, how would I even go about fixing them given that I am running on Mac locally?
This wasn't a problem before
It's possible that this isn't the trigger. However builds were working in a prior environment on CircleCI using a different Ruby version, they just aren't now.

A: The answer to this is that it was not the platform that was affecting things, it was where the gem had been installed. I'm going to leave the question up on SO though just as a testament to the null result.
The issue triggering the errors turned out to be changing where the gem is installed - SO question here


text:
Q: Some tags of the xml aren't deserialized So I have this class generated with xsd.exe, when I deserialize the XML into my object it doesn't read all the attributes. Looks like the last attribute within a tree isn't read.
This is one of object's class:
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.1055.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
[System.Xml.Serialization.XmlRootAttribute(IsNullable=true)]
public partial class relation : myXml {

/// <remarks/>
public object a;

/// <remarks/>
public object b;

/// <remarks/>
public object c;

/// <remarks/>
public object d;

/// <remarks/>
public object f;

/// <remarks/>
public object g;

/// <remarks/>
public object h;

/// <remarks/>
public object i;

/// <remarks/>
public object j;
}

Example XML:
<z id="Fo">
    <attributes>
        <Relation>1<Relation>
        <YVersion>16<YVersion>
        <W>
            1
            2
            <c>3</c>
            <d>4</d>
        </W>
    </attributes>
</z>

When I debug, my Object with all the deserialized XML has all the nodes until the node W including node W and it's parameters however the below nodes aren't deserialized somehow, in this case nodes A, B, C and D.
Regards,
Hugo

A: it sounds like W is a complex type, while Relation & YVersion are just integers. you need a default constructor on your attributes object that instantiates any complex types. Also any of these other types you want to serialize that have complex types as properties need to be instantiated in a default constructor for the serializer to be able to work with them.
So for example your attributes class would look like this:
[Serializable]
public class Attributes
{
  public int Relation {get; set;}

public int YVersion {get; set;}

  public MyType W {get; set;}

  public Attributes()
  {
     W = new MyType();
  }

}

Keep in mind that you can't pass any parameters to the constructor because the serializer won't have any objects to pass to it.


text:
Q: python 3.6: No module named _QuantLib after installation of QuantLib and QuantLib-SWIG I am trying to install QuantLib and Python QuantLib-SWIG on Mac OSX 10.12.5 Sierra and Python 3.6.1., but get error messages:
ImportError: dlopen(build/lib.macosx-10.7-x86_64-
3.6/QuantLib/_QuantLib.cpython-36m-darwin.so, 2): Symbol not found: __
ZN8QuantLib10DateParser14parseFormattedERKSsS2_
Referenced from: build/lib.macosx-10.7-x86_64-
3.6/QuantLib/_QuantLib.cpython-36m-darwin.so
Expected in: flat namespace
in build/lib.macosx-10.7-x86_64-3.6/QuantLib/_QuantLib.cpython-36m-darwin.so

as well as:
ModuleNotFoundError: No module named '_QuantLib'

Luigi gave a very useful suggestion in this thread on the QuantLib users' mailing list, which I implemented and made some progress, but I still cannot finish installation for Python 3.6.
I have been able to successfully build QuantLib for Python 2.
I also tried to build QuantLib with dynamic loading below (i.e. I rm'ed /usr/local/lib/libQuantLib* and then reran the process without '--disable-shared --enable-static' in step #5 below, but that also failed.... :(.)
Anyone have any advice? Thank you in advance.
Error log
~/QuantLib-SWIG-1.10/Python>  /Users/tf/anaconda/bin/python3.6 setup.py
install
running install
running build
running build_py
running build_ext
running install_lib
creating /Users/tf/anaconda/lib/python3.6/site-packages/QuantLib
copying build/lib.macosx-10.7-x86_64-3.6/QuantLib/__init__.py -> /Users/tf/anaconda/lib/python3.6/site-packages/QuantLib
copying build/lib.macosx-10.7-x86_64-3.6/QuantLib/_QuantLib.cpython-36m-darwin.so -> /Users/tf/anaconda/lib/python3.6/site-packages/QuantLib
copying build/lib.macosx-10.7-x86_64-3.6/QuantLib/QuantLib.py -> /Users/tf/anaconda/lib/python3.6/site-packages/QuantLib
byte-compiling /Users/tf/anaconda/lib/python3.6/site-packages/QuantLib/__init__.py to __init__.cpython-36.pyc
byte-compiling /Users/tf/anaconda/lib/python3.6/site-packages/QuantLib/QuantLib.py to QuantLib.cpython-36.pyc
running install_egg_info
Writing /Users/tf/anaconda/lib/python3.6/site-packages/QuantLib_Python-1.10-py3.6.egg-info
~/QuantLib-SWIG-1.10/Python> /Users/tf/anaconda/bin/python3.6 setup.py test
running test
running build
running build_py
running build_ext
Traceback (most recent call last):
  File "build/lib.macosx-10.7-x86_64-3.6/QuantLib/QuantLib.py", line 18, in swig_import_helper
    return importlib.import_module(mname)
  File "/Users/tf/anaconda/lib/python3.6/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 978, in _gcd_import
  File "<frozen importlib._bootstrap>", line 961, in _find_and_load
  File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 648, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 560, in module_from_spec
  File "<frozen importlib._bootstrap_external>", line 922, in create_module
  File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed
ImportError: dlopen(build/lib.macosx-10.7-x86_64-3.6/QuantLib/_QuantLib.cpython-36m-darwin.so, 2): Symbol not found: __ZN8QuantLib10DateParser14parseFormattedERKSsS2_
  Referenced from: build/lib.macosx-10.7-x86_64-3.6/QuantLib/_QuantLib.cpython-36m-darwin.so
  Expected in: flat namespace
 in build/lib.macosx-10.7-x86_64-3.6/QuantLib/_QuantLib.cpython-36m-darwin.so

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "setup.py", line 252, in <module>
    'build_ext': my_build_ext
  File "/Users/tf/anaconda/lib/python3.6/distutils/core.py", line 148, in setup
    dist.run_commands()
  File "/Users/tf/anaconda/lib/python3.6/distutils/dist.py", line 955, in run_commands
    self.run_command(cmd)
  File "/Users/tf/anaconda/lib/python3.6/distutils/dist.py", line 974, in run_command
    cmd_obj.run()
  File "setup.py", line 58, in run
    module = __import__('QuantLibTestSuite', globals(), locals(), [''])
  File "test/QuantLibTestSuite.py", line 22, in <module>
    from date import DateTest
  File "test/date.py", line 18, in <module>
    import QuantLib
  File "build/lib.macosx-10.7-x86_64-3.6/QuantLib/__init__.py", line 21, in <module>
    from .QuantLib import *
  File "build/lib.macosx-10.7-x86_64-3.6/QuantLib/QuantLib.py", line 21, in <module>
    _QuantLib = swig_import_helper()
  File "build/lib.macosx-10.7-x86_64-3.6/QuantLib/QuantLib.py", line 20, in swig_import_helper
    return importlib.import_module('_QuantLib')
  File "/Users/tf/anaconda/lib/python3.6/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
ModuleNotFoundError: No module named '_QuantLib'

How I am trying to install QuantLib

*

*Install:

*

*Xcode 8.3.3

*Apple's Command Line Developer Tools, by running on terminal: xcode-select --install

*brew

*boost, by running on terminal: brew install boost

*Download the tars from sourceforge:

*

*QuantLib 1.10

*QuantLib-SWIG 1.10

*Extract the above to home directory:
       /Users/tf/

*Switch to QuantLib-1.10 by running on terminal:
       cd ~/QuantLib-1.10

*Run on terminal:
       #./configure --with-boost-include=/usr/local/include/ --with-boost-lib=/usr/local/lib/ --prefix=/usr/local/ CXXFLAGS='-O2 -stdlib=libc++ -mmacosx-version-min=10.9' LDFLAGS='-stdlib=libc++ -mmacosx-version-min=10.9' --disable-shared --enable-static

*Run on terminal:
       make && sudo make install

*Test C++ installation by running on terminal:
       cd Examples/BermudanSwaption && g++ -I/usr/local/include/ -I/usr/local/include/boost BermudanSwaption.cpp -o bermudanswaption -L/usr/local/lib/ -lQuantLib

*Switch to QuantLib-SWIG-1.10 by running on terminal:
       cd ~/QuantLib-SWIG-1.10
Run on terminal:
       ./configure CXXFLAGS='-O2 -stdlib=libc++ -mmacosx-version-min=10.9' LDFLAGS='-stdlib=libc++ -mmacosx-version-min=10.9'

*Make the C++ Python version by running on terminal:
       cd Python && /Users/tf/anaconda/bin/python3.6 setup.py build

*Install to anaconda by running on terminal:
       /Users/tf/anaconda/bin/python3.6 setup.py install

*Check by running on terminal:
       /Users/tf/anaconda/bin/python3.6 setup.py test

A: How I successfully installed QuantLib-SWIG, with Luigi's help

*

*Install:

*

*Xcode 8.3.3

*Apple's Command Line Developer Tools, by running on terminal: xcode-select --install

*brew

*boost, by running on terminal: brew install boost

*Download the tars from sourceforge:

*

*QuantLib 1.10

*QuantLib-SWIG 1.10

*Extract the above to home directory: /Users/tf/

*Switch to QuantLib-1.10 by running on terminal: cd ~/QuantLib-1.10

*Run on terminal: ./configure --with-boost-include=/usr/local/include/ --with-boost-lib=/usr/local/lib/ --prefix=/usr/local/ CXXFLAGS='-O2 -stdlib=libc++ -mmacosx-version-min=10.9' LDFLAGS='-stdlib=libc++ -mmacosx-version-min=10.9' --disable-shared --enable-static

*Run on terminal: make && sudo make install

*Test C++ installation by running on terminal: cd Examples/BermudanSwaption && g++ -I/usr/local/include/ -I/usr/local/include/boost BermudanSwaption.cpp -o bermudanswaption -L/usr/local/lib/ -lQuantLib

*Switch to QuantLib-SWIG-1.10 by running on terminal: cd ~/QuantLib-SWIG-1.10
Run on terminal: ./configure CXXFLAGS='-O2 -stdlib=libc++ -mmacosx-version-min=10.9' LDFLAGS='-stdlib=libc++ -mmacosx-version-min=10.9'

*Make the C++ Python version by running on terminal: cd Python && export CXXFLAGS='-O2 -stdlib=libc++ -mmacosx-version-min=10.9' && export LDFLAGS='-stdlib=libc++ -mmacosx-version-min=10.9' && /Users/tf/anaconda/bin/python3.6 setup.py build

*Install to anaconda by running on terminal: /Users/tf/anaconda/bin/python3.6 setup.py install

*Check by running on terminal: /Users/tf/anaconda/bin/python3.6 setup.py test


text:
Q: Is there a way to detect iOS safari while filtering out iOS Chrome, Firefox and other browsers? So for those who worked on iOS web applications probably know that due to Apple's policy, Chrome and other mobile browsers on iOS use a very ancient javascript engine. This is why we need to disable some of the rendering for Chrome and other none-safari browsers for iOS.
I had been reading this question and there is no useful answer there. Here are some of my approaches (failed):
Use is_iOS = navigator.userAgent.match(/(iPad|iPhone|iPod)/g) to detect if the browser is on iOS. And then use:
is_FF = navigator.userAgent.match(/(firefox)/g) and is_Chrome = navigator.userAgent.match(/(chrome)/g)
to kill off those firefox and chrome browsers.
I then realized all the browsers share identical user agent string with iOS safari. So I imagine the method should be running a javascript function that only Safari can run and then determine if the browser is Safari.

A: So, there's two schools of thought when choosing which native functionality you should use while working in browsers. One school of thought is checking the userAgent as you are doing here and using/removing features based on the userAgent.
The problem with checking userAgent is that it gets complicated really fast. You have already run into an interesting problem, but what will happen when you find that ie8 does not have the feature you are looking for?
A better solution may be to check if the feature exists in its current context without worrying about userAgent. A great example would be the new HTML5 audio element. Based on browser support, we can tell that it does not exist in ie8 nor Safari < 4.0. Instead of checking if the browser matches the ones mentioned here you can just check if the feature exists. As we know that the audio element is an instance of the Audio class. We can simply check:
if (window.Audio) {
    //load and play the HTML5 audio element here
}

That is much simpler than checking the userAgent.


text:
Q: Possible to run a given JUnit test programatically from my own Eclipse Plugin? How?
Possible Duplicate:
Call JUnit from other Eclipse Plugin

I am trying to have a set of JUnit4 tests be run programatically from my own Eclipse plugin. Is it possible? If yes, how?
Keep in mind what I'm looking for is to have Eclipse show up the usual TestsView, just as if I had done a standard run on a test manually (otherwise, I could have just initiated a standard run with the JUnit library classes).

A: After some digging..
JUnitLaunchShortcut jUnitLaunchShortcut = new JUnitLaunchShortcut();
jUnitLaunchShortcut.launch(structuredSelection, "run");


text:
Q: How do I find what my DPI setting is in OS X? I don't have a retina display, and display settings doesn't show any relevant info. How can I see what my DPI in OS X is?

A: You can easily calculate DPI on sites like this: https://www.sven.de/dpi/

A: You can calculate Pixels Per Inch using this PPI/DPI calculator tool!
Hope it helps!


text:
Q: Display sankey in old browser version I have problem with sorting sankey diagram in older version borwser - Chrome v49. My chart looks like this:
sankey
How to present sankey on familiar design in older borwser? In jsfiddle in newer browser version charts looks correctly. I've implemented sorting function but it doesn't work in older browser.
My jsfiddle
function sortData(fixedData) {
        return fixedData.sort((a, b) => b[2] - a[2]);
}

//const sortedData = sortData(fixedData);

const chart = Highcharts.chart('container', {

    title: {
        text: 'Highcharts Sankey Diagram'
    },

    series: [{
        keys: ['from', 'to', 'weight'],
        data: fixedData,
        type: 'sankey',
        name: 'Sankey demo series'
    }]
});

I'll be grateful for any solutions!

EDIT
So my script exactly look like this
Correctly works in OPERA v58.
Doesn't correctly works in CHROME v49

A: You need to sort your data by the sum of the values from the same name, not by individual values:
const fixedData = [
    ...
];

let sum;

fixedData.forEach(function(el1) {
    sum = 0;
    fixedData.forEach(function(el2) {
        if (el2[0] === el1[0]) {
            sum += el2[2]
        }
    });
    el1.push(sum);
});

function sortData(arr) {
    return [...arr].sort(function(b, a) {
        return b[3] - a[3]
    });
}

Live demo: http://jsfiddle.net/BlackLabel/td1ob0wg/


text:
Q: How do I get rid of the extra padding on these images? I have been trying to make a small game, where I ran into a error.

body{
  font-family: 'Raleway', sans-serif;
  margin: 0;
}

#title{
  text-align: center;
  font-size: 96px;
  margin-bottom: 5px;
}

.boardpic{
  margin: 0;
  padding: 0;
  width: 32px;
  height: 32px;
}

#board{
  background-color: black;
  padding: 3px;
  width: 512px;
  height: 512px;
}

    <title>
      Drawify | 0.0.1
    </title>
    <link rel="stylesheet" type="text/css" href="styles.css">
    <link href="https://fonts.googleapis.com/css?family=Raleway:700" rel="stylesheet">

      Drawify

As you can see above, the images still have padding, even though I set their margin and padding to 0. (I just realized that the images don't load as they are local. It is just a 32x32 image of white.)

A: Quick trick
set a font-size:0 on the board
#board{
  background-color: black;
  padding: 3px;
  width: 512px;
  height: 512px;
  font-size:0
}

Snippet

body{
  font-family: 'Raleway', sans-serif;
  margin: 0;
}

#title{
  text-align: center;
  font-size: 96px;
  margin-bottom: 5px;
}

.boardpic{
  margin: 0;
  padding: 0;
  width: 32px;
  height: 32px;
}

#board{
  background-color: black;
  padding: 3px;
  width: 512px;
  height: 512px;
  font-size:0;
}

    <title>
      Drawify | 0.0.1
    </title>
    <link rel="stylesheet" type="text/css" href="styles.css">
    <link href="https://fonts.googleapis.com/css?family=Raleway:700" rel="stylesheet">

      Drawify

A: Use float property. It will be better to use a float:right in your css to make the white spaces go away. Please have a try
.boardpic{
  margin: 0;
  padding: 0;
  width: 32px;
  height: 32px;
  float:right;
}


text:
Q: Python : How to get index of sub array with most elements in 2D array I've been looking for the most efficient method to get the index of a sub array with the most elements within it. For example :
array = [[a,b,c],[a,b],[a,b,c,d,e,f]]

The answer I should get would be 2.
How can I get the index of this without using a lengthy for loop process to check each block? Also without the use of Numpy.

A: >>> l = [[1,2,3], [4,5], [6,7,8,9,10]]
>>> max(enumerate(l), key=lambda sub: len(sub[1]))[0]
2

This will return the lowest index of an element with the maximum number of items (there could be more than one).
Unwrapping what's happening:
>>> list(enumerate(l))
[(0, [1, 2, 3]), (1, [4, 5]), (2, [6, 7, 8, 9, 10])]

-> iterable of (index, value) pairs.
>>> max(enumerate(l), key=lambda sub: len(sub[1]))
(2, [6, 7, 8, 9, 10])

-> (index, value) pair with the longest value (sublist).
>>> max(enumerate(l), key=lambda sub: len(sub[1]))[0]
2

-> just the index.
More readable alternative, but with two full passes over the data in the worst case:
>>> l.index(max(l, key=len))
2

Some low effort timings:
In [1]: l = [[0]*i for i in range(10000)]
In [2]: %timeit max(enumerate(l), key=lambda sub: len(sub[1]))[0]
2.05 ms ± 5.95 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
In [3]: %timeit l.index(max(l, key=len))
791 µs ± 4.22 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

Looks like the second version is faster even for a list with 10000 elements where the last element is the longest. This is probably due to only calling very efficient builtin functions instead of the custom lambda.
Conclusion:
Use l.index(max(l, key=len)).
(Final edit: the first version could still be faster if you happen to have a list holding objects where calling index would trigger some very costly __eq__ checks.)

A: Slightly roundabout, but does the job:
>>> a = [[1, 2, 3], [2, 3], [4, 5, 6, 7, 8]]
>>> max(enumerate(a), key=lambda (_, el): len(el))
(2, [4, 5, 6, 7, 8])

This gives both the element and its index. I'll leave it as an exercise for the reader to figure out how to reduce that to just the index.
If you need just the element, things are much simpler:
>>> max(a, key=len)
[4, 5, 6, 7, 8]

A: If you want to keep the systax simple,
>>> array = [[a,b,c],[a,b],[a,b,c,d,e,f]]
>>> array.index(max(array, key=len))
2

A: We can use lamba to sort the array by len and then just take the index of the last item
x = array.index(sorted(array, key=len)[-1])
# 2


text:
Q: How to save component data in an Angular service? I currently have a dice game component on Angular and the dice roll results are saved in a TypeScript array then displayed in HTML. Now I'm told I need to save the results in a service so that if I travel to another page and come back, the same results are still displayed. I've searched for ways to do it but I can only find ways to save data from a component to another, not in the same one. If anyone knows how I can achieve this, please help! Here is my code. Regards,
diceResults: number[] = [];

  rollTheDice() {
    for (let i in this.diceGame) {
      for (let a = 0; a < this.diceGame[i].numberOfDices; a++) {
        this.diceResults.push((Math.random() * (this.diceGame[i].numberOfFaces - 1) + 1))
      }
    }
  }

 <button *ngFor="let dice of diceResults" class="btn btn-large bg-warning m-1">{{ dice | number: '1.0-0' }}</button>

A: Building on @CallMeAnytimeOkay answer.
To declare a service, you would need to specify it as a provider in a module.
Let says in your app.module.ts for simplicity sake:
@NgModule({
  declarations: [AppComponent],
  imports: [...],
  providers: [YourServiceName],
})
export class AppModule {}

Then create the service file yourServiceName.service.ts:
@Injectable({providedIn: 'root'}) //Note that you will need to declare it as `@Injectable`.
export class YourServiceName {
  private _diceResults: number[] | null = null;
  public set diceResults(result: number[] | null) {
    this._diceResults = result;
    if(result != null) localStorage.setItem("diceResults", JSON.stringify(result));
    else localStorage.removeItem("diceResults");
  }

  public get diceResults(): number[] | null {
    if(this._diceResults == null) {
      const data = localStorage.getItem("diceResults");
      this._diceResults = JSON.parse(data)
    }
    return this._diceResults;
  }
}

Then declare the variable, getter, and setter as @CallMeAnytimeOkay mentioned.
To use the variable, you will need to inject the service into your component.
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent {
  diceResults: number[] = [];

  constructor(public yourService: YourServiceName) { }

  rollTheDice() {
    for (let i in this.diceGame) {
      for (let a = 0; a < this.diceGame[i].numberOfDices; a++) {
        this.diceResults.push((Math.random() * (this.diceGame[i].numberOfFaces - 1) + 1))
      }
    }
    this.yourService.diceResults = this.diceResults;
  }
}

A: You can save data in a service as follows:
export YourServiceName {
private diceResults: number[] = [];

}

Create a getter and setter in that service:
setDice(diceValues : number[]) {
this.diceResults = diceValues
}
getDice():void {
return this.diceResults
}

Then you can call these in components.

A: Create a new Service that should oversee the data saving and implement logic in that service.
It should have a fitting object to store the values.
It should have functions to manipulate that object, preferably with a parameter which holds the value to be persisted.
Then inject your service in your component where the dice results is created/calculated and then call the manipulation method from your service with the result as the parameter. For example when you press the button.
Further reading:
Angular Data Tutorial


text:
Q: Regex also capture everything besides capture group I have come up with a javascript regex that captures Street Numbers from an address string:
(\d+-\d+|\d+\/\d+|\d+\w{0,2})

now I would like to capture also the rest of the string (before and after) in additional capture groups.
Formats that I will test against:
Streetname 23
Streetname 12-15
Streetname 12/15
Streetname 13c
Streetname 34 with additional text

A: You may use this regex with 3 captured groups:
/^(.*?)\b(\d+(?:[\/-]\d+|\w{0,2}))(.*)$/gm

RegEx Demo
RegEx Details:

*

*^: Start

*(.*?): Match 0 or more characters at start (non-greedy) in 1st capture group

*\b: Word boundary

*(\d+(?:[\/-]\d+|\w{0,2})): Match street no in 2nd capture group

*(.*): 3rd capture group to match remaining text till end

*$: End

Flags

*

*g: Global match; find all matches rather than stopping after the first match

*m: Multiline


text:
Q: Razor Page throws error whenever change is made to cshtml without rebuilding the project Probably because I updated my .NET Core to latest 2.1 recently. Now in a Razor page project of mine, whenever I change the .cshtml content, the following error shows up:

An error occurred during the compilation of a resource required to
  process this request. Please review the following specific error
  details and modify your source code appropriately. Generated Code
The type 'RazorInjectAttribute' exists in both
  'Microsoft.AspNetCore.Mvc.Razor, Version=2.1.0.0, Culture=neutral,
  PublicKeyToken=adb9793829ddae60' and 'Microsoft.AspNetCore.Mvc.Razor,
  Version=2.1.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'
  +
          [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
  The type 'RazorInjectAttribute' exists in both
  'Microsoft.AspNetCore.Mvc.Razor, Version=2.1.0.0, Culture=neutral,
  PublicKeyToken=adb9793829ddae60' and 'Microsoft.AspNetCore.Mvc.Razor,
  Version=2.1.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'
  +
          [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
  The type 'RazorInjectAttribute' exists in both
  'Microsoft.AspNetCore.Mvc.Razor, Version=2.1.0.0, Culture=neutral,
  PublicKeyToken=adb9793829ddae60' and 'Microsoft.AspNetCore.Mvc.Razor,
  Version=2.1.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'
  +
          [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
  The type 'RazorInjectAttribute' exists in both
  'Microsoft.AspNetCore.Mvc.Razor, Version=2.1.0.0, Culture=neutral,
  PublicKeyToken=adb9793829ddae60' and 'Microsoft.AspNetCore.Mvc.Razor,
  Version=2.1.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'
  +
          [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
  The type 'RazorInjectAttribute' exists in both
  'Microsoft.AspNetCore.Mvc.Razor, Version=2.1.0.0, Culture=neutral,
  PublicKeyToken=adb9793829ddae60' and 'Microsoft.AspNetCore.Mvc.Razor,
  Version=2.1.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'
  +
          [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]

The error goes away when I perform a build (Ctrl Shift B). This is very annoying. Anyone knows a fix for it?