text:
Q: Why isn't there a native json_decode in Twig? I know how to set up a json_decode function in twig.. but why is there no native support for decoding in twig? I can easily call json_encode without setting up a Twig Filter, but that is not the case for json_decode.
It seems logical to have it has a native function. Am I missing the rational behind not having it? Maybe it's computationally expensive?

A: json_encode makes sense, json_decode however does not really.
It adds a non trivial dependency towards the fact that the data passed is JSON.
Filters are here to transform data not crafting data. Computations (that are not transformations) should be made ahead of time.
One could also argue that json_encode should be done ahead of time but considering how frequent it is to return/send JSON it seems fair enough to do it in the template.
PS :
This seems to be a primarily opinion based question (unless there is an official answer to it).


text:
Q: Rails nested_form inside nested_form I have the following models and relations:
Rate fields
  t.string :type
  t.string :name

class Rate < ActiveRecord::Base
  has_many :category_rate_requests
end

CategoryRateRequests fields
  t.date :date_from
  t.date :date_to

class CategoryRateRequests < ActiveRecord::Base
  belongs_to :rate
  has_many :category_rates
end

CategoryRate
  t.integer :room_category_id
  t.integer :new_rate_id
  t.integer :category_rate_request_id
  t.integer :amount

class CategoryRate < ActiveRecord::Base
  belongs_to :rate
  belongs_to :category_rate_request
  belongs_to :room_category
end

And I'm trying to have a nested_form inside a nested_form
= nested_form_for @rate do |f|
  = label_tag :name, t('rates.new.name'), class: 'grey h2'
  = f.text_field(:name, required: true, class: 'form-input form-control full-width-input')
  = f.fields_for :category_rate_request do |request|
    = request.text_field(:date_from,  class: 'date-input form-control start-date-input', type: 'text', 'data-provide': 'datepicker', placeholder: t('common.date_from'))
    = request.text_field(:date_to, class: 'date-input form-control end-date-input', type: 'text', 'data-provide': 'datepicker', placeholder: t('common.date_to'))
    = request.fields_for :category_rate, do |u|
      = u.number_field(:price, class: "form-control", placeholder:  placeholder)

Overall this is the format. It has more things, but to not include too much unnecesary information I omitted some fields of the form.
But I get the following error

Completed 500 Internal Server Error in 690ms (ActiveRecord: 6.1ms)
SyntaxError - syntax error, unexpected keyword_do_block ;
  _slim_controls2 = request.fields_for :new_category_rate, do |u|;
                                                               ^ /project/app/views/new_rates/_category_rate_requests.html.slim:61:
  syntax error, unexpected keyword_ensure, expecting end-of-input:

That line marked in red is:
= request.fields_for :new_category_rate, do |u|
Is there any way I can have the attributes of all three models in one form? In the Rate form more precisely.

A: I don't know if you need to use that gem for a particular reason, but I think it hasn't been updated for too long for use it.
I use Cocoon, and with simple form you just need to do:
simple_form_for @a do |f|
  f.simple_fields_for :b do |b_f|
    b_f.simple_fields_for :c do |c_f|
      ...
    end
  end
end

You can use link_to_add_association and link_to_remove_association in a very friendly way too.

A: (copied from comment)
You have an extra comma in the erroring line. Change it to:
= request.fields_for :new_category_rate do |u|

redpajama_set_name: RedPajamaStackExchange


text:
Q: I cannot stop my php form from sending if fields are blank My form is driving me crazy, it should all be set up to stop sending if fields are empty but it always goes through. If none or all are filled it it will always show my 'Thanks, your message successfully sent' message.
This is my form:
<?php
//////////////////////////
//Specify default values//
//////////////////////////

//Your E-mail
$your_email = 'myemail';

//Default Subject if 'subject' field not specified
$default_subject = 'From My Contact Form';

//Message if 'name' field not specified
$name_not_specified = 'Please type a valid name';

//Message if 'message' field not specified
$message_not_specified = 'Please type a vaild message';

//Message if e-mail sent successfully
$email_was_sent = 'Thanks, your message successfully sent';

//Message if e-mail not sent (server not configured)
$server_not_configured = 'Sorry, mail server not configured';

///////////////////////////
//Contact Form Processing//
///////////////////////////
$errors = array();
if(isset($_POST['message']) and isset($_POST['name'])) {
    if(!empty($_POST['name']))
        $sender_name  = stripslashes(strip_tags(trim($_POST['name'])));

    if(!empty($_POST['message']))
        $message      = stripslashes(strip_tags(trim($_POST['message'])));

    if(!empty($_POST['email']))
        $sender_email = stripslashes(strip_tags(trim($_POST['email'])));

    if(!empty($_POST['subject']))
        $subject      = stripslashes(strip_tags(trim($_POST['subject'])));

    //Message if no sender name was specified
    if(empty($sender_name)) {
        $errors[] = $name_not_specified;
    }

    //Message if no message was specified
    if(empty($message)) {
        $errors[] = $message_not_specified;
    }

    $from = (!empty($sender_email)) ? 'From: '.$sender_email : '';

    $subject = (!empty($subject)) ? $subject : $default_subject;

    $message = (!empty($message)) ? wordwrap($message, 70) : '';

    //sending message if no errors
    if(empty($errors)) {
        if (mail($your_email, $subject, $message, $from)) {
            echo $email_was_sent;
        } else {
            $errors[] = $server_not_configured;
            echo implode('
', $errors );
        }
    } else {
        echo implode('
', $errors );
    }
}
?>

A: CLIENT SIDE METHOD Add required attribute to each element of the field you wan't to be filled before form is submitted!
SERVER SIDE METHOD
If you wan't to do it on server side check if the field is not empty and otherwise redirect back:
if(!(isset($_POST['message']) and isset($_POST['name'])))
    header('locaition: formurl');

Most recommended: Any client-side validation MUST be repeated server-side

A: Imporant, but slightly off-topic
Though this does not really answer your question, I do urge you to look into Mail-injection. Whenever you decide to send a mail message using client-data, you are at risk. You don't seem to be sanitizing the data enough.
I have reviewed code on a couple of occasions that did similar things (sending mails with PHP, or processing contact forms). What I had to say about that, especially on the subject of mail-injection can be found here, and here. Both code-reviews contain links that might also be worth reading.

Anyway, to answer your question:
If you don't want PHP to reach a certain statement (ie: mail()) in when something goes wrong, use code that allows you to control the flow (stop execution before the statement is reached).
The simplest, and easiest way to do this is through use of a function:
/**
 * Sends mail using data in $data argument
 * requires $fields to be an assoc array where
 * keys == field names, and values = null|| default value
 * null for required fields, default value for optional fields
 * If $data is invalid, an InvalidArgumentException is thrown
 * @param array $data
 * @param array $fields
 * @return bool mail() return value
 * @throws InvalidArgumentException
 */
function sendMail(array $data, array $fields)
{
    foreach ($fields as $field => $val)
    {
        if (isset($data[$field]))
        {//data is set
            if ($field === 'email')
            {//sanitize
                $val = filter_var($data[$field], FILTER_SANITIZE_EMAIL);
                if (!filter_var($val, FILTER_VALIDATE_EMAIL))
                {//if email is not valid, throw exception
                    throw new InvalidArgumentException(
                        sprintf(
                            'invalid %s value: %s',
                             $field,
                             $data[$field]
                        )
                    );
                }
            }
            else
            {//basic, crude sanitation, not enough to protect agains mail injection
                $data[$field] = nl2br(strip_tags(trim($data[$field])));
            }
        }
        else
        {
            if (!$val)
                throw new InvalidArgumentException(
                    sprintf(
                        '%s is a required field',
                        $field
                    )
                );
             $data[$field] = $val;
        }
    }
    return mail('your_email', $data['subject'], wordwrap($data['message'],70), 'From: '.$data['email']);
}

Note that I added special sanitation/validation checks for email addresses. A function worth remembering is filter_var. It has special constants to validate and/or sanitize values. See which filters are available here.
Now this code may seem quite verbose (and it is). If you want, you could easily replace all the throw new InvalidArgumentException statements with a simple return 'The error message string'; statement. This will change the way you use this function.
With the exceptions being thrown, you use the function like so:
if ($_POST)
{//if there is post data
    try
    {//try - catch block
        //which fields are required, which have default values, defined here
        $validate = array(
            'email'   => null,//required
            'message' => null,//required
            'name'    => 'No Name',//default val,
            'subject' => 'Default subject'//default
        );
        //call function, check what it returns
        if (sendMail($_POST, $validate))
            echo 'Message was sent';//echos if return value was true
        else//if false:
            echo 'failed to send message';
    }
    catch(InvalidArgumentException $e)
    {//if an exception was thrown
        echo 'Error: ', $e->getMessage();//echo the error message
    }
}

Now, assume we've replaced all the throw statements with a simple return 'error-string'; statement. Now the usage looks like this:
if ($_POST)
{
    $validate = array();//same array as above
    $return = sendMail($_POST, $validate);
    if ($return === true)//use type and value check: ===, not ==
        echo 'Message sent';
    elseif ($return === false)
        echo 'Failed to send message';
    else
        echo 'Error: ', $return;//$return is a string: error message returned by function
}

That would be my way to tackle your problem

A: The problem is fairly easy, you are not telling your script to stop if one of them is empty.
Add this as follows to your script:
if($errors) {
    foreach($errors as $value) {
         echo $value . "
";
    }
    exit();
}

This will stop your script after sending the errors.

A: The solution is:
(...)
///////////////////////////
//Contact Form Processing//
///////////////////////////
$errors = array();
if(!empty($_POST['message']) and !empty($_POST['name'])) {
(...)

In case it's still wrong, make sure fields are really empty.
(...)
///////////////////////////
//Contact Form Processing//
///////////////////////////
$errors = array();
if(!empty($_POST['message']) and trim($_POST['message']) and !empty($_POST['name']) and trim($_POST['name'])) {
(...)


text:
Q: Why does my Echo Server not work on localhost? I am trying to create an echo server with Node.js so it should read body of incoming requests and send that same body as the response. You can see below my code. Basically when I run it and on another terminal, I type curl --location --request POST 'localhost:3000' --header 'Content-Type: text/plain' --data-raw 'Test message' to test it, it prints the body inside the curl terminal and server terminal, but not on localhost.
const http = require('http');

http.createServer((request, response) => {

    let body = [];
    request.on('data', (chunk) => {
      body.push(chunk);
    }).on('end', () => {
      response.writeHead(200, { 'Content-Type': 'text/plain' });
      body = Buffer.concat(body).toString();

      response.write(JSON.stringify(body));
      console.log(JSON.stringify(body));
      response.end();
    });
}).listen(3000, 'localhost');

A: curl doesn't print the request body, it prints the response body the server is returning to you. In other words - this echo server works as planned.


text:
Q: read html nodes in r I need toget a set of vector from the the internet which is available in html format.
I'm reading the webpage this way:
add=url
doc=htmlTreeParse(add)

This how doc looks:

doc
        $file
        [1] "http://ifis.iowafloodcenter.org/ifis/ifis5/ws/objects.php?id=741&type=4"

  $version
  [1] ""

  $children
  $children$html

743,762,754,759,761,744,741,755,758,742,757,716,760

  attr(,"class")
 [1] "HTMLDocument"

I wish to obtain numbers under  as vector.
I tried using :
xmlValue(xmlRoot(doc) )

But this does not give me vector.
How can it be done?
Thank you for reading

A: Here is it:
getURL(add,encoding = "iso8859-8")
v2=strsplit(v, "\\,")
as.numeric(v2[[1]][[2]])

A: Try using
 `getURL(add)`

from RCurl package


text:
Q: Multiple select into? In MySQL, you can write something like
INSERT INTO t1 (col1) SELECT col1 FROM t2

To copy some data over. What if I want to copy some data over from multiple tables? Can I write something like
INSERT INTO t1 (col1) SELECT col1 FROM t2, SELECT col1 FROM t3

?

A: i think it should be
INSERT INTO t1 (col1) SELECT col1 FROM t2 UNION SELECT col1 FROM t3

EDIT: Now before you go copying data, you may want to verify using
UNION vs UNION ALL
UNION will remove duplicates in the data.
UNION ALL will produce a simple concatenation of the two result sets.


text:
Q: Custom pin with alphanumeric representation in MapKit I am now at a point of teaching myself the use of MapKit in Objective C.  I got to the point where I can autozoom to a location that contains several annotations.  I represent the annotations with the built in pins.  If you click on the pin I have a an alphanumeric 2 character string to represent that spot.
I thought to myself, for better usability, why not replace the pins with the actual data.  Kind of like a weathermap where they show the temperature as a pin.  Is this doable?
I researched this and all I could find is this:
- (MKAnnotationView *)mapView:(MKMapView *)map viewForAnnotation:(id <MKAnnotation>)annotation
{
    static NSString *AnnotationViewID = @"annotationViewID";

    MKAnnotationView *annotationView = (MKAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:AnnotationViewID];

    if (annotationView == nil) {
        annotationView = [[[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID] autorelease];
    }

    annotationView.image = [UIImage imageNamed:@"location.png"];
    annotationView.annotation = annotation;

    return annotationView;
}

The problem is that I cannot and should not have to have a custom image for each combination of the two characters.  Is there a way for me to draw these numbers at the location of the pin.
I found this reference:
https://developer.apple.com/library/ios/documentation/userexperience/conceptual/LocationAwarenessPG/AnnotatingMaps/AnnotatingMaps.html
Am I on the right track.  Are there some full examples I can leverage to better understand the flow.
I want to be able to select that custom pin however and segue or show more details.
Thank you for your time.

A: Anna, thank you for the link, I tried it and it worked.  I made some changes to improve the esthetic of the label and I thought I would post my findings here for reference:
-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id)annotation {
    if ([annotation isKindOfClass:[MKUserLocation class]])
        return nil;
static NSString *reuseId = @"MapViewController";
MKAnnotationView *av = [mapView dequeueReusableAnnotationViewWithIdentifier:reuseId];
if (av == nil)
{
    av = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:reuseId];

    UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 20)];
    //UILabel *lbl = [[UILabel alloc] init];;
    lbl.backgroundColor = [UIColor clearColor];  // This makes the background clear and just shows the text
    lbl.textColor = [UIColor whiteColor];  // Use any colour you wish
    lbl.alpha = 1.0; //0.5;
    lbl.tag = 42;
    lbl.font = [UIFont fontWithName:@"Helvetica-Bold" size:16.0];   // This is optional, I found this fond and size most readable
    [av addSubview:lbl];

    //Following lets the callout still work if you tap on the label...
    av.canShowCallout = YES;
    av.frame = lbl.frame;
} else {
    av.annotation = annotation;
}

UILabel *lbl = (UILabel *)[av viewWithTag:42];
// I added this to the text to improve its visibility by essentially adding a stroke around the text.  Well its a poor man's stroke by adding a shadow
lbl.layer.shadowColor = [[UIColor blackColor] CGColor];
lbl.layer.shadowOffset = CGSizeMake(0.0f, 0.0f);
lbl.layer.shadowOpacity = 1.0f;
lbl.layer.shadowRadius = 1.0f;

lbl.text = annotation.title;

return av;

}


text:
Q: sub-selecting panda dataframe with special character I am quite new to python. I try to get subselect a dataframe from a dataframe base on column
df = pd.read_csv('some_file.csv',sep=";")

then I try
df = df['Scanner Typique Covid (Oui/Non)']

and I get
KeyError: 'Scanner Typique Covid (Oui/Non)'

I tryied to add encoding = 'utf-8' as an argument for read_csv method, with no success. Someone has an idea ?

A: Try adding a / in front of the /
df = df['Scanner Typique Covid (Oui//Non)']

If that doesn't work, try adding another /


text:
Q: Database designing with ERD or DFD actually this is a really basic question as i am new to database designing. I am student too, i study chunks of information but not as a whole. Now my purpose is to study or learn whole process. thats why i started designing database on my own but i found that that ERD and DFD(Data Flow Model) are necessary to create database from scratch. I viewed a file having different case studies in it. But every thing i viewed was started from direct relational tables.
I was unable to find such case studies having ERD or DFD in it.
 So my basic question is that, are there case studies with ERD or DFD? Can someone point me to the useful link?
Thanks for your help in advance and down votes are also welcome.

A: ER modeling, as originally devised by Peter Chen, is not a very good model for database design.  What it really excels in is data analysis.  Analyzing your data requirements before you begin designing your database is a really good idea  (although, in the real world, you often have to reiterate because the analysis is never complete).  A good ER model will allow you to connect each value to be stored in the database with a particular subject matter entity or relationship, and with a particular attribute
Converting an ER model into a relational model is not hard. and you generally end up with a design that's at least third normal form without even trying hard.
Where it gets confusing is that a lot of professionals use ER diagrams to depict a relational model rather than an ER model.  Here are the main differences between ER and relational:
In an ER model you don't have foreign keys.  Relationships are identified in the model, but they are not implemented.
In an ER model, you don't have or need junction boxes that are used to implement many-to-many relationships in a relational model.
normalization is not relevant to the ER model.  normalization is a feature of a design, not a feature of data requirements.
In practice, as already said,  a lot of professionals don't really distinguish between ER modeling and relational modeling.  But in the classical three stage approach, you create a conceptual model using ER modeling, a logical model using relational modeling, and a physical model using SQL modeling that's DBMS specific.  The three models address different issues.


text:
Q: Trouble rotating matrix with python I've created a function that successfully rotates the outside layer of a matrix.  I've tried adding a loop so that it does the same thing for the interior layers of the matrix, but I haven't had any luck.
def rotateMatrix(mat,size):
    temp = []
    for i in range(size):
        temp.append(mat[0][i])
    for i in range(size-1):
        mat[0][i] = mat[size-(1+i)][0]
        mat[size-(1+i)][0] = mat[size-1][size-(1+i)]
        mat[size-1][size-(1+i)] = mat[0+i][size-1]
        mat[0+i][size-1] = temp[i]
    return mat

Is there a way I could change this slightly to allow for rotation of the interior layers?
I am trying to do this without using any libraries or built in functions.

A: Maybe you are looking for numpy.transpose()?
>>> import numpy as np
>>> x = np.array([[0, 1], [2, 3]])
>>> np.transpose(x)
array([[0, 2],
       [1, 3]])

A: This will rotate the matrix by 90 degrees.
Notice the rotation is not done in-place, another matrix is allocated for the result.
def rotate_matrix(matrix):
    size = len(matrix)
    # init rotated matrix with None elements
    rotated_matrix = [[None]*size for _ in range(size)]
    for i in xrange(size):
        for j in xrange(size):
            rotated_matrix[j][size-1-i] = matrix[i][j]
    return rotated_matrix

matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]]
rotated_matrix = rotate_matrix(matrix)
print rotated_matrix
>> [[7, 4, 1],
>>  [8, 5, 2],
>>  [9, 6, 3]]

