text:
Q: I'm getting a POST (Internal Server Error) in Angular app I'm trying a user registration form using MEAN, but I keep getting error 500 on passing data to the database.
I tried using save instead of the register, but that doesn't hash the password.
I had this method working on a project without angular, but it's not working here.
If there is an alternative to save the data with a hashed password, that's also helpful.
This is the post code:
    app.post('/signup', VerifyToken, (req,res) =>
{
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS");
    console.log(req.body);

    const errors = validationResult(req);
    if (!errors.isEmpty())
    {
        return res.status(422).jsonp(errors.array());
    }
    else
    {
        User = new userData(
        {
            name: req.body.user.name,
            email: req.body.user.email,
            blood: req.body.user.blood,
            address1: req.body.user.address1,
            address2: req.body.user.address2,
        });

        userData.register(User, req.body.user.password);
    }
});

This is the service that sends data:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class UsersService {

  constructor(private http:HttpClient) { }
  // getUsers()
  // {
  //   return this.http.get('');
  // }

  newUser(user)
  {
    return this.http.post('http://localhost:5000/signup',{'user' : user})
    .subscribe(data => {console.log(data)});
  }
};

And this is the signup component TS code:
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { UserModel } from './user.model';
import { UsersService } from '../users.service';

@Component({
  selector: 'app-signup',
  templateUrl: './signup.component.html',
  styleUrls: ['./signup.component.css']
})
export class SignupComponent implements OnInit {

  constructor(private usersService: UsersService, private router: Router) { }

  title: String = "Register as a new Donor here";
  userItem = new UserModel(null,null,null,null,null,null);
  ngOnInit(): void {
  }

  AddUser()
  {
    this.usersService.newUser(this.userItem);
    console.log("called");
    alert("success");
    this.router.navigate(['/']);
  }

}

This is the HTML code of the signup component:

{{title}}

    <form (ngSubmit)="AddUser()">

            <input type="text" class="form-control" id="fullName" name="name" [(ngModel)]="userItem.name" placeholder="Enter Full Name" required>

            <input type="email" class="form-control" id="email" name="email" [(ngModel)]="userItem.email" placeholder="Enter Email address" required>

            <select class="form-control" name="blood" id="bloodType" [(ngModel)]="userItem.blood" required>
                <option value="0">Select Blood Type</option>
                <option value="A+">A+</option>
                <option value="A-">A-</option>
                <option value="B+">B+</option>
                <option value="B-">B-</option>
                <option value="O+">O+</option>
                <option value="O-">O-</option>
                <option value="AB+">AB+</option>
                <option value="AB-">AB-</option>
                <option value="Bombay">Bombay Blood group</option>
            </select>

            <input type="text" class="form-control" id="addressL1" name="address1" [(ngModel)]="userItem.address1" placeholder="Enter Address Line 1" required>

            <input type="text" class="form-control" id="addressL2" name="address2" [(ngModel)]="userItem.address2" placeholder="Enter Address Line 2" required>

            <input type="password" class="form-control" id="password" name="password" [(ngModel)]="userItem.password" placeholder="Enter Password" required>

            <input type="password" class="form-control" id="confPassword" name="confPassword" placeholder="Confirm Password" required>

        <button type="submit" value="submit" class="btn btn-primary">Register</button>
    </form>


