text:
Q: Node orm2 socket integration Local environment configuration
Win 7 64bit
Nodeclipse
MySQL Workbench
Application configuration
NodeJS              0.10.5
Express Framework   3.4.7
orm                 2.1.19
mysql               2.0.0-alpha8
Issue
I need to integrate orm2 functionalities and models to the socket.io part of my exoress application, in order to obtain the 100% of potentiality of these two technologies together.
Details
As it is said in the documentation of the orm2 npm extension, there is an easy way to integrate orm to application express framework. For my add-to-cart functionality I wish I catch the addToCart emitted event and use the orm to update and persist the cart.
I have integrated orm into express with this code and creating the models:
var connection = dbConnectionParam.protocol+'://'+dbConnectionParam.username+':'+dbConnectionParam.password+'@'+
dbConnectionParam.host+'/'+dbConnectionParam.database+'?pool=true&debug=true';
app.use(orm.express(connection, {
    define: function (db, models) {
        models.Formato = db.define('...

From the main app file I have:
var SessionSockets = require('session.socket.io');
var sessionSockets = new SessionSockets(
        io, sessionStore, express.cookieParser(loadconfig.loadKey('secret')));
sessionSockets.on('connection', function(err, socket, session) {
    socket.on('addToCart', function(data) { ...

Direct Question
Is there a way to integrate orm to socket.io framework?
If there is not, moving model definitions into an external node-module may be a good way, but how can I tune the db-connections performance? Pooling should be enough ?

A: You can retrieve the models using this steps.

*

*create a global variable i.e var db = null;

*In your page route, before returning the response, assign the db to the value of req.models i.e db = req.models

*Retrieve db in your socket and work with your models.


text:
Q: Confusing setter and getter? Why does using the setter throw 'str' object is not callable? I heard that using getter and setter functions such as set_value() and get_value() isn't Pythonic, and it is always better to use a property object with a setter and getter.
I ran the code below, and I get an error 'str' object is not callable'. When I search for this error, I find many examples of code where the class have an attribute and a method with the same name  (like if I write  self.name instead of  self.__name in the __init__ method).
But I have used two underscores before the attribute - so it shouldn't have happened here. It looks like when I try to call name.setter I actually call a property, and receive back the string stored in self.__name - and it is to this string I then tried to call something else.
But why? In all examples of setter, they have the same name as property and it doesn't lead to problem. Why does it throw an error here, and how do I fix it?
class Dog():
    def __init__(self, name):
        self.__name = name

    @property
    def name(self):
        return self.__name

    @name.setter
    def name(self, name_in):
        self.__name = name_in

dog = Dog("Barbos")
print(dog.name)                 # this works
dog.name("Juchka")              # and this throws an error:
                                # TypeError: 'str' object is not callable

A: You are still thinking in terms of methods here. A setter is not directly called. Instead, a setter is called when you assign to the name.
Use assignment:
dog.name = "Juchka"

Python translates this into a call to the setter method.
Just accessing dog.name calls the getter, and the getter method returned a string.  Calling is a separate expression from looking up the object to apply the call to; dog.name("Juchka") first executes dog.name, and applies the ("Juchka") call expression to the result of that attribute lookup. The attribute lookup returned "Barbos", and "Barbos"("Juchka") indeed does not work.
Demo:
>>> dog = Dog("Barbos")
>>> dog.name
'Barbos'
>>> 'Barbos'("Juchka")  # what really happens when you try to call dog.name(...)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable
>>> dog.name = "Juchka"
>>> dog.name
'Juchka'

redpajama_set_name: RedPajamaStackExchange


text:
Q: Most frequent remainder when 1000 is divided by all integers from 1 to 1000 Divide 1000 by each integer from 1 to 1000 and record their remainders.
Among the 1000 remainders recorded, what number do you see most frequently?

A: If you prefer a brute force computational method the following C code will yield an answer of 10.

int main(int argc, char *argv)
{
  // array to keep track of the number of each divisor present
  int divisor[1001] = {0};
/* counts how many of each divisor there are */
  for(int i = 1; i <= 1000; i++)
  {
    divisor[1000%i] = divisor[1000%i] + 1;
  }
int max = 0;
  int maxdivisor = 0;
/* finds most abundant divisor */
  for(int i = 0; i <= 1000; i++)
  {
    if(b[i] > max)
    {
      max = divisor[i];
      maxdivisor = i;
    }
  }
printf("%d",maxdivisor);
return 0;
}

A: Same experiment for 5041. Guess why. $5040 = 7! = 2^4 \cdot 3^2 \cdot 5 \cdot 7 \; . $
59 rem      1
21 rem     25
18 rem     49
16 rem     91
15 rem     73
14 rem     43
14 rem     19
14 rem    121
13 rem    145
12 rem      9
12 rem     61
12 rem    181
12 rem    169
12 rem    127
11 rem     85
11 rem     81
11 rem     41
11 rem    241
11 rem    113
10 rem     97
10 rem    361
10 rem     36
10 rem    289
10 rem    253
10 rem    211

Let's see, a divisor $n$ of $990$ gives a remainder of $10$ as long as $n$ itself is larger than 10.  $$ 990 = 2 \cdot 3^2 \cdot 5 \cdot 11 $$ has 24 divisors, of which 7 are no larger than 10: 1,2,3,5,6,9,10.  Then 24 - 7 = 17.
For comparison, 1000 has 16 divisors, so the remainder $0$ occurs 16 times.
17 rem     10
16 rem      0
12 rem     40
10 rem     20
 9 rem     64
 9 rem     28
 9 rem     16
 9 rem     12
 8 rem      8
 8 rem     76
 8 rem      4
 8 rem     34
 7 rem     48
 7 rem      1
 6 rem     88
 6 rem     80


text:
Q: Finding the campuses where are the classes are taught I have CAMPUS_IDs(NY1, PA1, VA1) and CLASS_IDs(around 10 classes)
So i have to create a table that has columns Campus_id and Class_id and assign in which campus the classes are taught. The problem is that some classes are taught in all campuses and some of them are taught in just one campus. How to design that table? I tried to create following table but it is messy:
_____________________
| class_id  |campus_id
---------------------
| math101   | NY1    |
---------------------
| pyt218    | PA1    |
---------------------
| C767      | VA1    |
---------------------
| pyt218    | PA1    |
_____________________

and the campus_id with class_id are foreign keys for another tables.

A: So you want to list all Campuses where the classes are taught? For an output like
class_id | campus_id
math101  | NY1, PA1
pyt218   | PA1, VA1, NY1
...

you can use the wm_concat function available in Oracle 10g:
with d as (
  select 'NY1' as campus_id, 'math101' as class_id from dual union all
  select 'PA1' as campus_id, 'math101' as class_id from dual union all
  select 'VA1' as campus_id, 'pyt218' as class_id from dual union all
  select 'PA1' as campus_id, 'pyt218' as class_id from dual union all
  select 'PA1' as campus_id, 'class3' as class_id from dual union all
  select 'VA1' as campus_id, 'class3' as class_id from dual union all
  select 'VA1' as campus_id, 'math101' as class_id from dual union all
  select 'NY1' as campus_id, 'class3' as class_id from dual
)
select class_id, wm_concat(campus_Id)
From d
group by class_id

In Oracle 11.2, there is a new function "listagg" which can be used to generate the same result:
with d as (
  select 'NY1' as campus_id, 'math101' as class_id from dual union all
  ...
)
select class_id, listagg(campus_id, ',') within group (order by campus_id)
From d
group by class_id


text:
Q: Parsing exception - jMeter json post processor; while extracting last element of json response I need to extract the last element from my json response, i am using json post processor.
json Path -

$.self[(@.length-1)].cashCardId

After using this path, i got this error -

Exception: Could not parse token starting at position 6. Expected ?,
  ', 0-9, *

After going through the error, i tried this jsonpath, but it throw "NO MATCH"

$.self['(@.length-1)'].cashCardId

But when i evaluate my jsonPath in an online evaluator, it works fine. Looks like there is any kind of bug in jmeter source, or may be i am producing some syntactical error.
{
    "gift": [
    ],
    "self": [
         {
            "cashInitialAmount": 2000.0,
            "serialNumber": "M79H3LSU",
            "creationTime": 1563783465000,
            "endDate": "2036-01-01",
            "cardType": "ECARD",
            "buyerId": 397,
            "cashPendingAmount": 2000.0,
            "cardSerial": "M79H3LSU",
            "purchaseOrderId": 6123682,
            "initialOffer": 0.0,
            "customerId": 397,
            "offerId": null,
            "cashCardId": 188503,
            "purchaseTime": 1563783465000,
            "lastModified": 1563783465000,
            "activationTime": 1563783465000,
            "cardNumber": "M79H3LSU",
            "cardStatus": "ACTIVE",
            "startDate": "2019-07-22"
        },
        {
            "cashInitialAmount": 2000.0,
            "serialNumber": "2OI5U2UV",
            "creationTime": 1563783382000,
            "endDate": "2036-01-01",
            "cardType": "ECARD",
            "buyerId": 397,
            "cashPendingAmount": 2000.0,
            "cardSerial": "2OI5U2UV",
            "purchaseOrderId": 6123680,
            "initialOffer": 0.0,
            "customerId": 397,
            "offerId": null,
            "cashCardId": 188502,
            "purchaseTime": 1563783382000,
            "lastModified": 1563783382000,
            "activationTime": 1563783382000,
            "cardNumber": "2OI5U2UV",
            "cardStatus": "ACTIVE",
            "startDate": "2019-07-22"
        },
        {
            "cashInitialAmount": 2000.0,
            "serialNumber": "S7EJDE77",
            "creationTime": 1563794985000,
            "endDate": "2036-01-01",
            "cardType": "ECARD",
            "buyerId": 397,
            "cashPendingAmount": 2000.0,
            "cardSerial": "S7EJDE77",
            "purchaseOrderId": 6123723,
            "initialOffer": 0.0,
            "customerId": 397,
            "offerId": null,
            "cashCardId": 188511,
            "purchaseTime": 1563794985000,
            "lastModified": 1563794985000,
            "activationTime": 1563794985000,
            "cardNumber": "S7EJDE77",
            "cardStatus": "ACTIVE",
            "startDate": "2019-07-22"
        }
    ]
}

A: For whatever reason, the jsonpath syntax works slightly differently for Goessner's jsonpath (JavaScript, https://goessner.net/articles/JsonPath/) vs. the Jayway implementation (Java, https://github.com/json-path/JsonPath)
For one, length is an array property in Goessner's, but in Jayway's its a function, so for e.g. $.self.length will work for Goessner but not for Jayway, you would need $.self.length()
For Jayway's array[-1] will give you the last element. So for your case, the expression $.self[-1].cashCardId should give you what you want.
The different implementations can be tested here: https://jsonpath.herokuapp.com/


text:
Q: Could I install my OSX system into and boot from the external hard drive I have a model of Retina MBP late 2013, my internal hard drive is failing and I do not want to by an ssd replacement...(quite expensive!).
I have a Sumsung MZ-750250B with a hard drive enclosure and with usb3.0 connection cable. Now could I install the OSX system into this hard drive and boot from it every time? And whether the reading and writing is fast enough?
Thank you.

A: Yes, this is possible. For full details refer to How to set up and use an external Mac startup disk. If you have any problems, feel free to come back here and search for an answer (or ask another question if you can't find a solution).
In terms of your Samsung MZ-750250B, if you actually meant a Samsung MZ-750250GB then this is actually a SSD and supports a sequential read speed of up to 540 MB/s and a sequential write speed of up to 520 MB/s. I think you'll find this is more than enough for everyday use.


text:
Q: Ubuntu init script Mon Jul 28 14:30:29 2014 : Error: Failed to load virtual server inner-tunnel
Mon Jul 28 14:30:29 2014 : Error: /etc/freeradius/sites-enabled/inner-tunnel[47]: Errors parsing authorize section.
Mon Jul 28 14:30:29 2014 : Error: /etc/freeradius/sites-enabled/inner-tunnel[131]: Failed to load module "sql".
Mon Jul 28 14:30:29 2014 : Error: /etc/freeradius/sql.conf[22]: Instantiation failed for module "sql"
Mon Jul 28 14:30:29 2014 : Info: rlm_sql (sql): Closing sqlsocket 0
Mon Jul 28 14:30:29 2014 : Info: rlm_sql (sql): Closing sqlsocket 1
Mon Jul 28 14:30:29 2014 : Info: rlm_sql (sql): Closing sqlsocket 2
Mon Jul 28 14:30:29 2014 : Info: rlm_sql (sql): Closing sqlsocket 3
Mon Jul 28 14:30:29 2014 : Info: rlm_sql (sql): Closing sqlsocket 4
Mon Jul 28 14:30:29 2014 : Error: Failed to load clients from SQL.
Mon Jul 28 14:30:29 2014 : Info: rlm_sql (sql): There are no DB handles to use! skipped 5, tried to connect 0
Mon Jul 28 14:30:29 2014 : Error: rlm_sql (sql): Failed to connect DB handle #0
Mon Jul 28 14:30:29 2014 : Error: rlm_sql_mysql: Mysql error 'Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)'
Mon Jul 28 14:30:29 2014 : Error: rlm_sql_mysql: Couldn't connect socket to MySQL server radius@localhost:radius
Mon Jul 28 14:30:29 2014 : Info: rlm_sql_mysql: Starting connect to MySQL server for #0
Mon Jul 28 14:30:29 2014 : Info: rlm_sql (sql): Attempting to connect rlm_sql_mysql #0
Mon Jul 28 14:30:29 2014 : Info: rlm_sql (sql): Attempting to connect to radius@localhost:/radius
Mon Jul 28 14:30:29 2014 : Info: rlm_sql (sql): Driver rlm_sql_mysql (module rlm_sql_mysql) loaded and linked
Mon Jul 28 14:30:28 2014 : Error: Failed to load virtual server inner-tunnel
Mon Jul 28 14:30:28 2014 : Error: /etc/freeradius/sites-enabled/inner-tunnel[47]: Errors parsing authorize section.
Mon Jul 28 14:30:28 2014 : Error: /etc/freeradius/sites-enabled/inner-tunnel[131]: Failed to load module "sql".
Mon Jul 28 14:30:28 2014 : Error: /etc/freeradius/sql.conf[22]: Instantiation failed for module "sql"
Mon Jul 28 14:30:28 2014 : Info: rlm_sql (sql): Closing sqlsocket 0
Mon Jul 28 14:30:28 2014 : Info: rlm_sql (sql): Closing sqlsocket 1
Mon Jul 28 14:30:28 2014 : Info: rlm_sql (sql): Closing sqlsocket 2
Mon Jul 28 14:30:28 2014 : Info: rlm_sql (sql): Closing sqlsocket 3
Mon Jul 28 14:30:28 2014 : Info: rlm_sql (sql): Closing sqlsocket 4
Mon Jul 28 14:30:28 2014 : Error: Failed to load clients from SQL.
Mon Jul 28 14:30:28 2014 : Info: rlm_sql (sql): There are no DB handles to use! skipped 5, tried to connect 0
Mon Jul 28 14:30:28 2014 : Error: rlm_sql (sql): Failed to connect DB handle #0
Mon Jul 28 14:30:28 2014 : Error: rlm_sql_mysql: Mysql error 'Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)'
Mon Jul 28 14:30:28 2014 : Error: rlm_sql_mysql: Couldn't connect socket to MySQL server radius@localhost:radius
Mon Jul 28 14:30:28 2014 : Info: rlm_sql_mysql: Starting connect to MySQL server for #0
Mon Jul 28 14:30:28 2014 : Info: rlm_sql (sql): Attempting to connect rlm_sql_mysql #0
Mon Jul 28 14:30:28 2014 : Info: rlm_sql (sql): Attempting to connect to radius@localhost:/radius
Mon Jul 28 14:30:28 2014 : Info: rlm_sql (sql): Driver rlm_sql_mysql (module rlm_sql_mysql) loaded and linked

this is the daloradius log, and someone told me , it is sql services haven't started, what is why i would like to delay the start daloradius service. belowing is my method to let daloradius service start after 200 seconds.
i would like to let the script sleep 200 seconds only start the daloradius. this is the command i had tried, but seem like not working.
start on login-session-start
script
sleep 200000
exec > freeradius -X
end script

OR
start on login-session-start
script
sleep 200000
freeradius -X
end script

and the script i save it as etc/init/VPN.conf

A: Here is your problem:
Mon Jul 28 14:30:29 2014 : Error: rlm_sql_mysql: Mysql error 'Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)'

This (2) means No such file or directory, i.e. the socket is not present.
Did you actually install the MySQL server?
sudo apt-get install mysql-server

Did you start the server?
sudo service mysql restart

A: Why not put (/bin/sleep 200 && /path/to/freeradius -X) in /etc/rc.local ?
http://wiki.ubuntuusers.de/rc.local
P.s: sleep-function uses seconds.


text:
Q: Read a list out of a txt element by element I have a txt file with about 5000 names("MARY","PATRICIA","LINDA",...). I want to put that names into a list in python. I searched for a solution, but I could only find some methodes to read txt files line by line or as one element, but I need to read it element by element. Is there a nice way to do that?

A: Python itself can't do that out of the box, as in you can't say something like text.readlines() and have it work on each separate element. What you can do is read the text and use the split method of strings. For exsmple, if the data is separated by commas, text.split(",") will return you a list that contains all the elements.
If words are separated by spaces only, you can just call the split() method without any arguments.

A: I may be a bit late, try this in python3:
with open("list.txt", "r") as f:
    for name in f.readlines():
        print(name)


text:
Q: Identify GCP HTTP(s) Cloud Function Invoker's identity inside Python code Is there a simple way to get the Invoker's username/email when a cloud function has been called using: gcloud functions call <function-name>
The cloud function is supposed to generate something for the user, but needs to use the username.
Passing it using --data parameter is not suitable as that way, we can't verify if the user is passing their own username or something else.
I've printed the headers inside the function, but they don't contain anything to do with the User who called it.

A: I ended up passing an id_token in the payload to the CF and inside it using a google python library to validate it and extract the user email.
Although not the same use case, I found some sample code here: https://developers.google.com/identity/one-tap/android/idtoken-auth
from google.oauth2 import id_token
from google.auth.transport import requests

# (Receive token by HTTPS POST)
# ...

try:
    idinfo = id_token.verify_oauth2_token(token, requests.Request())
    user_email = idinfo['email']
    #From here on I can split the email and get the username...
    #Now that I have the username, I can create the resources I needed with their username appended to the resource name.
except ValueError:
    # Invalid token
    pass

The token was passed to the CF in the payload data like this: {"identity_token":"$(gcloud auth print-identity-token)"} from user side.
Hopefully this comes in handy for someone that has similar use case.


text:
Q: iText 7 table's bottom border not being drawn I am using iText 7 for creating a table inside the PDF file. I have successfully created the table but the table's bottom border is not being drawn.
Screenshot of the Result:

My Code:
 private void Convert()
    {
        String dest = "D:/addingTable.pdf";
        var table = new Table(1, true);
        Border b = new SolidBorder(ColorConstants.RED, 5);
        table.SetBorder(b);
        using (var writer = new PdfWriter(dest))
        {
            using (var pdf = new PdfDocument(writer))
            {
                var doc = new Document(pdf);

                var name = new Paragraph("Hello World!").SetFontColor(ColorConstants.BLUE).SetTextAlignment(iText.Layout.Properties.TextAlignment.CENTER).SetFontSize(13);
                table.AddCell(new Cell().Add(name));
                doc.Add(table);
            }
        }
        Process.Start(dest);
    }

A: You explicitly create the Table with largeTable support set to true:
var table = new Table(1, true);

This allows to add large tables to a PDF without the whole table structure having to reside in memory at the same time: You can add it piecewise and flush all aggregated data every once in a while.
[add first few rows]
doc.Add(table);
[add next few rows]
table.Flush();
[add next few rows]
table.Flush();
...
[add final rows]
table.Complete();

In your code you forgot the final
table.Complete();

(or you simply did not want to create the table with largeTable support to start with).


text:
Q: How should I pass a large amount of Redux actions from a container to presentational component? I have the following container component which is connected to the Redux store. I wish to pass six actions to the LayerList presentational component.
LayerListContainer.jsx
import React from 'react';
import { connect } from 'react-redux'
import LayerList from '../components/LayerList'

// import actions
import * as LayerActions from '../actions/index'

export const LayerListContainer = ({ layers }) => (

     <LayerList layers={layers} /* I want to pass actions to this component/>

)

const mapStateToProps = state => ({
  layers: state.layers
})

// Use default export for the connected component (for app)
export default connect(mapStateToProps, LayerActions)(LayerListContainer)

Here are the actions I wish to pass:
actions/index.js
export const addLayer = (name) => ({
    type: ADD_LAYER,
    id: nextLayerId++,
    name,
})

export const removeLayer = (id) => ({
    type: REMOVE_LAYER,
    id
})

export const toggleDragLayer = (id) => ({
    type: TOGGLE_DRAG_LAYER,
    id
})

export const moveLayerIndex = (id, destinationIndex) => ({
    type: MOVE_LAYER_INDEX,
    id,
    destinationIndex
})

export const updateLayerColour = (id, colour) => ({
    type: UPDATE_LAYER_COLOUR,
    id,
    colour
})

export const toggleLayerVisibility = (id) => ({
    type: TOGGLE_LAYER_VISIBILITY,
    id
})

Perhaps you don't consider this to be a large amount of actions. If not I would still be interested to know what best practices are for future reference on passing many actions from a container component.

A: You can pass every properties of your container to your presentational using the ... spread operator syntax like this
export const LayerListContainer = props => (

    <LayerList {...props} />

);

Or if you just want to pass actions, you have to use bindActionCreators
import { bindActionCreators } from 'redux'

// ...

export const LayerListContainer = ({ layers, actions }) => (

    <LayerList layers={layers} actions={actions} />

);

// ..

const mapDispatchToProps = dispatch => ({
  actions: bindActionCreators(LayerActions, dispatch)
})

export default connect(mapStateToProps, mapDispatchToProps)(LayerListContainer)


text:
Q: Installing R on Ubuntu 20.04 I am trying to install R on ubuntu 20.04. using the following commands.
sudo add-apt-repository 'deb https://cloud.r-project.org/bin/linux/ubuntu focal-cran40/'

I get the following error.

E: The repository 'http://ppa.launchpad.net/marutter/rdev/ubuntu focal Release' does not have a
Release file.
N: Updating from such a repository can't be done securely, and is therefore disabled by default.
N: See apt-secure(8) manpage for repository creation and user configuration details.

When I tried to run R in the terminal, I get the following message

Command 'R' not found, but can be installed with:

Could you please help with the installation of R on Ubuntu

A: You are missing a slash in your ppa link. The correct command is
sudo add-apt-repository 'deb https://cloud.r-project.org/bin/linux/ubuntu/focal-cran40/'

Just a little advise: don't just copy everything from a guide or tutorial you read, try to actually understand it. And more importantly don't add random ppas you didn't at least look over. Thats quite the security issue.


text:
Q: Struggling from or struggling with? Why is the sentence "She is struggling from an illness" incorrect?
I know the correct sentence is "She is struggling with an illness", but  "struggling from" just sounds more natural to me.

A: This expression has more inspiring context behind. "Struggling with illness" sounds like you're strong enough to fight and win while "struggling from smth" associates with the action when you're trying to fend off.
But this is just my opinion.
E.g.: Footballers struggle with injuries.
Footballers struggle from poor form.

A: In my opinion based upon my research,"struggle" can be used as verb or noun. Now, I am explaining usage of "struggle" as 'verb' in detail:
Usage of "struggle" as verb:
1.a) struggle + (for something): It means to try very hard to do something when it is difficult or when there are a lot of problems.
e.g, a country struggling for independence. Here, struggle is coming
    with 'for' + 'something' is independence.
1.b) struggle + (adverb/preposition): to move somewhere or do something with difficulty.    e.g, He struggled out of his wheelchair.
1.c) struggle + (against/with somebody/something): to fight against somebody or something in order to prevent a bad situation or result. e.g, He struggled against cancer for two years. OR She is struggling with an illness.[Your Query's Answer is 'struggle' + 'with' + 'something']
1.d) struggle + (with somebody): to fight somebody or try to get away from them. e.g, Tim was hit in the mouth as he struggle with the enemies.
1.e) struggle + (with somebody) + (for something): to compete or argue with somebody, especially in order to get something. e.g, I am struggling with my neighbours for my property.
If you need the usage for "struggle" as a noun, I can do it.


text:
Q: Using if with Scanner in Java isn't working properly when comparing strings import java.util.*;

class Sept1Little {
    public static void main (String args []) {

        Scanner s = new Scanner(System.in);

        System.out.println("Hey! I'm not gonna program today o.o but I'm gonna do a little program :3");
        System.out.println("Let's play with some math!");
        System.out.println("Enter two numbers and magic will happen");
        System.out.print("Enter the first number: ");
        float a = s.nextInt();
        System.out.print("Enter the second number: ");
        float b = s.nextFloat();
        float c = (float) Math.pow( a, b);
        System.out.printf("The number is :%f\n" , c);
        System.out.println("We love Bernie Sanders!");
        System.out.println("Come on, let's push him over the line!");
        int poll1 = 30;
        System.out.println("Current poll amount: " + poll1);
        System.out.println("Let's add 7% and an extra 1%!");
        int poll2 = poll1 + 7;
        int poll3 = ++poll2;
        System.out.println("Bernie Sanders would get :" + poll3 + ". Bernie would get a better percentage than Hillo Clinto-Money");
        System.out.println("Write in the best US President Nominee: ");
        String president = Keyboard.readString();
        if (president.equals("Bernie Sanders")){
            System.out.println("You chose Bernie Sanders.");

        }
        else if (president.equals("Donald Trump")) {
            System.out.println("You chose Donald Trump");

        }
        else if (president.equals("Hillary Clinton")) {
            System.out.println("You chose Hillary Clinton ");

        }
        else {
            System.out.println("Choose someone we know...");

        }
        System.out.println("Let's calculate how much money you owe the govt by... SQUARE ROOTING IT!");
        System.out.print("Enter the amount of money you owe the govt: ");
        float debt1 = Keyboard.readFloat();
        System.out.printf("The amount is now :%f\n" , Math.sqrt(debt1));
        System.out.println("Welcome to the Euro to Dollar Convertor!");
        System.out.print("Enter the amount in US Dollars you wish to convert to Euro: ");
        float euro1 = Keyboard.readFloat();
        final float rate = (float) 1.13;
        System.out.printf("The amount in Euro is %f\n" , euro1 / rate);
    }
}

As you can see, I am using Keyboard.readString(); when I ask for the nominee. When I use s.readLine();, it doesn't work, it skips to the else clause and then it crashes since it takes the president input for the float value afterwards. I'm sorry that it is a bit political but I didn't bother fiddling with it. When I put "Bernie Sanders" as "BernieSanders", I don't get the error, anyone knows why?

A: I guess that it is because s.nextFloat(); and s.nextInt(); only reads the float and the int, respectively, not the full line so the cursor of the Scanner it's after the float or the int and not in the next line. Here an example:
If your input it's:
5 Bench
Prove

And you have in your code:
a= s.nextInt(); //5
b= s.nextLine(); //" Bench"

Why it isn't catching the Prove value? Because after using s.nextInt() the cursor of the Scanner it's after the 5 and not in the next line (the line in which we have Prove). To avoid it you have to read the rest of the line (useless for you because you don't want it) but without getting this value. Like this:
a= s.nextInt(); //5
s.nextLine(); //We go to the next line
b= s.nextLine(); //"Prove"

P.S.: You have to use s.nextLine(); each time you use a s.nextInt(); or s.nextFloat(); as the example that I put above.
I expect it will be helpful for you!


text:
Q: Changing schema of avro file when writing to it in append mode I'm looking for a way to modify the schema of an avro file in python. Taking the following example,  using the fastavro package, first write out some initial records, with corresponding schema:
from fastavro import writer, parse_schema

schema = {
    'name': 'test',
    'type': 'record',
    'fields': [
        {'name': 'id', 'type': 'int'},
        {'name': 'val', 'type': 'long'},
    ],
}
records = [
    {u'id': 1, u'val': 0.2},
    {u'id': 2, u'val': 3.1},
]
with open('test.avro', 'wb') as f:
    writer(f, parse_schema(schema), records)

Uhoh, I've got some more records, but they contain None values. I'd like to append these records to the avro file, and modify my schema accordingly:
more_records = [
    {u'id': 3, u'val': 1.5},
    {u'id': 2, u'val': None},
]
schema['fields'][1]['type'] = ['long', 'null']

with open('test.avro', 'a+b') as f:
    writer(f, parse_schema(schema), more_records)

Instead of overwriting the schema, this results in an error:
ValueError: Provided schema {'type': 'record', 'name': 'test', 'fields': [{'name': 'id', 'type': 'int'}, {'name': 'val', 'type': ['long', 'null']}], '__fastavro_parsed': True, '__named_schemas': {'test': {'type': 'record', 'name': 'test', 'fields': [{'name': 'id', 'type': 'int'}, {'name': 'val', 'type': ['long', 'null']}]}}} does not match file writer_schema {'type': 'record', 'name': 'test', 'fields': [{'name': 'id', 'type': 'int'}, {'name': 'val', 'type': 'long'}], '__fastavro_parsed': True, '__named_schemas': {'test': {'type': 'record', 'name': 'test', 'fields': [{'name': 'id', 'type': 'int'}, {'name': 'val', 'type': 'long'}]}}}

Is there a workaround for this? The fastavro docs for this suggest it's not possible, but I'm hoping someone knows of a way!
Cheers

A: The append API in fastavro does not currently support this. You could open an issue in that repository and discuss if something like this makes sense.


text:
Q: How to define a strongly coupled type depends on a defined object type MyObjType = {
  a: number,
  b?: string
}

type Column<Data, DataKey extends keyof Data> = {
  accessor: DataKey,
  value: Data[DataKey]
}

const column: Column<MyObjType, keyof MyObjType>[] = [{
  accessor: 'a',
  value: "" // (property) value: string | number | undefined
}]

But I want the type of value to be number when accessor is 'a', value is undefined | string when accessor is 'b'
how to define the Column type to make it works?

A: Got Answer from @captain-yossarian


text:
Q: Insert part of a PL/SQL output into a message body and email it I am trying create a PL/SQL program that will allow me to automatically send out emails from the data picked up in the output of the SQL command.
My current output columns are
DB_NAME    SC_NAME    RO_NAME    User_NAME    EMAIL_ID.

There are about 293 rows in the output. Out of those 293... there are about 11 distinct outputs in the the User_NAME column.
Now for example: One of the distinct outputs in the User_NAME column is John. Now... for every row that is John... I want to send an email to the email id mentioned in the corresponding EMAIL_ID row.
How do I extract that information to send an email based on each of the distinct outputs?
*EDIT*
http://i.imgur.com/0q5pAQS.png
If you look at the image above... I want to email to JMGR@gmail.com the first three rows ( where User_name is JOHN). And then i want to email MMGR@gmail.com the 4th row (where User_name is MIKE)
And so forth.
The image above is all i have so far.

A: You want to use the LISTAGG() function:
select EMAIL_ID,
       LISTAGG(DB_NAME || ' ' || SC_NAME || ' ' || RO_NAME, ', ') WITHIN group(order by DB_NAME, SC_NAME, RO_NAME) MESSAGE
 from table
 group by EMAIL_ID


text:
Q: What is the directory of ActionScript 3.0 classes files? Im trying to find transformGestureEvent class file on my windows, have looked through Adobe Flash CC folder and also appData but couldnt find it.

A: TransformGestureEvent is part of the built-in classes of Flash Player, AIR and Flash Lite.
You can find it on the package: flash.events


text:
Q: Too many query rows: 50001 in export csv I need to create a axpex class that create and send a csv report.
In a @future static method I have this query:
List<Activity__c> activityList = [
SELECT fields....
, (SELECT Id, fields... FROM ContactAttendances__r WHERE ...)
, (SELECT Id, fields... FROM UserAttendances__r WHERE ...)
FROM Activity__c WHERE Active__c = true AND ...];

...More process with this activityList and call another private methods...
Finally I create blob and send it via email.
The query returns 9000 rows without subquery.
With subquery throws a limit exception (Too many query rows: 50001)
I see apex batch but it does not work for data return, only for insert/updates/etc.
Any idea to avoid this error?

A: Your issue here is that you are using a future method and that the limit of records returned with a SOQL query in future method is same as synchronous limit, i.e., of 50,000. If you refer to the Execution Governors and Limits, and refer "Per-Transaction Apex Limits" section, you will find this detail in there as below, which does not differentiate this particular limit but instead is applicable to both sync and async transactions.

This table lists limits for synchronous Apex and asynchronous Apex (Batch Apex and future methods) when they're different. Otherwise, this table lists only one limit that applies to both synchronous and asynchronous Apex.
Total number of records retrieved by SOQL queries -- 50,000

So irrespective of a synchronous or asynchronous transaction, the number of records returned is maximum 50,000 and that is where your method is failing.

As for your question:

Any idea to avoid this error?

What you need here is to use an Apex Batch instead of a future method. And because future or batch will be both executed asynchronously, so you may just like to promote your code in a batch class.
In the same link for governor limits, you will notice this statement as below:

These limits count for each Apex transaction. For Batch Apex, these limits are reset for each execution of a batch of records in the execute method.

This signifies that every batch which is capable of handling a maximum of 50 million records returned by Database.QueryLocator (anything more than that still fails) but in batches sent to the execute method.
Best practices around future method also mentions to use a batch for performance reasons.

Consider using batch Apex instead of future methods to process large numbers of records.


text:
Q: Create unique URL in PHP for each entry So i am trying to create independent web pages via PHP for practice im trying to learn.
What i want to do is to create unique URLs for each entry on my site.
Lets say my website is simple, it just asks the user to enter a name and records it to the database, and creates a unique URL for that user so he can go to his url and view his name.
I am looking to create a URL for each user lets say upto 8 characters a-z A-Z 0-9 that would look like url.com/uI53841a
So if John goes to create a website it creates a url he can visit url.com/uI53841a for example.
My database would look like this below:
create table if not exists `entry` (
    `uniqueURL` VARCHAR(8),
    `name` VARCHAR(16),
    primary key (`uniqueURL`)
) engine=innodb default charset=utf8;

How would i go about generating a unique ID for each person who submits their name to my site? And how do i go about making sure there are never any duplicates?
I am new to PHP and trying to learn, i see you can create md5 hashses but how can you randomize that and check theres no duplicates?

A: Checkout this library.
Small snippet from docs:
<?php

$hashids = new Hashids\Hashids();

$id = $hashids->encode(1, 2, 3);
$numbers = $hashids->decode($id);

var_dump($id, $numbers);

More info from official site.
P.S.
With primary key contrait for uniqueUrl you may check the result of insert with php. If it fails, it means that constrait is violated.
You may simply generate url based on other unique string, for example use raw id as url (as Dagon said in comments to the answer). But you should use aforementioned lib if you do not want to expose your database ids to the user (it's quote from github).

A: Heres one i found and worked on a little but which also works well!
function keygen()
{
    $chars = "abcdefghijklmnopqrstuvwxyz";
    $chars .= "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    $chars .= "0123456789";
    while (1) {
        $key = '';
        srand((double) microtime() * 1000000);
        for ($i = 0; $i < 8; $i++) {
            $key .= substr($chars, (rand() % (strlen($chars))), 1);
        }
        break;
    }
    return $key;
}


text:
Q: How can I loop through this array using javascript? Given this script:

<video id="myVideo" width="1000" height="800" controls autoplay loop>

  Your browser does not support the video tag.
</video>

 Play

Now I want to fill in myLoop function.
I want to loop each pairs 5 times before jump to the next pair in the array.
For example,
-the first pair: 'journey27.mp4', loop "[1, 2]" 5 times
then the next pair: 'journey27.mp4', loop "[5, 7]" 5 times
then the next pair: 'journey28.mp4', loop "[10, 12]" 5 times
then the next pair: 'journey28.mp4', loop "[13, 17]" 5 times
and so on
Note: The playVideo function above works
How can I loop through this array using javascript?

A: Use global variables to hold the current indexes and repetition count for the video. Increment the repetition count, and when reaches 5 increment the indexes.
There's no loop, the iteration happens when the user clicks the link.

var sentences=
[
 ['journey27.mp4',
  [
    [1, 2],
    [5, 7]
  ]
 ],
 ['journey28.mp4',
  [
    [10, 12],
    [13, 17],
    [25, 36]
  ]
 ],
 ['journey30.mp4',
  [
    [13, 15],
    [15, 19],
    [21, 30]
  ]
 ]
];

function playVideo(myUrl, startTime, endTime) {
  console.log(`Playing ${myUrl} from ${startTime} to ${endTime}`);
}

let video_index = 0;
let time_index = 0;
let repeat = 0;

function myLoop(){
  playVideo(sentences[video_index][0], sentences[video_index][1][time_index][0], sentences[video_index][1][time_index][1]);
  repeat++;
  if (repeat >= 5) {
    repeat = 0;
    time_index++;
    if (time_index >= sentences[video_index][1].length) {
      time_index = 0;
      video_index++;
    }
  }
}
 Play


text:
Q: How much memory is required to represent an address? Consider the following piece of code.
int var;

cout << (long)&var;

My doubt is how do we know that long int has sufficient width to hold the memory location indicated by &var. What if it is not sufficient?
The full code which I am executing...
//: C03:YourPets2.cpp
// From Thinking in C++, 2nd Edition
// Available at http://www.BruceEckel.com
// (c) Bruce Eckel 2000
// Copyright notice in Copyright.txt
#include <iostream>
using namespace std;

int dog, cat, bird, fish;

void f(int pet) {
  cout << "pet id number: " << pet << endl;
}

int main() {
  int i, j, k;
  cout << "Address size " << sizeof(&f) << endl;
  cout << "Long size " << sizeof(long) << endl;
  cout << "Intptr size " << sizeof(intptr_t) << endl;
  cout << "f(): " << &f << endl;
  cout << "f(): " << (long)&f << endl;
  cout << "f(): " << (long long)&f << endl;
  cout << "dog: " << (long)&dog << endl;
  cout << "cat: " << &cat << endl;
  cout << "bird: " << &bird << endl;
  cout << "fish: " << (long)&fish << endl;
  cout << "i: " << (long)&i << endl;
  cout << "i: " << (long long)&i << endl;
  cout << "j: " << (long)&j << endl;
  cout << "k: " << (long)&k << endl;
} ///:~

The result which I am getting:
Address size 4
Long size 4
Intptr size 4
f(): 1
f(): 134514548
f(): 134514548
dog: 134521044
cat: 0x804a0d8
bird: 0x804a0dc
fish: 134521056
i: -1074729380
i: -1074729380
j: -1074729384
k: -1074729388

A: You don't. It's possible - if unlikely - for pointers to have larger storage requirements than any integer. If there is an integer type that is suitable then there will be a typedef for it std::intptr_t (and possible also std::uintptr_t) defined in <cstdint> (C++11 only).
You can test for the presence of intptr_t at the preprocessor stage by testing for the definedness of the macro INTPTR_MAX (or INTPTR_MIN) after #include <cstdint>.
If you just want to print a pointer value using std::cout then you can cast to void* (unnecessary for int* but necessary for char*) and use << directly without a cast to an integer type.

A: You can use an assert (or a different kind of check).
The check should be in the form

assert( sizeof( &var ) <= sizeof(long) );


text:
Q: Using select method in form_for in rails I would like to use a method inside a form_for in rails to create a select tag with options where the value of the options come from one array and the options enclosed by the option tags come from another array.
For example, the first option would be:
<option value = Array1[0]> Array2[0] </option>

How do I do this?  Can I use 'select' such as:
= form_for @activity do |f|
  = f.select(Array1, Array2, {:selected => nil, :prompt => 'Select Stage'})

I couldn't get something like this working, even though this format seemed consistent with options_for_select as described in the rails API at api.rubyonrails.org.

A: Try this:
= f.select(:method, Array2.zip(Array1), { :selected => nil, :prompt => 'Select Stage' })

The zip method will combine two arrays to make one two-dimensional array.
So, for example, [1,2,3].zip([4,5,6]) will return [[1,4], [2,5], [3,6]].
select can then interpret this as a list of option texts and option values.
Given [['Male', 'm'], ['Female', 'f']], select will return
<option value="m">Male</option>
<option value="f">Female</option>


text:
Q: Proper activerecord connection pool size with sidekiq and postgres for multiple sidekiq processes? I'm running 7 sidekiq processes (currency set to 40) plus a passenger webserver, connecting to a postgres database. Rails pool setting is set to 100 and and postgres max_connections setting is also the default 100.
I just added a new job class where each job makes multiple postgres requests, and I started getting this error on many sidekiq jobs and sometimes on my webserver: PG::ConnectionBad: FATAL: remaining connection slots are reserved for non-replication superuser connections
I tried increasing postgres max_connections to 200, and the error still occurs. Then I tried reducing the activerecord pool setting to 25 (25 connections for each process = 200 total connections), figuring I might start getting DB connection timeout errors but at least it would stop the "no remaining connection slots" errors.
But I'm still getting the remaining connection slots are reserved error.
The smarter way to to deal with this issue might be to load the important postgres data that I keep reusing into redis, and then access it from redis - which obivously plays much more nicely and quickly with sidekiq. But even as I do that, I'd like to understand what's going on here with the postgres connections:

*

*Am I likely leaking connections, and is that something I should be
managing inside the sidekiq jobs?

(see Releasing ActiveRecord connection before the end of a Sidekiq job)

*

*Should I look into more obscure things like locking/contention issues
or threading issues with the PG driver?

(see https://github.com/mperham/sidekiq/issues/594. I think I'm using ActiveRecord pretty simply without much obscure or abnormal logic for a rails app...)

*

*Or maybe I'm just not understanding how the ActiveRecord pool setting
and postgres max_connection settings work together...?

A: My situation may be too specific to help many others running into this error, but I'll share what I've found out in case it helps to point you in the right direction.
Am I likely leaking connections, and is that something I should be managing inside the sidekiq jobs?
No, not likely. Sidekiq's default middleware includes a hook to close connections even if a job fails. It took me a long time to understand what the heck that means, so if you're not sure what that means, tl;dr: Sidekiq won't leak connections if you're using it normally.
Should I look into more obscure things like locking/contention issues or threading issues with the PG driver?
Unless you're using a very obscure setup, its probably something more simple.
Or maybe I'm just not understanding how the ActiveRecord pool setting and postgres max_connection settings work together...?
Anyone can feel free to correct me if I'm wrong, but here's the guidelines I'm going on for pool settings, max_connections, and sidekiq processes:
Minimum DB pool size = sidekiq concurrency setting
Maximum DB pool size* = postgres max_connections / total sidekiq processes (+ leave a few connections for web processes)
*note that active record will only create a new connection when a new thread needs one, so if 95% of your threads don't use postgres at the same time, you should be able to get away with far fewer max_connections than if every thread is trying to check out a connection at the same time.
What fixed my problem:
On my Ubuntu machine, I had changed the vm.overcommit_memory setting to 1 as recommended by redis, so that it can spawn it's write to disk process without breaking the machine.
This is the right way to go, but leaves postgres vulnerable to being killed by OOM (out of memory) Killer if memory usage gets too high. Turns out that postgres will stop allowing new connections if it receives a kill signal from the OOM Killer.
Once I restarted postgres, sidekiq was able to connect again. The longer term solution is simply to work on memory leaks and make sure memory usage doesn't get too high. Also it's possible to configure the OOM killer to prioritize killing my sidekiqs before killing postgres.


text:
Q: Is $f(\frac{x+y}{x-y})=\frac{f(x)+f(y)}{f(x)-f(y)}$ an odd function? This is what I did to prove that:

But I am not sure if the proof is valid.

A: If you swap the roles of the variables $x$ and $y$, the argument in the LHS gets negated and the value of the RHS gets negated as well.
$$f\left(\frac{y+x}{y-x}\right)=f\left(-\frac{x+y}{x-y}\right),$$
$$\frac{f(y)+f(x)}{f(y)-f(x)}=-\frac{f(x)+f(y)}{f(x)-f(y)}.$$

A: Well, even if $f (-\alpha ) = f (\alpha) $, then $$\frac {f (-y)+f (-x)}{f (-y)-f (-x)} = \frac {f (y)+f (x)}{f (y)-f (x)} $$ $$=-\frac {f (x)+f (y)}{f (x)-f (y)} $$ $$=-f (\frac {x+y}{x-y}) $$
Hope it helps.


text:
Q: How can I rejoin a Windows machine to the domain without losing user data if trust relationship on machine was broken Long story short. A new machine was added to our domain with the same machine name as a pre-existing machine.
Rather than receiving an error from the domain when this was being done, it simply replaced the older machine. As a result, the user is no longer able to login to the domain on the old machine.
How can I rejoin that machine to the domain without losing that user's data/configuration?
The quick solution seems to be unjoin the domain using the local admin user on that machine and then rejoining it. However, I believe this will create a new user when the user logs back in meaning they'll lose everything they have setup such as desktop icons and programs installed only for that user.
How can I get around this problem?

A: Remove client from domain, rename client, rejoin domain.  The user account and configuration should be there unless there's something else going on.


text:
Q: Angular dropdown not clearing items So I have a form with two dropdowns (or select tags) one for countries and the other for states. The idea is that when you select a country that selection causes a call to be made that gets you a list of states/provinces for that given country. So it works for the most part however when the update to states list happens instead of clearing the list and adding the new items it just adds the new items to the existing list. Even though I set the component member back to an empty array. I am not sure what I am doing wrong and would love some insight from my fellow developers.
Here is the HTML

        Country:
        <select class="form-control" [(ngModel)]="Country"
            (change)="countryChanged($event.target.value)">
          <option *ngFor="let c of countries" [ngValue]="c.country_code">
             {{c.country_name}}</option>
        </select>

        State:
        <select class="form-control" [(ngModel)]="State">
          <option *ngFor="let s of states" [ngValue]="s.state_code">
              {{s.state_name}}</option>
        </select>

And here is the component Type Script
 countries: Country[];
    states: State[];

    countryChanged(selected: string) {
    if (selected === undefined) {
      selected = this._customer.country;
    }

    if (selected.length > 2 ) {
      selected = selected.substr(selected.length - 2, 2);
    }

    this.states = [];
    this.getStates(selected).subscribe(data => {
      this.states = data as State[];
    })
  }

  getCounties() {
    return this.http.get(this.config.envSpecific.apiUrl + '/api/country');
  }

  getStates(countryCode: string) {
    return this.http.get(this.config.envSpecific.apiUrl + '/api/states/' + countryCode);
  }

A: Not sure why this fixed it but when I put some code in to handle undefined states better it started working correctly


text:
Q: Why are there differences in data when comparing table to itself? TSQL I'm comparing two tables that should have the same data.  I've got a couple of different queries that are supposed to return rows that don't match.  However, the queries return rows that DO match.  I'm not sure why.  Here is an example:
select
which = 'TableA',
*
from (
select * from compareTempA
except
select * from compareTempB
) x
union all
select
'TableB',
*
from (
select * from compareTempB
except
select * from compareTempA

) x
order by dateindex, empid, serviceSales, productSales

For some reason I get results like the following:

As you can see these rows appear to match.  I've also tried:
select sum(case when A.productSales = B.productSales then 0 else 1 end) from
compareTempA A
join compareTempB B
on A.dateindex = B.dateindex
and A.empid = B.empid
and A.storeid = B.storeid

To which I get 3011.  I'm baffled because the data is supposed to be the same in both tables.  The only thing I can think of is that I formed the two tables by inserting into each of them in the following way:
insert into compareTempA
select * from someView

And I did the same for compareTempB.  I tried truncating the tables first and reinserting.  Please help!

A: The only thing that comes to my mind is that you are not using the same data type for the column productSales on both tables.
For example, if your data type on compareTempA is float and on compareTempB is decimal, that's exactly what should happen.
By the way, this happens even if both columns are float, due to the fact that float is not a precise datatype.
I suggest that you change your datatype to a precise one, like decimal.
"Approximate-number data types for use with floating point numeric data. Floating point data is approximate; therefore, not all values in the data type range can be represented exactly. The ISO synonym for real is float(24)."
Source: https://learn.microsoft.com/en-us/sql/t-sql/data-types/float-and-real-transact-sql?view=sql-server-2017
Similar problems:
Same problem here - https://stackoverflow.com/questions/16149966/comparing-2-float-values-in-sqlserver
Best Pratices Red Gate - https://documentation.red-gate.com/codeanalysis/best-practice-rules/bp023
Another question about floats and precise comparisions - https://stackoverflow.com/questions/10737004/should-we-use-float-as-primary-key-in-sql-server


text:
Q: Bind dropdown and textbox list dynamically in angular 2 I have one requirement for change password. There is a question dropdown and a textbox for answers. This will be generated dynamically in loop. I am able to generate it with below code:

<ng-template let-i="index" let-c="count" ngFor let-question [ngForOf]="QuestionModel">

<select class="form-control custom-select col-12" required >
        <option *ngFor="let myQuest of QuestionModel;"  [value]="myQuest.QuestionID"> {{myQuest.SecurityQuestion}} </option>
</select>

<input type="text" [(ngModel)]="QuestionModel[i]['SecurityAns']" [ngModelOptions]="{standalone: true}"   />

</ng-template>

I am using two way binding. The problem is that i cannot identify which answer belongs to which question. Below is the model where i have to update the selected answer.

{QuestionID: "0", SecurityQuestion: "What city were you born in?", SecurityAns: null}
{QuestionID: "1", SecurityQuestion: "What is the name of your best friend?", SecurityAns: null}
{QuestionID: "2", SecurityQuestion: "What is the name of your pet?", SecurityAns: null}

A: Try putting an ngModel on the select element:
<select [(ngModel)]="selectedValue">

A: Add this to the select element:
<select (change)="onQuestionChange($event)" >
Create the onQuestionChange() method in your ts file. The event argument will hold the property that you have binded to the value property of the <option> element.
Then you can get the question associated to this I'd from your QuestionModel

A: Finally, i have found a work around for my problem. My updated code is as below:

 <ng-template let-i="index" let-c="count" ngFor let-question [ngForOf]="QuestionModel_ddl">

                                Security Question {{i+1}} :

                                <select class="form-control custom-select col-12" (change)="UpdateModelDtls($event, i)" required>
                                    <option value=""></option>
                                    <option *ngFor="let myQuest of QuestionModel_ddl;" [value]="myQuest.QuestionID"> {{myQuest.SecurityQuestion}} </option>
                                </select>

                                Security Answer :

                                <input type="text" [(ngModel)]="QuestionModel_ddl[i]['SecurityAns']" required (focusout)="UpdateSeqAnswer($event, i)" [ngModelOptions]="{standalone: true}" />

                    </ng-template>

I have added two method UpdateModelDtls and UpdateSeqAnswer. And in Component, have defined it as

UpdateModelDtls($event: any, i: any) {
        debugger;

        var item = this.selectedDtls.find(x => x.Index == i);
        /* Check if item already present in selectedDtls array. If present, show msg as 'This question is already selected, please select a different question.'  */
        var IsPresent = this.selectedDtls.find(x => x.QID == this.QuestionModel_ddl[($event.target.selectedIndex - 1)]['QuestionID'] && x.Index != i);

        /* In case all the questions dropdowns are selected */
        if (item) {
            /* Remove the changed dropdown from selectedDtls array since we are making it as not-selected */

            var index = this.selectedDtls.indexOf(item);
            if (index > -1) {
                this.selectedDtls.splice(index, 1);
            }
        }

        if (IsPresent) {
            this.IsDuplicateQuestion = true;
            $event.target.selectedIndex = -1;
        }
        else {

            this.IsDuplicateQuestion = false;
            let item = {
                QID: this.QuestionModel_ddl[($event.target.selectedIndex - 1)]['QuestionID'],
                Index: i,
                SeqAns: this.QuestionModel_ddl[i]['SecurityAns']
            };
            this.selectedDtls.push(item);
        }
    }

    UpdateSeqAnswer($event: any, i: any) {
        debugger;
        var item = this.selectedDtls.find(x => x.Index == i);
        if (item)
            item.SeqAns = $event.target.value;
    }

export class SelectedDtls {
    QID: string;
    Index: number;
    SeqAns: string;
}

These two methods help to keep a temporary array (SelectedDtls) updated with the selected values.


text:
Q: Run Symfony command with Cronjob Kubernetes Each minute, I have a K8S Cronjob who run Symfony command. My problem is the huge time my pod warmup Symfony cache before execute the command : 56s ...
I search a solution for stock the cache in docker container but i can't execute cache:warmup during docker build, because commande need database and redis up.
Do you have a solution for me ?
Thanks !


text:
Q: iOS - Centering a webview with constraints At some recent point I started building an existing app with Xcode 11 and the iOS 13 SDK, and got hit with a few of the changes to how layout works.
First of all was the change to default view controller presentation, which was easy enough to get around by setting it explicitly to fullscreen.
More frustrating, however, is the constraint-based layout I've been using to center a webview (WKWebView) on the view controller's main view. The complication is that I need to adjust the width of the webview programmatically.
This was working nicely previously by adjusting the constraint constant for the webview's leading and trailing constraints. Now, however, it doesn't seem to adjust properly. I've tweaked pretty much every variable in the layout trying to get back to the previous behavior without success.
The basic structure looks like this:

The webview's layout info is:

And the three horizontally impacting restraints are:

(I've tried changing the webview's layout to Automatic from Translates Mask, adding/removing autoresizing constraints, etc.)
Anything immediately jump out that I'm doing wrong?


text:
Q: Cannot convert character to integer in c++ in loop Why my code shows nothing for the input of 10 5 3. It is work for everything till 1 to 9 but whenever it goes for 10 or greater then 10 then doesn't show any output. I also try to use atoi() for it but error in this line int x = str[j] - '0' . Please help me.
#include<iostream>
#include<string>
#include<cstdlib>
using namespace std;
int main()
{
    int n, sum = 1, num = 0;
    string str;
    cin >> n;
    for(int i = 0; i <= n; i++) {
        getline(cin, str);
        for(int j = 0; j < str.length(); j++) {
            if(str[j] != ' ') {
                int x = str[j] - '0'; // Here is the problem even I use atoi() but error
                sum *= x;
                num = sum;
            }
        }
        if(num != 0) {
            cout << num << endl;
            num = 0;
            sum = 1;
        }
    }
}

A: It's not clear from your post why you have two variable num and sum. It seems redundant.
Assuming you just need num, replace the lines
sum *= x;
num = sum;

by
num = (10*num + x);

to get the numbers right.
Also, when you encounter a space, you'll need to reset num to 0. Otherwise, the input 10 8 will be treated as 108.
for(int j = 0; j < str.length(); j++) {
    if(str[j] != ' ') {
        num = (10*num + x);
    } else {
       // Use num and then reset it 0
       // ...
       num = 0;
    }
}


text:
Q: C++ Variadic Function To Sort Arguments In-place While implementing a variation of a binary search problem, I needed to reorder slicing points (i.e start, mid, end) so that they are stored within the corresponding variable (e.g. (1,5,2) -> (1,2,5)). This is fairly simple to do with a few if statements and swaps. However as a thought experiment, I'm now interested in generalizing this to work with n many T type variables. I started experimenting with some intuitive solutions and as a starting place, I came up with this template function:
template<typename T>
void
sortInPlace(
    std::function<bool (const T&, const T&)> compareFunc,
    T& start,
    T& mid,
    T& end)
    {
        std::vector<T> packed {start, mid, end};
        std::sort(packed.begin(), packed.end(), compareFunc);
        auto packedAsTuple = make_tuple(packed[0], packed[1], packed[2]);
        std::tie(start, mid, end) = packedAsTuple;
    }

And when I ran the following, using typedef std::pair<int,int> Pivot:
//Comparison function to sort by pair.first, ascending:
std::function<bool(const Pivot&, const Pivot&)>
  comp =[](const Pivot & a, const Pivot & b) {
     return std::get < 0 > (a) < std::get < 0 > (b);
  };

int main(){
    Pivot a(8,1);
    Pivot b(2,3);
    Pivot c(4,6);

    sortInPlace(comp,a,b,c);
}

This turns out to work as intended:
a after sort: 2, 3
b after sort: 4, 6
c after sort: 8, 1

Ideally, the following step is to convert this template into a variadic template but I'm having trouble achieving this. I also have a few things that bother me regarding the current version:

*

*The usage of std::vector was an arbitrary decision. I've done this because it's unclear to me what structure/container is the best to use in packing of these values. Seems to me that the choice of structure needs to be constructed, sorted and unpacked/converted to tuples easily and I'm not sure if there is such a magical structure out there.

*Just to get something going, I had to settle with manually packing/unpacking the arguments. It is also unclear to me how to use std::tie or any other unpacking/moving operation with variable number (i.e. unknown in compile-time) of elements.

*While there is no particular reason to exclusively use stl functions/structures, I'd be surprised to learn that there is no intuitive way to achieve this using the abstractions provided within stl. As a result, I'm more interested in achieving my goal using minimal help outside of stl.

I embarked on this thought experiment expecting to end up with a syntactically-correct version of std::move(std::sort({x,y,z}, comp), {x,y,z}) and considering where my research has led me so far, I'm starting to think I'm over-complicating this problem. Any help, insight or suggestion would be much appreciated!

A: One possible C++17 solution with std::sort that generalizes your example:
template<class Comp, class... Ts>
void my_sort(Comp comp, Ts&... values) {
    using T = std::common_type_t<Ts...>;
    T vals[]{std::move(values)...};

    std::sort(std::begin(vals), std::end(vals), comp);

    auto it = std::begin(vals);
    ((values = std::move(*it++)), ...);
}

using Pivot = std::pair<int, int>;

const auto comp = [](Pivot a, Pivot b) {
    return std::get<0>(a) < std::get<0>(b);
};

Pivot a(8, 1);
Pivot b(2, 3);
Pivot c(4, 6);

my_sort(comp, a, b, c);

If the number N of parameters in the pack is small, you don't need std::sort at all. Just a series of (hardcoded) comparisons (and for small N the minimum number of comparisons is known exactly) will do the job - see sec. 5.3 Optimum sorting of Knuth's TAOCP vol. 3.


text:
Q: MySQL - Split field and group concat I need to join two MySQL tables - events & people, but I see problem when I have multiple people leading the same event.
PEOPLE
=================
ID|Name  |Surname|....
--------------------
 1|John  |Lennon
 2|Paul  |McCartney
 3|George|Harisson
 4|Ringo |Starr

Is there any possible way to get concat of 1 & 2, if the event table is something like
EVENTS
=================
event |leader|....
-----------------
Picnic|1+2

I do want some events to have only one leader, but also some with more than 2.
Is there any way to do something like this?
Thank you for your help.

A: The proper way to solve your problem is to have a events table:
eventid | event
---------------
1       | Picnic

and a events_leaders table:
eventid | leader
----------------
1       | 1
1       | 2

then you can just use a JOIN and a GROUP_CONCAT aggregate function:
SELECT
  events.event,
  GROUP_CONCAT(CONCAT(people.surname, ' ', people.name))
FROM
  events INNER JOIN events_leaders
  ON events.eventid = events_leaders.eventid
  INNER JOIN people
  ON events_leaders.leader = people.id
GROUP BY
  events.eventid,
  events.event

however, you can use FIND_IN_SET function and obtain the same result, but the query will be slower as it works on strings and cannot make use of an index:
SELECT
  events.event,
  GROUP_CONCAT(CONCAT(people.surname, ' ', people.name))
FROM
  events INNER JOIN people
  ON FIND_IN_SET(people.id, REPLACE(events.leaders, '+', ','))>0
GROUP BY
  events.event


text:
Q: Passing parameter to callableSatatement - ORA-01008: not all variables bound I have a PL/SQL query with parameter:
plSqlQuery =    "declare "
              + "  num integer := 1000;"
              + "  myStr varchar2(100):= ?;"
              + "begin "
              + "  dbms_output.put_line('abc');"
              + "  dbms_output.put_line('hello');"
              + "  dbms_output.put_line(myStr);"
              + "end;"

My Java method is something like this:
public static void getData(String sqlQuery) throws SQLException, IOException{
    Statement s =conn.createStatement();
    try{
    s.executeUpdate("begin dbms_output.enable();end;);
    s.executeUpdate(sqlQuery);

    try{
    CallableStatement call = conn.prepareCall("declare num integer = 10000; begin dbms_output.get_lines(?, num); end;)
    }
    call.registerOutParameter(1,Types.ARRAY, "DBMSOUTPUT_LINESARRAY");
    call.execute();

     Array array = null;
                    try {
                        array = call.getArray(1);
                        System.out.println(Arrays.asList((Object[])
                 array.getArray()));
                    }
                    finally {
                        if (array != null)
                            array.free();
                    }

Having both above now, I would like to execute my getData method, but I don't know how to pass a parameter to it (myStr).
Can you please tell my where in my Java method I should set my string parameter?
Should it be something like
s.setString(x, "abcdefg");

or
call.setString(2, "abcdefg");

it gives me an Oracle error like

ORA-01008: not all variables bound

I tried both to be honest but did not succeed.

A: If you are passing your string plSqlQuery as the parameter to your getData() method (e.g. by calling getData(plSqlQuery)) then you will run into an ORA-01008 'not all variables bound' error, because you're not specifying a value for the ? placeholder.
You can't use an ordinary Statement with placeholders, you must use a PreparedStatement instead.
Try replacing the line
    s.executeUpdate(sqlQuery);

with
    try (PreparedStatement pstmt = conn.prepareStatement(sqlQuery)) {
        pstmt.setString(1, "Some Value Here");
        pstmt.execute();
    }

A: I figured it out.
It works with 3 different statements :(
Statement s = conn.createStatement();
s.executeUpdate("begin dbms_output.enable();end;);

PreparedStatement ps = conn.prepareStatement(sqlQuery);
ps.setString(1, "abcdefg");

 CallableStatement call = conn.prepareCall("declare num integer = 10000; begin dbms_output.get_lines(?, num); end;)
 call.registerOutParameter(1,Types.ARRAY, "DBMSOUTPUT_LINESARRAY");
 call.execute();


text:
Q: Pass by reference notation My question is really straightforward and I believe understandable.
I've made this simple snippet to illustrate my conflict when I'm passing values by reference.
int main() {
 int a = 1;
 int &b = a;
}

I know that this is the correct way to do it but how does it make sense to take the address of b and make it equal to the value of a. Logically it should be: int &b = &a;

A: Many operators are context-sensitive. The & "operator" could mean three different things depending on context:

*

*It could be used when defining a reference
int& r = a;  // The variable r is a reference of the variable a

*It could be used to get a pointer to something
int* p = &a;  // Here & is the address-of operator which returns a pointer
              // Here it makes p point to the variable a

*It could be the bitwise AND operator
0x53 & 0x0f    // Here's a bitwise AND operation, the result is 0x03

A: You're mistaken by the syntax. This is unhappy, but & is both the addressof operator and the token meaning "referente to".
int &b = a;

This declares the variable b to be of type int& (reference to an int) and initialized to a. No address whatsoever.


text:
Q: vaadin: where can i set Reindeer.TABSHEET_SMALL on tabsheet I am using the default Reindeer them and would like to change the tabsheet size to  Reindeer.TABSHEET_SMALL
Where can I set the option?
Thanks!

A: You can do it by adding a style name for the tabsheet:
tabsheet.addStyleName(Reindeer.TABSHEET_SMALL);


text:
Q: Differential operator on linear functional Let $ L:\mathbb{R}^n\to\Bbb{R}$ be the function $L(x)=\langle x|y\rangle$ , where $\langle|\rangle$ denotes some inner product on $\Bbb{R}^n$ and y is a fixed vector in $\Bbb{R}^n$. Further denote by DL, the derivative of $L$. Then which of the following are necessarily correct?

*

*$ DL(u)= DL(v)$ for all $u, v \in \Bbb R^n$.

*$DL(0,0,...,0)= L$.

*$DL(1,1,...,1)= 0$.

*$DL(x)=||x||^2,\forall x\in\Bbb R^n$.

By the definition of linear functionals. It seems $L$ is a linear functional.
$$L(x)=<x|y>=<(x_1,...,x_n)|(y_1,...,y_n)>=\sum_{i=1}^n x_iy_i$$
How to use $D$ in this problem?
I saw some answers in this app. But every answer choose correct options as incorrect options.
Correct answers are (1) and (2).

A: For any linear operator $L:X\to Y$ the derivative is equal to $$D_xL=L$$ for all $x\in X.$

A: Your $L$ is linear, so its derivative is constant and equal to itself. So indeed 1 and 2 are correct. Concretely, for any $x,h\in\mathbb R^n$
$$
\frac{|L(x+h)-Lx-DL(x)h|}{\|h\|}=\frac{|Lh-DL(x)h|}{\|h\|}.
$$
The only way this quotient can go to zero with $\|h\|$ is that $DL(x)=L$.


text:
Q: Uploading file with ajax and java servlet I am trying to upload a csv file inside from a jsp page using a servlet that extends HttpServlet. Inside the jsp page I am using an ajax that should call the servlet.
This is the ajax part:
    $(function() {
    $(".upldBtn").click(function() {

        alert("Upload button pushed");

        $.ajax({
            type: "POST",
            url: contextPath + servletPath,
            data: "action=get&custIdList=" + $('#custIdList').val(),
            async: false,
            dataType: "text/csv; charset=utf-8",
            success: function(data){
                  alert("success");
              }
        });
    });

The contextPath and servletPath are also declared, I didn't specified them here.
In the jsp page, I have this form inside a table :
<form method="post" action="CSRUploadListServlet" enctype="multipart/form-data">
<input type="file" name="custIdList" id="custIdList" />
<input type="submit" value="Upload" class="upldBtn" />
</form>

Inside the servlet, I want to use this doPost method:
protected void doPost(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {

    String methodName = "doPost";

    logger.debug("[{}] call", methodName);

    // checks if the request actually contains upload file
    if (!ServletFileUpload.isMultipartContent(request)) {
        PrintWriter writer = response.getWriter();
        writer.println("Request does not contain upload data");
        logger.debug("[{}] Request does not contain upload data",
                methodName);
        writer.flush();
        return;
    }

    // configures upload settings
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(THRESHOLD_SIZE);
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
    logger.debug("[{}] factory= {} ", methodName, factory);

    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setFileSizeMax(MAX_FILE_SIZE);
    upload.setSizeMax(MAX_REQUEST_SIZE);
    logger.debug("[{}] upload= {} ", methodName, upload);

    // constructs the directory path to store upload file
    String uploadPath = getServletContext().getRealPath("")
            + File.separator + UPLOAD_DIRECTORY;
    // creates the directory if it does not exist
    File uploadDir = new File(uploadPath);
    if (!uploadDir.exists()) {
        uploadDir.mkdir();
        logger.debug("[{}] upload directory = {} ", methodName,
                uploadDir.mkdir());
    }

    try {
        // parses the request's content to extract file data
        List formItems = upload.parseRequest(request);
        Iterator iter = formItems.iterator();

        // iterates over form's fields
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            // processes only fields that are not form fields
            if (!item.isFormField()) {
                String fileName = new File(item.getName()).getName();
                String filePath = uploadPath + File.separator + fileName;
                File storeFile = new File(filePath);

                // saves the file on disk
                item.write(storeFile);
            }
        }
        request.setAttribute("message",
                "Upload has been done successfully!");
        logger.debug("[{}] Upload has been done successfully! ", methodName);
    } catch (Exception ex) {
        request.setAttribute("message",
                "There was an error: " + ex.getMessage());
        logger.debug("[{}] There was an error: {} ", methodName, ex);
    }
    getServletContext().getRequestDispatcher(
            "/WEB-INF/web/csrCustomerLists/message.jsp").forward(request,
            response);
}

All this gets stuck at if (!ServletFileUpload.isMultipartContent(request)), returning that: 'Request does not contain upload data'.
I am sure that I am not writing the ajax correctly, but I can't seem to find out where I am doing it wrong.
Thanks.

A: Hei! Try to put your html code differently, and then call the servlet from ajax, just the way you did there. I think the problem may be in the form you are using, that is rewriting some attributes or something like that.
I suggest an option with an iframe, loaded from the js code.The html code can be like this:
<button id="upldBtn" title="Upload" >Do the upload</button>

<input type="file" class="file" id="file" name="file" title="Please upload"/>

And the javascript code:
    $(function() {

    $('#upldBtn').click(function() {
        var contextPath = 'your path string';
        var servletName = 'your servlet name string';
        var iframe = $('');
        $("body").append(iframe);

         $("form#yourform").attr('action', contextPath+servletName);
         $("form#yourform").attr('enctype', "multipart/form-data");
         $("form#yourform").attr("target", "postiframe");
         $("form#yourform").attr("file", $('#file').val());

        $('yourform').submit(); //upload button
             $("#postiframe").load(function () {
                    iframeContents = $("#postiframe")[0].contentWindow.document.body.innerHTML;
                    $("#textarea").html(iframeContents);
                            $.ajax({
                                    type: "GET",
                                    url: contextPath+servletName,
                                    data: "action=download",
                                    async: false,
                                    dataType: "text",
                                    success: function(result) {
                                        //do something
                                    }
                                });
                } });
            });
});

Tell me if it is ok for you. :)
Cheers


text:
Q: The convolution of Fejér kernel with a non-trivial function is zero I'm trying to prove that it exists a non-trivial function $f\in L^1([-\pi,\pi])$ such that the convolution $(F_N*f)(x)=0$ for all x. I've tried to calculate the convolution:
$$(F_N*f)(x)=\frac{1}{2\pi} \int_{-\pi}^\pi F_n(x-t)f(t)dt=\frac{1}{2\pi} \int_{-\pi}^\pi \frac{1}{N+1} \left(\frac{\sin(\frac{(N+1)(x-t) }{2})}{\sin(\frac{(x-t)}{2})}\right)^2 f(t)dt.$$
Because the Fejér kernel is even and the integral is symmetric, my conclusion is that the function $f$ must be zero almost everywhere. But I don't understand how I find a function that is non-trivial.
Any help would be appreciated.

A: Take $f(x)=e^{i(N+1)x}$. Use the formual $F_N(x)=\sum_{|n| \leq N} c_n e^{inx}$ where $c_n=1-\frac {|n|} {N+1}$ to show that $F_N*f=0$.


text:
Q: Windows obstinately shrinking the pagefile I admit I have rather small free space available on my C:\ drive (only 3-4 GiBs usually, with a 4 GiB pagefile being around), but what really annoys me is this:
Windows sometimes does an operation(1) which supposedly requires more free space than available and thus, it shrinks my pagefile to 600-800 MiBs (or even less) and then allocates the space on my hard drive for that certain something.
After this (here comes the annoying part), it usually complains about running out of memory when I start a memory-heavy application or videogame (which is never a problem if the 4 GiB pagefile is a 4 GiB pagefile). And because the size is already allocated, I can't quickly set the pagefile back to its original size.
In system settings, the paging area has a fixed (hey, not so fixed, it seems afterall) size of 4096 MB. Windows is not supposed to shrink it, yet it does.
I started with a 45 GB partition, now I'm at 65 and it's not enough either.
I regularly clean my computer from stale temp files and other orphan or expired stuff (such as memory profiling reports), but seemingly the disk space is leaking away. Antivirus checks are regular too, so if it is a malware, it is a brand new never known one.
(1): I think it is the shadow copying for System Rescue, which is set to have 2 GB size available. But I never ran into this issue, all I see is that there is no space (few hundred MiBs) left on the partition, and the pagefile is yet again only a few MiBs large.

I'm thinking about recycling my Linux's swap partition (I have a dual-install setup on this drive) to become a Windows pagefile.sys hosting partition when Windows is booted, and turn back to a Linux swap when Linux is booted. If you could help me out about that, I have this other question here.

A: I've not experienced this myself, but the dialogue box does say Initial size and not minimum.  I'm assuming based on what is happening with your setup is that Windows occasionally decides to shrink the pagefile down from its initial size due to the chronic shortage of disk space.


text:
Q: Which algebraic-exponential functions (in $\mathbb C[z,e^z]$) have no complex roots? Question: For which two-variable polynomials $p$ with complex coefficients does the equation $p(z,e^z)=0$ have no roots in $\mathbb C$?
The existence of any non-trivial solutions, ie. those not of the form $Ae^{nz}$ for constant $A\neq0$ and integer $n\geq0$, would already be interesting.

A: Note that $p(z,e^z)$ is an entire function of order 1, so if it has finitely many roots $\rho_1,\ldots,\rho_n$ then by the Hadamard factorisation theorem we can write
$$p(z,e^z)=e^{az+b}(z-\rho_1)\cdots(z-\rho_n).$$
In particular, if $p(z,e^z)$ has no roots then it is the exponential of a linear polynomial.
Now the argument of $p(z,e^z)$ as $z\to\infty$ along the positive real axis must approach a constant. (Note that the argument for an entire function with no roots is globally defined.) But the argument for $e^{az+b}$ grows as $\operatorname{Im}(a)z$, so we see that $a$ must be real. By considering the growth rate of $p(z,e^z)$ it is now easy to show that $a\in\mathbb Z_{\geq0}$, so $p(z,e^z)$ must be of the "trivial" form stated in the question.


text:
Q: Bombelli's wild thought of cubic equations In many books, like Visual Complex Analysis. talk about the real original of complex number. the author begin with this equation:
$$x^3=15x+4$$
Then the author use the formula $$x=\sqrt[3]{q+\sqrt{q^2-p^3}}+\sqrt[3]{q-\sqrt{q^2-p^3}}$$
to say that the equation has a root $$x = \sqrt[3]{2+11i}+\sqrt[3]{2-11i}$$
Apparently, $x=4$ is a root of the equation $x^3=15x+4$. Then the author guess $$\sqrt[3]{2+11i}+\sqrt[3]{2-11i}  =4.$$ then introduction complex arithmetic. It seems very natural. but equation $x^3=15x+4$ has three different roots. why the author, or probably Bombelli guess this equal $4$, not other roots?

A: He (Bombelli) probably used the Cardano formula to obtain the $\textbf{one}$ root solution you just described $$x = \sqrt[3]{2+11i}+\sqrt[3]{2-11i}$$
He then had to find the cube roots of each of the radicals above. I am not sure exactly how he found them but he may have used the following sometimes used polynomial to find each of the cube roots
$$\frac{-64a^9+(48x)a^6+((15(x)^2)-3(3y)^2)a^3+(x)^3}{-64} = 0$$ where $x$ = $2$ and $y$ = $11i$ to get
$$a^9 + \frac{3}{2}a^6 - \frac{3327}{64}a^3 + \frac{1}{8} = 0$$
This polynomial has one rational root $a$ = $2$
He could now take the rational root $a$ = $2$ he found above to find $b$ in the equation below  in order to denest the two cube roots in Cardano's formula. The $2$ on the $RHS$ is the $2$ under the radical
$$ a^3+3ab^2=2$$
$$2^3 + 3(2)b^2 = 2$$
$$b=\pm \sqrt\frac{-6}{6} = \pm i$$
So using the $a$ he found and the $b$ he found he could derive the cube roots as $a + b$.
This gives the two results $$2 + i$$  and   $$2 -i$$ Each is the cube root of the nested radicals in the Cardano solution.
So using the $a$ he found and the $b$ he found he could observe that this was equal to the real root of $4$ found using other methods
$$\left(2 + i\right) + \left(2 - i\right)  = 4$$

A: $(2\pm i)^3=8\pm 3*4i-3*2\pm i=2\pm 11i$. Therefore $\sqrt[3]{2+11i}+\sqrt[3]{2-11i}=2+i+2-i=4.$


text:
Q: Using Action Mailer and ROR3 to send an email on the creation of user I'm trying to follow section 2.1 of this tutorial
When I create a new user, I just get this message:
NameError in UsersController#create

uninitialized constant UsersController::UserMailer

I've had a break from ROR, and now I've found I've forgotten quite a lot!
What are the most likely causes of this error?
My mailer (controller): app/mailers/usermailer.rb:
class Usermailer < ActionMailer::Base
  default from: "from@example.com"

  def welcome_email(user)
    @user = user
    @url = 'http://example.com/login'
    mail(to: @user.email, subject: 'Welcome to my awesome site')
  end
end

My view: app/usermailer/welcome_email.html.erb:
<!DOCTYPE html>

    <meta content='text/html; charset=UTF-8' http-equiv='Content-Type' />

Welcome to example.com, <%= @user.name %>

      You have successfully signed up to example.com,
      your username is: <%= @user.login %>.

      To login to the site, just follow this link: <%= @url %>.

Thanks for joining and have a great day!

</htm>

Not sure what this is classed as. A "view call" in the users controller to the view welcome_email to @user:
   UserMailer.welcome_email(@user).deliver

Here it is in context at app/controllers/users_controller.rb:
class UsersController < ApplicationController
  # GET /users
  # GET /users.json
  def index
    @users = User.all

    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @users }
    end
  end

  # GET /users/1
  # GET /users/1.json
  def show
    @user = User.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @user }
    end
  end

  # GET /users/new
  # GET /users/new.json
  def new
    @user = User.new

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @user }
    end
  end

  # GET /users/1/edit
  def edit
    @user = User.find(params[:id])
  end

  # POST /users
  # POST /users.json
  def create
    @user = User.new(params[:user])

    respond_to do |format|
      if @user.save

#
    # send welcome email after save
    UserMailer.welcome_email(@user).deliver

#
        format.html { redirect_to @user, notice: 'User was successfully created.' }
        format.json { render json: @user, status: :created, location: @user }
      else
        format.html { render action: "new" }
        format.json { render json: @user.errors, status: :unprocessable_entity }
      end
    end
  end

  # PUT /users/1
  # PUT /users/1.json
  def update
    @user = User.find(params[:id])

    respond_to do |format|
      if @user.update_attributes(params[:user])
        format.html { redirect_to @user, notice: 'User was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: "edit" }
        format.json { render json: @user.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /users/1
  # DELETE /users/1.json
  def destroy
    @user = User.find(params[:id])
    @user.destroy

    respond_to do |format|
      format.html { redirect_to users_url }
      format.json { head :no_content }
    end
  end
end

A: You're mixing your capitalization up a little. You should use UserMailer (with a capital 'M') to refer to the constant (a.k.a. class) and user_mailer for the file and directory names.
So for your mailer, the file name should be app/mailers/user_mailer.rb and then use:
class UserMailer < ActionMailer::Base

to define the class.
You'll also need to put the view for the mailer at app/views/user_mailer/welcome_email.html instead of app/usermailer/welcome_email.html.erb.
What Rails was trying to tell you from that error message (uninitialized constant UsersController::UserMailer) is that the UsersController can't find a constant called UserMailer anywhere. It checked in the load paths for a file with file name user_mailer.rb but couldn't find it because your file wasn't snake-cased properly. Had you fixed that, alone, then next it would have complained that it expected user_mailer.rb to define the UserMailer constant. The way rails does this is:
# First, going from the constant to the file name to look for:
UserMailer.name.underscore  # => 'user_mailer'

# Now, going from the file name to the expected constant defined in that file:
'user_mailer`.classify  # => 'UserMailer'
'UserMailer'.constantize  # => UserMailer


text:
Q: Unexpected output after typecasting For the following print statement
std::cout << 10.1 / 0.1 << " " << (int)(10.1 / 0.1) << std::endl;

My understanding is that (10.1/0.1) is 101.0 hence after typecasting as an int the result should be 101. Instead I received 101 100. Can somebody please explain me why it is so???


text:
Q: Elements in a Jlist are not displaying can someone help me? So I basically copied the code from the oracle documentation but nothing will display. There are no problems with the files I already checked that. Here's the code:
v=Archivio.LetturaRic();
dlm=new DefaultListModel();
for(int i=0; i<v.size();i++)
{
   dlm.addElement(((Ricetta)v.get(i)).nome);
}
list=new JList(dlm);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.setSelectedIndex(0);
list.addListSelectionListener(this);
list.setVisibleRowCount(-1);

A: Please Remove list.setVisibleRowCount(-1);


text:
Q: Adjectival form of "degrade"? For example, I want to say:

This book degrades Western culture.

In this form:

This book has been described as ??? to Western culture.

What would the adjectival form be? Is "degradeful" a word, or is there something better?

A: The commonest way of employing a verb as an adjective with an active sense—that is, with the sense that the noun modified is something which performs the action of the verb—is to use the present participle: the -ing form:

This book has been described as degrading to Western culture.

Likewise, the commonest way of employing a verb as an adjective with a passive sense , in which the noun modified is something which suffers the action of the verb, is to use the past participle:

Degraded Western culture is incapable of responding to the literary glories of the classics.