A: What do you think about using zip() as shown in the following:
>>> a = [[0, 1], [2, 3]]
>>> list(zip(*a))
[(0, 2), (1, 3)]
>>> list(map(list, list(zip(*a))))
[[0, 2], [1, 3]]


text:
Q: Induced map in homology for a map to a loop space Suppose $Y$ is an $(n-1)$-connected space, $n>2$, so we have Hurewicz isomorphisms $\pi_n(Y)\cong H_n(Y)$ and $\pi_{n-1}(\Omega Y)\cong H_{n-1}(\Omega Y)$. Let a map $\alpha\colon X\to\Omega Y$ be given. Naturally it induces a map $\beta\colon X\times S^1\to Y$. I want to show the following diagram is commutative:
$$\require{AMScd}
\begin{CD}
H_{n-1}(X) @>\times[S^1]>> H_n(X\times S^1)\\
@V\alpha_*VV @V\beta_*VV \\
H_{n-1}(\Omega Y) @<\cong<< H_n(Y).
\end{CD}
$$
Since $\Omega Y$ is path connected, we may homotope $\alpha$ to a based map. Then $\beta$ factors though the reduced suspension $\Sigma X$. If $X=S^{n-1}$ is a sphere, the commutativity would then follow from tracking down the definition of $\pi_n(Y)\xrightarrow{\cong}\pi_{n-1}(\Omega Y)$. However I don't know how this helps for the general case.
One can also phrase the question in cohomology in the obvious way. (In particular the cross product $\times[S^1]$ will be replaced by the slant product $/[S^1]$.)

A: The general case does follow from the case $Y=S^n$.
Without loss of generality $X=\Omega Y$ and $\alpha$ is the identity. Now the statement comes down to the assertion that the composition
$$
\pi_{n-1}\Omega Y\to H_{n-1}\Omega Y\to H_n(\Omega Y\times S^1)\to H_n Y
$$
corresponds to the Hurewicz map $\pi_nY\to H_nY$ via a natural isomorphism between $\pi_{n-1}\Omega Y$ and $\pi_nY$. This is true for all $Y$, and by naturality it is enough to prove it for $Y=S^n$.


text:
Q: asp.net mvc execute OrderProduct action from summary view I have the following problem,
I'm creating functionality for ordering products for internet shop.
Everything works fine, user can add products to cart. This is how user can complete order:
user goes to cart (cartview)  ,
user must provide shipping details (shippingDetailsView)  ,
summary page is displayed (summaryView)  ,
sending order to server ,
displaying thank you page,
however when user click "proceed" button in summaryView (which is strongly typed by OrderViewModel class) then CompleteOrder action is executed that gets the following parameters:
public ViewResult CompleteOrder(ShoppingCart shoppingCart, OrderViewModel orderViewModel, string returnUrl)

OrderViewModel class looks as follows
public class OrderViewModel
    {
        public Order Order { get; set; }
        public string ReturnUrl { get; set; }
    }

the problem is that Order object inside my orderViewModel object is null. I created some hiddenfields in my summaryView so the Order will be passed appropraite:
<%: Html.HiddenFor(x => x.Order.Client.Firstname)%>

However I don't think this is a good solution. How can I do it appropriate?

