text:
Q: writing and reading class of columns to csv For a dataframe, I'd like to save the data class of each column (eg. char, double, factor) to a csv, and then be able to read both the data, and the classes, back into R.
For example, my data might look like this:
df
#> # A tibble: 3 × 3
#>    item  cost blue
#>   <int> <int> <fct>
#> 1     1     4 1
#> 2     2    10 1
#> 3     3     3 0

(code for data input here:)
library(tidyverse)
df <- tibble::tribble(
  ~item, ~cost, ~blue,
     1L,    4L,    1L,
     2L,   10L,    1L,
     3L,    3L,    0L
  )

df <- df %>%
  mutate(blue = as.factor(blue))
df

I'm able to save the classes of the data, and the data, this way:
library(tidyverse)
classes <- map_df(df, class)

write_csv(classes, "classes.csv")
write_csv(df, "data.csv")

and I can read it back this way:
classes <- read.csv("classes.csv") %>%
  slice(1) %>%
  unlist()
classes
df2 <- read_csv("data.csv", col_types = classes)
df2

Is there a quicker way to do all of this?
Particularly with the way I'm saving classes and then reading it back in, then slicing and unlisting?

A: You could use writeLines and its counterpart readLines for the classes. Like this:
classes <- sapply(df, class)
writeLines(classes, "classes.txt")
#to read them
readLines("classes.txt")

However, consider also other formats like parquet (the R implementation is provided by the arrow package) for instance that preserve the data types and are implemented by many languages.

A: Try the csvy package. Also see the http://csvy.org/ site. This generates a single file rather than two files simplifying working with it (or optionally it can write the metadata to a separate file), there are csvy readers available in some other languages as well (see link just cited), the format is standardized and backwards compatible with csv which is probably better than rolling your own format.
library(csvy)
write_csvy(df, "df.csvy")

This produces this file:
#---
#profile: tabular-data-package
#name: df
#fields:
#- name: item
#  type: integer
#- name: cost
#  type: integer
#- name: blue
#  type: integer
#---
item,cost,blue
1,4,1
2,10,1
3,3,0

which can be read back in using:
read_csvy("df.csvy")

or read.csv("df.csvy", comment.char = "#") or any number of R packages which have functions to read csv files.
We can extract the metadata as a list using:
library(yaml)
md <- get_yaml_header("df.csvy")
md_list <- yaml.load(paste(md, collapse = "\n"))

str(md_list)
## List of 3
##  $ profile: chr "tabular-data-package"
##  $ name   : chr "df"
##  $ fields :List of 3
##   ..$ :List of 2
##   .. ..$ name: chr "item"
##   .. ..$ type: chr "integer"
##   ..$ :List of 2
##   .. ..$ name: chr "cost"
##   .. ..$ type: chr "integer"
##   ..$ :List of 2
##   .. ..$ name: chr "blue"
##   .. ..$ type: chr "integer"

Added
fwrite in the data.table package with argument yaml=TRUE can be used to write csvy files with slightly different content in the yaml headers.  The export function of the rio package can also generate csvy files using fwrite.

A: Another alternative is to use the readr::spec_csv() argument.

*

*take the csv file or final dataframe that you want and pass it through to spec_csv(), this will produce a cols class that will provide the column names and col_type arguments.

*you can save that as csv and then directly upload that to your col_type argument for future use


text:
Q: How to show only the name instead of the email address of the sender in a simple php mail script I have a simple php mail script which will send emails.
The problem is while sending it is displaying  sendername <senderemail@domain.com>
I have given in the code as $headers = "From: $name <$senderEmail>";
I want to display only name and not email address of the sender.
How do I do that?
Here is the program in its entirety.
<?php

if($_POST["submit"]) {
    $recipient=$_POST["senderemail"];
    $subject=$_POST["subject"];
    $name=$_POST["name"];
    $senderEmail=$_POST["email"];
    $city=$_POST["city"];
    $headers = "From: $name <$senderEmail>";
    $mailBody="$city\n";
    $process=explode(",",$recipient);
    reset($process);

    foreach ($process as $to) {
        mail($to,$subject, $mailBody,$headers);
    }

    $thankYou="
Thank you! Your Message has been sent.
";
    echo 'Thank you! Your Message has been sent.';
}
?>

A: A From header containing both name and address should be formatted like this:
From: User Name <user@example.com>