text:
Q: ASP.NET C# Email Attachments Eventually go to 0 Bytes When Sending to Multiple Email Addresses I have this routine that sends email to a list as follows and I have tested it. The first email that comes to me is fine but the second one has less bytes that the actual file rendering it corrupt for opening. How can I make it so that each email attachment is sent properly without sending any 0 byte attachments? I am sending the attachments through a ASP.NET C# webform directly to recipients but most of the PDF attachments come through as improperly decoded with that error message. Here is the main email code of the page:
if (emailIsValid(EmailToSend))
{
    string TheSubject = SubjectTxt.Text;
    string TheBody = "Dear " + FirstName + ",

" + MessageTxt.Text;
    TheBody = TheBody + " EMail Body "
    string BodyTxt = TheBody.Replace(Environment.NewLine, "
");

    MailMessage mailObj = new MailMessage(
        "noreply@company.com", EmailToSend, TheSubject, BodyTxt);
    SmtpClient SMTPServer = new SmtpClient("unknown.company.com");

    string RPT = FromTxt.Text;
    mailObj.ReplyToList.Add(RPT);
    mailObj.BodyEncoding = System.Text.Encoding.UTF8;
    mailObj.IsBodyHtml = true;

    string filePath = txtAttachment.PostedFile.FileName;
    string filename = Path.GetFileName(filePath);
    string ext = Path.GetExtension(filename);
    string contenttype = String.Empty;

    //Set the contenttype based on File Extension
    switch (ext)
    {
        case ".doc":
            contenttype = "application/vnd.ms-word";
            break;
        case ".docx":
            contenttype = "application/vnd.ms-word";
            break;
        case ".xls":
            contenttype = "application/vnd.ms-excel";
            break;
        case ".xlsx":
            contenttype = "application/vnd.ms-excel";
            break;
        case ".ppt":
            contenttype = "application/vnd.ms-powerpoint";
            break;
        case ".pptx":
            contenttype = "application/vnd.ms-powerpoint";
            break;
        case ".jpg":
            contenttype = "image/jpg";
            break;
        case ".png":
            contenttype = "image/png";
            break;
        case ".gif":
            contenttype = "image/gif";
            break;
        case ".pdf":
            contenttype = "application/pdf";
            break;
        case ".csv":
            contenttype = "text/csv";
            break;
        case ".txt":
            contenttype = "text/csv";
            break;
        default:
            contenttype = "Unknown Content Type";
            break;

    }

    if (txtAttachment.PostedFile != null && contenttype != "Unknown Content Type")
    {
        try
        {
            string strFileName =
            System.IO.Path.GetFileName(txtAttachment.PostedFile.FileName);
            Attachment attachFile =
            new Attachment(txtAttachment.PostedFile.InputStream, strFileName, contenttype);
            mailObj.Attachments.Add(attachFile);
        }
        catch
        {

        }
    }

    try
    {
        SMTPServer.Send(mailObj);

        SqlConnection con2 = new SqlConnection(CS);

        con2.Open();

        DateTime now = DateTime.Now;
    }
catch
    {
    }

A: Before
Attachment attachFile =
        new Attachment(txtAttachment.PostedFile.InputStream, strFileName, contenttype);

try resetting the stream cursor, like this:
txtAttachment.PostedFile.InputStream.Position = 0;
Attachment attachFile =
        new Attachment(txtAttachment.PostedFile.InputStream, strFileName, contenttype);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Realizar un recorrido de una columna e insertar un numero N de filas al encontrar un valor Ejemplo de insertar filas al encontrar un valor , en la imagen se resalta un ejemplo al encontrar.
Al encontrar una celda con un valor especifico se inserte un numero N de filas arriba de la celda que contiene el valor, lo estaba realizando de la siguiente manera pero no me inserta
Sub CargaMigra()

Dim fila As Integer

    fila = 1

    Do While Cells(fila, 1) = ""

        If Cells(fila, 5) = "4.000.000.0000" Then

            Rows.EntireRow.Insert

        End If

        fila = fila + 1

    Loop

End Sub

A: Tu código con mis comentarios:
 Sub CargaMigra()
    Dim fila As Integer
    'IMPORTANTE: Los integer (numeros enteros) en VBA solo almacenan numeros
    'en el rango de –32,768 a 32,767, por tanto si tienes filas superiores a
    '32,767 arrojará un error, por lo cual recomiendo usar LONG
    fila = 1
    Do While Cells(fila, 1) = ""
    'La linea dice esto:
    'Has un bucle (loop) mientras (while) la celda de la fila tal y la columna 1
    'no tengan ningún valor dentro, ningún texto, nada!
    'Por tanto, según dices que debe encontrar algún valor, pues no va a correr
    'si encuentra algo.
        If Cells(fila, 5) = "4.000.000.0000" Then
        'Segun tu código no llegaría acá, pero el IF revisar si la fila tiene
        'el siguiente texto "4.000.000.0000", no un numero, sino un texto
        'si quieres el numero 4000000 debes quitar los puntos y las comillas
        'así mismo debes hacer la prueba con el valor de la celda, no con la celda
        'Cells(fila, 5).value = 4000000 o en su defecto Cells(fila, 5).Value = "4.000.000.0000"
            Rows.EntireRow.Insert
            'y aquí insertas solo una celda... nada mas!
        End If
        fila = fila + 1
    Loop
End Sub

Ahora mi código con mis comentarios:
 Sub CargaMigra2()
    Dim fila As Long: fila = 1 'Así defines e inicializas la variable en una sola linea,
                               'con el tipo de variable long que tiene un rango de datos
                               'de –2,147,483,648 a 2,147,486,647. Mucho mejor

    'cuando quieres agregar filas, lo mejor es ir desde la última fila hacia la primera,
    'por tanto, imaginando que tus datos están el la columna C (colo como ejemplo)

    fila = Range(Cells(1048576, 3), Cells(1048576, 3)).End(xlUp).Row 'aquí se cual es la última linea

    Dim i
    Dim j
    Dim valorBuscado 'as Strig | as integer | as long | as boolean lo que nececites, y si no pones nada,
                     'es tipo Variant, es decir se asigna el tipo de dato según el dato que se guarde
                     'en la variable
    valorBuscado = 1
    Dim cantidadDeFilas As Integer: cantidadDeFilas = 10 'no se de donde asignas este valor
                                                         'o si siempre será el mismo, pero debes
                                                         'de definirlo en algún momento de alguna manera,
                                                         'pero tu ejemplo no define eso, acá puse 10 solo
                                                         'para hacer el ejemplo claro

    For i = fila To 1 Step -1 'imaginando que la hay que revisar hasta la fila uno, por eso ponemos el 1
                              'y Step -1 es para que el loop cuente hacia atras.
        If Cells(i, 3).Value = valorBuscado Then
            For j = 1 To cantidadDeFilas
                  Range(Cells(i, 3), Cells(i, 3)).EntireRow.Insert
                Next j
                'el loop anterior se repite de 1 a la cantidadDeFilas por tanto las filas se van a añadir
                'esa cantidad de veces sobre la fila en cuestión.
            End If
        Next i
    End Sub

Espero haber sido suficientemente claro.


text:
Q: Error while importing pandas in R via reticulate I am using R and I want to use a function I wrote in Python which needs to import pandas. Hence, I use the following code in R:
library(reticulate)
reticulate::py_install("pandas", force = TRUE)

which runs with no issues. Also, I already installed pandas in Python. Nevertheless, when I run the script which imports pandas:
source("script_with_pandas.py")

I get the following error:
Error in py_run_file_impl(file, local, convert) :
  ImportError: C extension: No module named 'pandas._libs.interval' not built. If you want to import pandas from the source directory, you may need to run 'python setup.py build_ext --force' to build the C extensions first.

Any idea how to solve this?

A: Try
reticulate::source_python("script_with_pandas.py")

But I'm pretty sure this is an environment issue. If you're using RStudio >=v1.4 then you can go to tools --> global options --> python interpreter and check which one you're using, that may be the problem. Aside from that, I think it's only a matter of installing the pandas package onto the right environment.


text:
Q: Does $this->get() only work for app routes in Laravel tests? I am trying to check if the file robots.txt exists, but my test returns 404. Visiting the url website.test/robots.txt manually works. This leads me to believe that the $this->get() method only works for defined routes.
Here is my trivial test that fails:
$response = $this->get(env('APP_URL') . '/robots.txt');
$response->assertSuccessful();

Does $this->get() only work for defined routes in Laravel tests, or am I doing something wrong?

A: Yes, ->get() will only work with defined routes as it doesn't actually make an HTTP request, it just creates a Request internally and then returns the response.
The easiest way to check that the file exists would be to do just that:
$this->assertTrue(file_exists(public_path('robots.txt')));

file_exists() docs
public_path() docs


text:
Q: How to move custom popuwindow in android I am displaying a custom poupwindow to the user. If the user drags the popup window, I want to move the position of the popup window.
Can anybody tell me how to do that?
Thanks

A: WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
lp.y = -60;
dialog.getWindow().setAttributes(lp);
dialog.show();

This will displace your dialog 60 pixels to the left of the screen. Playing with lp variable inside of an onTouch listener applied to the draggable portion of the dialog will do the trick.


text:
Q: 'Remembering' a variable when using a recursive algorithm? I have this code:
def function(pos):
    new_list = []

    if condition:
        for x in range(0,len(another_list)):
            new_pos = another_list[x]
            new_list.append(new_pos)
            function(new_pos)

where another_list is a list that is defined elsewhere, and I can access it.
When the given position meets a certain condition, I'm looping through another_list and I'm adding positions, but of course everytime I call function, new_list gets reset and all the values in it are removed.
I want to have new_list contain all the new_pos values and not get reset each time function gets called, and I only want it to be cleared when I tell it to. How should I achieve this?

A: This is typically done by adding an argument to the function to hold the "remembered" value and giving it a default value so it doesn't have to be provided to the upper-most level call. The function can return this value as shown if it's that type of function (as opposed to one that is executed only for its side-effects).
def function(pos, new_list=None):
    if new_list is None:
        new_list = []

    if condition:
        for x in range(0,len(another_list)):
            new_pos = another_list[x]
            new_list.append(new_pos)
            function(new_pos, new_list)

    return new_list

# same usage
pos = 42
result_list = function(pos)

A: I thought this might help you.
def function(first_pos):

    def foo(pos):
        if condition:
            for x in range(0, len(another_list)):
                new_pos = another_list[x]
                new_list.append(new_pos)
                foo(new_pos)

    new_list = []
    foo(first_pos)
    return new_list

A: If you're trying to accumulate the result of each function call, you could change the last line of your function to:
return new_list + function(new_pos)

Then, you'll also want to add a return new_list in the case where condition is not satisfied.
A generic recursive function of this nature might look like:
def generic_function(param):

    # break recursion when condition is not met
    if not condition:
        return []

    else:
        temporary_list = []
        # do stuff
        return temporary_list + generic_function(new_param)

This might be a better approach than trying to "remember" an object down through the recursion. If it turns out that is truly necessary, see martineau's answer which addresses that problem.

A: new_list=[] needs to be an argument with a default value in your function, so you pass it through to the next call, but when you call it the first time it defaults to an empty list


text: Q: Strange behaviour of Rmarkdown. It stops during execution for no apparent reason I have recently run into a very strange issue with Rmarkdown. When I run a chunk that takes a few minutes Rmarkdown just stops at some point. This does not happen every time, but often enough. The chunk runs some Rcpp code. I can't produce an example because the routines run are quite lengthy, sorry. I am attaching a screenshot that shows the progress of the chunk, but also shows that Rmarkdown has stopped (no red button). When it stops it also does not redraw the viewer.


text:
Q: FlowLayoutPanel FlowDirection issue I'm trying to add x Buttons to a FlowLayoutPanel which is docked (DocType fill) in a Panel.
I have set the FlowDirection to Topdown as I want something like:

However, the FlowLayoutPanel has a horizontal scrollbar, not a vertical one:

I add the buttons like this:
flowLayoutPanel1.Controls.Add(new Button { Text = "Chat", Width = flowLayoutPanel1.Width - flowLayoutPanel1.Margin.Left - flowLayoutPanel1.Margin.Right});

I also tried:
flowLayoutPanel1.Controls.Add(new Button { Text = "Chat", Dock = DockStyle.Fill});

And also:
flowLayoutPanel1.Controls.Add(new Button { Text = "Chat", Anchor = AnchorStyles.Left | AnchorStyles.Right});

I tried this and also looked here. Both don't work for me.
Thanks for your help.

A: after some digging here I found it out.
I had to set the FlowLayoutPanel.WrapContents Property to false.


text:
Q: Is there a way to remove image metadata from all existing images in S3? I have a huge S3 bucket of images, it's impractical to manually edit each one or write a script to strip the metadata one by one, is there another way to strip the image metadata from all of the images?
To be clear: I mean the image metadata (Exif etc), NOT the s3 metadata.
Thank you!

A: No, I recommend using S3 Batch Operations + AWS Lambda scripts to do this.


text:
Q: Does the margin of a classifier scale with the dimension of the problem? Consider a binary classification problem on $\mathcal Z=\mathcal X \times \mathcal Y $, where $\mathcal X$ is some subset of $\mathbb R^d$ and $\mathcal Y = \{-1;1\}$. You have a dataset of $n$ samples $(x_i,y_i)\in\mathcal X \times \mathcal Y $ which are i.i.d. according to some probability distribution on $\mathcal Z$.
Now, say you train a classifier $\hat f$ on this dataset (could be an SVM, a Neural Network, Naive Bayes... anything really). In this setting, one would define the margin $\hat \gamma$ of the classifier $\hat f$ as
$$\hat \gamma := \min_{1\le i\le n} y_i\ \hat f(x_i) $$
My question is the following : is there any relationship between the margin $\mathbf{\hat \gamma}$ and the dimension of the problem $\mathbf d$ ? What if the problem is infinite dimensional (e.g. functional data classification) ?
Intuitively, due to the curse of dimensionality, one would expect the points to be "more separated" as the dimension increases and thus a larger margin on the training sample should also be progressively easier to achieve, maybe up to some assumptions on the underlying distribution of the datapoints (e.g. Tsybakov noise condition).
I have however not been able to find any results of that sort in the literature, and I'm not sure of how to prove it myself.
Any mention of a paper/book/resource that discusses or tackles a similar question, or ideas on how to approach it would be very much appreciated.

Update : Here is my attempt at being more specific in explaining what I'm looking for, please bear with me.
It is known (or at least observed in practical cases) that, for any given class of classifiers $\mathcal C_d$, as the dimensionality $d$ increases, the classifiers in $C_d$ will be able to progressively achieve better results on the training dataset. In the limit case of $d=\infty$, it has even been shown that zero training error is achievable with minimal assumptions (Delaigle and Hall (2012)). Although this fact can be intuitively understood as a consequence of the curse of dimensionality, the theoretical results supporting it are fairly scarce.
I would thus like to know how to quantify how "easier" it gets to classify training data as the dimension increases : It seems that the classification margin is one the most appropriate metric to measure performance of a classifier, as it effectively measures how well-separated the classifier manages to make the points. On top of that, margin has been quite extensively studied from a theoretical standpoint. In particular, it has been shown that having a margin as large as possible is desirable (Pappu and Pardalos (2014), Vapnik and Chapelle (2000), Cai, Zhang and Peng (2009)...).
So far, the only references I have been able to find which investigate the relationship between margin and dimensionality only deal with the asymptotics of the overparametrized regime, i.e. when
$$n\to\infty,\ \ d\to\infty,\ \ n/d\to\psi\in\mathbb R$$
and seem to support the intuition that learning to separate the training set gets easier as dimension increases (Huang (2019), Montanari et al. (2019)). I would be interested in results/discussions for the non overparametrized, non-asymptotic case, i.e. for fixed $n$ and $d$, or for fixed $n$ and $d\to\infty$.
Lastly, it seems, according to my knowledge, that SVMs (which are margin-based) seem to be among the best performing algorithms in high-dimensional settings, i.e. they are less prone to overfitting compared to other models. Any reference which investigate that issue from a theoretical perspective or provide key related results ?


text:
Q: Comments.php is not getting called on main blog page I'm creating a custom theme for my blog and I've been working on the comments for a while now. I've tried a few different strategies and read a lot of the codex and questions on here but I can't seem to get the comments to work.
I've created a custom comments.php file and placed it in the theme directory but I know it's not even getting included in the blog because I put in some console logs and they are not showing up.
It seems the problem is even more complicated than just that though, because I can get the comment form to show up, but I've tried to enter some test comments and when I click submit on the form, no comments get submitted to the database and it just redirects me to the single.php for the blog entry that I'm trying to comment on.
I've tried copying the comments.php from the 2016 theme but that made no difference either.
I've been following a few different tutorials on how to set this up and I've tried to find my answer in the wordpress codex pages that discuss comments.php but I haven't had any luck. If anyone could take a look at my blog, and let me know where I might be going wrong, I'd really appreciate the help.
I'm calling the comments section with this line of code:
<?php comments_template(); ?>

Here is the code for my custom comments.php:
<?php
if(!empty($_SERVER['SCRIPT_FILENAME']) && 'comments.php' == basename($_SERVER['SCRIPT_FILENAME'])) :
    die("You shall not pass!");
endif;

if ( post_password_required() ) {
    return;
}
?>

    <?php if ( have_comments() ) : ?>

            <?php
                $comments_number = get_comments_number();
                if ( 1 === $comments_number ) {
                    /* translators: %s: post title */
                    printf( _x( 'One thought on “%s”', 'comments title', 'twentysixteen' ), get_the_title() );
                } else {
                    printf(
                        /* translators: 1: number of comments, 2: post title */
                        _nx(
                            '%1$s thought on “%2$s”',
                            '%1$s thoughts on “%2$s”',
                            $comments_number,
                            'comments title',
                            'twentysixteen'
                        ),
                        number_format_i18n( $comments_number ),
                        get_the_title()
                    );
                }
            ?>

        <?php the_comments_navigation(); ?>

            <?php
                wp_list_comments( array(
                    'style'       => 'ol',
                    'short_ping'  => true,
                    'avatar_size' => 42,
                ) );
            ?>

        <?php the_comments_navigation(); ?>

    <?php endif; // Check for have_comments(). ?>

    <?php
        // If comments are closed and there are comments, let's leave a little note, shall we?
        if ( ! comments_open() && get_comments_number() && post_type_supports( get_post_type(), 'comments' ) ) :
    ?>

<?php _e( 'Comments are closed.', 'twentysixteen' ); ?>

    <?php endif; ?>

    <?php
        comment_form( array(
            'title_reply_before' => '
',
            'title_reply_after'  => '
',
        ) );
    ?>

If any more code is needed please let me know and I will post it as soon as I can. I'd really like to get to the bottom of this. Thanks in advance!

A: Comments can be enabled on the archive page by setting the global variable $withcomments to true before calling comments_template():
global $withcomments;
$withcomments = true;
comments_template( '', true );

As Michael pointed out in a comment on the original post, comments_template() does not return output when $withcomments is true, or in a number of other scenarios:
function comments_template( $file = '/comments.php', $separate_comments = false ) {
    global $wp_query, $withcomments, $post, $wpdb, $id, $comment,
           $user_login, $user_ID, $user_identity, $overridden_cpage;

    if ( !(is_single() || is_page() || $withcomments) || empty($post) )
        return;
    ...

comment-reply JS
Normally, you'd want to include the comment-reply JS where comments are being handled (single posts), but the the built in comment-reply JS script does not seem to be intended for use on pages with multiple posts, so you'll need to roll your own solution instead.


text:
Q: Whitespace stripped from input on AWS Automation Document I'm trying to use an AWS Automation Document to generate new AMI's with security updates.
I have an input parameter for the command I want to run on the ec2 machine before generating the new image. If that input parameter is of type "String", everything works fine. If it is of type "StringList" then I lose all the whitespace.
Example with input type "String":
In the input field I enter: sudo yum -y update --security. Document receives and runs this command on the ec2 machine: sudo yum -y update --security. Everything works correctly.
Example with input type "StringList":
In the input field I enter: sudo yum -y update --security. Document receives and attempts to run this command on the ec2 machine: sudoyum-yupdate--security. Receive an error because the command cannot be found.
Is there anyway I can have it not strip out the whitespace? I know I can just use type "String" for the input parameter and it will work, but I'd like to have the option of passing in multiple commands to run if possible.


text:
Q: How to set the monitor to its native resolution which is not listed in the resolutions list? After installing Ubuntu 10.04 with my Samsung SyncMaster B2030, native resolution (1600X900) is not found in the list of resolutions.

A: First type in xrandr in your terminal and see which is the connected device. It maybe VGA1 as it is in this case. If not then replace VGA1 by your connected device in the commands below. Then create a new document and name it eg:- "yourname.sh" Type in:
xrandr --newmode "1600x900_60.00"  118.25  1600 1696 1856 2112  900 903 908 934 -hsync +vsync
xrandr --addmode VGA1 1600x900_60.00
xrandr --output VGA1 --mode 1600x900_60.00
unity --replace

and save it in your home folder (this is for resolution 1600x900). Make it executable by:
chmod a+x ~/yourname.sh

open startup applications and click "ADD". Give a name and type in the command line
bash /home/yourname/yourname.sh

click save. The change appears after you log out and log in

A:
Native resolution for Samsung SyncMaster B2030 is 1600 * 600 60 Hz

*

*Generate the modeline using cvt:
cvt 1600 900 60

which will be:
# 1600x900 59.95 Hz (CVT 1.44M9) hsync: 55.99 kHz; pclk: 118.25 MHz
Modeline "1600x900_60.00"  118.25  1600 1696 1856 2112  900 903 908 934 -hsync +vsync

*Get the name of the output to which your display is connected:
xrandr

This outputs among other things:
Screen 0: minimum 320 x 200, current 1600 x 900, maximum 8192 x 8192
VGA1 connected 1600x900+0+0 (normal left inverted right x axis y axis) 0mm x 0mm

In this example the name of the output is VGA1.

*Create the new modeline (with the values from the output of cvt):
xrandr --newmode "1600x900_60.00"  118.25  1600 1696 1856 2112  900 903 908 934 -hsync +vsync

Note:

*

*the above should be in a single line

*make note of  x in 1600 x 900_60.00

*Add the above created modeline:
xrandr --addmode VGA1 1600x900_60.00

*If everything went well xrandr will list your newly added resolution.

*Test the newly added resolution:
xrandr --output VGA1 --mode 1600x900_60.00

The resolution you set with the above commands will not persist across sessions. Until Ubuntu 11.04 you can add the following lines at the beginning of your /etc/gdm/Init/Default to set the resolution automatically every time you log in:
xrandr --newmode "1600x900_60.00"  118.25  1600 1696 1856 2112  900 903 908 934 -hsync +vsync
xrandr --addmode VGA1 1600x900_60.00
xrandr --output VGA1 --mode 1600x900_60.00

This question describes other ways to make xrandr customizations permanent.

A: If you don't want to go through the bother of running all the commands as instructed in other answers, you can use ResolutionX. This is a tool that does it all for you:

*

*executes the cvt command

*executes the newmode, addmode and output commands

*creates a startup file that executes the above upon login.


text:
Q: How to close port 80 in windows vista? i have a virtual machine with OS server 2003
connection bridged
i need to test if the webapplication on guest webserver will be available for users on the network, so i need to close port 80 on vista while still open on win server 2003, however, i can't close port 80 on vista

A: If you are using a bridged connections, then the virtual machine will have its own IP address on the same network the host system is connected to. So, opening and closing ports on the host system should have no relationship at all to which ports are available to the guest system.
This could change if you are using some form of NAT for your virtual machine networks; but definitely not if you are using a bridged connection.
About your question: port 80 is usually used by IIS on Windows system, so you should check if it's installed and running; if this is the case, you can either stop IIS (by stopping the "World Wide Web Publishing Service") or uninstall it from "Programs and Features", provided you don't actually need it, of course.
If IIS is not installed and/or not started, then something else is using port 80; you can use the command netstat -nao to check the PID of the owner process, and then use the Task Manager (by adding the PID column to the process list) to check which process is associated with that PID.

A: I am sorry, but VMWare company confess that the situation is different with windows vista
Troubleshooting blocked inbound network traffic on Windows Vista or 2008 after installing a VMware product
Symptoms
* Inbound network traffic stops after installing a VMware product.
* Networking fails.
*
  Blocked TCP/IP ports.
*
  Problems with networking on a Windows Vista or 2008 host.

Purpose
This article describes how to re-establish inbound network traffic to a computer with a Microsoft Vista or 2008 operating system that used to receive this traffic but suddenly stopped after a VMware product was installed.
Resolution
In some cases, the installation of a VMware product to a computer with a Microsoft Vista or 2008 operating system prevents all inbound networking traffic from reaching the computer. This is caused by the Windows Firewall assigning the VMware virtual NICs to the Public network.
Inbound networking traffic can be re-enabled by performing one of four corrective procedures.  Which procedure is performed depends on your environment and business requirements.  Each corrective procedure below has a summary of reasons for and against its use.
Reconfigure the Windows Firewall
This procedure requires extensive knowledge of the Windows Vista or 2008 operating system and its implementation of the Windows Firewall. Doing this ensures a permanent solution resulting in no unexpected behaviour in either the Windows operating system or the VMware product in use. Any description of the tasks required are beyond the scope of this article. For more information, refer to Windows operating system documentation.
Note: Only perform this if you have an in depth understanding of Windows Firewall.
Note: Modifying the access rules for the Public network will affect all NICs that belong to the Public network.
Move the VMware virtual NICs to the Private network
This procedure is simple to perform and has the least impact on both the Windows Vista or 2008 operating system and the VMware product in use. However, after any reboot of the operating system the NICs are moved back to the Public network again. Using this procedure requires supervision of the operating system to ensure that it is performed after every reboot.
To move the VMware virtual NICs to a Private network:

*

*Click Start > Control Panel > Network and Sharing Center.

*Click Customize.

*Click Private.

*Click Next.
5.
  Click Close.

Disable the VMware virtual NICs
This procedure is simple to perform, but it prevents both NAT and Host Only networking from functioning in any virtual machine. Only Bridged networking is available. If neither NAT nor Host only networking is required, this is the simplest and most permanent procedure.
To disable the VMware virtual NICs:

*

*Click Start > Control Panel > Network and Sharing Center.
2.
  Click Manage network connections.
3.
  Click VMware Network Adapter / VMnet1 / Unidentified network.
4.
  Click Disable this network device.
5.
  Click VMware Network Adapter / VMnet8 / Unidentified network.
6.
  Click Disable this network device.

Redefine the VMware virtual NICs as endpoint devices
This procedure is permanent and allows for the continued use of Bridged, NAT, and Host Only networking. However, doing this causes the VMware virtual NICs to disappear from the Network and Sharing Center, even though they remain visible under Network Connections. This also causes the VMware virtual NICs to be exempt from all Windows Firewall access rules. When implemented, the control of virtual machine network access must be done from the guest operating system of each virtual machine. This bypasses the default security model of Windows Vista with respect to the the VMware virtual NICs, and the implications of using this procedure must be carefully considered.
To redefine the VMware virtual NICs as endpoint devices:

*

*Click Start > Run.
2.
  Type regedit and click OK.
3.
  Double-click HKEY_LOCAL_MACHINE>System>CurrentControlSet>Control>Class>{4D36E972-E325-11CE-BFC1-08002BE10318}.
Caution: VMware recommends that you back up this registry key before proceeding:
 1.
    If {4D36E972-E325-11CE-BFC1-08002BE10318} is not still highlighted, click it.
 2.
    Click File > Export.
 3.
    Pick a location and name for the Registration File (*.reg) .
 4.
    Click Save.

4.
  Click 0000.
5.
  Look at the content of the Data field associated with the DriverDesc entry.
6.
  If you see VMware Virtual Ethernet Adapter for VMnetx , where x is replaced by a number, then:
 1.
    Right-click an empty space in the right content pane.
 2.
    Click New > Dword.
 3.
    Type *NdisDeviceType and press Enter.

    Note: Ensure to include the asterisk (* ) at the beginning of the entry.

 4.
    Double-click *NdisDeviceType.
 5.
    Type 1 and press Enter.

7.
  Repeat steps 4-6, replacing 0000 in step 4 with the next entry in numerical order, until you have reached the end of all numerical entries.
8.
  Follow the Disable the VMware virtual NICs section of this article above.
9.
  Repeat step 8 but click Enable this network device instead.
http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1004813

A: I think thhis may also imply on your case,
But I am sure now that VMWare on windows 7 connects far away from the Kernel of the Windows, that add space for firewalls to act


text:
Q: Dynamic variable assignment using eval in Matlab R2013a I am trying to assign values to a dynamic variable using eval in Matlab. I'm using Matlab R2013a. I can easily do it older versions but not in R2013a. Yes, I'm aware of the pitfalls of using eval, etc. I tried assignin as well, but that wasn't successful.
Bins = [10 100 20];
Cols = numel(Bins);

for i = 1:Cols
    eval(['Var' num2str(i) ' = Cols+i']);
end

Error --> Attempt to add "Var" to a static workspace.
Desired Output
    Var1 = 4
    Var2 = 5
    Var3 = 6

A: Is that code inside of a nested function? See this article from The MathWorks.
If you must create variables that way (there are much better options) then you'll need to do it within the main function or use a sub-function. See this article on sharing data between workspaces for details on the different types of functions and how to use them.


text:
Q: Getting an XML sent by Webservice(POST method) in C# .NET I am developing this application where I need to send an XML file to a webservice and read it from the webservice, and applying the business logic from the webservice, it will send an XML as response.
The thing is that I do know how to read the response the webservice sends, but I don't know how to retrieve the XML that the request sends to the webservice, the variable always comes null. If someone could help me out, I'd be really glad.
Request Method:
(...)
    using (var client = new HttpClient())
        {

            var XMLRequest = Util.BuildXML.CreateRequestXML();

            string url = string.Format(WEB_API_HOST + "/Application/MyMethod/");

            HttpRequestMessage httpRequest = new HttpRequestMessage()
            {
                RequestUri = new Uri(url, UriKind.Absolute),
                Method = HttpMethod.Post,
                Content = new StringContent(XMLRequest.ToString(), Encoding.UTF8, "text/xml")
            };

            var task = client.SendAsync(httpRequest).ContinueWith((taskwithmsg) =>
            {
                var response = taskwithmsg.Result;

                if (response.IsSuccessStatusCode)
                {
                    var xmlResponse = response.Content.ReadAsStringAsync().Result;
                    XmlDocument doc = new XmlDocument();
                    doc.LoadXml(xmlResponse);

                    var test = doc.SelectSingleNode("RESPONSE/...").InnerText;

                }
                else
                {
                    var contentTask = response.Content.ReadAsStringAsync().Result;

                    throw new Exception(contentTask);
                }
            });

            task.Wait();
        }
    (...)

And the Webservice ( that is supposed to receive the XML and read it)
[AcceptVerbs("GET", "POST")]
    public HttpResponseMessage MyMethod(XmlDocument doc)
    {

        // Any doc.SelectSingleNode() wouldn't work, the doc variable is null.

        var response = new StringBuilder();

        response.Append("<?xml version=\"1.0\" standalone=\"yes\"?>");
        response.Append("<RESPONSE>");
        (...)
        response.Append("</RESPONSE>");

        var xmlResponse = new HttpResponseMessage()
        {
            Content = new StringContent(response.ToString(), Encoding.UTF8, "text/xml")
        };

        return xmlResponse;
    }

So how do I get to read the xml in the "MyMethod" method?
Thanks a bunch!


text:
Q: Copy a table to new window I'm trying to open up a new browser window, and copy a table from the parent window into this new window.  I'm using Prototype.js and this is the code I have:
prog_window = window.open();
prog_window.document.write("");
table_clone = Element.clone('prog_table',true);
prog_window.document.addElement(table_clone);

I get an error on the third line: "TypeError: Result of expression 'Element.clone' [undefined] is not a function."  I've tried a few variations for the third line, but I always get the same error.  I've quadruple checked the id of the  so that is not the problem.  Documentation on the clone function is extremely limited, so if there is something I'm missing, could someone please point it out?
Thanks in advance, Dave

A: Another option for you would be to do something like the following:
prog_window = window.open();
prog_window.document.write("

"
prog_window.getElementById('table').innerHTML =
       document.getElementById('current_table').innerHTML;

There are obviously many ways to do this in JavaScript.  Couple other things you could try would be to start at the parent window and call back to the "parent" window to do the cloning.


text:
Q: python login form with pandas not Working I'm trying to make a login using my CSV file and i'm using pandas to read my csv file but i keep getting this error
AttributeError: 'DataFrame' object has no attribute 'brugernavn'
I can't seem to figured out if my csv file is setup wrong or my code ain't done correctly
import pandas as pd

 class Login:
   def Userlogin(self):
      userData = pd.read_csv('Csv/Users.csv')
      df = pd.DataFrame(userData)

      print('Log ind\n')
      user = input('Brugernavn : ')
      pasw = input('Password : ')

      matching_creds = (len(df[(df.brugernavn == user) & (df.password == pasw)]) > 0)

      if matching_creds:
          print('succes')
      else:
      print('kontakt admin')

LoginHandler = Login()
LoginHandler.Userlogin()

This is my CSV FILE
brugernavn;password;fornavn;efternavn;rolle;stilling
Val;1234;Valon;abc;1;Udvikler
Casper;1234;Casper;abc;1;Udvikler
Peter;1234;Peter;Blink;3;Teknikker
Grete;1234;Grete;Hansen;2;Administration

A: You need to specify that the csv is semicolon separated. I also fixed the password checker.
import pandas as pd

class Login:
    def Userlogin(self):
        userData = pd.read_csv('Csv/Users.csv', sep=';')
        df = pd.DataFrame(userData)
        print('Log ind\n')
        user = input('Brugernavn : ')
        pasw = input('Password : ')

        # get index of username if it exists
        index = df[df['brugernavn'] == user].index.values
        # see if the password matches for that user
        matching_creds = True if len(index) > 0 and str(df.at[index[0], 'password']) == pasw else False

        if matching_creds:
            print('succes')
        else:
            print('kontakt admin')

LoginHandler = Login()
LoginHandler.Userlogin()

As a side note, you never want to store passwords in plain text. You should store the hash of the password and compare the hashes.


text:
Q: Javascript date validation on onkeyUp using the leap year functionality I have this piece of code where i am trying to validate the jquery based Date of Birth Validation.
is there any JS function which also checks the full date if it falls in a leap year or not, i am trying this but it does seems to be working
function isValidDate(s) {
  var bits = s.split('/');
  var d = new Date(bits[2] + '/' + bits[1] + '/' + bits[0]);
  return !!(d && (d.getMonth() + 1) == bits[1] && d.getDate() == Number(bits[0]));
}

date i tested is: 02/29/1920 - it is giving false (edited)
testing it like this:
    function init_inputOnKeyUp(){
        $('select[name="day"],select[name="year"]').off('change');
        $('select[name="month"],select[name="day"],select[name="year"]').on('change', function(e) {
        if (type == 'select') {
            var newdate = $('select[name="month"]').val() + '/' + $('select[name="day"]').val() + '/' + $('select[name="year"]').val();
                        var results = isValidDate(newdate.toString());
                        console.log(results);
                        console.log(newdate.toString());
        }
        });
}

problem i can't use any extra library like moment.js
the error is it is always giving me false when i try to validate with a full date
also i changed my function toL
this function should return me true, but it is returning me "undefined"
function isValidDate(sDate) {
    var dateformat = /^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{4}$/;
    if (sDate.match(dateformat)) {
        var seperator1 = sDate.split('/');
        var seperator2 = sDate.split('-');

        if (seperator1.length > 1) {
            var splitdate = sDate.split('/');
        } else if (seperator2.length > 1) {
            var splitdate = sDate.split('-');
        }
        var dd = parseInt(splitdate[0]);
        var mm = parseInt(splitdate[1]);
        var yy = parseInt(splitdate[2]);
        var ListofDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
        if (mm == 1 || mm > 2) {
            if (dd > ListofDays[mm - 1]) {
                return false;
            }
        }
        if (mm == 2) {
            var lyear = false;
            if ((!(yy % 4) && yy % 100) || !(yy % 400)) {
                lyear = true;
            }
            if ((lyear == false) && (dd >= 29)) {
                return false;
            }
            if ((lyear == true) && (dd > 29)) {
                return false;
            }
        }
    } else {
        return false;
    }
}


text:
Q: Functions $f$ that $f(f(x))=x$, but $f:S^1\to S^1$ Background
Denote $e_A$ the identity map from $A$ to itself. Questions such like solving $f$ in the functional equation $f\circ f=e_\mathbb{R}$ or $f\circ f=e_{\mathbb{R}\setminus\{a_1,\ldots,a_n\}}$ with or without limitation of the continuousness of $f$ have already been discussed in this question. Given that there are some solutions like $f:x\mapsto1/x$ with domain  $\mathbb R\setminus\{0\}$, it is natural to try to extend the domain to $\mathbb{R}\cup \{\infty\}$. To find the solutions with better properties, it is necessary to add a restriction of the solution. As it is hard to analysis of the nature of $f$ at infinity, the following question arises since $\mathbb{R}\cup\{\infty\}$ and $S^1$ are same to some extent.

Question
  Let $S^1\subset\mathbb R^2$ be the unit circle centered at the origin, can we find all continuous solutions to the equation $f\circ f=e_{S^1}$ with the restriction that there exists a real-analytic function $g$ s.t. $(\cos g(x),\sin g(x))=f((\cos x,\sin x))$ for all $x\in\mathbb R$?

It is not hard to see that there exists a constant integer $n$ such that $g(x)-2\pi nx$ have a period $2\pi$. Plus, because $f$ is a continuous bijection, $n$ has to be $\pm1$. So the question boils down to finding a function with the following conditions: $g\in C^\omega(\mathbb R)$, $g(x)=\pm x+\sum_{n=-\infty}^\infty c_ne^{inx}$ and a functional equation with respect to $g$. I'm still struggling with the functional equation.


text:
Q: JMS webservice. unable to view the WSDL I registered one web service using JMS transport.
Registration was done using java and cxf.
JMS used is active MQ. And the registration was successful as the registration code executed successfully.
But I want to get the wsdl of the web service registered.
When transport is HTTP , I can type http://localhost:8080/AlarmRetriever?wsdl in browser to see the wsdl.
But for jms , this is not working.I tried like jms://localhost:2463/AlarmRetriever?wsdl.
Please help me to view the wsdl of the web service registered.


text:
Q: Update tag breaks panel being updated i have a problem with a primefaces panel not being updated by a dialog.
Here is the code:
I am using a templete with <ui:composition> tags. Here is the template:
<h:body style="margin: 0px;">

    <h:form id="menu-bar-form-id" style="width: 100%">

            <ui:insert name="content">Content Section</ui:insert>

    </h:form>

</h:body>

Inside the content div i have a panel that nests a datatable and outside the panel i have a dialog that adds data to that datatable:

                    <h:outputText value="#{modul.modTitle}" />

                          #{lectie.lesTitle}

                                 #{task.tskTitle}

I update this panel using a modal dialog.

            <h:panelGrid id="lectie_update_panel" columns="3"
                columnClasses="label, value">
                <h:outputText value="Titlu: *" />

                <h:outputText value="Video link: *" />

                <h:outputText value="Thumbnail: * " />

                <h:outputText value="Task-uri: * " />

                          #{task.tskTitle}

            </h:panelGrid>

The problem i am facing is the "update" attribute on the ajax event in the panel. If i remove the attribute, the panel gets updated (data gets added and displayed to the datatable). If i leave it there, it does not (data gets added in the list but does not show up in the datatable.
Here is the backing bean:
package com.conneqtlife.edu.managedbean;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

import org.primefaces.event.FileUploadEvent;
import org.primefaces.event.FlowEvent;
import org.primefaces.model.UploadedFile;
import org.springframework.stereotype.Component;

import com.conneqtlife.edu.model.Curs;
import com.conneqtlife.edu.model.Lectie;
import com.conneqtlife.edu.model.Modul;
import com.conneqtlife.edu.model.Task;

@Component("uploadCourseBean")
public class UploadCourse implements Serializable {

    private static final long serialVersionUID = 1L;

    private Curs curs = new Curs();
    private List<Modul> modul = new ArrayList<Modul>();
    private Modul modulToAdd = new Modul();
    private Modul selectedModul = new Modul();
    private UploadedFile cursThumbnail;
    private UploadedFile modulThumbnail;

    private List<Lectie> lectii = new ArrayList<Lectie>();
    private Lectie lectieToAdd = new Lectie();

    private Task taskToAdd = new Task();

    public UploadCourse() {
    }

    public Task getTaskToAdd() {
        return taskToAdd;
    }

    public void setTaskToAdd(Task taskToAdd) {
        this.taskToAdd = taskToAdd;
    }

    public Modul getSelectedModul() {
        return selectedModul;
    }

    public void setSelectedModul(Modul selectedModul) {
        this.selectedModul = selectedModul;
    }

    public List<Lectie> getLectii() {
        return lectii;
    }

    public void setLectii(List<Lectie> lectii) {
        this.lectii = lectii;
    }

    public Lectie getLectieToAdd() {
        return lectieToAdd;
    }

    public void setLectieToAdd(Lectie lectieToAdd) {
        this.lectieToAdd = lectieToAdd;
    }

    public Curs getCurs() {
        return curs;
    }

    public void setCurs(Curs curs) {
        this.curs = curs;
    }

    public List<Modul> getModul() {
        return modul;
    }

    public void setModul(List<Modul> modul) {
        this.modul = modul;
    }

    public Modul getModulToAdd() {
        return modulToAdd;
    }

    public void setModulToAdd(Modul modulToAdd) {
        this.modulToAdd = modulToAdd;
    }

    public UploadedFile getCursThumbnail() {
        return cursThumbnail;
    }

    public void setCursThumbnail(UploadedFile cursThumbnail) {
        this.cursThumbnail = cursThumbnail;
    }

    public UploadedFile getModulThumbnail() {
        return modulThumbnail;
    }

    public void setModulThumbnail(UploadedFile modulThumbnail) {
        this.modulThumbnail = modulThumbnail;
    }

    public void save() {
        FacesMessage msg = new FacesMessage("Successful", "Welcome :");
        FacesContext.getCurrentInstance().addMessage(null, msg);
    }

    public String onFlowProcess(FlowEvent event) {
        return event.getNewStep();
    }

    public void upload() {
        if (cursThumbnail != null) {
            FacesMessage message = new FacesMessage("Successful", cursThumbnail.getFileName() + " is uploaded.");
            FacesContext.getCurrentInstance().addMessage(null, message);
        }
    }

    public void handleFileUpload(FileUploadEvent event) {
        FacesMessage msg = new FacesMessage("Successful", event.getFile().getFileName() + " is uploaded.");
        FacesContext.getCurrentInstance().addMessage(null, msg);
    }

    public void createNew() {
        if (modul.contains(modulToAdd)) {
            FacesMessage msg = new FacesMessage("Dublicated", "This module has already been added");
            FacesContext.getCurrentInstance().addMessage(null, msg);
        } else {
            modulToAdd.setLectii(new ArrayList<Lectie>());
            modul.add(modulToAdd);
            modulToAdd = new Modul();
        }
    }

    public void createNewLectie() {
        Modul selectedModul = new Modul();

        for (Modul modul : modul) {
            if (modul.getModTitle().equals(this.selectedModul.getModTitle())) {
                selectedModul = modul;
            }
        }

        if (lectii.contains(lectieToAdd)) {
            FacesMessage msg = new FacesMessage("Dublicated", "This module has already been added");
            FacesContext.getCurrentInstance().addMessage(null, msg);
        } else {
            selectedModul.getLectii().add(lectieToAdd);
            lectieToAdd = new Lectie();
        }
    }

    public void createNewTask() {
        if (lectieToAdd.getTasks() == null) {
            lectieToAdd.setTasks(new ArrayList<Task>());
        }

        lectieToAdd.getTasks().add(taskToAdd);
        taskToAdd = new Task();

    }

    public void selectCurrentModule(Modul module) {
        this.selectedModul = module;
    }

    public void selectCurrentLesson(Lectie lectie) {
        this.lectieToAdd = lectie;

//      RequestContext context = RequestContext.getCurrentInstance();
//      context.update("dialog_lectie_id");
//      context.execute("PF('lectieDialog').show();");
    }

    public void removeTask(Task task) {
        try {
            for (int i = 0; i <= lectieToAdd.getTasks().size(); i++) {
                if (lectieToAdd.getTasks().get(i).getTskTitle().equals(task.getTskTitle())) {
                    lectieToAdd.getTasks().remove(i);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

I am using Primefaces 6.2, Tomcat 7 and JSF2.2.
What is the problem here? What am i missing?
Any help is greatly appreciated.
Thanks!


text:
Q: Python copy a string for specified number of times I have the file phones.txt which contains phone numbers , one phone per line like this
00000000
1111111
222222

I want to create a python script which asks the user for how many folders he want to create then I want the script to calculate the number of folders and the number of lines in the file phones.txt then calculate how many times every number will be copied then copy it to the folders in the file phone.txt
Like if the user input 9 the script will devide 9 on the lines number which is 3 . That means that the first number will be copied to first 3 folder "1,2,3" and the second number will be copied to folders "4,5,6" and the last one to folders "7,8,9"
Now My code :-
folders = int(raw_input( "How many folders for perfix {0} : ".format(name)))
for i in range(folders):
    pathname = os.path.join(fullPath, str(i+1))
    os.mkdir( pathname )
    #### NOW WHAT TO DO HERE ? ####

I stopped in this place , any help ?

A: You can use the following:
import math

# read the phone numbers from file
with open('phone.txt', 'r') as f:
    progs = f.read().splitlines()

folders = input( "How many folders for perfix {0} : ".format(name))
# calculate how many folders a number is in
# therefore use the highest possible number (e.g. if folders is 8 use 3)
num = int(math.ceil(float(folders)/len(progs)))

# loop through the number of folders to create
for i in xrange(folders):
    # create folder
    pathname = os.path.join(fullPath, str(i+1))
    os.mkdir( pathname )

    # create file
    filename = os.path.join(pathname, 'number.txt')
    with open(filename, 'w') as f:
        f.write(progs[i/num])

This also works for cases where the user input is not dividable by the number of progs.
E.g. if the user types 8 and there are 3 phone numbers the numbers will be added to the folders like this:

*

*'00000000' to folder 1,2,3

*'1111111'  to folder 4,5,6

*'222222'   to folder 7,8


text:
Q: The continuity of a function of two variables, how can we determine it exists? if we find that limit for x-axis and y-axis exist does is it enough to say there is continuity?
or we have always to look in circle way around the point?
for example:
$\lim_{(x,y)\to (0,0) } \frac{xy^{3}}{x^{2}+y^{6}}$ , when (x,y)=(0,0) the value is zero of the function
for partition limits of x and y the limit is 0.
then we check when y=mx (I also i need an explanation on that as to how it works) also the limit is 0.
so far we also can't conclude that the function is continuous right?
then we do $x=ky^{3}$ that we $k=1$ the limit is 0.5, so that's when we can say the function isn't continuous.
but how did they determine the $x=ky^{3}$ part? based on what? and what is the meaning of $x=ky^{3}$ graphical wise?

A: Let $f(x,y)=\frac{xy^{3}}{x^{2}+y^{6}}$ if $(x,y) \ne (0,0)$ and $f(0,0)=0.$

*

*show that , for $x \ne 0$, we have $f(x,mx)=\frac{m^3x^2}{1+m^6x^4}$. Hence $f(x,mx) \to 0$ as $x \to 0.$

*show that , for $y \ne 0$, we have $f(y^3,y)= 1/2.$. Hence $f(y^3,y) \to 1/2$ as $y \to 0.$


text:
Q: iterate and garbage collection in Haskell I have a question about how the GHC implements a simple code. A question of performance and also technical.
This is a simple example from John Hughes' "Why Functional Programming Matters" article. The square root calculation.
To do the calculation we need the previous approximation and we can use the iterate function that creates a list with approximations:
[a0, f(a0), f(f(a0), ...] and so on
And then with within it will stop when it is convenient:
within eps (a:b:xs) = if abs(a-b) < eps then b else within eps (b:xs)

The question is how is this performed in constant space?
Does the GC know in the recursive call, within eps (b: xs) that head a of the list is no longer in scope and then it is collected?
If this is the case, then at each iteration, would the GHC always create and then destroy a location in memory (variable)? And how can this perform as well as in a procedural language where the variable is always reused?

A:
Does the GC know in the recursive call, within eps (b: xs) that head a of the list is no longer in scope and then it is collected?

Correct.

If this is the case, then at each iteration, would the GHC always create and then destroy a location in memory (variable)?

For this example, almost certainly yes. There are some cases where list fusion can turn list-based algorithms into tight, non-allocating loops; this is most likely to happen if you use only built-in functions for producing and consuming the list.

how can this perform as well as in a procedural language where the variable is always reused?

The allocator and GC are tuned for doing lots of allocation and collection. Usually allocation just bumps a pointer. Occasionally you hit a GC, but only one Float needs to be copied from the first generation to the second (or only a Float and a few closures or whatever -- you get the idea, most of the data need not be touched as it's not reachable), which is similarly very cheap. There is some overhead, obviously, but usually the computation you're doing is complicated enough that it takes the majority of the run time.


text:
Q: Algorithmic question regarding permutations An algorithm i'm reading has the first step saying. The algorithm is a path enumeration algorithm which puts all permutations into lexicographic order. The algorithm works as follows
Input: A natural number $n \geq 3$. A set $\{p_{1},p_{2},...,p_{n}\}$ of points in the plane.
Output: A permutation $\pi^{*}:\{1,2,...,n\} \rightarrow \{1,2,...,n\}$ with $cost(\pi^{*})=\sum_{i=1}^{n} d(p_{\pi^{*}(i)},p_{\pi^{*}(i+1)})$ minimum.
$(1)$ Set $\pi(i)=i$ and $\pi^{*}=i$ for $i=1,2,...,n$. Set $i=n-1.$
$(2)$ Let $k=\{\pi(i)+1,\pi(i)+2,...,n+1\}/\{\pi(i-1),\pi(i-2),...,\pi(1)\}$
$(3)$ If $k \leq n$ then:
set $\pi(i)=k$.
If $i=n$ and $\mathrm{cost}(\pi) \leq \mathrm{cost}(\pi^{*})$ then set $\pi=\pi^{*}$.
If $i<n$ set $\pi(i+1)=0$ and $i=i+1$.
If $k=n+1$ then set $i=i-1$.
If $i \geq 1$ go to $(2)$.
It then proceeds to say in any reasonable computer $(1)$ will take at least $2n+1$ steps as at least this many variable assignments are done. I do not see this surely $n$ variable assignments are done?

A: Well, you're

*

*assigning to the variable $i$ the values from $1$ to $n$ -> $n$ steps

*assigning to the variable $\pi(i)$ the value $i$ for all $i$ -> $n$ steps

*assigning to the variable $i$ the value $n-1$ -> $1$ step
so $2n+1$ assignments in total


text:
Q: Find $\int_{a}^{b}\frac{x^{n-1}\left((n-2)x^2+(n-1)(a+b)x+nab\right)}{(x+a)^2(x+b)^2}dx$ Prove that $$\int_{a}^{b}\frac{x^{n-1}\left((n-2)x^2+(n-1)(a+b)x+nab\right)}{(x+a)^2(x+b)^2}dx=\frac{b^{n-1}-a^{n-1}}{2(a+b)}$$
I tried replacing $x$ by $x-a-b$ but problem is getting messy and complicated,is there any other way out?

A: We can write it as $$ \frac{x^{n-1}\left((n-2)x^2+(n-1)(a+b)x+nab\right)}{(x+a)^2(x+b)^2} = \frac{d}{dx}\left[\frac{x^n}{(x+a)\cdot (x+b)}\right]$$
So
\begin{align} \int \frac{x^{n-1}\left((n-2)x^2+(n-1)(a+b)x+nab\right)}{(x+a)^2(x+b)^2}dx
& = \int \frac{d}{dx}\left[\frac{x^n}{(x+a)\cdot (x+b)}\right]dx \\
& = \left[\frac{x^n}{(x+a)(x+b)}\right]_{a}^{b} \\
&  = \frac{b^{n-1}-a^{n-1}}{2(a+b)}.
\end{align}


text:
Q: Account doesn't have permission to suggest edits I tried to edit this question on SuperUser using the SE Andriod app (v1.0.51) and got the following error in the red bar at the top:

Account is not allowed to suggest edits.

I get the same error when trying to Preview the edit as well.
I can (and did) successfully submit the edit from the website.

A: SE Apps don't support suggested edits (they can't push suggested edits to the review queues). Gain full editing privs and won't have any problems anymore :)


text:
Q: How to compile OpenGL with a python C++ extension using distutils on Mac OSX? When I try it I get:

ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/cscalelib.so, 2): Symbol not found: _glBindFramebufferEXT
    Referenced from: /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/cscalelib.so
    Expected in: dynamic lookup

I've tried all sort of things in the setup.py file. What do I actually need to put in it to link to OpenGL properly? My code compiles fine so there's no point putting that on there. Here is setup.py
from distutils.core import setup, Extension

module1 = Extension('cscalelib',
              extra_compile_args = ["-framework OpenGL", "-lm", "-lGL", "-lGLU"],
                    sources = ['cscalelib.cpp'])

setup (name = 'cscalelib',
       version = '0.1',
       description = 'Test for setup_framebuffer',
       ext_modules = [module1])

A: I didn't realise I had to remove the build directory. Now it imports correctly.
For anyone that needs to know you need: extra_link_args=['-framework', 'OpenGL'] Delete the build directory and try it again. It will work.


text:
Q: Types of parameters 'event' and 'event' are incompatible I have a project, which is an employee monitoring project, and it has several components, and among these components is having a group of buttons together.
I have a set of buttons, and I call these buttons in another component, but when I write the code, I have this one error.
Type '(event: React.MouseEvent<Document, MouseEvent>) => void' is not assignable to type '(event:
   MouseEvent | TouchEvent) => void'.
  Types of parameters 'event' and 'event' are incompatible.
    Type 'MouseEvent | TouchEvent' is not assignable to type 'MouseEvent<Document, MouseEvent>'.
      Type 'MouseEvent' is missing the following properties from type 'MouseEvent<Document,
      MouseEvent>': nativeEvent, isDefaultPrevented, isPropagationStopped, persi
           st

How can I fix it?
And this file has the design of the buttons and gave them their own style
And when I activated this file it gave me this error which is above.
const options = ['Member', 'Admin'];

export default function SplitButton() {
    const [open, setOpen] = React.useState(false);
    const anchorRef = React.useRef<HTMLDivElement>(null);
    const [selectedIndex, setSelectedIndex] = React.useState(1);

    const handleClick = () => {
        console.info(`You clicked ${options[selectedIndex]}`);
    };

    const handleMenuItemClick = (
        event: React.MouseEvent<HTMLLIElement, MouseEvent>,
        index: number,
    ) => {
        setSelectedIndex(index);
        setOpen(false);
    };

    const handleToggle = () => {
        setOpen((prevOpen) => !prevOpen);
    };

    const handleClose = (event: React.MouseEvent<Document, MouseEvent>) => {
        if (anchorRef.current && anchorRef.current.contains(event.target as HTMLElement)) {
            return;
        }

        setOpen(false);
    };

    // @ts-ignore
    return (
        <Grid container direction="column" alignItems="center">
            <Grid item xs={12}>
                <ButtonGroup variant="contained" color="primary" ref={anchorRef} aria-label="split
                    button">
                    <Button onClick={handleClick}>{options[selectedIndex]}</Button>
                    <Button
                        color="primary"
                        size="small"
                        aria-controls={open ? 'split-button-menu' : undefined}
                        aria-expanded={open ? 'true' : undefined}
                        aria-label="select merge strategy"
                        aria-haspopup="menu"
                        onClick={handleToggle}
                    >
                        <ArrowDropDownIcon />
                    </Button>
                </ButtonGroup>
                <Popper open={open} anchorEl={anchorRef.current} role={undefined} transition
                   disablePortal>
                    {({ TransitionProps, placement }) => (
                        <Grow
                            {...TransitionProps}
                            style={{
                                transformOrigin: placement === 'bottom' ? 'center top' : 'center
                       bottom',
                            }}
                        >
                            <Paper>
                                <ClickAwayListener onClickAway={handleClose}>
                                    <MenuList id="split-button-menu">
                                        {options.map((option, index) => (
                                            <MenuItem
                                                key={option}
                                                disabled={index === 2}
                                                selected={index === selectedIndex}
                                                onClick={(event) => handleMenuItemClick(event,
                                           index)}
                                            >
                                                {option}
                                            </MenuItem>
                                        ))}
                                    </MenuList>
                                </ClickAwayListener>
                            </Paper>
                        </Grow>
                    )}
                </Popper>
            </Grid>
        </Grid>
    );
}

A: Try changing your handleClose method to:
const handleClose = (event: MouseEvent | TouchEvent) => {
    if (anchorRef.current && anchorRef.current.contains(event.target as HTMLElement)) {
        return;
    }

    setOpen(false);
};

Why? The error message says that your handleClose method is not compatible with what ClickAwayListener can accept as input for its onClickAway callback.
Currently, your handleClose has the signature
(React.MouseEvent<Document, MouseEvent>) => void

while what is expected by ClickAwayListener's onClickAway is
(MouseEvent | TouchEvent) => void

A: try this
event:(MouseEvent | TouchEvent) => void

A: Had the same problem myself.  Looks like MouseEvent needs its template argument of HTMLElement
function onMenuClick(e: MouseEvent<HTMLElement>): void {
        console.log('got the click');
    }

That took care of the warning.  Let me know if you are still having trouble.


text:
Q: useContext is giving undefined I'm trying to pass value from my parent component for making some API call. I'm using context to pass the value between two components but I'm getting undefined in the console log. Could you guys please help me.
Parent component.
import Travel from './Travel'

export const TransactionAccountIdContext = createContext();

export default function Accounts() {

  const [accountId, setAccountId] = useState(0);
  const setTransactionAccountId = e => {
    console.log("Clicked ID", e.currentTarget.value);
    setAccountId(e.currentTarget.value);
  };

  return (

      <Button
        variant="contained"
        value={account.id}
        onClick={setTransactionAccountId}
        className={classes.button}
        startIcon={<ReceiptIcon />}
      >
        Show Transactions
      </Button>
      <TransactionAccountIdContext.Provider value={"1212121"}>
        <Travel />
      </TransactionAccountIdContext.Provider>

  );
}

child component (Travel.jsx)
import TransactionAccountIdContext from "./accounts";

export default function MaterialTableDemo() {
  const accountId = useContext(TransactionAccountIdContext);
  console.log("accountId", accountId);

  return
{accountId}
;
}

I'm also making some API calls using react hooks in parent and child components but I have removed it here to reduce the size of the question. Could anyone of you please tell us what can be the issue.

A: I believe this is due to your import syntax in Travel.jsx.
Your TransactionAccountIdContext is being exported from the parent as a named constant. It needs to be destructured from the import in the child component.
eg:
/// Travel.jsx
import { TransactionAccountIdContext } from "./accounts";


text:
Q: How to filter a particular directory and copy the rest of the folders in java I am trying to copy folders and files which is working fine but I need help on how to filter a single folder and copy the rest of the folders. For example, I have directories like carsfolder and truckfolder in(C:\vehicle\carsfolder and C:\vehicle\truckfolder). When I use the below code it copies both carsfolder and truckfolder but I wanted to copy only carsfolder. How can I do that. Your help is highly appreciated.(Using Swing and Java 1.6)
 class CopyTask extends SwingWorker<Void, Integer>
                 {
                   private File source;
                   private File target;
                   private long totalBytes = 0;
                   private long copiedBytes = 0;
                   public CopyTask(File src, File dest)
                 {
                    this.source = src;
                    this.target = dest;
                    progressAll.setValue(0);

                  }
         @Override
         public Void doInBackground() throws Exception
                 {

                    ta.append("Retrieving info ... ");  //append to TextArea
                    retrieveTotalBytes(source);
                    ta.append("Done!\n");
                    copyFiles(source, target);
                    return null;
                 }
         @Override
       public void process(List<Integer> chunks)
              {
                for(int i : chunks)
              {
                         }
        }
         @Override
         public void done()
                    {
                      setProgress(100);
                      }
        private void retrieveTotalBytes(File sourceFile)
                    {
                    try
                    {
                      File[] files = sourceFile.listFiles();
                      for(File file : files)
                    {
                     if(file.isDirectory()) retrieveTotalBytes(file);
                     else totalBytes += file.length();
                     }
                  }
                 catch(Exception ee)
                   {
                                            }
               }
    private void copyFiles(File sourceFile, File targetFile) throws IOException
                   {
                     if(sourceFile.isDirectory())
                   {
         try{
                if(!targetFile.exists()) targetFile.mkdirs();
                String[] filePaths = sourceFile.list();
                for(String filePath : filePaths)
               {
                File srcFile = new File(sourceFile, filePath);
                File destFile = new File(targetFile, filePath);
                copyFiles(srcFile, destFile);
               }
          }
        catch(Exception ie)
              {
                                   }
         }
    else
             {
                try
                     {
                        ta.append("Copying " + sourceFile.getAbsolutePath() + " to " + targetFile.getAbsolutePath() );
                        bis = new BufferedInputStream(new FileInputStream(sourceFile));
                        bos = new BufferedOutputStream(new FileOutputStream(targetFile));
                        long fileBytes = sourceFile.length();
                        long soFar = 0;
                        int theByte;
             while((theByte = bis.read()) != -1)
                       {
                         bos.write(theByte);
                         setProgress((int) (copiedBytes++ * 100 / totalBytes));
                         publish((int) (soFar++ * 100 / fileBytes));
                       }
                          bis.close();
                          bos.close();
                          publish(100);
                          ta.append(" Done!\n");
                      }
           catch(Exception excep)
                            {
                              setProgress(0);
                              bos.flush();
                              bis.close();
                              bos.close();

                            }
          finally{
                    try {
                          bos.flush();
                        }
                    catch (Exception e) {
                         }
                    try {
                            bis.close();
                        }
                    catch (Exception e) {
                        }
                   try {
                       bos.close();
                       }
                   catch (Exception e) {
                    }
                }
}
}
}

A: Maybe you can introduce a regex or list of regexes that specify which files and dirs to exclude?
For example, to exclude truckfolder, use a "exclusion" regex like "C:\\vehicle\\truckfolder.*".
Then, in your code, before you copy anything, check to make sure the absolute path of the sourcefile doesn't match the exclusion regex(s).


text:
Q: Node globby error while using multi patterns I use node glob which is working OK .
I use it for one folder1 like following
      glob('folder1/*.js'), function(err, files){
        if (err) {
            console.log('Not able to get files from folder: ', err);
        } else {
            files.forEach(function (file) {

https://github.com/isaacs/node-glob
Now I want to read in one shot from folder2 also and I try to use globby like following and I got error
    globby(['folder1/*.js','folder2/*.js']).then( function(err, files){
        if (err) {
            console.log('Not able to get files from folder: ', err);
        } else {
            //Get plugin configuration & provided actions
            files.forEach(function (file) {

https://github.com/sindresorhus/globby
in this case the files are coming as undfiend and I got to the error  any idea why

A: Try to remove err argument from the then callback. Use catch to handle errors
globby(['folder1/*.js','folder2/*.js']).then( function(files){...}).catch(function(err){...})


text:
Q: Add label to card (the label is from another board) I have a label that I created on board B1, and a card on B2.
Now I want to add the label to the card.
When I POST the id of the label to /1/cards/<cardid>/idLabels I get a 404.
When I POST the id of a label that was created on B1: success.
However when I look at the labels resource of the card, every label includes a board ID, and IDs are globally unique.
Can I add a label from a different board, or doesn't Trello work like that?

A: Every label from every board has got a different ID. So you cannot use same label ID for more than 1 board.
I would advise to

*

*create a new label if needed

*if you are using generic labels which can be defined by color (yellow, orange, red, blue, green, etc) you can get their unique ids by calling /boards/BOARD_ID/labels and looping though the json until you find the right color name.


text:
Q: Loading Select2 with a selected option WITHOUT triggering change? Is there any way to load select2 to a default value without triggering the change event?
Currently, I am doing:
$('#mylist').val(2).trigger("change");

But this creates a delay where the user will at first see one option and then it will change, which is quite an annoyance.

A: If you want to set a selected option, normaly you can do:
 $('#element').val('your_val').trigger('change');

But if you dont want to run the trigger, you  must to destroy it first and then assign val before create again, like this:
$('#element').select2('destroy');
$('#element').val('your_val').select2();

A: I know I'm really late to answer this question. I was facing the same issue. But doing a bit of research I found a solution that works like a charm.
You can set an option using below code
$("#mylist").val(2).trigger('change.select2');
This solution will not trigger the main change event but sets the option to the select2 component.
Hope that helps you.

A: Set a default value in your HTML:
<select id="myList">
   <option id="foo">option 1</option>
   <option id="bar" selected="selected">option 2</option>
</select>

Then call select2 on your element to initialize it:
$('#myList').select2();
or
$('#myList').select2("val", null);


text:
Q: socialtext API programming I need to consume socialText API using php/Java/C# (any of those languages). I went through
https://www.socialtext.net/st-rest-docs/Tutorial#examples and throughout the internet.
They really don't have a proper documentation it seems
But I was unable to find out a proper way of consuming socialText rest API..
I am stuck with logging to socialText also.
All I need is logging to socialText account and get content from given URL.
Any help I highly appreciate..
Thank you.

A: I could get you started with c#.
You can use the HTTPWebRequest class to do RESTful call to the socialText API.
Then set the required Headers as mentioned in their documentation and then simply make the call.
The response would be JSON (as per the documentation), so you will have to create a class (perhaps MyResponse) according to it and then Deserialize the response received in to your class and use the resulting object as per your needs.
A rough draft of the code would look like this:
HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
    if (response.StatusCode != HttpStatusCode.OK)
         throw new Exception(String.Format("Server error (HTTP {0}: {1}).", response.StatusCode, response.StatusDescription));
    var jsonSerializer = new DataContractJsonSerializer(typeof(Response));
    object objResponse = jsonSerializer.ReadObject(response.GetResponseStream());
    MyResponse jsonResponse = objResponse as MyResponse;
    return jsonResponse;
}

See this link for more details: http://msdn.microsoft.com/en-us/library/hh674188.aspx


text:
Q: ng-template not displaying views in jsFiddle I was learning about AngularJS views from here. The example which the site has shown is supposed to output this:

However, the output is not showing in my fiddle:

         var mainApp = angular.module("mainApp", ['ngRoute']);
         mainApp.config(['$routeProvider', function($routeProvider) {
            $routeProvider.

            when('/addStudent', {
               templateUrl: 'addStudent.htm',
               controller: 'AddStudentController'
            }).

            when('/viewStudents', {
               templateUrl: 'viewStudents.htm',
               controller: 'ViewStudentsController'
            }).

            otherwise({
               redirectTo: '/addStudent'
            });
         }]);

         mainApp.controller('AddStudentController', function($scope) {
            $scope.message = "This page will be used to display add student form";
         });

         mainApp.controller('ViewStudentsController', function($scope) {
            $scope.message = "This page will be used to display all the students";
         });

AngularJS ng-template example

Add Student

View Students

I believe, I have selected LOAD TYPE correctly:

What am I doing wrong here?

A: You have wrong hrefs, those should have / before them. Also you haven't added angular-route.js in your Fiddle.
Markup

Add Student

View Students

Demo Fiddle

A: In order to get ngRoute working you have to add :

The problem was caused by missing inclusion of ngRoute module
working example


text:
Q: data-ng-bind-html works but not curly {{}} brackets so when I use this code, the data-ng-bind-html properly displays the topics but when I actually use topic.pagetitle, nothing shows, there is an empty  tag. Anyone know what could be going on?

        {{topic.pagetitle}}

A: You are attempting to use an unsafe value in a safe context. See Strict Contextual Escaping

A: The ngBindHtml works by setting the innerHTML on the element. This means that anything you put inside that tag will be overwritten by the ngBindHtml value. This is mentioned at the top of the documentation for that directive https://docs.angularjs.org/api/ng/directive/ngBindHtml
Here is an example (code missing for brevity):
CONTROLLER
...
scope.foo = ' I am the foo '
scope.bar = 'Bar'
...

VIEW

{{ bar }}

{{ bar }}

BROWSER
I am the foo
I am the foo
Bar


text:
Q: How can I use AppleScript to type? How can I use AppleScript to type in a specified area on the screen? I've tried the keystroke command, but it doesn't seem to work. Also, how can I use AppleScript to display an image? Here is the code I have so far:
set theText to text returned of (display dialog "Put what you want to autotype here." default answer "" buttons {"OK", "cancel"} default button 1)
display dialog "select where you want me to type " & theText & " Your text will be typed in the area selected. you have 10 seconds to select once you click 'OK'" buttons {"OK"}
delay 10
say "typing"
--command for typing here
end
end
end

A: tell application "System Events"
    set textToType to "text here"
    keystroke textToType
end tell

Replace within the quotes of "text here" to what ever you need.

A: You can also use key code to type individual keys or achieve most functions using your keyboard.

key code 8 using {command down, shift down} --> ⌘+shift+C

Here is the full list of key codes:
https://eastmanreference.com/complete-list-of-applescript-key-codes


text:
Q: I am fetching images and want save images in single pdf file I am fetching images and want to save images into single pdf file.
Below is the code which is creating multiple pdf for multiple images but I want all images should saved into single pdf :
in = Image.open(r". Output\demod.png" % i)
im = im.convert('RGB')
im = im.crop((left, top, right, bottom))
print(im)
imagelist = [im] print(imagelist)
pdf_path = im.save(r". \pdf\my_images%d.pdf" % i, save_all=True, append_images=imagelist)
in.close()
print("successfully made pdf file")

Could you please help me to resolve this?

A: Try this:
pdf = FPDF()

for img in [Image.open(r".\Output\demod.png" * i)]:
    im = img.convert('RGB')

    cropped img = im.crop((left, top, right, bottom))
    cropped_img.save(r".\Output\cropped%d.png" % i)
    pdf.add page ()
    pdf.image (r".\Output\cropped%d.png" & i, randint(1,20),randint(1, 20))

pdf.output('finalpdf.pdf', 'f')


text:
Q: connect host localhost with guest localhost I am running a vm with ip 192.168.122.69 and I want to run a server that must run from host ip 10.0.2.2. The server is running on port 8081 and I can connect to it at 192.168.122.69:8081 from the host.
The exact application is in developing a react app and sharing a react app server instance. However, I am mainly asking this as for educational purposes.. i.e. how do I make it so that connecting to 10.0.2.2:8081 is exactly the same as connecting to 192.168.122.69:8081 on the host or 127.0.0.1:8081 on the guest. I really just can not grasp how the routing, bridges, dns, whatever works so a thorough explanation would be very much appreciated.
I have done countless hours of research into this and while I'm sure I've gone over the answer several times, I haven't been able to grasp it.

A: As far as making it so that, on the guestVM, connecting to 192.168.122.69:8081 is the same as connecting to 127.0.0.1:8001 just depends on the Web Server config. In the web server config files, publish the page on all IP addresses.
As far as port forwarding the address form host to guest, it really depends on your setup; most importantly what hypervisor you are using and what the host OS is.
Is it VMware? Then this article answers your question.


text:
Q: Fading in input field, displacing the rest of the website I'm making a website, and, the main part of the website is a canvas where I, through javascript and jquery made an application. For getting input from the user, I was advised to fade in some input fields placed using absolute positioning. It works, but as they fade in, they somewhat displace the rest of the website. Anything I can do to make it not displace the rest of the website? Also, be sure to let me know of other ways of getting input from the user.
Here's a link to a hosted version of the website.

A: Since my comments are turning into an answer, I may as well add the answer:
Another way of getting user input is prompt()
To fix your absolute positioning problems, wrap your content in a wrapper div e.g:
<div style="width: 500px; margin: 0 auto;position:relative;">
  <!--content here-->
</div>

Then make sure each of your inputs has their position as absolute.
NOTE: The absolute values you use will no longer be relative to the document, but to the new wrapper, so top: 0; left: 0 will place an element at the top left of the wrapper


text:
Q: Defining a differential for quotients Let $f \colon M \to N$ be a smooth map between smooth manifolds and $f$ being a surjective submersion. Assuming we have a proper Lie-group action $G$ on $M$, with only one orbit type and $G$ acts on $N$ also proper. Furthermore let $f$ be $G$-equivariant.
We can now consider the quotientmap
$f' \colon M/G \to N/G$.
Is it now possible to define a differential
$d_{[x]}f' \colon T_{[x]} (M/G) \to T_{f'([x])} (N/G)$?
Edit:
Well, since $M$ has only one orbit-type, we know, that $M/G$ has a manifold structure. If $x\in M$ is such, that there is a subset $U \subset N$ around $f(x)$ and such that for all $y \in U$, the isotropy-group $G_y$ is conjugate to $G_{f(x)}$, then $U/G$ has also a manifold structure and I don't see any problem defining the differential.
So my question is more, what's happening in $x\in M$ such that $G\cdot f(x)$ is not the principal orbit in $N$.


text:
Q: .NET MAUI Binding a List to a Context View So I have a list which shows Tags which are supposed to be able to be deleted created and modified and for that i want it to be binded with the context view
On the Xaml file i have wrote this
<ScrollView
                WidthRequest="1400"
                HeightRequest="600"
                HorizontalOptions="StartAndExpand"
                >
                <VerticalStackLayout
                    Spacing="5"
                    >
                    <CollectionView
                        x:Name="Tags"
                        ItemsSource="{Binding TagList}"  ** Here would be the binding i think
                        SelectionMode="None"
                        >
                        <CollectionView.ItemTemplate>
                            <DataTemplate>
                                <HorizontalStackLayout
                                    VerticalOptions="StartAndExpand"
                                    Margin="30,0,0,0">
                                    <controls:TagView
                                        Padding="5"
                                        TagTitle="{Binding TagTitle, FallbackValue='1'}"
                                        TagNr="{Binding TagNr, FallbackValue='1'}"
                                        ValField="{Binding ValField}"
                                        ShowBtn="{Binding ShowBtn}"
                                        />
                                </HorizontalStackLayout>
                            </DataTemplate>
                        </CollectionView.ItemTemplate>
                    </CollectionView>
                </VerticalStackLayout>
            </ScrollView>

and here is the C# code to that

public static List<TagView> TagList { get; set; } = new();

public MainPage()
    {
        InitializeComponent();
        Tags.BindingContext = TagList;

    }

i have already tried to bind it per ItemsSource but if i did it with that, then it wont update changes to the list
If you could help then i would appreciate it. Thanks!!

A: You probably want to use an ObservableCollection<TagView> instead of a List. An ObservableCollection will notify the UI of changes in the collection and update accordingly.
Basically the ObservableCollection has INotifyPropertyChanged functionality built-in. If you want to use a List you will have to notify the UI manually that an update has happened.


text:
Q: django-tenant-schemas 1.10.0: TypeError: TenantTutorialMiddleware() takes no arguments I am trying to use django-tenant-schemas 1.10.0. I have installed it and made migrations successfully. But the command "python manage.py runserver" produces the error:

Exception ignored in thread started by: .wrapper at 0x000002282DBC2790>
  Traceback (most recent call last):
File "D:\projects\django-tenant-schemas-master\django-tenant-schemas-master\examples\lib\site-packages\django\utils\autoreload.py", line 227, in wrapper
      fn(*args, **kwargs)
File "D:\projects\django-tenant-schemas-master\django-tenant-schemas-master\examples\lib\site-packages\django\core\management\commands\runserver.py", line 147, in inner_run
      handler = self.get_handler(*args, **options)
File "D:\projects\django-tenant-schemas-master\django-tenant-schemas-master\examples\lib\site-packages\django\contrib\staticfiles\management\commands\runserver.py", line 27, in get_handler
      handler = super(Command, self).get_handler(*args, **options)
File "D:\projects\django-tenant-schemas-master\django-tenant-schemas-master\examples\lib\site-packages\django\core\management\commands\runserver.py", line 68, in get_handler
      return get_internal_wsgi_application()
File "D:\projects\django-tenant-schemas-master\django-tenant-schemas-master\examples\lib\site-packages\django\core\servers\basehttp.py", line 47, in get_internal_wsgi_application
      return import_string(app_path)
File "D:\projects\django-tenant-schemas-master\django-tenant-schemas-master\examples\lib\site-packages\django\utils\module_loading.py", line 20, in import_string
      module = import_module(module_path)
File "c:\program files\python38\lib\importlib__init__.py", line 127, in import_module
      return _bootstrap._gcd_import(name[level:], package, level)
File "", line 1014, in _gcd_import
File "", line 991, in _find_and_load
File "", line 975, in _find_and_load_unlocked
File "", line 671, in _load_unlocked
File "", line 783, in exec_module
File "", line 219, in _call_with_frames_removed
File "D:\projects\django-tenant-schemas-master\django-tenant-schemas-master\examples\tenant_tutorial\tenant_tutorial\wsgi.py", line 28, in
      application = get_wsgi_application()
File "D:\projects\django-tenant-schemas-master\django-tenant-schemas-master\examples\lib\site-packages\django\core\wsgi.py", line 14, in get_wsgi_application
      return WSGIHandler()
File "D:\projects\django-tenant-schemas-master\django-tenant-schemas-master\examples\lib\site-packages\django\core\handlers\wsgi.py", line 151, in init
      self.load_middleware()
File "D:\projects\django-tenant-schemas-master\django-tenant-schemas-master\examples\lib\site-packages\django\core\handlers\base.py", line 82, in load_middleware
      mw_instance = middleware(handler)
TypeError: TenantTutorialMiddleware() takes no arguments

I'm using Postgres database. The error was the same when I tried with Django 1.11, 2.2, and 3.0.
Please someone help me!


text:
Q: Update Data Extension in Parent BU when Data Extension in Child BU gets updated( move data from Child BU to Parent Can someone please help me with this scenario?
I have a data extension in Child Business Unit and the same data extension in Parent Business Unit. The Child Business Unit gets updated randomly and I want the parent unit to get updated when ever the child unit is got updated.
How can I acheive this ?
** Note (We  are using Enterprise 1.0 Business unit which means we don't have shared data extensions feature available )**

A: If you have Marketing Cloud SFTP, you could create an automation in Child BU, that would export all the data from your DE to FTP, and another automation in Parent BU, that would import this file from FTP and update the data in your DE in Parent BU.
This wouldn't be possible in real-time though, you could automate it to run every hour or so.
Check out the Marketing Cloud SFTP Guide and Automation Studio


text:
Q: How can one show that $\sum_{j=0}^r \frac{1}{j!(r-j)!} = \frac{2^r}{r!}$ for $r \in \mathbb{N}$? I ran into this sum while calculating the marginal pdf of a joint distribution function. I wasn't sure how to evaluate it, so I plugged it into Wolfram expecting something ugly. Fortunately, there's this nice closed form equality, but I don't know how to arrive at the result analytically.
Edit: Just realized that I could do this by induction. But that's rather unsatisfactory, since I wouldn't have arrived at the idea to prove this without Wolfram.

A: $$\sum_{j=0}^r \frac{r!}{j!(r-j)!} = \sum_{j=0}^r \frac{r!}{j!(r-j)!} 1^j 1^{r-j} = (1+1)^r = 2^r$$ by the binomial theorem. Now divide by $r!$


text:
Q: Embed a UIwebView in a UITableViewCell I want embed a UIWebView in a UITableViewCell. But there are some problems :
1, I setup the cell's database in method:
    (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    UITableViewCell * cell = [tableView
    dequeueReusableCellWithIdentifier:cellIdenWebViewIntro
    forIndexPath:indexPath];

    PlayListModel * model = [PlayListModel new];
    cell.model = model;
    return cell;

    }

And IN the Cell , i setup the webView and send url request in setModel Method:
- (void)setModel:(PlayListModel *)model{
    _model = model;

    NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://temp url"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];

    [self.webView loadRequest:request];
}

It's a quite normal way to config the cell. but when the tableView scroll down and scrolling back to the webViewCell, the system called (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath again, so the webView will send url request again and again. So it's there a way to cache the HTML content of webView. and if the user did not pop out the current view controller I will reuse the HTML for the webView but no to send request multi times.
p.s I already set a cache policy when creating an NSURLRequest, but it did not work.

A: Yes, it's expected. TableView will call cellForRowAtIndexPath method on scrolling.
What you can do is you download the HTML content of that URL and store it. So, when the cell gets reload you can check that if you have HTML content of that URL then load it from stored variable or database.
For downloading file, check here.

A: There is another way to download HTML content by javascript.
// DidFinishLoad
-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
    NSString *getHTMLJSCode = @"document.getElementsByTagName('html')[0].innerHTML";
    [wkWebView evaluateJavaScript:getHTMLJSCode completionHandler:^(id _Nullable content, NSError * _Nullable error)
     {
         if (error) {
             NSLog(@"Error: %@",error);
             return;
         }

         NSLog(@"Content: %@",content);
         self.HTMLSourceCode = content; // cache
     }];
}

You can load request on first loading then cache it.
if (HTMLSourceCode) {
    // To load cached webpage.
    [wkWebView loadHTMLString:HTMLSourceCode baseURL:[NSURL URLWithString:_urlString]];
}
else {
    //...
    [wkWebView loadWithURLRequest:request]
}