A: Since CompleteOrder already has the ReturnUrl parameter, why not simplify your model and just pass the Order itself:
public ViewResult CompleteOrder(ShoppingCart shoppingCart, Order order, string returnUrl


text:
Q: Cucumber doesn't found step file "implement missing steps with the snippets" I have designed my FW and I have exactly placed runner and step files in the package. But I am not able to run the TC, it saying Test pending though steps are defined.
PFA my project structure.
enter image description here
My step file:
package com.reThink.steps;

import net.thucydides.core.annotations.Steps;

import com.reThink.helper.LoginHelper;
import com.reThink.util.CBTestProperties;
import com.reThink.util.Constants;
import com.reThink.util.Log;

import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;

public class LoginSteps {

@Steps
LoginHelper loginHelper;

private String username = null;
private String password = null;

/**
 * Method to navigate to login page
 *
 * @param
 * @return
 */
@Given("^I am on the reThink Login page$")
public void givenIamonthehomepage() throws Exception {
    loginHelper.openLoginPage();
}

/**
 * Method to login as a Admin user
 *
 * @param
 * @return
 */
@When("^I login as an Admin user$")
public void loginWithAdminUser() throws Exception {
    loginHelper.openLoginPage();
    username = CBTestProperties.Instance
            .getTestProperty(Constants.ADMINUSERNAME);
    password = CBTestProperties.Instance
            .getTestProperty(Constants.ADMINPASSWORD);
    loginHelper.loginToRethink(username, password);
}

/**
 * I should be login successfully
 *
 * @param
 * @return
 */
@Then("^I should be logged in successfully$")
public void thenItShouldBeLoggedIn() throws Exception {
    // assertThat(homePageHelper.isLoginSuccessful(username));
    Log.info("Successfully logged in");
}

}
Feature file
@Logon_Admin_User
Scenario: Login to reThink with Admin User credentials
Given I am on the reThink Login page
When I login as an Admin user
Then I should be logged in successfully

A: You are missing glue path in cucumber options of runner class. Please try with followings.
@RunWith(CucumberWithSerenity.class)
@CucumberOptions(features="src/test/resources/features",tags="@Logon_Admin_user",glue = { "com.reThink.steps" })
public class TestRunnerSuite{}


text:
Q: How to share folders using Oracle, Windows and Ubuntu I use my laptop TOSHIBA, 4gig RAM, more 40gig free disks spaces and Vista Home Premium 64bits with service pack 2.
I installed Oracle VM VirtalBox with success, after I installed UBUNTU version 8 with success !
I need to transfer files between Vista and UBUNTU on the same laptop, how I can do that ?
Can I use SAMBA ? I try to use SAMBA but it is not success ! How I can install SAMBA on UBUNTU v.8 ?

A: You need to create a shared folder on the "host" that is shared by the "guest" Go to https://www.virtualbox.org/manual/ch04.html#sharedfolders for more information as it is rather detailed. The online user manual is here https://www.virtualbox.org/manual/UserManual.html


text:
Q: Join mp3 file pairs in folder with ffmpeg I've got a load of mp3 files in a folder, and I want to merge each pair (Part 1 and Part 2) into a single mp3 file. All of the files are in the same format.
I know I can do this on a pair of files:
ffmpeg -i "concat:01 Snow White Part 1.mp3|01 Snow White Part 2.mp3" -acodec copy "01 Snow White.mp3"

.. but how would I do it on a whole folder? This is the folder contents:
01 Snow White Part 1.mp3
01 Snow White Part 2.mp3
02 Jack and the Beanstalk Part 1.mp3
02 Jack and the Beanstalk Part 2.mp3
03 The Wizard of Oz Part 1.mp3
03 The Wizard of Oz Part 2.mp3
04 Thumbelina Part 1.mp3
04 Thumbelina Part 2.mp3
05 Puss in Boots Part 1.mp3
05 Puss in Boots Part 2.mp3
06 The Lions Glasses Part 1.mp3
06 The Lions Glasses Part 2.mp3
07 The Snow Queen Part 1.mp3
07 The Snow Queen Part 2.mp3
08 Alibaba and the Forty Thieves Part 1.mp3
08 Alibaba and the Forty Thieves Part 2.mp3
09 The Emperor's New Clothes Part 1.mp3
09 The Emperor's New Clothes Part 2.mp3
10 Little Red Riding Hood Part 1.mp3
10 Little Red Riding Hood Part 2.mp3

A: Assuming you're using bash on Linux, and assuming all file pairs are numbered as you had listed, I would iterate through the numbers with a for loop.
for c in {1..10}; do
  c=$(printf '%02.f' "$i")
  fnames=$(find . -maxdepth 1 -name "${i}*" | sort)
  parts=$(wc -l <<< "$fnames")
  if [ "$parts" -gt 1 ]; then
    fnameout="${fnames%% Part 1*}.mp3"
    ffmpeg -i "concat: $f" -acodec copy "$fnameout"
  fi
done

If there are any files not paired up, they will be ignored. For testing purposes, I would add echo before ffmpeg, then make the last line done > test.txt so I could check for either mistakes or brilliance.
I hope this helps.

A: This is how I did it in macOS/zsh. I'm sure there's an easier way
PART1FILES=( )
for f in *1.mp3; do
  PART1FILES+=($f)
done
PART2FILES=( )
for f in *2.mp3; do
  PART2FILES+=($f)
done

INDEX=0
for i in $PART1FILES; do
    FILE1=$i
    FILE2=$PART2FILES[INDEX+1]
    NEWFILE="${FILE1:0:-11}.mp3"
    ffmpeg -i "concat:$FILE1|$FILE2" -acodec copy "$NEWFILE"
    let INDEX=${INDEX}+1
done


text:
Q: Huge number while calculating error of predictions I built a multiple linear regression model. My prediction and test values looks close as follow:

I want to calculate error percentage. But got huge numbers in this piece of code:
from sklearn import metrics
print('Mean Absolute Error:', metrics.mean_absolute_error(y_test, y_pred))

Output:
Mean Absolute Error: 137610.86451426445

What should I do now?

A: In general, while performing the regression, we normalize the data fed to the model. This improves predictions and avoids the gradients to actually explode.
See here for more information.
You can carry out normalization in a simple way using,
x_new = x - x.min() / ( x.max() - x.min() )

Where x is the sample from the dataset, x.min() returns the minimum value from the dataset and x.max() returns the maximum value from the data. x_new is the normalized value between 0 and 1.
Hence, you get values which belong to the interval [ 0 , 1 ].

Also, we get smaller values for loss functions like MAE and MSE. The gradients don't explode or have huge values. The training goes on smoothly.

Tip:
Also, read about Standardization of data. Standardization vs. Normalization could be a great read. Maybe, you can read this.


text:
Q: Help identifying this damaged FFC/FPC connector I am trying to identify this damaged connector on one of the PCBs of a Konica Minolta Vivid 910 laser 3D scanner. I wish to find a suitable match for replacement.
It connects the main logic board with the LCD via a FFC cable. (The LCD itself has a small board and connector also, although I don't believe the two are the same connector).
The connector has 33pins, and I'm pretty confident it has a pitch of 0.5mm.

The connector width is 20mm from side to side. Although the front facing corners are damaged so it could have been marginally wider.

I am uncertain of the contact orientation however. I seem to see two sets of matching rows, with the lower apparently protruding slightly more. However the FFC cable only has contacts on one side, suggesting the connector would not be dual contact.
From the photos, I'm inclined to think it is a bottom contact connector.

On this photo you can see the FFC end is one sided, and you can also see the dark grey tab/drawer which now does not fit the connector. Pay no attention to the tape botch-job. It was painful to watch, and I'm not sure about the orientation it's presenting the cable in is correct.

For reference here are two photos of the connector on the LCD side.
I believe it is substantially different, especially the big dark grey flap tab.

I do not have immediate access to this board, as it is in my university, but could recheck facts in the near future if needed.
So, to recap: I believe I am looking for a 33pin 0.5mm pitch, probably bottom contact, FFC connector. I am unsure if the clamping mechanism was a flip tap or a drawer tab.
I am also wondering if it matters either way. Since I am replacing the connector can I not basically match pitch and pin numbers and accommodating for cable orientation select any clamping method that seems reasonably adequate?
In any case, matching the original connector would be nice.
I don't think its a complete match but the closest I've got is this Hirose Connector:
FH12-33S-0.5SH(55)
https://www.mouser.es/ProductDetail/Hirose-Connector/FH12-33S-05SH55?qs=Ux3WWAnHpjB322do3zzp5w==
Let me know what you all think. Thank you very much for the help.
P.S.#2
Also, is 33pins an uncommon number of contacts for FPC/FFC? I seem to find less results with 33pins.

A: Its a Hirose connector, I'm 99% sure (that's before I saw the link in the post). Model # FH12A-33S-0.5SH(55)
See if you can sample one from Hirose directly.
On yours, I think the sides that retain the latch got ripped off somehow

Source: https://www.digikey.com/product-detail/en/hirose-electric-co-ltd/FH12A-33S-0-5SH-55/HFK133TR-ND/1110336


text:
Q: Java Garbage Collector - Not running normally at regular intervals I have a program that is constantly running. Normally, it seems to garbage collect, and remain under about 8MB of memory usage. However, every weekend, it refuses to garbage collect unless I make an explicit call to it. However, if it nears the maximum heap size, it will still garbage collect. However the only reason this issue was noticed, is because it actually crashed from running out of memory on one weekend i.e. it must have reached the maximum heap size, and not run the garbage collector.
The following image (click to see) is a graph of the program's memory usage over a day. On the sides of the graph, you can see the normal behaviour of the program's memory usage, but the first large peak is what seems to start over the weekend. This particular graph is a strange example, because after I made an explicit call to the garbage collector, it ran successfully, but then it went and climbed back to the maximum heap size and successfully garbage collected on it's own twice.
What is going on here?
EDIT:
Ok, from the comments, it seems I haven't provided enough information. The program simply receives a stream of UDP packets, which are placed in a queue (set to have a maximum size of 1000 objects), which are then processed to have their data stored in a database. On average, it gets about 80 packets per second, but can peak to 150. It's running under Windows Server 2008.
The thing is, this activity is fairly consistent, and if anything, at the time that the memory usage starts it's steady climb, the activity should be lower, not higher. Mind you, the graph I posted above is the only one I have that extends back that far, since I only changed the Java Visual VM wrapper to keep graph data back far enough to see it this week, so I have no idea if it's exactly the same time every week, because I can't watch it over the weekend, as it's on a private network, and I'm not at work on the weekend.
Here is a graph of the next day:
This is pretty much what the memory usage looks like every other day of the week. The program is never restarted, and we only tell it to garbage collect on a Monday morning because of this issue. One week we tried restarting it on a Friday afternoon, and it still started climbing sometime over the weekend, so the time that we restart it doesn't seem to have anything to do with the memory usage next week.
The fact that it successfully garbage collects all those objects when we tell it to implies to me that the objects are collectable, it's just not doing it until it reaches the maximum heap size, or we explicitly call the garbage collector. A heap dump doesn't tell us anything, because when we try to perform one, it suddenly runs the garbage collector, and then outputs a heap dump, which of course looks perfectly normal at this point.
So I suppose I have two questions: Why is it suddenly not garbage collecting the way it does the rest of the week, and why is it that on one occassion, the garbage collection that occurs when it reaches the maximum heap size was unable to collect all those objects (i.e. why would there be references to so many objects that one time, when every other time there must not be)?
UPDATE:
This morning has been an interesting one. As I mentioned in the comments, the program is running on a client's system. Our contact in the client organisation reports that at 1am, this program failed, and he had to restart it manually when he got into work this morning, and that once again, the server time was incorrect. This is an issue we've had with them in the past, but until now, the issue never seemed to be related.
Looking through the logs that our program produces, we can deduce the following information:

*

*At 01:00, the server has somehow resynced it's time, setting it to 00:28.

*At 00:45 (according to the new, incorrect server time), one of the message processing threads in the program has thrown an out of memory error.

*However, the other message processing thread (there are two types of messages we receive, they are processed slightly differently, but they are both constantly coming in), continues to run, and as usual, the memory usage continues to climb with no garbage collection (as seen from the graphs we have been recording, once again).

*At 00:56, the logs stop, until about 7am when the program was restarted by our client. However, the memory usage graph, for this time, was still steadily increasing.

Unfortunately, because of the change in server time, this makes the times on our memory usage graph unreliable. However, it seems to be that it tried to garbage collect, failed, increased the heap space to the maximum available size, and killed that thread all at once. Now that the maximum heap space has increased, it's happy to use all of it without performing a major garbage collection.
So now I ask this: if the server time changes suddenly like it did, can that cause a problem with the garbage collection process?

A: If possible, I would setup the process to dump the heap if it runs out of memory - so you can analyze it if (when) it happens again. Not an answer, but a potential route to a solution.
Here are the JVM options, taken from Oracle's Java HotSpot VM Options page. (This assumes you have an Oracle JVM):

-XX:HeapDumpPath=./java_pid.hprof
Path to directory or filename for heap
  dump. Manageable. (Introduced in 1.4.2
  update 12, 5.0 update 7.)
-XX:-HeapDumpOnOutOfMemoryError
Dump heap to file when
  java.lang.OutOfMemoryError is thrown.
  Manageable. (Introduced in 1.4.2
  update 12, 5.0 update 7.)

A: Ok guys, thanks for all your help. The correct answer however, turned out to have nothing to do with the program itself.
It seems that at the time that the memory usage started it's steady climb, the server was synchronising it's time from somewhere internal, though our client's IT contact has no idea where. Obviously, wherever it was coming from, was not a good clock, since the time was half an hour behind. We turned off this synchronisation, and now that I have checked it again this morning, the problem did not occur. So if the time on your system suddenly changes, apparently this causes problems for the garbage collector. At least that's what this implies to me.
As for why this wasn't occuring on any other parts of our system on this server (which are also written in Java), we probably simply haven't noticed, as they don't deal with as large a number of objects, and so they would never have hit their out of memory state.
I find this strange, since I would have thought that the invoking of the garbage collector would be completely related to memory usage, and not on the system time at all. Clearly, my understanding of how the garbage collector works is woefully inadequate.

A:
However the only reason this issue was noticed, is because it actually crashed from running out of memory on one weekend i.e. it must have reached the maximum heap size, and not run the garbage collector.

I think your diagnosis is incorrect.  Unless there is something seriously broken about your JVM, then the application will only throw an OOME after it has just run a full garbage collect, and discovered that it still doesn't have enough free heap to proceed*.
I suspect that what is going on here is one or more of the following:

*

*Your application has a slow memory leak.  Each time you restart the application, the leaked memory gets reclaimed.  So, if you restart the application regularly during the week, this could explain why it only crashes on the weekend.

*Your application is doing computations that require varying amounts of memory to complete.  On that weekend, someone sent it a request that required more memory that was available.
Running the GC by hand is not actually going to solve the problem in either case.  What you need to do is to investigate the possibility of memory leaks, and also look at the application memory size to see if it is large enough for the tasks that are being performed.
If you can capture heap stats over a long period, a memory leak will show up as a downwards trend over time in the amount of memory available after full garbage collections.  (That is the height of the longest "teeth" of the sawtooth pattern.)  A workload-related memory shortage will probably show up as an occasional sharp downwards trend in the same measure over a relatively short period of time, followed by a recovery.  You may see both, then you could have both things happening.
* Actually, the criteria for deciding when to give up with an OOME are a bit more complicated than this.  They depend on certain JVM tuning options, and can include the percentage of time spent running the GC.
FOLLOWUP
@Ogre - I'd need a lot more information about your application to be able to answer that question (about memory leaks) with any specificity.
With your new evidence, there are two further possibilities:

*

*Your application may be getting stuck in a loop that leaks memory as a result of the clock time-warping.

*The clock time-warping may cause the GC to think that it is taking too large a percentage of run time and trigger an OOME as a result.  This behaviour depends on your JVM settings.
Either way, you should lean hard on your client to get them to stop adjusting the system clock like that.  (A 32 minute timewarp is way too much!!).  Get them to install a system service to keep the clock in sync with network time hour by hour (or more frequent).  Critically, get them to use a service with an option to adjusts the clock in small increments.
(Re the 2nd bullet: there is a GC monitoring mechanism in the JVM that measures the percentage of overall time that the JVM is spending running the GC, relative to doing useful work.  This is designed to prevent the JVM from grinding to a halt when your application is really running out of memory.
This mechanism would be implemented by sampling the wall-clock time at various points.  But if the wall-clock time is timewarped at a critical point, it is easy to see how the JVM may think that a particular GC run took much longer than it actually did ... and trigger the OOME.)


text:
Q: Why using ADODB.Stream with ASCII charset special chars as ä are converted to a? I'm having a problem trying to output the content of some variables in vb6 into a text file. The thing is that when a special character from extended ASCII appears as ä, ü, á it is transformed in the output to the matching basic ASCII char like a, u, a.
I've tried to export it like UTF-8 and then the character is shown correctly, but I need the output to be ASCII. Also, looks strange for me that the filename can normally contain this chars (ä, ü, á...) without sustitution.
Can this be because "ASCII" charset is just the basic and not the extended? Maybe because of the CodePages configured in Windows? I've tried with a couple of them (German, English) with the same result.
This is the code I'm using:
Set fileStream = New ADODB.Stream
If Not fileStream Is Nothing Then
    inputString = textPreAppend + inputString
    fileStream.charSet = "ASCII"
    fileStream.Open
    fileStream.WriteText inputString
    fileStream.Flush
    fileStream.SaveToFile fileName, adSaveCreateOverWrite
    fileStream.Flush
    fileStream.Close
End If
Set fileStream = Nothing

Thanks in advance!

A: Both PRB: Charset Property of ADO Stream Object May Require Microsoft Internet Explorer Upgrade and Charset Property (ADO) suggest that ADO CharSet values are those listed under HKEY_CLASSES_ROOT\MIME\Database\Charset but that clearly is not the entire story.
For example both values "ascii" and "us-ascii" are listed there as aliases of "iso-8859-1" however running with my locale set to U.S. English they act like a 7-bit ASCII MIME type.  They'd almost have to, since there is nothing else provided for requesting 7-bit ASCII encoding anyway.
This produces the result you seem to want:
Option Explicit

Private Sub Main()
    Dim fileStream As ADODB.Stream
    Dim inputString As String
    Const FileName As String = "outputfile.txt"

    Set fileStream = New ADODB.Stream
    inputString = "The thing is that when a special character" & vbNewLine _
                & "from extended ASCII appears as ä, ü, á it" & vbNewLine _
                & "is transformed in the output to the matching" & vbNewLine _
                & "basic ASCII char like a, u, a." & vbNewLine
    With fileStream
        .Type = adTypeText
        .Charset = "iso-8859-1"
        .Open
        .WriteText inputString
        .SaveToFile FileName, adSaveCreateOverWrite
        .Close
    End With
End Sub

Output:
The thing is that when a special character
from extended ASCII appears as ä, ü, á it
is transformed in the output to the matching
basic ASCII char like a, u, a.

We have to assume that asking for "ascii" (the values are all lowercased though clearly are not case-sensitive) means 7-bit ASCII, perhaps localized.
Using UTF-8 is a bad idea unless you want UTF-8.  While a lot of *nix systems pretend there is no difference, the Stream will write a BOM and of course those extended (non-ASCII) characters are multibyte encoded.

A: Why can't you just do something like the following? This works ok for me:
    Dim FileNo As Integer
    Dim strFile As String

    strFile = "C:\Test.txt"
    FileNo = FreeFile

    Dim strVariable As String
    strVariable = "some text with extended chars in: ÙÑáêôü"

    Open strFile For Append As #FileNo

    Print #FileNo, strVariable

    Close #FileNo


text:
Q: How to combine video segments on a server and then stream to web and iphone I am trying to work out a solution to achieve the following:
I have a number of videos ( all same format and dimensions ) that I wish to be able to dynamically combine based on a web front end, and then stream the result.
I need to stream to web ( flash ) as well as iPhone ( http live streaming )
My current thoughts are to take the videos and then combine them with ffmpeg-php on the server, then with the resulting file provide it for viewing either as a progressive or through the use of flash media server / wowza server.
My question is: Are there better ways to handle this.... ( some smarts within wowza or flash media server that could do this for me)

A: It will likely be much easier to use some sort of playlist.
For the iOS devices, HTTP Live Streaming readily support such a mechanism with the .m3u8 files.  For the Flash-based players, you could implement something custom or use JW Player which can do such magic.
Working with FFmpeg will be much more complex:

*

*if your video sources are notably different in size or CODEC parameters, the poor quality and outright failures will happen

*transcoding can easily degrade quality if you are not well versed in such matters.

*dramatically more CPU resources will be required on the server.  Like >10,000% more than a playlist approach, depending.


text:
Q: Irrationality of sum of b-ary interpretations of positive rational number Given a finite rational number $n$ such that $0<n<1$, how can one determine whether the sum:
$$
\sum_{b=2}^{\infty} n_b,
$$
where $n_b$ denotes the $b$-ary interpretation of $n$, is rational or irrational? In other words, how can one determine the rationality of, for instance:
$$
0.1234_2+0.1234_3+0.1234_4+0.1234_5+\ldots?
$$

A: Your question statement is a little confusing -- how does one go from the number $n$ to the decimal expansion? I'll assume you just write it in base 10 and then move on. I will also assume that by finite you mean its decimal expansion is finite. So let $n_b = \sum_{i=1}^{n} a_i / b^i$, where $a_i$ is the $i$th digit from the decimal point.
If $a_1 \neq 0$, then the series does not converge because one has the sum $ \sum_{b=1}^{\infty} a_i/b$, which diverges because it is the harmonic series.
Otherwise, we have $a_1 = 0$, and the answer depends on an open question; in particular it depends on the positive integer values of $\zeta$. If only even terms appear, then it is definitely irrational because the sum is of the form
$$
\sum_{i=1}^{n} c_i \pi^{2i}
$$
and the powers of $\pi$ are linearly independent over $\mathbb{Q}$ ($\pi$ is transcendental). Otherwise, the answer depends on which values of the odd positive integers are irrational (not fully known, although there are infinitely many which are), and whether they are linearly independent to $\pi$.


text:
Q: How do include functiont using Laravel 5.4 i have a problem when include a view in laravel 5.4
this is the error:

3/3) ErrorException Undefined variable: categories (View:
  C:\xampp\htdocs\blog\resources\views\partials\index.blade.php) (View:
  C:\xampp\htdocs\blog\resources\views\partials\index.blade.php)