If you don't provide a name, it will display the email address.
PHPMailer has built-in support for creating this header correctly for you via the From and FromName properties, and the setFrom method (it doesn't matter which you use):
$mail->setFrom('user@example/com', 'User Name');

or
$mail->From = 'user@example/com';
$mail->FromName = 'User Name';

A: Your generated message already seems to contain the user's full name in the From: header (assuming $name is the human-readable name).  How this is displayed by any individual user agent is no longer in your hands.  Very often, it will display both parts regardless; or only shorten to the human-readable name if the sender's email address is in the recipient's address book.  (Thunderbird takes this a step further and displays the information from the address book rather than the actual information in the message!)
One common problem is if the generated message has a different Sender: header; often, this will cause the recipient's user agent to display more than just the usual full name.  Your question doesn't mention this, nor does it show one of the generated messages; but perhaps this will help you find a solution.

redpajama_set_name: RedPajamaStackExchange


text:
Q: AngularJS: Directive can not find dependency injected Here is my plunker - http://plnkr.co/edit/uqSB1gIz6XEmJfC8zHNb?p=preview
I am trying to inject Angular Strap
The index.html is including the right dependencies and in correct order

My console says
Error: Unknown provider: $strap.directivesProvider <- $strap.directives <- notificationDirective
@http://code.angularjs.org/1.1.5/angular.min.js:29
c@http://code.angularjs.org/1.1.5/angular.min.js:27
@http://code.angularjs.org/1.1.5/angular.min.js:30
c@http://code.angularjs.org/1.1.5/angular.min.js:27
d@http://code.angularjs.org/1.1.5/angular.min.js:27
@http://code.angularjs.org/1.1.5/angular.min.js:37
forEach@[native code]

A: The module dependency for AngularStrap is listed in the wrong place.  '$strap-directives'  is a module dependency, not a service dependency, so it needs to be listed during the app bootstrap like:
var app = angular.module('myApp', ['$strap.directives']);

It also needs to be removed as a service DI in your directive:
app.directive('notification', function(){
    return {
        restrict: 'E',
        replace: true,
        scope: {
            ngModel: '='
        },
        template: '
Test
'
    }
});

This is the way they configure the Plunkers on the AngularStrap site as well.

A: $strap.directives is a module. You need to define it as a dependency for your own module:
var app = angular.module('myApp', ['$strap.directives']);

You need not inject this into the directive. Thus your directive will only look like:
app.directive('notification', function(){
  return {
    restrict: 'E',
    replace: true,
    scope: {
      ngModel: '='
    },
    template: '
Test
'
  }
});


text:
Q: Multiple Monitors with one DisplayPort I've read that DisplayPort supports multiple monitors. My question is how can I connect 3 monitors with one display port, is there such a splitter? I have 2 DVI monitors and one VGA (which I could use DVI to VGA convereter)
If I could do it, will I be limitted by the GPU? Is it possible that my GPU only allow for 2 monitors?

A: DisplayPort 1.2 supports daisy-chaining like this in the spec, but I am not aware of any products on the market that currently support it, either on the video card side or the monitor side.  I expect you'll see them in the next year or so, though, now that the specifications are official (and I believe there are already controllers entering production).

A: The DisplayPort Spec supports the daisy chaining of multiple monitors, but not the splitting of the signal.  Unfortunate, to support this you need to have at least 2 DisplayPort equipped monitors that support daisy chaining (of which there are none to my knowledge).
Given your situation, your best bet would be something like the Matrox TripleHead ToGo, which allows you to connect multiple monitors to a single port (and tricks your computer into only seeing one while spreading the image across several).
Using a solution like that, your main limitation is the power of your graphics card and how many pixels it can render well.


text:
Q: How to change the default color on MahApps Metro slider <Slider x:Name="CustomSliderVertical"
        Height="10"
        Width="150"
        Margin="0,10"
        Maximum="50"
        SmallChange="0.1"
        LargeChange="5"
        TickPlacement="None"
        TickFrequency="10"
        Value="5"
        Style="{DynamicResource FlatSlider}"
        ToolTip="{Binding RelativeSource={RelativeSource Self}, Path=Value}"
        VerticalAlignment="Center">
</Slider>

So i want to do some style.
How to change colors of this Slider (thump black color)

A: Set the BorderBrush property of the Slider to some other Brush than Black:
<Slider x:Name="CustomSliderVertical"
        Height="10"
        Width="150"
        Margin="0,10"
        Maximum="50"
        SmallChange="0.1"
        LargeChange="5"
        TickPlacement="None"
        TickFrequency="10"
        Value="5"
        Style="{DynamicResource FlatSlider}"
        ToolTip="{Binding RelativeSource={RelativeSource Self}, Path=Value}"
        VerticalAlignment="Center"
        BorderBrush="Red">
</Slider>


text:
Q: Jquery Datatable in Angular 2 Application I'm trying to import Metronic datatable in my angular 2 app, I import all the script and reference (with the html tag <script>..</script> and <link>) in the main html page, the same where I initialize angular 2 (with System.import()..), but it don't work, it show me the table without the search/reordering feature.
Any advice? How can I import these in angular 2?
Thanks in advance
<script src="/core-js/client/shim.min.js"></script>
<script src="/zone.js/dist/zone.js"></script>
<script src="/systemjs/dist/system.src.js"></script>
<script src="systemjs.config.js"></script>
<script>
    System.import('main.js').catch(function(err){ console.error(err); });
</script>

<link href="/theme2/global/plugins/datatables/datatables.min.css" rel="stylesheet" type="text/css" />
<link href="/theme2/global/plugins/datatables/plugins/bootstrap/datatables.bootstrap.css" rel="stylesheet" type="text/css" />

<script src="/theme2/global/scripts/datatable.js" type="text/javascript"></script>
<script src="/theme2/global/plugins/datatables/datatables.min.js" type="text/javascript"></script>
<script src="/theme2/global/plugins/datatables/plugins/bootstrap/datatables.bootstrap.js" type="text/javascript"></script>

A: Try to import library in .angular-cli.json file
{
"scripts": [/themes/..*.js],
}

Also , make sure if the library can be installed using npm install package.


text:
Q: Datagrid - Scrolling will crop images horizontally instead of vertically I needed to invert Columns/Rows on my DataGrid (see WPF horizontal DataGrid and RotatedDataGrid)
Once I inverted it, I am having some weird effects on the images displayed inside my datagrid.
When I scroll down, the column 1 will crop the image by the left and a little on the right. The more I go down, the more it crops the left until there is nothing more.

How can I solve that ?
Here a full simple example if you want to test it (you just need to copy/paste it in a new project and scroll down to see the problem)
MainWindows.xaml
    <Window x:Class="RotatedDataGrid.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="150" Width="1000">
    <Grid>
        <DataGrid x:Name="MyRotatedDataGrid" HorizontalContentAlignment="Center"
                     ScrollViewer.HorizontalScrollBarVisibility="Visible" ScrollViewer.VerticalScrollBarVisibility="Visible"
                     AutoGenerateColumns="True"
                     ItemsSource="{Binding Customers}">
            <DataGrid.Resources>
                <Style x:Key="DataGridBase" TargetType="Control">
                    <Setter Property="LayoutTransform">
                        <Setter.Value>
                            <TransformGroup>
                                <RotateTransform Angle="-90" />
                                <ScaleTransform ScaleX="1" ScaleY="-1" />
                            </TransformGroup>
                        </Setter.Value>
                    </Setter>
                    <Setter Property="TextOptions.TextFormattingMode" Value="Display" />
                </Style >
                <Style TargetType="DataGridCell" BasedOn="{StaticResource DataGridBase}"/>
                <Style TargetType="DataGridColumnHeader" BasedOn="{StaticResource DataGridBase}"/>
                <Style TargetType="DataGridRowHeader" BasedOn="{StaticResource DataGridBase}"/>
            </DataGrid.Resources>

            <DataGrid.LayoutTransform>
                <TransformGroup>
                    <RotateTransform Angle="90" />
                    <MatrixTransform Matrix="-1, 0, 0, 1, 0, 0" />
                </TransformGroup>
            </DataGrid.LayoutTransform>

            <DataGrid.GroupStyle>
                <GroupStyle>
                    <GroupStyle.HeaderTemplate>
                        <DataTemplate>
                            <StackPanel>
                                <TextBlock Text="{Binding Path=Name}" FontWeight="Bold" Padding="3"/>
                            </StackPanel>
                        </DataTemplate>
                    </GroupStyle.HeaderTemplate>
                    <GroupStyle.ContainerStyle>
                        <Style TargetType="{x:Type GroupItem}">
                            <Setter Property="Template">
                                <Setter.Value>
                                    <ControlTemplate TargetType="{x:Type GroupItem}">
                                        <Expander>
                                            <Expander.Header>
                                                <StackPanel Orientation="Horizontal">
                                                    <TextBlock Text="{Binding Path=Name}"/>
                                                    <TextBlock Text="{Binding Path=ItemCount}" Margin="8,0,4,0"/>
                                                    <TextBlock Text="Items"/>
                                                </StackPanel>
                                            </Expander.Header>
                                            <ItemsPresenter />
                                        </Expander>
                                    </ControlTemplate>
                                </Setter.Value>
                            </Setter>
                        </Style>
                    </GroupStyle.ContainerStyle>
                </GroupStyle>
            </DataGrid.GroupStyle>

        </DataGrid>
    </Grid>
</Window>

MainWindow.xaml.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace RotatedDataGrid
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public ICollectionView Customers { get; private set; }
        public ICollectionView GroupedCustomers { get; private set; }

        public MainWindow()
        {
            InitializeComponent();

            var _customers = new List<Customer>
                                 {
                                     new Customer
                                         {
                                             FirstName = "Christian",
                                             LastName = "Moser",
                                             Gender = Gender.Male,
                                             WebSite = new Uri("http://www.wpftutorial.net"),
                                             ReceiveNewsletter = true,
                                             Image = "Images/christian.jpg"
                                         },
                                     new Customer
                                         {
                                             FirstName = "Peter",
                                             LastName = "Meyer",
                                             Gender = Gender.Male,
                                             WebSite = new Uri("http://www.petermeyer.com"),
                                             Image = "Images/peter.jpg"
                                         },
                                     new Customer
                                         {
                                             FirstName = "Lisa",
                                             LastName = "Simpson",
                                             Gender = Gender.Female,
                                             WebSite = new Uri("http://www.thesimpsons.com"),
                                             Image = "Images/lisa.jpg"
                                         },
                                     new Customer
                                         {
                                             FirstName = "Betty",
                                             LastName = "Bossy",
                                             Gender = Gender.Female,
                                             WebSite = new Uri("http://www.bettybossy.ch"),
                                             Image = "Images/betty.jpg"
                                         }
                                 };

            Customers = CollectionViewSource.GetDefaultView(_customers);

            GroupedCustomers = new ListCollectionView(_customers);
            GroupedCustomers.GroupDescriptions.Add(new PropertyGroupDescription("Gender"));

            MyRotatedDataGrid.DataContext = this;
        }
    }

     public enum Gender
    {
        Male,
        Female
    }

     public class Customer : INotifyPropertyChanged
     {
         private string _firstName;
         private string _lastName;
         private Gender _gender;
         private Uri _webSite;
         private bool _newsletter;
         private string _image;

         public string FirstName
         {
             get { return _firstName; }
             set
             {
                 _firstName = value;
                 NotifyPropertyChanged("FirstName");
             }
         }

         public string LastName
         {
             get { return _lastName; }
             set
             {
                 _lastName = value;
                 NotifyPropertyChanged("LastName");
             }
         }

         public Gender Gender
         {
             get { return _gender; }
             set
             {
                 _gender = value;
                 NotifyPropertyChanged("Gender");
             }
         }

         public Uri WebSite
         {
             get { return _webSite; }
             set
             {
                 _webSite = value;
                 NotifyPropertyChanged("WebSite");
             }
         }

         public bool ReceiveNewsletter
         {
             get { return _newsletter; }
             set
             {
                 _newsletter = value;
                 NotifyPropertyChanged("Newsletter");
             }
         }

         public string Image
         {
             get { return _image; }
             set
             {
                 _image = value;
                 NotifyPropertyChanged("Image");
             }
         }

         #region INotifyPropertyChanged Members

         public event PropertyChangedEventHandler PropertyChanged;

         #endregion

         #region Private Helpers

         private void NotifyPropertyChanged(string propertyName)
         {
             if (PropertyChanged != null)
             {
                 PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
             }
         }

         #endregion
     }
}

A: Ok I found how to solve it.
The transformation applied into the DataGridCell was creating this scrollviewer problem. To solve that, I removed the layout transform on the DataGridCell (by removing the BaseOn code) and I applied the transformation into the DataGridCell Template.
WRONG
<Style TargetType="DataGridCell" BasedOn="{StaticResource DataGridBase}"/>

RIGHT
<Style TargetType="DataGridCell">
  <Setter Property="Template">
    <Setter.Value>
       <ControlTemplate TargetType="{x:Type DataGridCell}">
           <Grid>
                <Grid.LayoutTransform>
                   <TransformGroup>
                        <RotateTransform Angle="90" />
                        <MatrixTransform Matrix="-1, 0, 0, 1, 0, 0" />
                   </TransformGroup>
               </Grid.LayoutTransform>
               <ContentPresenter/>
           </Grid>
        </ControlTemplate>
      </Setter.Value>
   </Setter>
</Style>


text:
Q: How to iterate a json array in karate? No able to iterate karate request with each value of array
I am getting a json array in response and want to store that in array variable and iterate my next api request with each values as path parameter in karate. any probable solution available in karate for this?


text:
Q: Comic book with a boy and animals I read this comic book as a child, but can't recall its name and Google couldn't help.
It's about a boy and lots of animals. As far as I can remember the boy regularly enters a dream-world, where he encounters a lot of different animals (can't remember what exactly he was doing there). His mother gives him a goldfish, which he names Moby Dick. This fish also enters the dream world.
In my version the first two pages of the book contained a huge picture of different animals (whale, penguin & others).I read it in German, not sure if this was the original language or a translation.
Anybody know what I'm looking for?

A: This is Hé, Nic! Tu rêves? (Hey, Nick! Are You Dreaming?), the first book of a Belgian series about a boy named Nic and the adventures he has while dreaming. According to French WikiPedia, it was heavily inspried by Little Nemo.

It was written by Morphée (Philippe Vandooren), drawn by Hermann (best known for Jeremiah) and colouring was done by Vittorio Leonardo. It was published by Dupuis.
It consists of a number of linked stories, each starting when Nic falls asleep. He dreams another chapter of his adventure, somewhat related to what he did before falling asleep. The major antagonist is Captain Bang, who wants to capture all the animals for his zoo. Nic tries to thwart his plans. When he succeeds, the captain gets so mad that he explodes with a bang, leaving only his hat behind.