my index:
@extends('layouts.master')

@section('content')

@include('partials.index')

@endsection
________
// this is index in partials

Категория:

                Дабавить Катигорию

                @foreach($categories as $cat)

                            photo)}}" alt="...">

{{$cat->title}}

                                <form action="{{url('categories/' . $cat->id)}}" method="POST">
                                    {{csrf_field()}}
                                    {{method_field('DELETE')}}

                                        id . '/description')}}" class="btn btn-primary" role="button">подробности
                                        id . '/edit')}}" class="btn btn-warning" role="button">редактировать
                                        <button type="submit" class="btn btn-danger">удалить</button>

                                </form>

                @endforeach

My controller:
this is my controller
  <?php

    namespace App\Http\Controllers;

    use Illuminate\Http\Request;
    use Illuminate\Http\UploadedFile;

    use App\Http\Requests\catRequest;

    use App\Category;
    use App\User;
    use Auth;
    use Illuminate\Support\Facades\Storage;

    class CategoryController extends Controller
    {
        //middleware auth
        public function __construct()
        {
            $this->middleware('auth');

        }
        public function show($id )
        {

            $cat = Category::query()->find($id);

            return view('categories.description' , ['categories' => $cat]);
        }

        public function index(){
           //$listCat = Category::all();

           $listCat = Category::where('user_id' , Auth::user()->id)->get();
            return view('categories.index' , ['categories' => $listCat]);
        }
        public function create(){
            return view('categories.create');
        }
        public function store( catRequest $request  ){

             //return $request->all();
            $cat = new Category();
            $cat->title = $request->input('title');
            $cat->description = $request->input('description');
            $cat->user_id = Auth::user()->id;

            if($request->hasFile('photo')){
                $cat->photo = $request->photo->store('photo');
            }
            $cat->save();
            session()->flash('success' , 'Катигория дабавлена');
            return redirect('categories');

        }

        /**
         * @param $id
         * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
         */
        public function edit($id){

            $cat = Category::query()->find($id);

            return view('categories.edit' , ['categories' => $cat]);
        }

        /**
         * @param Request $request
         * @param $id
         */
        public function update(catRequest $request, $id){
            $cat = Category::query()->find($id);
            $cat->title = $request->input('title');
            $cat->description = $request->input('description');
            if($request->hasFile('photo')){
                $cat->photo = $request->photo->store('photo');
            }
            $cat->save();
            return redirect('categories');
        }
        public function destroy(Request $request, $id){
            $cat = Category::query()->find($id);
            $cat->delete();
            return redirect('categories');

        }
    }

A: It appears that your error is describing a missing variable

ErrorException Undefined variable: categories.

This means that the blade template can't see the $categories variable that you are using in the for loop.
Check your web.php or app/Http/Controller/file.php where the blade template is being called and be sure you are passing a variable along to the view function.
example
return view('greeting', ['name' => 'James']); // <= passing a variable $name with string 'James'

Laravel Reference https://laravel.com/docs/5.4/views


text:
Q: Can PhoneGap work with local SQLite3 databases? I was wondering if PhoneGap can work with local SQLite3 databases and what level of SQLite3 support it has.

A: Ya it does work, you can use either of following:
It's important to remember that PhoneGap is web apps packaged in a browser component. Everything that applies to mobile WebKit will apply to PhoneGap as well, and the environment in PhoneGap is also very similar to opening an HTML-file in a desktop browser.
Web SQL Database:
http://www.w3.org/TR/webdatabase/
PhoneGap SQLite Plugin:
https://github.com/davibe/Phonegap-SQLitePlugin

A: Phonegap works very well with local SQLite3 database.
check out this link for tutorial http://groups.google.com/group/phonegap/browse_thread/thread/07cf9f48e3cd0663?pli=1


text:
Q: What is sum of the Bernoulli numbers? $$\sum_{n=0}^\infty B_n =  ?$$
I tried Wolfram Alpha but I can't seem to get the input correct.

A: Using divergent summation (Nörlund sum) one can find it numerically that it is surely $\zeta(2)-1 \approx 0.644934$.
I've asked this question a couple of years ago in the usenet (sc.math) in a more general form, where the bernoulli-numbers are cofactored with sequences of binomial-coefficients. One reader (Robert Israel) showed an analytical derivation using the psi-function, which gave as a result, that the results were systematically $\zeta(2)-1,\zeta(3)-1,\zeta(4)-1,...$ with that binomial-coefficients as cofactors. (See the link at the end below)
I've an old article (with many inexact and sloppy formulation due to my limited knowledge then) containing a compilation of similar sums on my website where in the appendix I've reproduced that proof.
On page 5 you can find the definition of a matrix, which contains the bernoulli-numbers and indicated cofactors; this matrix contains the coefficients of the integrals of the Bernoulli-polynomials (or, equivalently said, the coefficients of the Faulhaber-polynomials for the sums-of-like-powers) if you read it rowwise instead of columnwise.
Here is a link to the discussion in the google-news-archive

A: From the the definition of the Bernoulli numbers $B_n$, we know that,  $ \frac{x}{e^x-1}=\sum_{n=0}^{\infty}\frac{B_nx^n}{n!} $ ........(1)
Multiply oth the sides of this equation by $x^ke^{-x}$ , so we get $ \frac{x^{k+1}e^{-x}}{e^x-1}=\sum_{n=0}^{\infty}\frac{B_nx^{n+k}e^{-x}}{n!} $
Integrate both the sides of this equation from zero to infinity,so we get
$ \int_{0}^{\infty}\frac{x^{k+1}e^{-x}}{e^x-1}dx=\int_{0}^{\infty}\sum_{n=0}^{\infty}\frac{B_nx^{n+k}e^{-x}}{n!}dx $
We note here that, definition given as per Eq.(1) is valid only for '$ 0 \leq x < 2 \pi $' and therefore the integral taken on both the sides w.r.t. '$x$' in the range of $0$ to $\infty$ is a valid step only at LHS but since infinite series at RHS is convergent only under above constraints of x , hence such integral on RHS will give rise to a divergent sum.  But, I think, in the sense of analytic continuation only, the divergent sum on RHS can be said to have the finite value equal to value of the integral at LHS. But, direct calculation will always say that RHS is a divergent sum.
Other similar example i can give here is, the sum of factorials and alternate sum of factorials of all integers. These sums are actually divergent, but a finite value can be assigned to it. This is a famous sum given by Euler and by Ramanujan also.
Now, proceeding further,
$ \int_{0}^{\infty}\frac{x^{k+1}e^{-x}}{e^x-1}dx=\sum_{n=0}^{\infty}\frac{B_n}{n!}\int_{0}^{\infty}x^{n+k}e^{-x}dx $
$ \int_{0}^{\infty}\frac{x^{k+1}e^{-x}}{e^x-1}dx=\sum_{n=0}^{\infty}\frac{B_n}{n!}\times (n+k)! $
$ \int_{0}^{\infty}\frac{x^{k+1}e^{-x}}{e^x-1}dx=\sum_{n=0}^{\infty}\frac{B_n(n+k)!}{n!} $
So, finally we got $ \sum_{n=0}^{\infty}\frac{B_n(n+k)!}{n!}=\int_{0}^{\infty}\frac{x^{k+1}e^{-x}}{e^x-1}dx $
So, let $I=\int_{0}^{\infty}\frac{x^{k+1}e^{-x}}{e^x-1}dx$
This can be written equivalently as,
$I=\int_{0}^{\infty}x^{k+1}e^{-2x}(\frac{1}{1-e^{-x}})dx$
Since, $e^{-x}<1 $ for $0<x<\infty $ , hence we can write,
$I=\int_{0}^{\infty}x^{k+1}e^{-2x}(1+e^{-x}+e^{-2x}+e^{-3x}+e^{-4x}+......)dx$
$I=\int_{0}^{\infty}x^{k+1}e^{-2x}dx+\int_{0}^{\infty}x^{k+1}e^{-3x}dx+\int_{0}^{\infty}x^{k+1}e^{-4x}dx+\int_{0}^{\infty}x^{k+1}e^{-5x}dx+......$
Now, consider a general term of above integral as, $I_r=\int_{0}^{\infty}x^{k+1}e^{-rx}dx$
Substitute, $rx=t$ , so we get $ rdx=dt$  i.e.  $dx=\frac{1}{r}dt$ and $x=\frac{t}{r}$
The limits of integration will remain the same, hence we finally get
$I_r=\frac{1}{r^{k+2}}\int_{0}^{\infty}t^{k+1}e^{-t}dt$ which is $I_r=\frac{1}{r^{k+2}}\times (k+1)!$
So, finally we got,  $I_r=\frac{(k+1)!}{r^{(k+2)}}$
Hence, from the form of above integral $I$ , we can write
$I=\frac{(k+1)!}{2^{k+2}}+\frac{(k+1)!}{3^{k+2}}+\frac{(k+1)!}{4^{k+2}}+.... $
i.e. $I=(k+1)!(\zeta(k+2)-1) $
So, we finally got $ \sum_{n=0}^{\infty}\frac{B_n(n+k)!}{n!}=\int_{0}^{\infty}\frac{x^{k+1}e^{-x}}{e^x-1}dx=(k+1)!(\zeta(k+2)-1) $
Dividing everything by 'k!' , we get,
So, we finally got $ \sum_{n=0}^{\infty}\frac{B_n(n+k)!}{k!n!}=\frac{1}{k!}\int_{0}^{\infty}\frac{x^{k+1}e^{-x}}{e^x-1}dx=(k+1)(\zeta(k+2)-1) $
As per definition of Binomial coefficient, we know that $\frac{(n+k)!}{k!n!}$ can be replaced by Binomial coefficient ${n+k}\choose{k}$
So, when $k=0$ , we get $\sum_{n=0}^{\infty} B_n=\int_{0}^{\infty}\frac{x^{1}e^{-x}}{e^x-1}dx=\zeta(2)-1 $
I have plotted $y=\frac{x^{k+1}e^{-x}}{e^x-1}$ for different values of 'k' I have also checked and confirmed the validity of the result $ \int_{0}^{\infty}\frac{x^{1}e^{-x}}{e^x-1}dx=\zeta(2)-1 $ which holds 100 percent true as the graph suggest that this integral do converge to finite value
This result is analogous in some sense to analytic continuation of a function - just as in case of Zeta function values at negative integers.
If anyone could suggest me some good e-books about detailed analysis of such concepts , i will be very much thankful.


text:
Q: Proving a certain set is inductive Let's give some context. We have to prove «Krull's theorem», which states that:

If $A$ is a commutative ring, $N$ is its (nil)radical, i.e. the set of its nilpotent elements $\{x\in A:\exists p\in\mathbb{N}:x^p=0\}$, and $N_0$ is the intersection of all its prime ideals, then:
  $$N=N_0.$$

We prove it by proving $N\subseteq N_0$ and $N_0\subseteq N$. For the second one we prove $A\smallsetminus N_0\subseteq A\smallsetminus N$, i.e. that $x\not\in N_0\implies x\not\in N$. The proof starts by setting $S=\{1,x,x^2,\dots\}$ and seeing it is a multiplicative submonoid of $(A,\cdot)$. Since $x^p\neq0\forall p\in\mathbb{N}$, we deduce that $\{0\}\cap S=\varnothing$. That means that:
$$\Pi=\{I\leq A:I\cap S=\varnothing\}\neq\varnothing,$$
where by $\leq$ I denote "is an ideal of". Then we state $\Pi$ is inductive, and thus by Zorn's lemma has a maximal element $J$. The proof then moves on to proving $J$ is prime, which concludes our proof, since $x\not\in J$. We have the following definition of "inductive":

A set of sets where each ascending chain has a supremum (i.e. a maximal element) is inductive.

So the question is: how do I prove this $\Pi$ is inductive?

A: If $P \subseteq \Pi$ is a chain, then $\cup P$ is an upper bound.


text:
Q: TypeError: __init__() takes 4 positional arguments but 5 were given, added all elements still problem on accesing elements I am trying for multiple inheritance, but upon passing super() on my child class , it showing  Type error. How can i solve the issue im new to python
class Employee:
    def __init__(self,first,last,salary):
        self.first=first
        self.last=last
        self.salary=salary
        self.email="{}{}@company.com".format(first,last)

class administrator:
    def __init__(self,age):
        self.age=age

class Manager(Employee,administrator):
    def __init__(self,first,last,salary,age,gender):

        super().__init__(first,last,salary,age)
        self.gender=gender

manager1=Manager("Max","Milan",50000,26,"male")

print(manager1.email)
print(manager1.gender)

I was expecting when
print(manager1.email)
print(manager1.gender) to produce following outputs
MaxMilan@company.com
male