The German version is called He, Robin. Träumst Du? and is available on Amazon.de.


text:
Q: Objective-C - помогите с регулярным выражением NSString text = @"Начало текста [id23542234|Tony] конец текста.";

*

*Необходимо из текста выше получить id23542234 и Tony в переменные.

*Необходимо в тексте выше заменить [id23542234|Tony] на Tony.

Вот набросал регулярное выражение. Правильное?
\\[[id]{2}[0-9]+\\|[a-z,а-я]+\\]

Как это кокретно на Objective-C реализовать?
P.S. Разобрался сам:
Регулярное выражение правильное.
Используем класс NSRegularExpression.
С помощью regularExpressionWithPattern находим вхождения.
А с помощью stringByReplacingMatchesInString заменяем в исходном тексте,
A: Привет, Tony!
Вашу задачу можно решить следующим регулярным выражением:
/@".+?\[(id\d+)|\s\].+?/g

*

*ищем @"Начало текста [

*.+? означает, что мы "не жадно" берем текст, пока не встретим следующую инструкцию

*\[(id\d+)|\s\] ищет строку вида [id23542234|Tony] (после которой идет любой текст)

*(id\d+)| означает, что мы ищем id + цифра, повторяющаяся сколько угодно раз + |

*нужный нам фрагмент оборачиваем в скобочки, это и будет искомой группой

Надеюсь, мой ответ Вам помог : )


text:
Q: php force download using header() broken downloaded file So firstly i would like to tell that i am quite newbie in header usage and playing with output buffers. So im developing php portlet for liferay and i have some problem with file downloads. I tried to do it simply with 'a href' but problem is that file uploaded via php is unavailable till apache is refreshed so i tried another way with header() function.
So i will try to explain my problem. When i tried following code on simple php project it works fine :
    <?php

$path = "/mysecretdir/upload/"; // change the path to fit your websites document structure
$fullPath = $path.$_GET['download_file'];

if ($fd = fopen ($fullPath, "r")) {

    $fsize = filesize($fullPath);

    $path_parts = pathinfo($fullPath);
    $ext = strtolower($path_parts["extension"]);

    switch($ext) {

        case "pdf":
            $ctype = "application/pdf";
            break;
        case "exe":
            $ctype = "application/octet-stream";
            break;
        case "zip":
            $ctype = "application/zip";
            break;
        case "doc":
            $ctype = "application/msword";
            break;
        case "xls":
            $ctype = "application/vnd.ms-excel";
            break;
        case "ppt":
            $ctype = "application/vnd.ms-powerpoint";
            break;
        case "gif":
            $ctype = "image/gif";
            break;
        case "png":
            $ctype = "image/png";
            break;
        case "jpeg":
            $ctype = "image/jpg";
            break;
        case "jpg":
            $ctype = "image/jpg";
            break;
        case "mp3":
            $ctype = "audio/mp3";
            break;
        case "wav":
            $ctype = "audio/x-wav";
            break;
        case "wma":
            $ctype = "audio/x-wav";
            break;
        case "mpeg":
            $ctype = "video/mpeg";
            break;
        case "mpg":
            $ctype = "video/mpeg";
            break;
        case "mpe":
            $ctype = "video/mpeg";
            break;
        case "mov":
            $ctype = "video/quicktime";
            break;
        case "avi":
            $ctype = "video/x-msvideo";
            break;
        case "src":
            $ctype = "plain/text";
            break;
        default:
            $ctype = "application/force-download";
    }

    header("Pragma: public");

    header("Expires: 0");

    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");

    header("Cache-Control: private",false);

    header("Content-type: " . $ctype);

    header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\"");

    header("Content-Transfer-Encoding: binary");

    //header("Content-length: $fsize");
    header("Cache-control: public"); //use this to open files directly

    while(!feof($fd)) {
        echo fread($fd, 4096);
    flush();
    }
}
fclose ($fd);
?>

from index.php im calling it with href="download.php?download_file=/something/"
Ok but now the point. When i am using it in liferay portlet the file is weird. It puts whole generated HTML file in the created file. So its broken. I dunno why. I dont know if headers are sending some information from elsewhere and also dont know how to fix it.
I was searching for hours for some solution but dont know how to make somehow "session" for headers, because i think there is problem with them. Becasue without echo it prints only content of file and in other project - more simple php app not as a part of portal it works! but maybe i am wrong.
So please can someone help me? Any advise?

A: I can't help you on specific php-portlet problems (I never used Liferay with php) but it sounds like you get the whole page HTML generated "around" your downloaded file. This is what you get when you just render a portlet: A portlet is always embedded in a HTML page, thus you cannot provide specific headers on the HTTP level with the standard render output of a portlet.
What you want is the serveResource lifecycle phase of a portlet. This will allow you to serve content that is not part of the page, but you have full control over the download and HTTP headers. How to do that with php portlets, I'll have to leave to you.
Edit (additional information): As you asked in the comments, I found an older (might need to be adapted) Wiki article that talks about using state=exclusive to do the same trick - instead of the serveResource that I suggested above. I don't know if this is due to the age of the article or because PHP portlets don't support that lifecycle, but you might find something there and in the related&linked articles. Note: serveResource would - if I'm not mistaken - generate a p_p_lifecycle=2 parameter, while this example uses p_p_lifecycle=0 (render) and p_p_state=exclusive. Try if this fits your requirements
However, please consider Marc B's comment about your code being insecure and too hardcoded. There are better solutions for the underlying problem - e.g. Liferay provides the Document Library to up/download files out of the box. And that doesn't have these problems.