text:
Q: Cannot Delete Git/GitHub Repository I am totally new to version control of any kind, including: Git and Github. But yesterday I thought I would give it a try for some lecture slides I was working on. You can see my botched attempts at: https://github.com/meaneych
I hastily created a number of repositories. But now I don't want them and would to delete them from Git/Github (I kind of want to undo everything and just start from scratch).
I followed the instruction for deleting repositories at:
https://help.github.com/articles/deleting-a-repository
However, when I go to click on the "Delete this repository" button nothing happens (i.e. I don't get prompted with the pop up that should occur at step 4). Why? Have I locked some files, is there some kind of a file access issue, or have I committed some kind of an illegal move that will not allow me to fully delete a repository?

I also tried to follow the command line instructions given here: How do I delete a local repository in git? However, the repositories still remain in Git/Github (I still see them). And also, when in the Mac Github GUI I can't access the Menu - Edit - Delete button to try to delete any local or Guthub repositories as shown here:

I am totally new to Git/Github and just want to start from scratch. How would I delete all these local and Github repositories I made in error? Thanks in advance for your help.

A: Do you use NoScript or similar addons? It blocks the delete popup for me, if it's activated on the site. If so, try whitelisting github.com.
Edit: unfortunately, I don't have easy access to Safari, so I can't provide help specific to that browser.


text:
Q: Remove Gitlab EE from Centos7 I just installed https://about.gitlab.com/installation/#centos on Centos7 vps running Apache.  I should have read more before doing so as it conflicts with Apache and I don't want the EE edition.  How should I remove it?
curl https://packages.gitlab.com/install/repositories/gitlab/gitlab-ee/script.rpm.sh | sudo bash
sudo yum install gitlab-ee
sudo gitlab-ctl reconfigure

I tried the following.
sudo gitlab-ctl stop
sudo gitlab-ctl uninstall
rpm -e gitlab

And after rebooting, am far from uninstalled
[michael@vps~]$ ps -ef | grep gitlab
root       730     1  0 13:49 ?        00:00:00 runsvdir -P /opt/gitlab/service log: ...........................................................................................................................................................................................................................................................................................................................................................................................................
root       743   730  0 13:49 ?        00:00:00 runsv gitlab-workhorse
root       750   730  0 13:49 ?        00:00:00 runsv gitlab-monitor
root       751   743  0 13:49 ?        00:00:00 svlogd -tt /var/log/gitlab/gitlab-workhorse
root       752   741  0 13:49 ?        00:00:00 svlogd -tt /var/log/gitlab/sidekiq
git        753   743  0 13:49 ?        00:00:00 /opt/gitlab/embedded/bin/gitlab-workhorse -listenNetwork unix -listenUmask 0 -listenAddr /var/opt/gitlab/gitlab-workhorse/socket -authBackend http://localhost:8080 -authSocket /var/opt/gitlab/gitlab-rails/sockets/gitlab.socket -documentRoot /opt/gitlab/embedded/service/gitlab-rails/public -pprofListenAddr  -secretPath /opt/gitlab/embedded/service/gitlab-rails/.gitlab_workhorse_secret -config config.toml
git        754   741 21 13:49 ?        00:00:15 sidekiq 5.0.0 gitlab-rails [0 of 25 busy]
root       755   739  0 13:49 ?        00:00:00 svlogd -tt /var/log/gitlab/postgresql
root       756   738  0 13:49 ?        00:00:00 svlogd -tt /var/log/gitlab/redis
gitlab-+   757   739  0 13:49 ?        00:00:00 /opt/gitlab/embedded/bin/postgres -D /var/opt/gitlab/postgresql/data
gitlab-+   758   738  0 13:49 ?        00:00:00 /opt/gitlab/embedded/bin/redis-server 127.0.0.1:0
root       759   740  0 13:49 ?        00:00:00 svlogd -tt /var/log/gitlab/unicorn
git        760   740  0 13:49 ?        00:00:00 /bin/bash /opt/gitlab/embedded/bin/gitlab-unicorn-wrapper
root       761   749  0 13:49 ?        00:00:00 svlogd -tt /var/log/gitlab/postgres-exporter
gitlab-+   762   749  0 13:49 ?        00:00:00 /opt/gitlab/embedded/bin/postgres_exporter -web.listen-address=localhost:9187
root       763   742  0 13:49 ?        00:00:00 svlogd -tt /var/log/gitlab/gitaly
git        764   742  0 13:49 ?        00:00:00 /opt/gitlab/embedded/bin/gitaly /var/opt/gitlab/gitaly/config.toml
root       765   744  0 13:49 ?        00:00:00 svlogd -tt /var/log/gitlab/nginx
root       766   744  0 13:49 ?        00:00:00 nginx: master process /opt/gitlab/embedded/sbin/nginx -p /var/opt/gitlab/nginx
root       767   745  0 13:49 ?        00:00:00 svlogd -tt /var/log/gitlab/logrotate
root       768   750  0 13:49 ?        00:00:00 svlogd -tt /var/log/gitlab/gitlab-monitor
root       769   745  0 13:49 ?        00:00:00 /bin/sh /opt/gitlab/embedded/bin/gitlab-logrotate-wrapper
git        770   750  0 13:49 ?        00:00:00 /opt/gitlab/embedded/bin/ruby /opt/gitlab/embedded/bin/gitlab-mon web -c /var/opt/gitlab/gitlab-monitor/gitlab-monitor.yml
root       771   746  0 13:49 ?        00:00:00 svlogd -tt /var/log/gitlab/prometheus
gitlab-+   772   746  0 13:49 ?        00:00:00 /opt/gitlab/embedded/bin/prometheus -web.listen-address=localhost:9090 -storage.local.path=/var/opt/gitlab/prometheus/data -storage.local.chunk-encoding-version=2 -storage.local.target-heap-size=68005724 -config.file=/var/opt/gitlab/prometheus/prometheus.yml
root       773   748  0 13:49 ?        00:00:00 svlogd -tt /var/log/gitlab/redis-exporter
gitlab-+   774   748  0 13:49 ?        00:00:00 /opt/gitlab/embedded/bin/redis_exporter -web.listen-address=localhost:9121 -redis.addr=unix:///var/opt/gitlab/redis/redis.socket
root       780   747  0 13:49 ?        00:00:00 svlogd -tt /var/log/gitlab/node-exporter
gitlab-+   781   747  0 13:49 ?        00:00:00 /opt/gitlab/embedded/bin/node_exporter -web.listen-address=localhost:9100 -collector.textfile.directory=/var/opt/gitlab/node-exporter/textfile_collector
gitlab-+   832   766  0 13:49 ?        00:00:00 nginx: worker process
gitlab-+   833   766  0 13:49 ?        00:00:00 nginx: worker process
gitlab-+   834   766  0 13:49 ?        00:00:00 nginx: cache manager process
gitlab-+   843   757  0 13:49 ?        00:00:00 postgres: checkpointer process
gitlab-+   844   757  0 13:49 ?        00:00:00 postgres: writer process
gitlab-+   845   757  0 13:49 ?        00:00:00 postgres: wal writer process
gitlab-+   846   757  0 13:49 ?        00:00:00 postgres: autovacuum launcher process
gitlab-+   847   757  0 13:49 ?        00:00:00 postgres: stats collector process
git        939     1 20 13:49 ?        00:00:14 unicorn master -D -E production -c /var/opt/gitlab/gitlab-rails/etc/unicorn.rb /opt/gitlab/embedded/service/gitlab-rails/config.ru
gitlab-+   997   757  0 13:49 ?        00:00:00 postgres: gitlab-psql postgres [local] idle
git       2631   939  0 13:50 ?        00:00:00 unicorn worker[0] -D -E production -c /var/opt/gitlab/gitlab-rails/etc/unicorn.rb /opt/gitlab/embedded/service/gitlab-rails/config.ru
git       2634   939  0 13:50 ?        00:00:00 unicorn worker[1] -D -E production -c /var/opt/gitlab/gitlab-rails/etc/unicorn.rb /opt/gitlab/embedded/service/gitlab-rails/config.ru
git       2639   939  0 13:50 ?        00:00:00 unicorn worker[2] -D -E production -c /var/opt/gitlab/gitlab-rails/etc/unicorn.rb /opt/gitlab/embedded/service/gitlab-rails/config.ru
gitlab-+  2685   757  0 13:50 ?        00:00:00 postgres: gitlab gitlabhq_production [local] idle
gitlab-+  2764   757  0 13:50 ?        00:00:00 postgres: gitlab gitlabhq_production [local] idle
gitlab-+  2765   757  0 13:50 ?        00:00:00 postgres: gitlab gitlabhq_production [local] idle
gitlab-+  2766   757  0 13:50 ?        00:00:00 postgres: gitlab gitlabhq_production [local] idle
gitlab-+  2767   757  0 13:50 ?        00:00:00 postgres: gitlab gitlabhq_production [local] idle
gitlab-+  2768   757  0 13:50 ?        00:00:00 postgres: gitlab gitlabhq_production [local] idle
gitlab-+  2769   757  0 13:50 ?        00:00:00 postgres: gitlab gitlabhq_production [local] idle
gitlab-+  2770   757  0 13:50 ?        00:00:00 postgres: gitlab gitlabhq_production [local] idle
michael   2784  2695  0 13:50 pts/0    00:00:00 grep --color=auto gitlab
[michael@vps~]$

A: Simplest way to undo installation is that run yum remove on every thing before that installed with yum install. In this case run sudo gitlab-ctl stop and then sudo yum remove gitlab-ee.

A: As a simple solution you could use yum history command. After you could run yum history undo <ID> and it will revert all changes done in requested ID. If you do it just now, you could undo latest ID.

A: It is a VPS. Destroy it, rebuild another VM if desired.
Studying the package management of an appliance and cleaning it up may be educational, but time consuming. Some appliances are only concerned about their one application and will leave configuration unmanaged by their packages.


text:
Q: Таймер для скачивания на PHP Здорова!
Как написать таймер на PHP типа, как на сайте depositfiles - через 30 или 60 секунд начнется скачивание(пример на картинке), если нужно использовать JS, то как это все соединить?
Однако, было бы лучше использовать чисто PHP.
А также можно ли управлять скоростью отсчета таймера? типа чтоб быстрее или медленнее считал?

A: Для этого вам нужен JavaScript
Например так:

setTimeout(() => alert('Начинаем скачивать'), 3000);
Скачивание скоро начнется

Источник: https://learn.javascript.ru/settimeout-setinterval

A: Выглядит примерно так:
function download() {
  // fetch code
}

setTimeout(download, 60000)


text:
Q: Tabs widget from Elementor is not showing the content in it to users. But at admin side it is working fine As you can see in attached screenshot it is just showing the title name of tabs nothing else. By clicking on the titles nothing it will do. So, This is how users having experience. It is working and showing perfect from admin view.
Any solution?

A: I had the same trouble. If it's working in the admin section, then generally cache / performance optimisations are switched off for admin so that any changes can be seen instantly. If it's not displaying when logged out check the developer console for messages. In my case I had to switch off the 'Defer Render-blocking JS' as scripts were not running with correct dependancies.
Hope this helps
ps if this doesn't work just temporarily diasble cache / performance optimisations to see if that's the cause and then work on each option until you find out whats wrong.


text:
Q: HttpPost for Action (save) ends in 404-error I have a C# Website and Web API combined. In the Web API part I have four Controllers (for Products, Categories, Users and Orders). The normal GetAllProducts, GetProduct, etc. that MVC API Controller default use are working fine, but now I want an Action method for a HttpPost (to Save Orders).
Here below is what I had before I wanted to add this Save-Action (PS: At the bottom you can see what I've tried to make the save Action work):
WebApiConfig.cs:
using WebMatrix.WebData;
using System.Web.Security;

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Only allow JSON response format
        var json = config.Formatters.JsonFormatter;
        json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
        config.Formatters.Remove(config.Formatters.XmlFormatter);

        // Default API HttpRoute
        // Call examples: "/api/products" or "/api/products/2"
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        // Configure the DependencyResolver and register all API-Controllers
        var container = new UnityContainer();
        container.RegisterType<IProductsRepository, ProductsRepository>(new HierarchicalLifetimeManager());
        container.RegisterType<ICategoriesRepository, CategoriesRepository>(new HierarchicalLifetimeManager());
        container.RegisterType<IOrdersRepository, OrdersRepository>(new HierarchicalLifetimeManager());
        container.RegisterType<IUsersRepository, UsersRepository>(new HierarchicalLifetimeManager());
        config.DependencyResolver = new ControllerDependencyFactory(container);

        // Some other stuff
        ...
    }
}

ControllerDependencyFactory.cs:
// This class uses the Inversion of Control (IoC) pattern, which creates
// instances of objects for you. All Web API Objects (API Controllers) are
// registered with this IDependencyResolver, so with a GET-request to the API
// this class will automatically create the correct instance of that API Controller.
public class ControllerDependencyFactory : IDependencyResolver
{
    protected IUnityContainer container;

    public ControllerDependencyFactory(IUnityContainer container)
    {
        if (container == null)
            throw new ArgumentNullException("container");

        this.container = container;
    }

    public object GetService(Type serviceType)
    {
        try
        {
            return container.Resolve(serviceType);
        }
        catch (ResolutionFailedException)
        {
            // WARNING: Do not throw any errors, we need to return null here
            return null;
        }
    }

    public IEnumerable<object> GetServices(Type serviceType)
    {
        try
        {
            return container.ResolveAll(serviceType);
        }
        catch (ResolutionFailedException)
        {
            // WARNING: Do not throw any errors, we need to return an empty List here
            return new List<object>();
        }
    }

    public IDependencyScope BeginScope()
    {
        var child = container.CreateChildContainer();
        return new ControllerDependencyFactory(child);
    }

    public void Dispose()
    {
        container.Dispose();
    }
}

IProductsRepository.cs:
public interface IProductsRepository
{
    IEnumerable<ProductsAPI> GetAll();
    ProductsAPI Get(int id);
    // No need for an Add, Update or Remove
}

ProductsRepository.cs:
public class ProductsRepository : IProductsRepository
{
    private List<ProductsAPI> products;
    private ProductController controller;

    public ProductsRepository()
    {
        // Get the Controller-instance from the RouteMaps instead of creating a new instance here
        getControllerInstance();
        products = controller.ListAll();
    }

    public IEnumerable<ProductsAPI> GetAll()
    {
        return products;
    }

    public ProductsAPI Get(int id)
    {
        return products.Find(p => p.ProductId == id);
    }

    // No need for an Add, Update or Remove

    private void getControllerInstance()
    {
        var url = "~/product";
        // Original path is stored and will be rewritten in the end
        var httpContext = new HttpContextWrapper(HttpContext.Current);
        string originalPath = httpContext.Request.Path;

        try
        {
            // Fake a request to the supplied URL into the routing system
            httpContext.RewritePath(url);
            RouteData urlRouteData = RouteTable.Routes.GetRouteData(httpContext);

            // If the route data was not found (e.g url leads to another site) then authorization is denied.
            // If you want to have a navigation to a different site, don't use AuthorizationMenu
            if (urlRouteData != null)
            {
                string controllerName = urlRouteData.Values["controller"].ToString();

                // Get an instance of the controller that would handle this route
                var requestContext = new RequestContext(httpContext, urlRouteData);
                var controllerFactory = ControllerBuilder.Current.GetControllerFactory();
                var controllerbase = (ControllerBase)controllerFactory.CreateController(requestContext, controllerName);
                controller = (ProductController)controllerbase;
            }
        }
        finally
        {
            // Reset our request path.
            httpContext.RewritePath(originalPath);
        }
    }

ProductsController.cs (only used by the Web API):
public class ProductsController : ApiController
{
    private IProductsRepository repository;

    public ProductsController()
    {
        repository = new ProductsRepository();
    }

    // GET /api/products
    public IEnumerable<ProductsAPI> GetAllProducts()
    {
        if(LockAPI.loggedIn)
            return repository.GetAll();

        return null;
    }

    // GET /api/products/5
    public ProductsAPI GetProduct(int id)
    {
        if (LockAPI.loggedIn)
        {
            ProductsAPI item = repository.Get(id);
            if (item == null)
                throw new HttpResponseException(HttpStatusCode.NotFound);
            return item;
        }

        return null;
    }
}

ProductController.cs (also used by the Website):
public class ProductController : Controller
{
    private IMyDatabase db;

    public ProductController()
    {
        this.db = new MyDatabase();
    }

    // Some methods used by the Website part
    ...

    // List all products
    // This method is only used for the Web API part of this project, that will be used in the Mobile App
    // Return: actual List of Products, instead of JSON format
    public List<ProductsAPI> ListAll()
    {
        List<ProductsAPI> products = db.Products
            .Where(p => p.Visible == true)
            .OrderBy(p => p.Name)
            .Select(p => new ProductsAPI()
            {
                ProductId = p.ProductId,
                Name = p.Name,
                Price = p.Price,
                CategoryId = p.CategoryId,
            })
            .ToList();

        return products;
    }
}

ProductsAPI.cs:
public class ProductsAPI
{
    // The Products Fields we use in the Mobile App
    public int ProductId { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
    public int CategoryId { get; set; }
}

So that's what I had, and I've added/changed the following:
In WebApiConfig.cs changed:
// Default API HttpRoute
// Call examples: "/api/products" or "/api/products/2"
config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional },
    constraints: new { id = @"^\d+$" } // Only integers
);

to:
// Default API HttpRoute
// Call example: "/api/orders"
config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}"
);
// API HttpRoute with ID
// Call example: "api/orders/2"
config.Routes.MapHttpRoute(
    name: "ApiWithID",
    routeTemplate: "api/{controller}/{id}",
    defaults: null,
    constraints: new { id = @"^\d+$" } // Only integers
);
// Api HttpRoute with Action
// Call example: "api/orders/save"
config.Routes.MapHttpRoute(
    name: "ApiWithAction",
    routeTemplate: "api/{controller}/{action}"
);

In the OrdersController.cs (only used by the Web API) added the following method:
// POST /api/orders/save
[HttpPost]
[ActionName("save")]
public Boolean SaveOrder([FromUri] string UniqueID, [FromBody] dynamic Data)
{
    if(LockAPI.loggedIn)
    {
        // Convert JSON body to a Key-Value Dictionary
        Dictionary<string, object> data = JsonConvert.DeserializeObject<Dictionary<string, object>>(Convert.ToString(Data));

        // Convert data-objects
        ...

        // Use this converted data to save the Orders
        // and return true or false based on the result
        ...
    }

    return false;
}

Now I'm using the FireFox RESTClient:
Method: POST - http://localhost/api/orders/save
Body: "productIds": "[20, 25]",     "prices": "[0.40, 7.40]",     dateInTicks: "1402444800"
And get the following response:
Status Code: 404 Not Found
Cache-Control: no-cache
Connection: Close
Content-Length: 212
Content-Type: application/json; charset=utf-8
Date: Tue, 24 Jun 2014 08:45:10 GMT
Expires: -1
Pragma: no-cache
Server: ASP.NET Development Server/11.0.0.0
X-AspNet-Version: 4.0.30319

{
    "$id": "1",
    "Message": "No HTTP resource was found that matches the request URI 'http://localhost/api/orders/save'.",
    "MessageDetail": "No action was found on the controller 'Orders' that matches the request."
}

How to get an HttpPost to a C# mvc Web API to work with Actions?

A: I first tried another MapHttpRoute again:
// Default API HttpRoute
// Call examples: "/api/products/all" or "/api/products/one/2" or "/api/orders/save" or "/api/test/enable"
config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{action}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

and a small change to the Web API Controllers:

*

*Added [ActionName("all")] to the GetAll-methods (this changes /api/products to /api/products/all)

*Added [ActionName("one")] to the Get-methods (this changes /api/products/2 to /api/products/one/2)

and changed the SaveOrder-method in the OrdersController to:
public Boolean SaveOrder([FromBody] string productIds, [FromBody] string newPrices, [FromBody] string dateInTicks)
{
    ...
}

When I did the same post with FireFox' RESTClient again, I had a 500-error:
Status Code: 500 Internal Server Error
Cache-Control: no-cache
Connection: Close
Content-Length: 226
Content-Type: application/json; charset=utf-8
Date: Tue, 24 Jun 2014 14:33:51 GMT
Expires: -1
Pragma: no-cache
Server: ASP.NET Development Server/11.0.0.0
X-AspNet-Version: 4.0.30319

{
    "$id": "1",
    "Message": "An error has occurred.",
    "ExceptionMessage": "Can't bind multiple parameters ('productIds' and 'dateInTicks') to the request's content.",
    "ExceptionType": "System.InvalidOperationException",
    "StackTrace": null
}

This made a lot more sense.
Then I changed the Save-method to:
public Boolean SaveOrder([FromBody] JObject jsonData)
{
    // TODO: Seperate the JSON Data

    // Rest the same as before
    ...
}

And now it goes to the method and I can debug through it.
Right now I still have problems converting the JSON in the body to the actual separated data, but that's something for a different question.


text:
Q: Hazelcast classpath error I am trying to use voldemort store to persist data in hazelcast. I implemented the mapstore interface. When i try to add a map entry in hazelcast i get this exception.
29 Mar, 2012 12:19:28 PM com.hazelcast.cluster.ClusterService
SEVERE: /192.168.100.120:5701 [dev] error processing messages  processable=com.hazelcast.cluster.ClusterService$1@561777b1
java.lang.NoClassDefFoundError: voldemort/client/StoreClientFactory
    at java.lang.Class.getDeclaredConstructors0(Native Method)
    at java.lang.Class.privateGetDeclaredConstructors(Class.java:2406)
    at java.lang.Class.getConstructor0(Class.java:2716)
    at java.lang.Class.newInstance0(Class.java:343)
    at java.lang.Class.newInstance(Class.java:325)
    at com.hazelcast.impl.CMap.<init>(CMap.java:203)
    at com.hazelcast.impl.ConcurrentMapManager.getOrCreateMap(ConcurrentMapManager.java:2160)
    at com.hazelcast.impl.FactoryImpl.createProxy(FactoryImpl.java:735)
    at com.hazelcast.impl.FactoryImpl$7.process(FactoryImpl.java:809)
    at com.hazelcast.cluster.ClusterService$1.process(ClusterService.java:126)
    at com.hazelcast.cluster.ClusterService.processProcessable(ClusterService.java:190)
    at com.hazelcast.cluster.ClusterService.dequeueProcessables(ClusterService.java:256)
    at com.hazelcast.cluster.ClusterService.run(ClusterService.java:201)
    at java.lang.Thread.run(Thread.java:679)
Caused by: java.lang.ClassNotFoundException: voldemort.client.StoreClientFactory
    at java.net.URLClassLoader$1.run(URLClassLoader.java:217)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:205)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:321)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:266)
    ... 14 more

This is the hazelcast run.sh script i've edited in order to include voldemort jars in the classpath.
#!/bin/sh
java -Djava.net.preferIPv4Stack=true -cp     ./:/home/gerrard/workspace/hazelcast/bin/:/home/gerrard/work/voldemort-    0.90.1/lib/:/home/gerrard/work/voldemort-0.90.1/dist/:/home/gerrard/work/voldemort-    0.90.1/bin/:../lib/hazelcast-2.0.1.jar com.hazelcast.examples.TestApp