A: If you started your PHP file with a space or any other character, headers won't work and the display/download will fail. Make sure you don't have anything before the <?php tag.
Other than that, this should work (if you're not getting errors in the browser).
On the other hand, if you see the actual PHP code, your server does not support PHP.


text:
Q: A multi-application of dijkstra's shortest path algorithm We are given a single train in a graph that must traverse a sparse graph. The train always starts at Station 0. Each vertex in that graph is a "Station" and the edge is an adjacent track to another station. We assume that the train can go backwards as well as forwards. We are given a list of stations that contain a "car" and given how many cars. Each car has a destination it needs to get to and destinations of cars from the same station can be different. At most, a station will only have 5 cars and the maximum number of cars that our train can hold is 100. I am solving this by using dijkstra's to find the nearest station with a car and then finding a path to that car's destination. The problem is, it's a very inefficient way of going about this, because my train only holds and transports 1 car at a time. I want to be able to make full use of my train's capacity, but the problem I'm facing is that if I store more than one at a time, how would I choose the path that I go to? Does anyone have any good ideas?
The reason why it's not a minimum spanning tree problem is:
   .C.
  .   .
 .     .
A       B

If you specifically define a path, you would have to say that the path from A to B is the above path, which it's not.

A: That's a Vehicle Routing Problem.
More specifically, this is the single-vehicle open static one-to-one capacitated pickup-and-delivery problem.

*

*Single vehicle: only one train

*Open: the vehicle is not required to return to the depot

*Static: all information is deterministic and known a priori

*One-to-one: each request originates at one location and is destined for
one other location

*capacitated: the vehicles have limited carrying capacity

*pickup-and-delivery: a number of goods need to be moved from certain pickup locations to other delivery locations

This problem is NP-hard. Exact solutions are usually branch-and-bound
or branch-and-cut algorithms. Many approximation algorithms have been proposed for different variants, so I'll only give you some leads:

*

*A Survey on Pickup and Delivery Problems [Parragh, Doerner, Hartl 2008]

*Single-Commodity Vehicle Routing Problem with Pickup and Delivery Service [Martinovic, Aleksi, Baumgartner 2008]

*Recent Models and Algorithms for One-to-One Pickup and Delivery Problems [Cordeau, Laporte, Ropke 2007]

*Static pickup and delivery problems: a classification scheme and survey [Berbeglia, Cordeau, Gribkovskaia, Laporte 2007]

*NEO

*jsprit


text:
Q: is 'pip check' broken? I'm seeing this issue on two different computers today:
python functioning correctly, pip check returns no broken dependencies.
create virtualenv virtualenv --system-site-packages ~/env and source ~/env/bin/activate. all good
pip check: still no broken dependencies
as an example,pip install six:
Requirement already satisfied: six in /usr/lib/python2.7/dist-packages (1.10.0)
pip install jupyter or pip install catkin_pkg, installation completes successfully, but:
python-dateutil 2.7.2 requires six>=1.5, which is not installed.
catkin-pkg 0.4.1 requires pyparsing, which is not installed.
ok weird, we just checked that six is installed, and at version 1.10, right?
gets weirder: pip install six again:
pip install six
Requirement already satisfied: six in /usr/lib/python2.7/dist-packages (1.10.0)
python-dateutil 2.7.2 requires six>=1.5, which is not installed.
What? is it, or is it not installed?
Making sure users can read the dist-packages files with sudo chmod -R go+rX /usr/lib/python2.7/dist-packages does not solve this.
At first I thought my system might have broken packages, but seeing this on two different machines is really weird.
Any ideas?

A: python-dateutil 2.7.2 requires six>=1.5, which is not installed

from the error its clear that module six's version should be greater than v1.5

so just list out the installed version by pip freeze
As of now six have latest version you can install by
pip install six==1.11.0

A: After waiting a few days, I upgraded pip, and the errors disappeared. It seems it was indeed a bug in pip version comparison, as described by Erik Cederstrand


text:
Q: How to minimize some of the stats in your script UI - Unity I am searching in google for my problem, but it is hard to find any information on the web when you don't know the exact word for it.
I saw this in a video and I really would like to know how can I do that. You can see a screenshot below about it:

If anyone knows the name of it or how to do it, i would appreciate it a lot.

A: To get the same visual as I stated in comment ( expandable element ) you need to either create your own EditorScript or use smaller data models.

Example usage of data models:
Let's say you want to display player's statistics inside of that expandable element, all you have to do is to create a class for that element ( PlayerStatistics and mark it with Serializable attribute:
[Serializable]
public class PlayerStatistics
{
    public float Health;
}

Now in your MonoBehaviour add this as a member field :
public class MeBehaviour
    : MonoBehaviour
{
    public PlayerStatistics PlayerStats;
}

Default editor behavior should automatically wrap PlayerStatistics inside an expandable element.

Another way is to use an array or List<> that will do basically the same.


text:
Q: How does the sudo key symbol work? I'm trying to write a script that requests the user password for some sudo-related commands. My goal is to emulate the default method that OS X uses to obtain the user's password, Password: followed by a key-like symbol, as seen in the screenshot attached below:

I tried the answer from How to get a password from a shell script without echoing over on Stack Overflow that uses read -s, but that results in Password: without the key symbol when run from a script, but displays the symbol when run from the Terminal itself . What is this key symbol, and can I find it under the Characters menu?

A: I get the key symbol when running read -s in Terminal.
As this seems to work the same for read -s as for sudo, I assume this is a feature of Terminal (to display a key symbol whenever input is requested in silent/hidden mode).

A: The simplest answer is just write the script without sudo
then tell the user to run it with sudo e.g. sudo script
the script will run with root privileges
`this has the advantage that the user knows what asks for and where the password is used, if in your script you could be taking a copy or leaving it in memory

A: I think it has something to do with whether the terminal echo option is disabled. I tried running stty -echo; cat; stty echo in my terminal and then typing something, and the key symbol showed. I then pressed Ctrl+D and it went away.


text:
Q: Team members power tools 2012 with TFS 2010 I have visual studio 2012 installed with TFS 2010. I installed power tools 2012 recently but I do not see the Team Members tab.
Is there compatibility issue between TFS 2010 and VS 2012?
If yes, any work around to see the Team Members tab in VS 2012 with TFS 2010?
I referred to the below link and it seems there are compatibility issues. Any work around?
User Check-In History in Visual Studio 2012 / 2013

A: I suggest you to use Power tools 2010 by Command Line, or add External Tool (Section Tools) in your Visual Studio.
link : http://blogs.msdn.com/b/buckh/archive/2010/04/23/tfs-2010-power-tools-are-now-available.aspx

A: You can install the 2010 and the 2012 versions of the power tools side-by-side as long as only one version of the Windows Explorer Extensions and the Powershell cmd-lets is installed.
If you want integration into Visual Studio 2012, you must install the 2012 version of the power tools. Some features (like the Create Project option of tfpt) might require you to use the version that matches the TFS version,which is why you'd do a side-by-side installation.
The Team Members tab in the Team Foundation Server Power Tools 2012 and up only work against server 2012 and up, due to changes in the datamodel used to define Teams.


text:
Q: iOS 8 keyboard extension only loading on iPhone 5 and 5s I am currently working on a keyboard extension for iOS 8.  Until recently, I was testing the extension exclusively on the iPhone 5 simulator.  Upon switching the simulator to the iPhone 6(both simulator and physical phone), 6 Plus, and 4s and clicking on a text field, the keyboard doesn't appear at all.  No error is shown either.  Thinking that this was a bug in my program, I tested a new program that just had the default code, and the same thing happened.  I am using the latest OS X, Xcode, and IOS Simulators.

A: There is a known issue with 8.1 that causes keyboards to not display in simulator.

Keyboards Known Issue
Additional Keyboards, including 3rd party keyboards, may not appear in
  Safari, Maps or 3rd party apps on the Simulator.
Workaround: Keyboards should be testable in Calendar, Spotlight,
  Contacts, and Photos.

I interpret this to mean your enclosing app won't work either. My keyboard won't display in Safari or Maps, but works fine in Photos search bar.

A: You have to clean the project EVERYTIME you change something in the code of an application linked to an App Extension on Xcode 6.1 (Acknowledged bug in Xcode 6.1 release notes)


text:
Q: How to distinguish between operating systems in Matlab? I have been performing simulations using MATLAB in Windows. However,now I am working on Ubuntu, so when I run a simulation that loads a file which contains needed data:
auxiliar_nm1 = load('C:\Users\Miguel\Dropbox\Tesina\Simulaciones\Quadrotor Simulation\M Model 1\auxiliar.txt', 'auxiliar_nm1');

I am getting the following error:
Unable to read file 'C:\Users\Miguel\Dropbox\Tesina\Simulaciones\Quadrotor Simulation\M Model 1\auxiliar.txt'. No such file or directory.

I know that I can just modify the path, so this problem will be solved, but I would like to know if it is possible to determine the operating system in MATLAB, and take a decision based on this parameter, so this script is available for both operating systems (Windows and Ubuntu).

A: The function computer gives you what you need:
switch computer
    case 'PCWIN'   % 32-bit Windows
        %...
    case 'PCWIN64' % 64-bit Windows
        %...
    case 'GLNXA64' % Linux
        %...
    case 'MACI64'  % Mac
        %...
end

Alternatively, you can use the specific functions ispc, isunix and ismac, although note that isunix returns true on Mac.

A: os = system_dependent('getos')

returns the full string of the OS, which you can parse in a conditional statement to run the desired load command.
strncmp(os,'Linux',5)

returns 1 if it's Linux (compares the first n characters only, in this case 5).
if(strncmp(os,'Linux',5)
  load('linux dependant path')
else
  load('Windows path')
end

A: What I have done is:
if ispc
    auxiliar_nm1 = load('C:\Users\Miguel\Dropbox\Tesina\Simulaciones\Quadrotor Simulation\M Model 1\auxiliar.txt', 'auxiliar_nm1');
elseif isunix
    auxiliar_nm1 = load('/home/m/Dropbox/Tesina/Simulaciones/Quadrotor Simulation/M Model 1/auxiliar.txt', 'auxiliar_nm1');
end


text:
Q: continuously playing video list like a tv channel i didn't find a easy way to explain this but i need to play videos from my hosting or youtube and make it look like a tv channel in my website .
meaning if two users for example enter at the same time from different places they will watch the same thing
which could for example : the third video in the play list from the minute 30 and if they closed and back after 5 min they will start from minute 35 in the third video
so far i can make a the my html5 playlist and play the videos but i'm stuck in how to programme the timing and from where a user should watch according to the timing hi started watching.
if there are any think that i'm missing or a CMS or  plugging or service or api that will help me realizing this task please feel free to answer me back ,PEACE

A: Ok it's clearer now.  Since you need the playlist on your site to be synced to the time of day you are looking at a combination of solutions to get this working.  Firstly your timer will need to use a single time zone (it doesn't matter where the user is accessing from).  Let's say you used GMT+0 - if two people accessed the site from the US and Europe the site would know it's the same time of day according to that timezone and deliver the same video to each user.  To do this you probably need to use server side scripting, there apparently are solutions in Javascript (see here) but I'd use php's date/time functions and then pass the result to javascript.  Then you need to hopefully use the youtube javascript api to compile or load your playlist and later on be able to access the videos according to time (the html5 playlist YouTube gives you on their site to embed won't be enough on it's own).  Hopefully the videos you want in the playlist are all on your youtube account and/or in their own playlist and so that should be relatively straightforward.  If you are doing anything more complex you will need the youtube php api instead but from what you describe that hopefully shouldn't be necessary.
Now come more questions.  How are you allocating videos according to time?  Are each of the videos a regular length, for example are there exactly 6 videos 10 minutes long each so 60 minutes of video that repeats every hour?  Or have you some other precise formula for how the videos will be shown according to a duration of time?  At the moment I can't give you code examples but I have outlined the combination of things that need to occur in order for this to work so that should give you a starting point.


text:
Q: Strange Queue.PriorityQueue behaviour with multiprocessing in Python 2.7.6 As you know from the title, I'm trying to use PriorityQueue with multiprocessing. More precisely, I wanted to make shared PriorityQueue, wrote some code and it doesn't run as I expected.
Look at the code:
import time
from multiprocessing import Process, Lock
from Queue import PriorityQueue

def worker(queue):
    lock = Lock()
    with lock:
        for i in range(100):
            queue.put(i)

    print "worker", queue.qsize()

pr_queue = PriorityQueue()
worker_process = Process(target = worker, args = (pr_queue,))
worker_process.start()

time.sleep(5)    # nope, race condition, you shall not pass (probably)
print "main", pr_queue.qsize()

Got the following output:
worker 100
main 0

What's happening and how to do what I want the right way?
Thank you.

A: The problem isn't that it's not picklable in this case - if you're using a Unix-like platform, the queue can be passed to the child without pickling. (On Windows, I think you would get a pickling error here, though). The root problem is that you're not using a process-safe queue. The only queues that can be used between processes are the Queue objects that live inside the multiprocessing module. Unfortunately, there is no PriorityQueue implementation available. However, you can easily create one by registering a PriorityQueue with a multiprocessing.Manager class, like this:
import time
from multiprocessing import Process
from multiprocessing.managers import SyncManager
from Queue import PriorityQueue

class MyManager(SyncManager):
    pass
MyManager.register("PriorityQueue", PriorityQueue)  # Register a shared PriorityQueue

def Manager():
    m = MyManager()
    m.start()
    return m

def worker(queue):
    print(queue)
    for i in range(100):
        queue.put(i)
    print "worker", queue.qsize()

m = Manager()
pr_queue = m.PriorityQueue()  # This is process-safe
worker_process = Process(target = worker, args = (pr_queue,))
worker_process.start()

time.sleep(5)    # nope, race condition, you shall not pass (probably)
print "main", pr_queue.qsize()

Output:
worker 100
main 100

Note that this probably won't perform quite as well as it would if it was standard multiprocessing.Queue subclass. The Manager-based PriorityQueue is implemented by creating a Manager server process which actually contains a regular PriorityQueue, and then providing your main and worker processes with Proxy objects that use IPC to read/write to the queue in the server process. Regular multiprocessing.Queues just write/read data to/from a Pipe. If that's a concern, you could try implementing your own multiprocessing.PriorityQueue by subclassing or delegating from multiprocessing.Queue. It may not be worth the effort, though.


text:
Q: nvidia-smi command not found Ubuntu 16.04 I am trying to install nvidia drivers on my ubuntu 16.04 (I have a GeForce GTX 960M). I tried a lot of methods explained on internet but none seems to work. (I saw How to install nvidia-smi?, nvidia-smi: command not found on Ubuntu 16, but these did not help...)
Indeed when I run nvidia-smi, I get nvidia-smi command not found, and when I run lshw -numeric -C display I see that my graphical card is has status display unclaimed. I don't know if it is related but it seems weird

A: Try updating the driver.

*

*Add the PPA by running the following commands in terminal:
sudo add-apt-repository ppa:graphics-drivers/ppa
sudo apt-get update

*Open Software & Updates from System Settings or directly from Dash, click on the Additional Drivers tab, select the driver you want to use, and click Apply changes.

*After the driver is downloaded and installed, restart your system.

A: The solution that worked for me was to disable secure boot when rebooting after installing the NVIDIA drivers.
sudo apt purge nvidia-*
sudo add-apt-repository ppa:graphics-drivers/ppa
sudo apt update
sudo apt install nvidia-381

Then reboot, in the menu choose "change secure boot options", put the password you previously chose and disable the secure boot.

A: In my case, just disabling secure boot in the BIOS solved the problem.

A: The driver's version depends on your GPU. Check it here, before installing any driver: https://www.nvidia.com/Download/index.aspx?lang=en-us

A: I've had this condition, this happens if you somehow boot the all-working system w/o an NVidia card and then NVidia drivers and utils disappear.
This is what helped:
(considering your CUDA version is 9.2 and driver version is 418)
sudo vi /etc/ld.so.conf.d/cuda-9-2.conf

/usr/local/cuda-9.0/targets/x86_64-linux/lib
/usr/lib/nvidia-418   ( <<- add this line)

Then do:
sudo dpkg-reconfigure nvidia-418

Then reboot. It should work.
So, in case, it still does not, just reinstall Cuda completely, that will do it.

A: You should use nvidia-current when you run install, so you can get the latest release.

A: This worked for me:
sudo apt purge nvidia-*
sudo add-apt-repository ppa:graphics-drivers/ppa
sudo apt update
sudo apt install nvidia-driver-396

Some use aptitude instead of apt:
sudo apt purge nvidia-*
sudo add-apt-repository ppa:graphics-drivers/ppa
sudo apt-get update
sudo apt-get install aptitude
sudo aptitude install nvidia-driver-396

If nothing works, please check your ubuntu (if that's your case) kernel as several guides state that some kernels are not supported by Nvidia. Ukuu is a simple tool to install different kernels and add them to GRUB. I changed mine (in ubuntu-18.04 LTS) to 4.18.4-041804-generic and find it pretty good and stable.
If this code doesn't work follow this tutorial until step 8. Though the main objective is the complete installation with also CUDA, cuDNN, NCCL, tensorflow, etc I found it good to install Nvidia drivers also (learnt the kernel issue from it, in the comments)

A: Only thing that worked for me was I had to uninstall everything related to nvidia and bumblebee, and upgrade my kernel from 4.4 to 4.8.17 with the help of the Ukuu package, and install 390 version of the drivers.

A: I had faced the same issue. All the answers will correctly let you solve the problem.
Problem:
But the main issue is with driver version. You would have enabled latest version like 430 or such. But idk why but later versions cause this error. Even if you disable secure boot, it'll say "Ubuntu is working on low graphics"
Solution:
Install the version lower than 400 say 381, or whatever your case be. Just search in additional drivers under Ubuntu software settings.

A: If none of these won't work, you might have secure boot activated, for example if you dual boot. Either turn it off, but if you cannot like me, this post made me able to get drivers working WITH secure boot: How to install nvidia driver with secure boot enabled?

A:

*Disable secure boot.

*Purge all existing Nvidia drivers. Take Trying to Install Nvidia packages, unable to correct problems you have held broken packages as a reference.

*Check which drivers are suggested with

ubuntu-drivers devices

and then install them:

sudo ubuntu-drivers autoinstall

See How do I know which NVIDIA driver I need? or https://linuxconfig.org/how-to-install-the-nvidia-drivers-on-ubuntu-20-04-focal-fossa-linux for more info.
3.(Optional) Install Cuda. Follow https://docs.nvidia.com/cuda/cuda-installation-guide-linux/index.html#ubuntu-installation. Make sure to install cuda version compatible with your drivers.

*Install the cuda toolkit:

sudo apt install nvidia-cuda-toolkit

See NVIDIA-SMI has failed because it couldn't communicate with the NVIDIA driver. Make sure that the latest NVIDIA driver is installed and running
and reboot with "sudo reboot".
5.

sudo prime-select nvidia

and reboot with "sudo reboot".
6.

nvidia-smi

*Profit

A: I will give a bit more troubleshooting instructions.
First, ensure you have "Secure boot" in your BIOS->Security menu set to Disabled.
Then, from the accepted answer:
sudo apt purge "*nvidia*"
sudo add-apt-repository ppa:graphics-drivers/ppa
sudo apt-get update -y
sudo apt-get install aptitude
sudo aptitude install -y nvidia-driver-XXX

where XXX stands for the driver version you can find on this webpage: https://www.nvidia.com/Download/index.aspx?lang=en-us.
At this moment, you could try the following:
sudo modprobe nvidia

If this command produces no output, you can reboot first or straightaway check your installation with the following:
nvidia-smi

If the modprobe command fails, welcome to the jungle.
If it is something like:
modprobe: ERROR: could not insert 'nvidia': Key was rejected by service

The issue is "Secure boot" is set to Enabled. Otherwise, copy your problem in Google and browse official Nvidia forums for support.
Keep in mind:

*

*installing a driver from the official Nvidia download webpage is not recommended. Your distribution should know which driver version it should use by default.


text:
Q: Вернуть false в случае возникновения исключения при соединении с БД Мое REST-приложение должно отправлять статус соединения с БД по запросу. В синглтоне, хранящем соединений, я сделал возможность реконнекта при обрыве соединения:
package zunami.repository;

import com.rethinkdb.RethinkDB;
import com.rethinkdb.net.Connection;

public class DBConnector {

    private static DBConnector instance;
    private Connection connection;

    private DBConnector() {
        connection = RethinkDB.r.connection().connect();
    }

    public Connection getConnection() {
        return connection;
    }

    public static DBConnector getInstance() {
        if (instance == null) {
            instance = new DBConnector();
        }
        else if (!instance.getConnection().isOpen()) {
            instance = new DBConnector();
        }

        return instance;
    }
}

Этот класс будет использоваться в репозиториях.
Контроллер для обработки запроса статуса приложения написан так:
@RestController
@RequestMapping("/api")
public class HealthController {

    @Autowired
    private Connection conn;

    @GetMapping("/health")
    public HealthResponse health() {
        conn = DBConnector.getInstance().getConnection();
        return HealthResponse.of(conn.isOpen());
    }

    private static class HealthResponse {

        private boolean ok;
        private boolean rethinkDB;
        private String version;

        public static HealthResponse of (boolean connectionStatus) {
            return new HealthResponse(connectionStatus);
        }

        private HealthResponse(boolean status) {
            this.ok = status;
            this.rethinkDB = status;
            this.version = "1.2.7";
        }

        public boolean isOk() {
            return ok;
        }

        public void setOk(boolean ok) {
            this.ok = ok;
        }

        public boolean isRethinkDB() {
            return rethinkDB;
        }

        public void setRethinkDB(boolean rethinkDB) {
            this.rethinkDB = rethinkDB;
        }

        public String getVersion() {
            return version;
        }

        public void setVersion(String version) {
            this.version = version;
        }
    }
}

Проблема состоит в том, что если я запрашиваю статус приложения в тот момент, когда БД упала, возвращается не статус соединения false, а текст исключения java.net.ConnectException. Если БД не лежит и соединение установилось корректно, то возвращается true, как задумано.
Как я могу использовать свой синглтон так, чтобы контроллер отправлял не текст исключения, а результат вызова метода Connection.isOpen?
Завернуть вызов синглтона в try-catch не получается.


text:
Q: Electron Field Emission through Dielectrics While reading about some new (now older technology), it said that vacuum tubes could run on electron field emission rather than photoionization. https://spectrum.ieee.org/semiconductors/devices/introducing-the-vacuum-transistor-a-device-made-of-nothing
It is some interesting stuff. In reading wikipedia (I know it's credibility, thus why I'm here), it says, "However, field emission can take place from solid or liquid surfaces, into vacuum, air, a fluid, or any non-conducting or weakly conducting dielectric." https://en.wikipedia.org/wiki/Field_electron_emission
So the question I have is, what would the effects be if the two electrodes were separated by a dielectric rather than a vacuum. It seems like one of the issues that NASA is having is that they are trying to reduce the probability of an electron intersecting with an atom, but if a dielectric was in the middle couldn't one compensate for that? Would electron field emission would still work? If anything you would have a constant rather than relying on a random probability and chance. In other words, the electron is jumping that gap, would there be different side effects if that gap is filled with nothing compared to a dielectric?
Edit:
@Vadim I think you figured out what I'm asking. Are field emission with tunneling via dielectrics and field emission with a vacuum able to be interchanged or would they act differently. NASA basically is creating a transistor/triode hybrid but one of the largest issues is the vacuum. Could you accomplish the same thing by replacing the vacuum with a dielectric or would it destroy the effect they are trying to achieve?
Edit 2:
First to answer my own question. Field emission with tunneling via dielectrics vs field emission through a vacuum are not exactly the same. When dealing with dielectrics if too high of a voltage is applied and too much tunneling occurs you will have achieved the breakdown voltage. Also, the electrons are still traveling through a medium and that medium may have an effect.
So using the NASA vacuum transistor as an example. Between the anode and cathode there is a vacuum. Currently they will jump through the vacuum from one to the other. (When vacuum tubes operated under high voltages with cold cathodes they often generate ionizing radiation, this may occur on a small scale here also.)
Now let's replace the vacuum with a dielectric. For the example lets use Aluminum Oxide. If too high of a voltage is used the dielectric breakdown voltage will be achieved and the logic gate will become stuck in a closed position. There also may be other effects. Near by components could possibly experience minute paramagnetic effects. Lastly, if enough energy is applied over time, the Aluminum Oxide could potentially undergo a small amount of electrolysis and become aluminum metal which would destroy it's dielectric qualities.
So for those wondering, if someone were experiment with these vacuum transistors (good luck finding equipment), could you replace the vacuum with a dielectric and still have a working component. The answer is possibly, you would need to keep the voltages lower than the breakdown voltage and longevity studies would need to be performed to confirm that the dielectric doesn't become stressed from constantly having electrons tunneled through it.


text:
Q: Can't get CryptosJS files I am trying to use the CryptoJS API in my express project, so I am trying to call the CryptoJS API on the clientside because I will be encrypting the users input
This is how I am calling all the files I need, the issue I am having right now is this:

To me it seems I am not sending the file to the server the right way, and that is where I am confused because I keep doing the app.get and try to get the file from the directory I specified. But it keeps not finding the directory which has confused me because I know that directory exists.
CODE

var express = require('express'),
    app = express(),
    server = require('http').createServer(app),
    io = require('socket.io').listen(server),
    users = {};

server.listen(3000);

app.get('/', function (req, res) {
    res.sendFile(__dirname + '/index.html');
});

app.use("/js", express.static(__dirname + "/js"));

app.use("/style", express.static(__dirname + "/style"));

app.get("/js/bower_components/crypto-js", function (req, res) {
    res.sendFile(__dirname + '/crypto-js.js');

});

io.sockets.on('connection', function (socket) {
    socket.on('new user', function (data, callback) {
        if (data in users) {
            callback(false);
        } else {
            callback(true);
            socket.nickname = data;
            users[socket.nickname] = socket
            updateNames();
        }

    });

    function updateNames() {
        io.sockets.emit('usernames', Object.keys(users));
    }

    socket.on('send message', function (data, callback) {
        var msg = data.trim();
        if (msg.substr(0, 3) === '/w ') {
            msg = msg.substr(3);
            var ind = msg.indexOf(' ');
            if (ind !== -1) {
                var name = msg.substr(0, ind);
                var msg = msg.substr(ind + 1);
                if (name in users) {
                    users[name].emit('whisper', {
                        msg: msg,
                        nick: socket.nickname
                    });
                    console.log('hi');
                } else {
                    callback('Error! Enter a valid user!');
                }
            } else {
                callback("Error! Enter a pm");
            }
        } else {
            io.sockets.emit('new message', {
                msg: msg,
                nick: socket.nickname
            });
        }
    });

    socket.on('disconnect', function (data) {
        if (!socket.nickname) return;
        delete users[socket.nickname];
        updateNames();

    });
});
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Chatty</title>
    <link rel="stylesheet" href="style/style.css">

        <form id="setNick">

Enter A Username:

            <input size="35" id="nickname">
            <input type="submit">
        </form>

            <form id='send-message'>
                <input size="35" id="message">
                <input type="submit">
            </form>

New Error

Directory Structure

A: You need to include the below line in your code to make your application to refer your JS folder/
So, you need to replace your current,
app.use("/js", express.static(__dirname + "/js"));

as,
app.use(express.static(path.join(__dirname, "js")));

Hope this helps!


text:
Q: Intuition behind power-law scale invariance I have seen this notion of a scale-invariant power law curve exhibiting the property that $f(cx) = a(cx)^{-k} = c^{-k}f(x)$, and I am confused about how I should be thinking of this as "scale-invariant"
When I see this term, scale-invariant, I think "one can zoom in or out and the picture looks exactly the same". If I were to plot a power law, $f(x) = ax^{k}$, wouldn't the only way I could get something that looks the same no matter how much I zoom in be when $k=1$? If I were to plot a parabola in the desmos graphing calculator for instance, and I were to zoom out continuously, eventually the plot just looks like a straight line along the y axis. In what sense is this scale invariant?
I know I definitely have the wrong idea about this somewhere, I just need to figure out where I am going wrong.

A: I'm not an expert, but I would say that the function $f(x) = a x^k$ is scale invariant in the following sense:
Consider some interval $(x, b x)$. In this interval, the function $f(x)$ goes from:
\begin{aligned}
f(x) \quad  &\text{    at }x,\\
f(bx) = b^{k}f(x) \quad  &\text{    at }bx.
\end{aligned}
Now, imagine that you scale the interval by some value $\lambda$. In other words, let's look at the interval $(\lambda x, \lambda b x)$. If we do the same analysis as before, we can see that the function $f(x)$ over the interval goes from
\begin{aligned}
f(\lambda x) = \lambda^{k} f(x) \quad  &\text{    at }\lambda x,\\
f(\lambda bx) = \lambda^{k}b^{k}f(x) \quad  &\text{    at }\lambda bx.
\end{aligned}
So you should be able to see that over the "scaled" interval, the function $f(x)$ behaves exactly like it does over the "unscaled" interval, except for a global multiplicative factor.
What this means is that if you look at a function like $f(x)$ over a range of (appropriately scaled) intervals, it will look identical, modulo the above-mentioned factor. If you'd like to see this more clearly, I've plotted the parabola that you mention below on Mathematica, over the range $(\lambda , \,2\lambda)$, while varying $\lambda$ from 1 to 100. You should be able to see that the form of the function remains the same (the "jiggling" you see is because the successive images are not aligned well):
Manipulate[Plot[x^2, {x, \[Lambda], 2 \[Lambda]}, PlotRange -> {{\[Lambda], 2 \[Lambda] }, {\[Lambda]^2, 4 \[Lambda]^2}}, PlotStyle -> {Black}], {\[Lambda], 1, 100}]

On the other hand, if you did the same thing with a function that isn't scale invariant like the exponential (as @GiorgioP suggested in a comment below), you'd see something very different for the same parameter range:


text:
Q: Why am I unable to play this mp3 using jquery and the jquery ui library? For some reason I'm unable to get the mp3 I want to be played to play with this code. Here's the fiddle:
 http://jsfiddle.net/haGYL/
Here's the code:

A: Observe the following part of your code.
function playAudio(fileName, myVolume) {

  // here you are checking if player can mp3 or ogg file
  var mediaExt = (myMedia.canPlayType('audio/mp3')) ? '.mp3'
    : (myMedia.canPlayType('audio/ogg')) ? '.ogg'
    : '';
  if (mediaExt) {

    //here you are adding the extention that the player can play with the passed file url. So if url is www.xxx.com/myAudioFile and mediaExt is .mp3, here it will become www.xxx.com/myAudioFile.mp3
    myMedia.src = fileName + mediaExt;
    myMedia.setAttribute('loop', 'loop');
    setVolume(myVolume);
    myMedia.play();
  }
}

And you are calling the above function as
playAudio('http://www.catholic.com/sites/default/files/audio/radioshows/ca140331b.mp3', 0);

Notice you are providing the extension also.
So while execution the playAudio method the effective file url is becoming like following
http://www.catholic.com/sites/default/files/audio/radioshows/ca140331b.mp3.mp3
OR
http://www.catholic.com/sites/default/files/audio/radioshows/ca140331b.mp3.ogg

So to run your code you just need to call the playAudio function as following
playAudio('http://www.catholic.com/sites/default/files/audio/radioshows/ca140331b', 0);

Notice I'm not passing the extension.
See the JSFiddle below.
Demo

A: here is your code working jsfiddle
 $(document).ready(function() {
  var myMedia = document.createElement('audio');
  $('#player').append(myMedia);
  myMedia.id = "myMedia";
  playAudio('http://www.catholic.com/sites/default/files/audio/radioshows/ca140331b', 0);
 });


text:
Q: Fastest way to insert and read 50,000+ records into Azure CosmosDB with Node as the title suggests I need to insert 50,000+ records into Azure CosmosDb running SQL mode and read them later on again programatically with Node. C# has the BulkExecutor, but what's the best and fastest way in Node?

A: In the short term, you could implement some of the same logic in the Bulk Executor library in Node.js. Biggest things are having to understand our underlying physical partitioning layer, which isn't easy.
In the mid-to-long term, we'll be adding bulk operation support to Node.js/Python. For now, you might save yourself some time making due with Java/.NET library until then.


text:
Q: Correct way to 'dd' an entire APFS disk The question has been answered but it's unclear.
Why can't I just dd an entire APFS disk?
The original question posts the dd command that was used to perform a byte-for-byte copy of a block device.  As pointed out, that command resulted in a incorrect clone.  The accepted answer explains why it failed but doesn't provide the correct dd command.
If I understand the explanation correctly, I should use the following dd command:
dd if=/dev/rdisk0 of=/dev/rdiskX bs=4096 obs=512

Or should I first re-initialize the target block device with a GPT partition scheme, create an APFS partition, and then perform a dd?
The goal is to take /dev/rdisk0 (source block device) and perform a byte-for-byte copy to a brand new external SSD (target block device).
Related Questions:

*

*I haven't been able to find a clear answer as to whether or not using dd is possible if the source block device has encrypted APFS partitions.

*Should I be using rdiskX or just diskX?

A: Neither is actually correct.
The problem has nothing at all to do with APFS. As the linked answer describes, it has to do with the location of the partitioning tables.
If your source and destination drives have the same sector sizes, you can just copy using ordinary dd without any special parameters.
If they do not have the same sector size (as in the linked example with an old traditional hard drive and a newer flash-based drive), the partitioning table needs to moved.
Essentially the computer will try to read the GPT partitioning table at the location of the second sector. For some drives that will be at byte 512 on the drive, for others it will be at byte 4096 on the drive.
The dd command you suggest with two different block sizes won't here. It means that dd will read in data in blocks of 4096 bytes, and write them out in blocks of 512 bytes - thus performing 4 writes for each read. However that still places all the data as the exact same byte indices on the target drive as they had on the source drive.
For your purpose you need to move the data that was previously at index 4096 to be at index 512.
Regarding your other questions:
Yes, encrypted partitions can be cloned with dd.
For this type of work you want to use rdisk instead of disk. The r means "raw" meaning that you're bypassing the disk cache. You'll end up with the same result, but it will go quicker that way.


text:
Q: How to see which objects is retaining another specific object I have an NSOutlineView which should dealloc when removed from screen but since that is not happening I suspect another object is holding a reference to it.
Is it possible to see how many references and which objects that have a reference to an object/view in Xcode or the Profiler?
Edit: Although I did find another solution I still would like to know if there is anyway to see a list of objects holding (retaining) a certain object/view

A: You're never going to be able to get a list of 'objects retaining a certain object' because the refcount is merely a count - there is no FIFO or LIFO or any sort of direct matching between a retain and a release - it's just a count.
What you can do is use Instruments to display a list of all objects responsible for retain call and release call on your object.  Use the Allocations tool, make sure "Record Reference Counts" is checked.  Then you can use the Statistics view to see all living objects in your running app.  Click the little right-arrow to the right of any object to see a table of retain/release calls for that object.  This is where you can see the refcount going up and down and hopefully find the object that is 'mysteriously' retaining and/or not releasing.
Some common over-retention problems are:  a. delegates needs to be weak properties, b. need to unregister any observers in the view controller or window controller, c. a view is retained when inserted into a view hierarchy.


text:
Q: Generalization of model performance (AUC) and tuning of a catboost classifier I was wondering if it is good practice to overfit on the training data while tuning a catboost classifier for a binary outcome.
Wouldn't it be better to reguralize until validation error equals training error, espescially if the test set has a different distribution of the predictors?
In general how should I compare the train/val/test AUC scores when training (and tuning) a catboost model for binary classification? Is there a tuning strategy that will ensure the best generalization error (other than having i.i.d. splits)?

A: I would suggest to avoid over-fitting your training data and focus on your (cross-) validation error. Our training error is not entirely useless but it is very prone to mislead us (i.e. if two classifiers have qualitative similar validation errors, pick the classifier with the lower training error but don't put too much faith on that choice between those two). Ultimately we want our classifier to perform well to new unseen data so training set performance by itself is not a strong indicator.
You mention that the test-set in question "has a different distribution of the predictors", this is potentially problematic because it suggests the occurrence of covariate shift, the input variables distribution changes. That is almost always detrimental to our learner performance and if anything it suggest we should focus even more in a robust validation procedure (e.g. repeated K-fold) instead of trying to lower our training error by over-fitting the training set. A good first reference on the subject is: A unifying view on dataset shift in classification (2012) by Moreno-Torres et al. if you want to probe this a bit further.
Regarding overall strategy: Unless there is a situation where there is an abundance of data, I would strongly suggest using cross-validation instead of a single validation set, so you can estimate the variability in the validation performance as well as have a more realistic view of the expected performance. To that regard, even if "a lot of data" is available, I would say, try a 2-fold CV just to ensure that on both partitions provide qualitative similar performance. Finally do note that random partitioning might not be the best practice and maybe stratifying the cross-validation procedure (e.g. by geographical regions, testing site, etc.) allows a more realistic scenario to evaluate generalisation performance.


text:
Q: csh to get difference been start and end time both inputs in hh:mm:ss format ./script.csh 05:25:00 02:30:50
should return output in mins
since i am looping through the series recursively how to compare values with new large value . would | bc work in csh ?

A: For full difference:
perl -e 'for(@ARGV){s/(..):(..):(..)/$1*3600+$2*60+$3/e} $_=(shift)-(shift); printf"%02d:%02d:%02d\n",$_/3600,$_/60%60,$_%60' 05:25:00 02:30:50

For difference in minutes:
perl -e 'for(@ARGV){s/(..):(..):(..)/$1*3600+$2*60+$3/e} $_=(shift)-(shift); printf"%d\n",$_/60' 05:25:00 02:30:50

Works in bash, too.

A: It's not clear whether you want the two dates to wrap through days, or you're assuming that they're both in the same day and may be in any order.
This answer assumes the first, i.e. timediff 23:00:00 01:00:00 should return 2 hours = 120 minutes.
Change @ s = 86400 + $s to @ s = - $s if that should return 22 hours = 79200 minutes.
alias timediff 'set t=(\!:*:gs/:/ * 3600 + /:gs/:/ * 60 + /:q);\\
   @ s = ($t[2]) - ($t[1]); if($s < 0) @ s = 86400 + $s;\\
   @ m = $s / 60;\\
   @ H = $s / 3600 M = $s % 3600 / 60 S = $s % 60;\\
   echo seconds=$s minutes=$m hours=$H\:$M\:$S'

timediff 05:25:00 02:30:50
seconds=75950 minutes=1265 hours=21:5:50

As a script:
set t=($argv:gs/:/ * 3600 + /:gs/:/ * 60 + /:q)
@ s = ($t[2]) - ($t[1]); if($s < 0) @ s = 86400 + $s
@ m = $s / 60
@ H = $s / 3600 M = $s % 3600 / 60 S = $s % 60
echo seconds=$s minutes=$m hours=$H\:$M\:$S


text:
Q: ¿Como mostar campo de otra tabla por medio de llave foránea en laravel? Buenas Estoy haciendo un pequeño proyecto para ir practicando laravel.
En mi proyecto los usuarios pueden hacer recargas por lo cual yo en una vita quiero mostrar el nombre del usuario con toda la información de la recarga , pero no he podido mostrar el nombre.
lo que quiero es mostrar el nombre del usuario el cual esta en otra tabla;
tabla usuarios
public function up()
{
    Schema::create('usuarios', function (Blueprint $table) {
        $table->increments('id');
        $table->string('nombre', 30);
        $table->string('apellidos', 60);
        $table->string('sexo' , 15);
        $table->integer('edad');
        $table->string('correo' , 50)->unique();
        $table->timestamps();
    });
}

tabla recargas
    public function up()
{
    Schema::create('recargas', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('usuario_id')->unsigned();
        $table->decimal('cantidad_recarga' , 8,2);
        $table->dateTime('fecha_recarga');
        $table->timestamps();

        $table->foreign('usuario_id')->references('id')->on('usuarios');
    });
}

Modelo Usuario
class Usuario extends Model
{
   protected $fillable = ['nombre' , 'apellidos' , 'edad' , 'sexo' , 'correo'];

   public function recargas()
  {
    return $this->hasMany('App\Recarga');
  }
}

Modelo Recarga
class Recarga extends Model
{
   public function usuario()
   {
    return $this->belongsTo('App\Usuario');
   }
}

Controlador de Recargas
use Illuminate\Http\Request;
use App\Recarga;

class RecargaController extends Controller
{
/**
 * Display a listing of the resource.
 *
 * @return \Illuminate\Http\Response
 */
public function index()
{
    $recargas = Recarga::all();
    return view('recargas.index' , compact('recargas'));
}

La vista donde quiero mostrar los datos
 Nuevo recarga

    Id
    Nombre
    Cantida Recarga
    Fecha Recarga
    Acciones

    @foreach ($recargas as $recarga)

          {{$recarga->id}}
           {{-- Aqui quisiero mostrar el nombre --}}
          {{$recarga->cantidad_recarga}}
          {{$recarga->fecha_recarga}}

            <form action="{{ route('recargas.destroy' , $recarga->id) }}" method="POST">
                  id) }}">  Actualizar

                 {{csrf_field()}}
                 @method('DELETE')
                 <button class="btn btn-danger" type="submit">Eliminar</button>
           </form>

  @endforeach

y por ultimo lo que me muestra el navegador

A: Veo en la otra respuesta que te muestran la ruta complicada usando joins, esto es totalmente innecesario cuando usas un framework como Laravel (o muchos otros) y tienes a Eloquent además.
Ya tienes las relaciones correctamente definidas entre tus modelos, lo que necesitas es replantear un poco la forma de abordar el problema, lo cual es muy sencillo y voy a retomar tus palabras:

quiero mostrar el nombre del usuario con toda la información de la recarga

Teniendo en cuenta que es el usuario quien tiene muchas recargas, es el dueño de estas, por llamarlo así, y tú mismo le estás dando el orden (con tus palabras) en que debe hacerse la consulta.
Es mucho más fácil partir del usuario «dueño» de las recargas, que intentar partir de una recarga cualquiera y deducir si pertenece a nuestro usuario en cuestión o no.
En la vida real es más fácil preguntarle a alguien cuantas casas tiene, que ir preguntando de casa en casa a quien le pertenece esta.
Yendo a la práctica, cargas los datos de las recargas relacionadas con dicho usuario con Eager Loading, pero siempre partiendo del usuario:
public function index()
{
    $usuarios = User::with('recargas')->get();
    return view('recargas.index' , compact('usuarios'));
}

Y en la vista debes iterar primero a través de los usuarios y luego a través de cada recarga:
@foreach ($usuarios as $usuario)

  @foreach ($usuario->recargas as $recarga)

      {{$recarga->id}}
       {{ $usuario->nombre }}
      {{$recarga->cantidad_recarga}}
      {{$recarga->fecha_recarga}}

        <form action="{{ route('recargas.destroy' , $recarga->id) }}" method="POST">
              id) }}">  Actualizar

             {{csrf_field()}}
             @method('DELETE')
             <button class="btn btn-danger" type="submit">Eliminar</button>
       </form>

  @endforeach

@endforeach

A: Para que puedas vincular ambos modelos, tienes varias opciones entre ellas:

*

*uso de los métodos JOIN para declarar tu consulta

*Eager loading

MÉTODO JOIN
Vamos con la primer opción, además de lo anterior identifico una relación de 1:M donde un usuario puede hacer muchas recargas, entonces tu consulta debería quedar así
$data = Usuario::join('recargas', 'users.id', 'recargas.usuario_id')
               ->select('usuarios.nombre', 'recargas.cantidad_recarga',
                        'recargas.fecha_recargas')
               ->get();

De modo que en la vista ahora puedas recorrer lo que te llega de este modo
@foreach($data as $dato)
   {{ $dato->nombre }}
   {{ $dato->fecha_recarga }}
   {{ $dato->cantidad_recarga }}
@endforeach

Como puedes ver en el método select() indico cuales columnas quiero recuperar y las nombro para después recuperarlas en la vista

El punto en como lo estabas haciendo, es que estaba mal, por que al
  hacer ModeloNombre::all(); solo te estas preocupando por recuperar
  los datos de la tabla que esta asociada con ese modo, es decir cuando
  pusiste Recarga::all(); solo estas recuperando las columnas de la
  tabla recargas pero no sus valores asociados con usuarios

USO DE EAGER LOADING
Viendo que tienes tus relaciones declaradas, puede ser del modo siguiente
$data = Usuario::with('recargas')->get();

Una vez hecho lo anterior, en tu vista deberás recorrer los valores que te lleguen de este modo
@foreach($data as $d)
   {{ $d->nombre }}
   @foreach($d->recargas as $recarga)
      {{ $recarga->fecha_recarga }}
      {{ $recarga->cantidad_recarga }}
   @endforeach
@endforeach

Cuando hago uso de $d->recargas estoy accediendo al nombre del
  método que tu declaraste en el modelo Usuario llamado así recargas

De modo que obtendrás a cada usuario y todas sus recargas asociadas


text:
Q: Run file not updating changes in GUI using Swing I'm doing a login screen with Swing. I edited the enable property of the only button that exists in the screen - the "Entrar", as shown in the picture below:
Login screen
But, when I hit Shift-F6 (Run file) it doesn't shows the change:
Login Screen after running single file
Here's the code:
package view;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
/**
 *
 * @author User
 */
public class Inicio extends javax.swing.JFrame {

    String usuario;
    String senha;

    int a;

    public Inicio() {

        initComponents();

        DocumentListener dUsuario = new DocumentListener(){
            @Override
            public void insertUpdate(DocumentEvent e) {
                try {
                    usuario = e.getDocument().getText(0, 0);
                    a = 1;
                } catch (BadLocationException ex) {
                    Logger.getLogger(Inicio.class.getName()).log(Level.SEVERE, null, ex);
                }
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
            }

            @Override
             public void changedUpdate(DocumentEvent e) {
                try {
                    usuario = e.getDocument().getText(0, 0);
                    a = 1;
                } catch (BadLocationException ex) {
                    Logger.getLogger(Inicio.class.getName()).log(Level.SEVERE, null, ex);
                }
            }

        };

        DocumentListener dSenha = new DocumentListener(){
            @Override
            public void insertUpdate(DocumentEvent e) {
                try {
                    senha = e.getDocument().getText(0, 0);
                    a = 2;
                } catch (BadLocationException ex) {
                    Logger.getLogger(Inicio.class.getName()).log(Level.SEVERE, null, ex);
                }
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
            }

            @Override
            public void changedUpdate(DocumentEvent e) {
                try {
                    senha = e.getDocument().getText(0, 0);
                    a = 2;
                } catch (BadLocationException ex) {
                    Logger.getLogger(Inicio.class.getName()).log(Level.SEVERE, null, ex);
                }
            }

        };

        tUsuario.getDocument().addDocumentListener(dUsuario);
        tSenha.getDocument().addDocumentListener(dSenha);

        if(a == 2) {
            if (bEntrar.isEnabled() == false) {
                bEntrar.setEnabled(true);
            }

        }else{
            if (bEntrar.isEnabled() == true) {
                bEntrar.setEnabled(false);
            }

        }

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        tSenha = new javax.swing.JPasswordField();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        tUsuario = new javax.swing.JFormattedTextField();
        bEntrar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setResizable(false);

        jLabel1.setForeground(new java.awt.Color(153, 153, 153));
        jLabel1.setText("Informe apenas os dígitos do CPF.");

        jLabel2.setText("Senha:");

        jLabel3.setText("CPF:");

        jLabel4.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        jLabel4.setText("LOGIN");

        try {
            tUsuario.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("###.###.###-##")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }

        bEntrar.setText("Entrar");
        bEntrar.setEnabled(false);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(184, 184, 184)
                .addComponent(jLabel4)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(0, 91, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING))
                .addGap(7, 7, 7)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addComponent(tSenha, javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(bEntrar, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 129, Short.MAX_VALUE))
                    .addComponent(tUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(55, 55, 55))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(50, 50, 50)
                .addComponent(jLabel4)
                .addGap(37, 37, 37)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(tUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(3, 3, 3)
                .addComponent(jLabel1)
                .addGap(9, 9, 9)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(tSenha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 58, Short.MAX_VALUE)
                .addComponent(bEntrar)
                .addGap(41, 41, 41))
        );

        pack();
    }// </editor-fold>

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Inicio.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Inicio.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Inicio.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Inicio.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Inicio().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JButton bEntrar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPasswordField tSenha;
    private javax.swing.JFormattedTextField tUsuario;
    // End of variables declaration

}

I edited the button properties using the Project view from Swing. So, what can I do to fix that? Is it a Netbeans bug? I'm using Netbeans IDE 8.2, by the way.

A: If you want to effect the state of the button based on changes which have occurred on the text fields, then those actions need to take place in the action handlers themselves (ie, the DocumentListeners)
The following is a very basic example, which disables the "action" button until both the user name and password fields are no longer empty
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private JTextField userNameField;
        private JPasswordField passwordField;
        private JButton actionButton;

        public TestPane() {
            userNameField = new JTextField(15);
            passwordField = new JPasswordField(15);
            actionButton = new JButton("Do stuff");

            actionButton.setEnabled(false);

            DocumentListener documentListener = new DocumentListener() {

                protected void stateDidChange() {
                    actionButton.setEnabled(userNameField.getText().length() > 0 && passwordField.getPassword().length > 0);
                }

                @Override
                public void insertUpdate(DocumentEvent e) {
                    stateDidChange();
                }

                @Override
                public void removeUpdate(DocumentEvent e) {
                    stateDidChange();
                }

                @Override
                public void changedUpdate(DocumentEvent e) {
                    stateDidChange();
                }
            };

            userNameField.getDocument().addDocumentListener(documentListener);
            passwordField.getDocument().addDocumentListener(documentListener);

            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridwidth = gbc.REMAINDER;

            add(userNameField, gbc);
            add(passwordField, gbc);
            add(actionButton, gbc);
        }

    }

}

Why is the initial state not been updated?

You define a as....
int a;

which gives it a initial (or default) value of 0.
You then use...
if(a == 2) {
    if (bEntrar.isEnabled() == false) {
        bEntrar.setEnabled(true);
    }
}else{
    if (bEntrar.isEnabled() == true) {
        bEntrar.setEnabled(false);
    }
}

to change the initial state.  Since a is 0, the else block is executed, the only condition which would change the button enabled state to false would be if the current enabled state is true

But when I use Shift+F6 to run the code it doesn't work

Do a "clean and build" and run the project, not the file.  In testing your code, the UI appears with the button already disabled