I've also added my implementation class in the hazelcast.xml file.
I've also added a classpath entry in the manifest file of hazelcast-2.0.1.jar.
Even then, when i try to add an entry it gives this noclassdef found error.
The class its trying to find is definitely in the voldemort folder that i've added to the classpath.
I still do not have a clue as to what the problem is. Can somebody suggest any alternative solutions ?
Thanks.

A: You can try Hazelcast Config and set the Factory object yourself.
// Build the config from xml file you have in the classpath
Config config = new XmlConfigBuilder().build();
MapStoreConfig msc = new MapStoreConfig..
msc.setFactoryImplementation(new StoreClientFactory());
MapConfig mapConfig = new MapConfig..
mapConfig.setMapStoreConfig(msc);
config.addMapConfig(mapconfig);

// init Hazelcast with this configuration
// make sure you call init fore any other Hazelcast operation!!
Hazelcast.init(config);

// then access to your map
Map map = Hazelcast.getMap("mymap");


text:
Q: Missing bytes in SQL Server data page Did not know how to call the Title properly. However, I am trying to understand how the data pages are stored. I've created simple table:
CREATE TABLE testFix
(
 id INT,
 v CHAR(10)
);

INSERT INTO dbo.testFix
(
    id,
    v
)
VALUES
(   1, -- id - int
    'asdasd' -- v - varchar(100)
)
GO 2
DBCC TRACEON(3604);

Then I got PageFID and PagePID by following command:
DBCC IND(tempdb, testFix, -1)
GO

Then the actual data pages:
DBCC PAGE (tempdb, 1, 368, 3)

So now I see:

Slot 0 Offset 0x60 Length 21
Record Type = PRIMARY_RECORD        Record Attributes =  NULL_BITMAP
  Record Size = 21
Memory Dump @0x000000287DD7A060
0000000000000000:   10001200 01000000 61736461 73642020 20200200
  ........asdasd    .. 0000000000000014:   00
  .
Slot 0 Column 1 Offset 0x4 Length 4 Length (physical) 4
id = 1
Slot 0 Column 2 Offset 0x8 Length 10 Length (physical) 10
v = asdasd
Slot 1 Offset 0x75 Length 21
Record Type = PRIMARY_RECORD        Record Attributes =  NULL_BITMAP
  Record Size = 21
Memory Dump @0x000000287DD7A075
0000000000000000:   10001200 01000000 61736461 73642020 20200200
  ........asdasd    .. 0000000000000014:   00
  .
Slot 1 Column 1 Offset 0x4 Length 4 Length (physical) 4
id = 1
Slot 1 Column 2 Offset 0x8 Length 10 Length (physical) 10
v = asdasd
Slot 2 Offset 0x8a Length 21
Record Type = PRIMARY_RECORD        Record Attributes =  NULL_BITMAP
  Record Size = 21
Memory Dump @0x000000287DD7A08A
0000000000000000:   10001200 01000000 61736461 73642020 20200200
  ........asdasd    .. 0000000000000014:   00

So the length of the record is 21 byte. However INT is 4 bytes and CHAR(10) is 10 bytes. 4+10=14. What for the other 7 bytes are used?

A: Here is the "anatomy" of data row

In red there are 7 bytes you are missing: Status Bits A (1), Status Bits B (1), Fdata length (2), Ncols (2), NullBits (1)
From this book: Pro SQL Server Internals by Korotkevitch D.


text:
Q: Prize collecting CVRP in Google ortools I have a problem that can be well modeled by the Prize Collecting CVRP with multiple vehicles and a single depot.  Each node visited has a benefit and there's an edge distance between each node.  Goal is to maximize the benefit of the visited nodes.  What's a little different from a typical CVRP with dropped nodes is that while there is no capacity constraint on the vehicles based upon their load, there is a max travel distance for each vehicle.
I've used ortools in Python for CVRP, but I don't know to approach this one. Any example code out there? My search yielded nothing.

A: You can achieve this by using penalties. (https://developers.google.com/optimization/routing/penalties)
by setting the penalties to be an order of magnitude higher than the distances between nodes, the optimization process effectively becomes minimizing the penalty (which is similar to maximizing the profit when penalty(node) = profit(node))


text:
Q: Find $n$ if the coefficient of $x^3$ and $x^4$ in the expansion of $(2+x)^n$ are in the ratio $4:11$. Find  $n$ if the coefficient of $x^3$ and $x^4$ in the expansion of $(2+x)^n$ are in the ratio $4:11$.

A: Hints:

*

*The expression $(2+x)^n$ can be written as $$\sum_{k=0}^{k=n} \binom{n}{k} x^k2^{n-k}$$ using the binomial theorem.

*Can you then find the coefficients of $x^3$ and $x^4$?

A: You consider the ratio:
$$\frac{\frac{n!}{3!(n-3)!}\cdot 2^{n-3}}{\frac{n!}{4!(n-4)!}\cdot 2^{n-4}}=\frac{4\cdot 2}{n-3}=\frac{4}{11} \Rightarrow n=25.$$


text:
Q: Request matched endpoint 405 HTTP Method Not Supported This sound simple I just change from post to get but the do not help. I am trying to make a login against ADF2016 and when I am getting redirected back, I get this error in my backend. Now I have tried all changes I can think of so it time ask a question here with hope of a resolution.
The trace log leading up the exception:
x=Microsoft.AspNetCore
x.Authentication.Cookies.CookieAuthenticationHandler: AuthenticationScheme: Identity.External signed in.
x.Hosting.Diagnostics: Request finished HTTP/1.1 POST https://.../backend/adfscallback application/x-www-form-urlencoded 5316 - 302 - - 318.8660ms
x.Hosting.Diagnostics: Request starting HTTP/1.1 GET https://.../backend/adfscallback - -
x.HostFiltering.HostFilteringMiddleware: All hosts are allowed.
x.DataProtection.KeyManagement.KeyRingBasedDataProtector: Performing protect operation to key {53f014ae-56d8-44e9-b9c8-d5f9b04ec57d} with purposes ('C:\home\site\wwwroot\frontend\backend', 'SessionMiddleware').
x.Routing.Matching.DfaMatcher: 1 candidate(s) found for the request path '/adfscallback'
x.Routing.EndpointRoutingMiddleware: Request matched endpoint '405 HTTP Method Not Supported'
x.Authentication.WsFederation.WsFederationHandler: Error from RemoteAuthentication: No message..
x.Diagnostics.DeveloperExceptionPageMiddleware: An unhandled exception has occurred while executing the request.
System.Exception: An error was encountered while handling the remote login.
 ---> System.Exception: No message.
   --- End of inner exception stack trace ---
   at Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler`1.HandleRequestAsync()
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Session.SessionMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Session.SessionMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

The trace leading up to the error after changing HttpPost to HttpGet
2021-12-06 15:49:32.755 +00:00 [Trace] Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector: Performing unprotect operation to key {53f014ae-56d8-44e9-b9c8-d5f9b04ec57d} with purposes ('C:\home\site\wwwroot\frontend\backend', 'Microsoft.AspNetCore.Authentication.WsFederation.WsFederationHandler', 'WsFederation', 'v1').
2021-12-06 15:49:32.976 +00:00 [Trace] Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector: Performing unprotect operation to key {53f014ae-56d8-44e9-b9c8-d5f9b04ec57d} with purposes ('C:\home\site\wwwroot\frontend\backend', 'Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware', 'Identity.External', 'v2').
2021-12-06 15:49:32.977 +00:00 [Trace] Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector: Performing protect operation to key {53f014ae-56d8-44e9-b9c8-d5f9b04ec57d} with purposes ('C:\home\site\wwwroot\frontend\backend', 'Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware', 'Identity.External', 'v2').
2021-12-06 15:49:32.977 +00:00 [Trace] Microsoft.AspNetCore.CookiePolicy.CookiePolicyMiddleware: Needs consent: False.
2021-12-06 15:49:32.978 +00:00 [Information] Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler: AuthenticationScheme: Identity.External signed in.
2021-12-06 15:49:32.978 +00:00 [Information] Microsoft.AspNetCore.Hosting.Diagnostics: Request finished HTTP/1.1 POST https://testlakemedelshantering.skane.se/backend/adfscallback application/x-www-form-urlencoded 5312 - 302 - - 286.3371ms
2021-12-06 15:49:33.015 +00:00 [Information] Microsoft.AspNetCore.Hosting.Diagnostics: Request starting HTTP/1.1 GET https://testlakemedelshantering.skane.se/backend/adfscallback - -
2021-12-06 15:49:33.015 +00:00 [Trace] Microsoft.AspNetCore.HostFiltering.HostFilteringMiddleware: All hosts are allowed.
2021-12-06 15:49:33.015 +00:00 [Trace] Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector: Performing protect operation to key {53f014ae-56d8-44e9-b9c8-d5f9b04ec57d} with purposes ('C:\home\site\wwwroot\frontend\backend', 'SessionMiddleware').
2021-12-06 15:49:33.015 +00:00 [Debug] Microsoft.AspNetCore.Routing.Matching.DfaMatcher: 1 candidate(s) found for the request path '/adfscallback'
2021-12-06 15:49:33.015 +00:00 [Debug] Microsoft.AspNetCore.Routing.Matching.DfaMatcher: Endpoint 'LakemedelsappenWeb.Controllers.AdfsCallbackController.CallbackAsync (LakemedelsappenWeb)' with route pattern 'AdfsCallback' is valid for the request path '/adfscallback'
2021-12-06 15:49:33.015 +00:00 [Debug] Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware: Request matched endpoint 'LakemedelsappenWeb.Controllers.AdfsCallbackController.CallbackAsync (LakemedelsappenWeb)'
2021-12-06 15:49:33.015 +00:00 [Information] Microsoft.AspNetCore.Authentication.WsFederation.WsFederationHandler: Error from RemoteAuthentication: No message..
2021-12-06 15:49:33.188 +00:00 [Error] Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware: An unhandled exception has occurred while executing the request.
System.Exception: An error was encountered while handling the remote login.
 ---> System.Exception: No message.
   --- End of inner exception stack trace ---
   at Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler`1.HandleRequestAsync()
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Session.SessionMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Session.SessionMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
2021-12-06 15:49:33.301 +00:00 [Information] Microsoft.AspNetCore.Hosting.Diagnostics: Request finished HTTP/1.1 GET https://testlakemedelshantering.skane.se/backend/adfscallback - - - 500 - text/html;+charset=utf-8 286.2665ms

The declaration for function I try to call:
[HttpPost]
public async Task<ContentResult> CallbackAsync(string returnUrl = null, string remoteError = null)

My startup.cs
public void ConfigureServices(IServiceCollection services)
{
     String connectionString = GetSqlServerConnectionString();
     services.AddSession();

     services.AddDbContext<ApplicationDbContext>(options =>
           options.UseSqlServer(connectionString));

     services.AddIdentity<IdentityUser, IdentityRole>()
          .AddEntityFrameworkStores<ApplicationDbContext>();

     services.AddAuthentication()
          .AddWsFederation(options =>
     {
          options.MetadataAddress = "https://.../FederationMetadata.xml";

          options.Wtrealm = "....";

           options.Wreply = "https://.../backend/adfscallback";

          options.CallbackPath = new PathString("/adfscallback");

     });

     services.AddControllersWithViews();
     }

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseSession();
    app.UseRouting();

    app.UseAuthentication();
    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
    });
}