text:
Q: Erro ao iniciar Apache Tomcat 9 Pergunta: Erro ao iniciar Apache Tomcat 9
GRAVE: A child container failed during start
    java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to initialize component [org.apache.catalina.webresources.JarResourceSet@299f9a81]
        at java.util.concurrent.FutureTask.report(FutureTask.java:122)
        at java.util.concurrent.FutureTask.get(FutureTask.java:192)
        at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:949)
        at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:839)
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
        at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1427)
        at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1417)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
        at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:134)
        at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:943)
        at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:258)
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
        at org.apache.catalina.core.StandardService.startInternal(StandardService.java:422)
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
        at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:770)
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
        at org.apache.catalina.startup.Catalina.start(Catalina.java:682)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:350)
        at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:492)

Caused by: org.apache.catalina.LifecycleException: Failed to initialize component [org.apache.catalina.webresources.JarResourceSet@299f9a81]
    at org.apache.catalina.util.LifecycleBase.handleSubClassException(LifecycleBase.java:441)
    at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:139)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:173)
    at org.apache.catalina.webresources.StandardRoot.startInternal(StandardRoot.java:724)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.StandardContext.resourcesStart(StandardContext.java:4758)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:4893)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1427)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1417)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
    at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:134)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:943)
    ... 21 more

Caused by: java.lang.IllegalArgumentException: java.util.zip.ZipException: invalid LOC header (bad signature)
    at org.apache.catalina.webresources.AbstractSingleArchiveResourceSet.initInternal(AbstractSingleArchiveResourceSet.java:143)
    at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:136)
    ... 33 more

Caused by: java.util.zip.ZipException: invalid LOC header (bad signature)
    at java.util.zip.ZipFile.read(Native Method)
    at java.util.zip.ZipFile.access$1400(ZipFile.java:60)
    at java.util.zip.ZipFile$ZipFileInputStream.read(ZipFile.java:734)
    at java.util.zip.ZipFile$ZipFileInflaterInputStream.fill(ZipFile.java:434)
    at java.util.zip.InflaterInputStream.read(InflaterInputStream.java:158)
    at sun.misc.IOUtils.readFully(IOUtils.java:65)
    at java.util.jar.JarFile.getBytes(JarFile.java:425)
    at java.util.jar.JarFile.getManifestFromReference(JarFile.java:193)
    at java.util.jar.JarFile.getManifest(JarFile.java:180)
    at org.apache.catalina.webresources.AbstractSingleArchiveResourceSet.initInternal(AbstractSingleArchiveResourceSet.java:141)
    ... 34 more

jul 22, 2018 9:07:27 AM org.apache.catalina.core.ContainerBase startInternal

GRAVE: A child container failed during start
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: A child container failed during start
    at java.util.concurrent.FutureTask.report(FutureTask.java:122)
    at java.util.concurrent.FutureTask.get(FutureTask.java:192)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:949)
    at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:258)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.StandardService.startInternal(StandardService.java:422)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:770)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:682)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:350)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:492)

Caused by: org.apache.catalina.LifecycleException: A child container failed during start
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:958)
    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:839)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1427)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1417)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
    at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:134)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:943)
    ... 13 more

jul 22, 2018 9:07:27 AM org.apache.catalina.startup.Catalina start

GRAVE: The required Server component failed to start so Tomcat is unable to start.
org.apache.catalina.LifecycleException: A child container failed during start
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:958)
    at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:258)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.StandardService.startInternal(StandardService.java:422)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:770)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:682)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:350)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:492)

A: Pesquisei o erro invalid LOC header (bad signature) no Stack Overflow e achei essa pergunta
O problema é ocasionado por um jar corrompido, você pode resolver removendo o jar em questão, as respostas sugerem remover todo o conteúdo da pasta ~/.m2/repository
Você pode utilizar o comando find  ~/.m2/repository/ -name "*jar" | xargs -L 1 zip -T | grep error | grep invalid sugerido nessa resposta para localizar apenas os arquivos que estão corrompidos para depois poder apagá-los.

A: Olá!
Vou registrar uma possivel (e mto simples) soluçao no windows, que deu certo p/ mim apos 3 meses testando de tudo (variaveis de ambiente, configurações na pasta bin...)
Instalei o JRE (64 bits).
Assim, o serviço rodou normal (pelo services.msc)


text:
Q: WPF bind TextBlock "text" in one user control to textbox in another UserControl Where both of them are hosted in a Frame inside mainWindow SUMMARY OF THE PROBLEM:
I have main window which has a frame and a button, in the frame i'm going to show one user control at a time (i provided an image of my usercontrol).
in the first UserControl, i will write 4 player names (two for each team).
after i press the button and i go to next usercontrol i want to show the names of the players in textblock. I also want to bind IsChecked property of radio button in first UserControl to the second UserControl. (i have other buttons that show up in mainWindow depends on what usercontrol is in the Frame right Now)
WHAT I TRIED:
I tried binding the textbox property to the textblock in the second usercontrol but it doesnt show or i cant access it.
because i have the button in the mainWindow i tried saving the names in variable then pass it to next usercontrol but didnt work also.
Also tried alot of random online solution i found online but nothing worked.
i need a way to expose the property of First UserControl to be used in the Second UserControl
MY CODE
MainWindow xaml
<Grid SnapsToDevicePixels="True" x:Name="myGrid" >
        <Grid.Background>
            <ImageBrush x:Name="myBackground" ImageSource="background1.png" Stretch="UniformToFill"/>

        </Grid.Background>

        <Grid.ColumnDefinitions>

        <ColumnDefinition Width="300" />
        <ColumnDefinition Width="*" />
        <ColumnDefinition Width="auto" />
        <ColumnDefinition Width="*" />
        <ColumnDefinition Width="300" />
        </Grid.ColumnDefinitions>

        <Grid.RowDefinitions>

            <RowDefinition Height="100" />
            <RowDefinition Height="*" />
            <RowDefinition Height=" auto" />
            <RowDefinition Height=" 20" />

        </Grid.RowDefinitions>

    <Frame  x:Name="Main" Grid.Row="0" Grid.RowSpan="2" Grid.Column="0" Grid.ColumnSpan="5" NavigationUIVisibility="Hidden" >

    </Frame>

    <Button Style="{StaticResource StandardButton}" Visibility="Visible" x:Name="playersBtn" Grid.Column="2" Grid.Row ="2"  Margin="100,40,100,40" FontSize="36"  Content="إبدأ" FontFamily="Ara Hamah Homs" Padding="50,0" Background="#FFFFE900" Click="playerInfoBtn" BorderBrush="{x:Null}" Foreground="Black"   >

    </Button>

MainWindow c#
namespace Try3
{

public partial class MainWindow : Window
{
    SoundPlayer MP = new SoundPlayer();

    public MainWindow()
    {
        InitializeComponent();
        MP.SoundLocation = "C:/Users/eadh2/Desktop/game tries/try3/try3/sound1.wav";
        MP.PlayLooping();

    }

    private void playerInfoBtn(object sender, RoutedEventArgs e)
    {
        Main.Content = new PlayersInfoPage();
        playersBtn.Visibility = Visibility.Hidden;
        startBtn.Visibility = Visibility.Visible;
        icon.Visibility = Visibility.Collapsed;
        ImageBrush b = new ImageBrush();
        b.ImageSource = new BitmapImage(new Uri("pack://application:,,,/background flat.png"));
        myGrid.Background = b;

    }

    private void startBtn_Click(object sender, RoutedEventArgs e)
    {
        Main.Content = new gamePage();
        startBtn.Visibility = Visibility.Collapsed;
        gamePageBoarder.Visibility = Visibility.Visible;

    }

    private void startBtn_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
    {
               startBtn.Background = Brushes.DarkGreen;

        }
    }
       }

First usercontrol xaml to enter player names (Image of First UserControl to enter player names)
<UserControl x:Class="Try3.PlayersInfoPage"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         xmlns:local="clr-namespace:Try3"
         mc:Ignorable="d"
         d:DesignHeight="862.179" d:DesignWidth="1210.632" >

<Grid  SnapsToDevicePixels="True">

    <Grid.ColumnDefinitions >
        <ColumnDefinition Width="150" />
        <ColumnDefinition Width="auto" />
        <ColumnDefinition Width="auto" />
        <ColumnDefinition Width=" *" />
        <ColumnDefinition Width="auto" />
        <ColumnDefinition Width="AUTO" />
        <ColumnDefinition Width="150" />

    </Grid.ColumnDefinitions>

    <Grid.RowDefinitions>

        <RowDefinition Height="100" />
        <RowDefinition Height="auto" />
        <RowDefinition Height="auto" />
        <RowDefinition Height="auto"  />
        <RowDefinition Height="auto"  />
        <RowDefinition Height="auto"  />
        <RowDefinition Height=" *" />
        <RowDefinition Height="30" />

    </Grid.RowDefinitions>

    <TextBlock  Grid.Column="1" Grid.Row="1" Grid.ColumnSpan="2" Text="بيانات الفريق الأحمر" FontSize="36" Margin="50,0,50,0" FontFamily="Ara Hamah Homs"  />
    <TextBox x:Name="redFirst" Grid.Row="2" Grid.Column="1" Grid.ColumnSpan="2" Margin="0,30,0,20" Padding="10" FontSize="36" HorizontalContentAlignment="Center" Text="اللاعب الأول" Foreground="#FF919191" GotMouseCapture="redFirst_GotMouseCapture" FontFamily="Ara Hamah Homs" />
    <TextBox x:Name="redSecond" Grid.Row="3" Grid.Column="1" Grid.ColumnSpan="2" Margin="0,30,0,110" Padding="10" FontSize="36" HorizontalContentAlignment="Center" Text="اللاعب الثاني" Foreground="#FF919191" GotMouseCapture="redSecond_GotMouseCapture1" FontFamily="Ara Hamah Homs" />

    <TextBlock Grid.Column="4" Grid.Row="1" Grid.ColumnSpan="2" Text="بيانات الفريق الأخضر " FontSize="36" Margin="50,0,50,20" FontFamily="Ara Hamah Homs"  />
    <TextBox x:Name="greenFirst" Grid.Row="2" Grid.Column="4" Grid.ColumnSpan="2" Margin="0,30,0,20" Padding="10" FontSize="36" HorizontalContentAlignment="Center" Text="اللاعب الأول"  Foreground="#FF919191" GotMouseCapture="greenFirst_GotMouseCapture2" FontFamily="Ara Hamah Homs" />
    <TextBox x:Name="greenSecond" Grid.Row="3" Grid.Column="4" Grid.ColumnSpan="2" Margin="0,30,0,110" Padding="10" FontSize="36" HorizontalContentAlignment="Center" Text="اللاعب الثاني" Foreground="#FF919191" GotMouseCapture="greenSecond_GotMouseCapture3" FontFamily="Ara Hamah Homs" />

    <Border x:Name="roundsBoarder" Grid.Column="3" Grid.Row="2" Grid.RowSpan="2" BorderThickness ="3" BorderBrush="Black" CornerRadius="0" Margin="20,50,20,130" MaxHeight="170" MaxWidth="350" VerticalAlignment="Center" Background="#99FFFFFF" MouseEnter="Border_MouseEnter" MouseLeave="roundsBoarder_MouseLeave">

        <StackPanel   HorizontalAlignment="Center"  >

        <StackPanel Orientation="Horizontal"   >
        <Viewbox Height="40" Width="40" >
            <RadioButton BorderBrush="#FFFFE900"    VerticalContentAlignment="Center" HorizontalAlignment="Left" GroupName="roundsNumber" FontFamily="Ara Hamah Homs" FontSize="12"/>
            </Viewbox>
            <TextBlock Text="جولة" FontSize="42" Margin="20,0,0,0" FontFamily="Alnaqaaa R" />

        </StackPanel>

        <StackPanel Orientation="Horizontal"   >
            <Viewbox Height="40" Width="40" >
                <RadioButton BorderBrush="#FFFFE900"    VerticalContentAlignment="Center" HorizontalAlignment="Left" GroupName="roundsNumber" FontFamily="Ara Hamah Homs" FontSize="12"/>
            </Viewbox>
            <TextBlock Text="ثلاث جولات" FontSize="42" Margin="20,0,0,0" FontFamily="Alnaqaaa R" />

        </StackPanel>

    </StackPanel>
    </Border>
</Grid>

First UserControl C#
using System;
 using System.Collections.Generic;
 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 Try3
 {
    public partial class PlayersInfoPage : UserControl
{

    public PlayersInfoPage()
    {
        InitializeComponent();
    }

    private void redFirst_GotMouseCapture(object sender, MouseEventArgs e)
    {
        redFirst.Text = "";
        redFirst.Foreground = Brushes.Black;
    }
    private void redSecond_GotMouseCapture1(object sender, MouseEventArgs e)
    {
        redSecond.Text = "";
        redSecond.Foreground = Brushes.Black;

    }

    private void greenFirst_GotMouseCapture2(object sender, MouseEventArgs e)
    {
        greenFirst.Text = "";
        greenFirst.Foreground = Brushes.Black;

    }

    private void greenSecond_GotMouseCapture3(object sender, MouseEventArgs e)
    {
        greenSecond.Text = "";
        greenSecond.Foreground = Brushes.Black;

    }

    private void Save_MouseEnter(object sender, MouseEventArgs e)
    {
    }

    private void Save_MouseLeave(object sender, MouseEventArgs e)
    {
    }

    private void Border_MouseEnter(object sender, MouseEventArgs e)
    {
        roundsBoarder.Background = new SolidColorBrush(Colors.White) { Opacity = 1 };
        roundsBoarder.CornerRadius = new CornerRadius(20);
    }

    private void roundsBoarder_MouseLeave(object sender, MouseEventArgs e)
    {
        roundsBoarder.Background = new SolidColorBrush(Colors.White) { Opacity = 0.6 };
        roundsBoarder.CornerRadius = new CornerRadius(0);

        }
        }
       }

Second UserControl xaml to show player names in each side
<UserControl x:Class="Try3.gamePage"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         xmlns:local="clr-namespace:try3"
         mc:Ignorable="d"
         d:DesignHeight="450" d:DesignWidth="800">
<Grid>
    <Grid.ColumnDefinitions >
        <ColumnDefinition Width="50" />
        <ColumnDefinition Width="60" />
        <ColumnDefinition Width="100" />
        <ColumnDefinition Width="auto" />
        <ColumnDefinition Width="*" />
        <ColumnDefinition Width="auto" />
        <ColumnDefinition Width="100" />
        <ColumnDefinition Width="60" />
        <ColumnDefinition Width="50" />

    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions >

        <RowDefinition Height="50" />
        <RowDefinition Height="*" />
        <RowDefinition Height="auto" />
        <RowDefinition Height="50" />
        <RowDefinition Height="auto" />
        <RowDefinition Height="*" />
        <RowDefinition Height="50" />

    </Grid.RowDefinitions>
    <StackPanel Orientation="Vertical" Grid.Column="1" Grid.ColumnSpan="2" Grid.Row="1"  >

    <TextBlock HorizontalAlignment="Center" FontSize="36" FontFamily="Ara Hamah Homs" Text="الفريق الأحمر" />
    <TextBlock   x:Name="redFirstPlayer" FontSize="24" FontFamily="Ara Hamah Homs" Text="اللاعب الاول" HorizontalAlignment="Center"/>
    <TextBlock   x:Name="redSecondPlayer" FontSize="24" FontFamily="Ara Hamah Homs" Text="اللاعب الثاني" HorizontalAlignment="Center"/>

    </StackPanel>

    <StackPanel Orientation="Vertical" Grid.Column="6" Grid.ColumnSpan="2" Grid.Row="1">

    <TextBlock  FontSize="36" FontFamily="Ara Hamah Homs" Text="الفريق الأخضر" HorizontalAlignment="Center" Margin="0,0,0,20"/>
    <TextBlock  x:Name="greenFirstPlayer" FontSize="24" FontFamily="Ara Hamah Homs" Text="اللاعب الاول" HorizontalAlignment="Center"/>
    <TextBlock  x:Name="greenSecondPlayer" FontSize="24" FontFamily="Ara Hamah Homs" Text="اللاعب الثاني" HorizontalAlignment="Center"/>

    </StackPanel>

    <TextBlock x:Name="redScore" Grid.Column="1" Grid.Row="3" FontSize="42" FontFamily="Ara Hamah Homs" Text="0" HorizontalAlignment="center" />
    <Image Source="trophy (1).png" Grid.Column="2" Grid.Row="3" HorizontalAlignment="Left"/>
    <TextBlock x:Name="greenScore" Grid.Column="7" Grid.Row="3" FontSize="42" FontFamily="Ara Hamah Homs" HorizontalAlignment="center" Text="0" />
    <Image Source="trophy (1).png" Grid.Column="6" Grid.Row="3" HorizontalAlignment="Right"/>
    <StackPanel Grid.Row="1" Grid.Column="6" Grid.ColumnSpan="2" Margin="0,50,0,0" >

    </StackPanel>
</Grid>

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to place a custom view from .xib on top of all other viewcontrollers? My setup is a TabBarController with two ViewControllers connected. I need the custom view (audio player) to stay on top when the ViewControllers are changed.
Will I need changes to AppDelegate or SceneDelegate?
What is the solution after ios 13?

A: Push the .xib on the topmost viewcontroller.
let keyWindow = UIApplication.shared.windows.filter
    {$0.isKeyWindow}.first

    if var topController = keyWindow?.rootViewController {
         while let presentedViewController =
         topController.presentedViewController {
             topController = presentedViewController
         }

        // topController should now be your topmost view controller
    }


text:
Q: Jackson to deserialize Map variable as empty Map instead of null I'm using Jackson to deserialize a JSON that could contain null values for Map variables. What I want is if the value is null, I want the map to be an empty HashMap instead of null.
JSON:
{"names":null, "descriptions":null, "nicknames":null...}

Java class:
private User {
    private Map<String,String> names = new HashMap<>();
    private Map<String,String> descriptions = new HashMap<>();
    private Map<String,String> nicknames = new HashMap<>();
}

Right now when the ObjectMapper deserializes the JSON, it overrides the fields, and sets names, descriptions, and nicknames as null.
Is there a a generic way so I would not have to add code each time I have a new map property?

A: Add a setter for your map:
public void setNames(Map<String, String> names) {
    this.names = (names == null) ? new HashMap<>() : names;
}

This setter will be detected by Jackson and will be used when the property is read from the JSON. So within your setter, you can check if the value is null, and if it is then you create a new HashMap.

A: You can setup you own module and override getNullValue()
see doc
http://jackson.codehaus.org/1.9.9/javadoc/org/codehaus/jackson/map/JsonDeserializer.html
Note
I register the Deserializer for all Map.class, not so exact
test code
    SimpleModule module = new SimpleModule("test",  new Version(1, 0, 0, null));

    module.addDeserializer(Map.class, new JsonDeserializer<Map>() {
        @Override
        public Map deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
            return jp.readValueAs(HashMap.class);
        }

        @Override
        public Map getNullValue() {
            return new HashMap();
        }
    });

    mapper.registerModule(module);

test case
String s = "{\"names\":{\"1\":2}, \"descriptions\":null, \"nicknames\":null}";

result
User{descriptions={}, names={1=2}, nicknames={}}

A: With recently released Jackson 2.3.0, there is a new option:
public class POJO {
   @JsonSerialize(nullsUsing=MyNullSerializer.class)
   public Map<String,Object> stuff;
}

so that you can define custom serialize that is only used for serializing null value of given property as any valid JSON value (note that it can not be used to "not write anything", since it does not control writing of property name).


text:
Q: Maven Repository Manager - Nexus vs Artifactory for Java Dependencies We have developed Java based micro services using spring framework where we have dependencies in the form of JAR's. I just wanted to know that which maven repository manager is more useful and efficient. By efficient I mean

*

*Fetching the dependencies from the remote repository at faster rate.

*Fetching third party dependencies (Rarely used) easily.

*Taking less  deployment time in Docker environment.

*Good consistency check and self healing mechanism.

*Pricing.

A: For our big projects with similar scheme (micro services, spring) we are using JFrog Artifactory.
Do not know your budget, but here you may find pricing:
JFROG
Regarding your requirements - it's supports that all.


text:
Q: Css help - background images and margins im trying to change the custom CSS of my page headers, but every time i try to add a top-margin to one of the nested divs, it moves the entire background image down.
Current code (abridged):

title

breadcrumbs

Ideally, all Im trying to do is have a background image that spans the entire header (150px), and then a transparent-color overlay on the background text.
Using margin-top:25px because when i tried adding a vertical-align:middle to .wf-table, nothing happened.
Suggestions?

A: The trouble is that your .wf-table element was not respecting #fancy-header as its parent. The trick is to add float: left and it'll behave in this case as you expect. Check it out here - https://jsfiddle.net/96hf0nqa/
Floats are a little tricky but super important for effective CSS. You can read a lot about them here. Good luck!

A: If your  is the main container to be full-screen then ideally you should be using a grid approach.
Not sure if you use a grid or not? In this case the wf-wrap is your grid-row:
.wf-wrap {
    box-sizing: border-box; /* box model fix */
    max-width: 94rem; /* 960px - gutter */
    padding: 0 1rem; /* grid gutter */
    margin: 0 auto; /* to center */
    height: 100%;
    position: relative; /* to init the absolute offset of it's children */
}

Then your wf-table should be positioned absolute to have full control:
.wf-table {
    position: absolute; /* to control top left right bottom */
    top: 2.5rem; /* default offset */
    z-index: 1 /* if overlap requires it */;
}

DEMO

Typically a grid-row is divided into columns. The position relative belongs on a column actually.
.column {
    box-sizing: border-box;
    padding: 0 1rem;
    float: left;
    height: 100%;
    position: relative;
}

.g50 { max-width: 50%; width: 100%; }

So your HTML can be made a little bit more generic to gain control on the position of elements inside columns.

DEMO
Additionally there is a way to vertically align a block element in CSS3:
.middle-y {
    position: absolute;
    top: 50%;
    -webkit-transform: translateY(-50%);
    -moz-transform: translateY(-50%);
    -o-transform: translateY(-50%);
    -ms-transform: translateY(-50%);
    transform: translateY(-50%);
}


text:
Q: hashedSecret too short to be a bcrypted password not auth I'm adapting the login function from this blogpost. The User struct (see below) has four fields, id, name, email and password. You can see a row from the database below. The fmt.Printlnin the login function shows the user to be like this after the query to the database
 &{3 testuser $2a$10$hS7sth8jIBN2/IXFTWBibu3Ko5BXm9zHO5AJZRAbAOQ04uv.Gs5Ym [116 101 115 116 117 115 101 114 64 103 109 97 105 108 46 99 111 109]}

In other words, it has the id (3), the name (testuser), the hashed password, but then also an array of numbers which surprised me a bit because it's not in the row from the database (see below). You'll also notice that the fmt.Println is not displaying the email, even though that's visible in the row from the database, so there seems to be a problem here.
When bcrypt compares the hash and the password in the Login function, it's giving me this error
hashedSecret too short to be a bcrypted password not auth

Can you explain why this error's being thrown?
func Login(password, email string) (u *User, err error) {
    u = &User{}
    err = db.QueryRow("select * from users where email=$1 ", email).Scan(&u.Id, &u.Name, &u.Password, &u.Email)
    fmt.Println("u", u)

    if err != nil {
        fmt.Println("err", err)
    }

    err = bcrypt.CompareHashAndPassword(u.Password, []byte(password))
    if err != nil {
        u = nil
    }
    return
}

I have a user struct with the following fields
type User struct {
    Id       int
    Name     string
    Email    string
    Password []byte
}

I created a table for it in postgres like this
CREATE TABLE "public"."users" (
    "id" int4 NOT NULL DEFAULT nextval('users_id_seq'::regclass),
    "username" varchar(255) NOT NULL COLLATE "default",
    "email" varchar(255) NOT NULL COLLATE "default",
    "password" bytea
)
WITH (OIDS=FALSE);

this is a row from the database
id |  username  |        email         |                                                          password
----+------------+----------------------+----------------------------------------------------------------------------------------------------------------------------
  3 | testuser   | testuser@gmail.com   | \x24326124313024685337737468386a49424e322f495846545742696275334b6f3542586d397a484f35414a5a524162414f51303475762e477335596d

A: The array of numbers is the email address.
package main

import (
    "fmt"
)

func main() {
    email := []byte{116, 101, 115, 116, 117, 115, 101, 114, 64, 103, 109, 97, 105, 108, 46, 99, 111, 109}
    fmt.Println(email)
    fmt.Println(string(email))
}

Output:
[116 101 115 116 117 115 101 114 64 103 109 97 105 108 46 99 111 109]
testuser@gmail.com

After further study, I see you have select *. Don't do that! You get items returned by the database, not necessarily what you want. Always be explicit in the fields you want returned and their order.
From the select *, using the CREATE TABLE definition, you likely got id, username, email, and password. From your Scan, you set  User type Id to id, Name to username, Password to email, and Email to password. In other words, u.Password contains email (they have the same Go data type) and email is too short to masquerade as a hashed password.
Match the fields in the select and the Scan, for example,
"select id, username, password, email from users where email=$1 "

Scan(&u.Id, &u.Name, &u.Password, &u.Email)


text:
Q: How to display HTML data from database Using java/struts2.0, I am working on webpage where it fetches the data from MYSQL database and display it in the browser.
The database column contains the data in html format like
 Good Looking  wrapped in h1 tag. Now when i pull the data from DB and it shows exact same way as it is in DB having html tags around it.

I tried to store data encoding html tags as well but still no luck.
I am wondering if i have to do any kind of massage before i handover this data to JSP page.
Any help in this regard would be highly appreciated.


text:
Q: Using Intel TBB in debug mode I am trying to debug a C++ code using Intel Thread Building Blocks, with the procedure I have found here
Debugging in threading building Blocks.
My question is related to the following sentence.

Be sure to compile with the macro TBB_USE_DEBUG set to 1 so that TBB's checking will be enabled.

I have added the macro #define TBB_USE_DEBUG 1
at the beginning of my main function. However, when compiling I get the following warning
warning: "TBB_USE_DEBUG" redefined
 #define TBB_USE_DEBUG 1
/usr/include/tbb/tbb_config.h:287:0: note: this is the location of the previous definition
 #define TBB_USE_DEBUG 0

Hence my two questions:

*

*Did I put the macro at the good place ?

*How can I check that my code indeed linked with the debug library ?

A: You have to put the #define before you include anything from the TBB library. In particular, make sure it comes before any #include <tbb> that may be in your source or header files.

A: According to errortext, the define was inserted after includes. Meaning, it is very probably without any effect, because

*

*the define is evaluated only in previously included headers

*or because sources other than your main-function do not see the macro

To fix this

*

*preferred: set the define for all source-files as compiler-parameter. That is often the -D parameter

*or set the define before any includes in ALL sources. Often done by a delegating header.

I dont know how to test whether debug is active, as i dont know TBB.


text:
Q: Book from childhood with some sort of shuttle craft crashed on a mountain I'm trying to remember the title to a book that I read some time in the 80s I think.  The only thing I have to go on is what the cover of the paperback looked like.  I'll try to describe as much detail as possible.
The main color of the book cover is blue.  There is a large gray mountain which we are zoomed up against.  Against the mountain is a small crashed space ship or some form of what I'll call a shuttlecraft (e.g. it is meant for traversing around a planet, not into space).  It looks like it could seat 1-2 people.  It has a clear sphere dome over the cockpit.

A: You can probably find it looking through these site:

*

*http://scifibookart.com/

*http://www.penguinsciencefiction.org/

*http://www.goodshowsir.co.uk/
Could It be:

(okay this one is just actual crazy looking)


text:
Q: Task scheduler terminates completed task I am running a task using the Task Scheduler on a Windows Server 2012 R2 server.  Today I was examining the task's history.  My task completed successfully.
Task Scheduler successfully finished "{a17b1690-5381-4163-a7e5-ab01af11a18e}" instance of the "MyTask" task for user "MyUsername".

However, I noticed that the event following that task's completion was in the "Task terminated" category.
Task Scheduler terminated "{a17b1690-5381-4163-a7e5-ab01af11a18e}"  instance of the "MyTask"  task.

I have been trying to figure what caused this.  I do have the following setting checked:
If the running task does not end when requested, force it to stop.

Could this be why the Task Scheduler terminated the task?  I thought the task was done?

A: Yes, I'm almost certain those two log entries are related and they match up with the configuration setting you have.
I would look at the application configuration to see why it's taking longer than excepted, if its taking as long as you expect, consider tweaking the settings to allow it to run for longer.


text:
Q: What are the default mappings for the up and down arrows keys in zsh I am trying to bind the default functionality of the up and down arrow keys in zsh to something else. I.e. Now when I press up, it basically shows me the previous command and when I press up again it shows me the command before that. I would like to bind this functionality to another key (say ^k and ^j). So the bind would look like:
bindkey '^k' up-line-or-history
bindkey '^j' down-line-or-history

However, I was searching around and found many possibilities: up-line, up-line-or-history etc. Which mappings are the default used by zsh for the up and down arrow keys ? I'm guessing its up-line-or-history and down-line-or-history but I can't be too sure.
Version:
zsh 5.7.1 (x86_64-apple-darwin19.0)

A: up-line is unbound by default; from man zshzle

up-line (unbound) (unbound) (unbound)

which you can confirm by grepping for up-line in the output of bindkeys:
% bindkey | grep up-line
"^P" up-line-or-history
"^[OA" up-line-or-history
"^[[A" up-line-or-history

The documentation mentions that up-line-history is bound to ^P and up-arrow:

up-line-or-history (^P ESC-[A) (k) (ESC-[A)

Both ^[OA and ^[[A refer to the up-arrow key; I believe the duplication depends on your terminal emulator's settings, with the sequence generated by up-arrow depending on the "mode" of the terminal.


text:
Q: Is it possible to use SIM7600 modem for both data and SMS simultaneously? I am interested in using the SIM7600 module for designing a system with LTE communication. The module will be connected to the host system via USB.
I would like the host system's Linux to use PPP to connect to the internet via the module and to be able to send/receive SMS at the same time. So, I will need at least 2 USB virtual ports for these two capabilities. I've seen in the hardware design document that 4 virtual ports are available: audio, AT, diagnostics and NMEA. I guess the AT port will be used for the PPP connection.
So, are there other virtual ports (different from the 4 above) I can use for SMS AT commands, or can I use one of the remaining 3?

A:
I would like the host system's Linux to use PPP to connect to the internet via the module and to be able to send/receive SMS at the same time.

So, the usual: AT commands for both

So, I will need at least 2 USB virtual ports for these two capabilities.

no, why should you?
Modems have (and have had since AT commands became a thing) something called "escape sequence" with which your host can escape from data communication and issue new commands.

I've seen in the hardware design document that 4 virtual ports are available: audio, AT, diagnostics and NMEA. I guess the AT port will be used for the PPP connection.

Note that this really is a setup as you'd see it in a modem for deeply embedded systems, less than for high-speed data comms with a fully fledged Linux host.
It's pretty common these days that USB LTE modems do have an endpoint for AT commands (i.e. a "CDC device"), but also a separate network card endpoint for IP packets. You might want to check whether the device you're planning on using is really what you want, or whether a more consumer-typical LTE modem isn't what you're after, considering your rich host.


text:
Q: RegEx to replace certain text in Notepad++ I have text from chats containing 200.000+ lines in format like this:
[21-Nov-22 04:49 PM] VillagerA
Hi

[21-Nov-22 04:50 PM] VillagerB
Hello

[21-Nov-22 04:50 PM] VillagerA
Hi again

[21-Nov-22 04:51 PM] VillagerB
Hello again

This is just an example. I'm using different names for VillagerA and VillagerB.
I want to change the format to:
VillagerA: Hi
VillagerB: Hello
VillagerA: Hi again
VillagerB: Hello again

I've searched for similar questions like this, but I can't understand how to replace some characters using RegEx on Notepad++. Can someone help me?
Thanks in advance.

A: *

*Find what: ^.+\] (.+)$\R(.+)\R?\s*$

*Replace with: $1: $2

*Enable Wrap Around

*Search mode: Regular Expression


text:
Q: How do you delete a file from a Windows installation if you see the error 'filename too long' I had a directory 'c:\windows.old\ leftover from upgrading Windows 8 to 8.1.  I wanted to delete the directory and could kill most of it using Windows Explorer shift+delete (delete no undelete).
However there were a few tricks left in there from good old MSFT themselves.  For some odd reason they decided that having really long names (RLNs) for the cache entries was a Good Idea.  Most Windows utilities (Del/Dir/PowerShell get-children) just die a stinking death when they see a file with a RLN.
So off on the hunt for something to put them out of their too-long misery.

A: I found this PowerShell add-on module at http://poshcode.org/2488.  Joel's ps module adds several commands to ps, including get-longpath and remove-longpath.

*

*Download the zip from his site and unzip it to C:\windows\system32\WindowsPowerShell\1.0\modules.  You should now have an Experimental.IO folder in the ps modules directory.

*Crank up PowerShell ISE (windows key+x, select Windows
PowerShell ISE) or open the PowerShell command windows (Windows key+x,
Windows PowerShell).

*Navigate to the directory with the offending RLN files (e.g. 'c:\Windows.old\users{{username}}\Appdata\Local\Microsoft\Windows Store\Cache\0'.  Your ps prompt should now be:
Now on to more productive work.
    PS C:\Windows.old\users{{username}}\AppData\Local\Microsoft\Windows Store\Cache\0>

*Enter this command: Get-LongPath | Remove-LongPath

This will pipe the RLN filenames to Remove-LongPath.  PowerShell just returns to the command prompt, but you verify there are no long files by entering Get-Longpath (or its alias glp) and Dir to see there are no long any RLN files in the directory.
As a last note, if you want to save yourself about an hour, refer to this SO post to ask Windows to delete the Windows.old folder on your behalf from the Disk Cleanup utility.

A: 1) Put Linux on a thumb drive. Ubuntu will be fine.
2) Boot to the thumb drive.
3) Delete the files in question from the UI or from the command line:
rm /path/to/file/that/you're/deleting/42915u02u51...24521.doc
Honestly deleting it wth a Linux thumb drive is far simpler and more reliable than hoping Windows utilities and workarounds won't muck it up.


text:
Q: Error when setting Worksheet.PageSetup.XxxFooter I'm using Excel 2007. Here's the code:
Dim ws As Worksheet, lf As String, cf As String, rf As String
...
rf = "&""-,Italic""&K7F7F7F" & "Some text"
...
ws.PageSetup.LeftFooter = lf
ws.PageSetup.CenterFooter = cf
ws.PageSetup.RightFooter = rf

I get the following error on the last line.
Run-time error '1004': Unable to set the RightFooter property of the PageSetup class

The LeftFooter and CenterFooter properties get set just fine. However, if I change the order in which the properties are set, then the last one, be it LeftFooter or CenterFooter triggers the error, and the previous two always get set successfully. So that tells me that it's not an error in the syntax for the footer or anything.
Note that I'm setting some font to italic and a different color in all three footer sections. If I remove the part about changing to italic and color (only on the last of the footer sections), then it executes without error.EDIT Also, if I remove only the italic part, then the code executes without error./EDIT
I was getting this error at first, then played around with variables and concatenation until finally it worked, but now it's broken again, and I cannot figure out the problem.
This question seems possibly related, but I'm not sure. I tried the fix that worked for that guy (using a Replace that does nothing really except return a new string), but I still get the same error.
I've tried using no concatenation to set lf, cf, and rf, merging variables, and a lot of other stuff (in desperation) that should not have an effect anyway, and I keep getting this error. Does anyone have any idea what the problem could be?
UPDATE
I never found an answer to my question, so I just removed the italic font style, and the rest was working. I was happy enough. Now, though, I've had to create the header and footer for a landscape sheet (the other was portrait). The header and footer are the exact same as for the portrait sheet excep that some text in the center footer section is longer. The rest is the exact same. The entire procedure to create the footer was copied and only the one piece of text was changed. Now I'm getting the same error as before (without the italic part). As before, it occurs on the last footer section being set. Note that the portrait footer is still functioning properly. This is driving me nuts, and I'm losing precious time on a matter that you'd think would be fairly straightforward.
Can anyone replicate the error?
Here's the full code:
Private Const LINE_CLR As String = "&K538ED5" ' RGB(83, 142, 213)
'Private Const TEXT_STYLE AS STRING = "&""-,Italic"""
Private Const TEXT_STYLE As String = ""
Private Const TEXT_CLR As String = "&K7F7F7F" ' RGB(127, 127, 127)
Private Const FTR_INDENT_RT As String = "          "
Private Const FTR_INDENT_LT As String = "          "

' *****************************************************************************
Private Function HOR_LINE_PORTRAIT() As String
    HOR_LINE_PORTRAIT = String(128, "_")
End Function

' *****************************************************************************
Private Function HOR_LINE_LANDSCAPE() As String
    HOR_LINE_LANDSCAPE = String(191, "_")
End Function

' *****************************************************************************
Public Sub CreateFooter_Landscape( _
        ByRef ws As Worksheet, _
        ByVal txt1 As String, _
        ByVal txt2 As String, _
        ByVal txt3 As String)
    Dim txtL As String, txtC As String, txtR As String
    Dim lf As String, cf As String, rf As String ' left, center, and right footer

    txtL = "Some text1: " & txt1
    txtC = "Some text2: " & txt2
    txtR = "Some text3 " & txt3

    lf = TEXT_STYLE & TEXT_CLR & FTR_INDENT_LT & txtL
    cf = LINE_CLR & HOR_LINE_LANDSCAPE & Chr(10) & TEXT_STYLE & TEXT_CLR & txtC
    rf = TEXT_STYLE & TEXT_CLR & txtR & FTR_INDENT_RT

    ws.PageSetup.LeftFooter = lf
    ws.PageSetup.CenterFooter = cf
    ws.PageSetup.RightFooter = rf
End Sub

A: I still don't have a definitive answer on this, but in my trials I've noticed a few things (above all that setting headers and footers via VBA is very quirky):

*

*I had a horizontal bar in the center footer section (in the form of a string of underscores) that spanned the entire page width. I noticed that if I greatly reduced the width of the bar that the error disappeared. However, the bar needs to span the entire page width, so this is not an acceptable solution, just an observation

*I had a separate procedure to set the header and the footer of sheets. I passed the text for the footer via parameters of the procedure. I noticed, however, that if I left everything else the same and just overwrote the parameter variable (when concatenating text) with a hard-code value that the error disappeared. Again, this is not an option, because the value cannot be hard-coded.

*Also, in concatenating strings, I called a function directly (that returned a String). However, if I replaced the function call with a local variable, the the error disappeared. I did make this change, but due to the other factors, I still get the error.
I'll try to update this answer if I find anything else, or get lucky with a "real" answer.
UPDATE
I ended up just converting the horizontal bar from underscores to an image and I got it to work. So I guess the underscores in the center section, but overlapping the left and right sections was causing some sort of problem. I haven't tried to add the italic style back in yet, and I don't think I will. It's working, and I've spent WAY too much time on this.


text:
Q: What fields between the rationals and the reals allow to define the usual 2D distance? Consider a field $K$, let's say $K \subseteq \mathbb R$. We can consider the 'plane' $K \times K$. I am wondering in which cases the distance function $d: K \times K \to \mathbb R$, defined as is normal by $d(x, y) = \sqrt{x^2 + y^2}$, takes values in $K$.
Certainly this is not true for $\mathbb Q$: we have $d(1, 1) = \sqrt{2} \notin \mathbb Q$. If we take any $K$ which is closed under taking square roots of non-negative numbers, then certainly $d$ will take values in $K$.
However, a priori it might still be true that $a \in K$ positive has no square root, yet this does not provide an obstruction because there is no way to write $a = x^2 + y^2$. Thus I am wondering:

Are there fields $K \subseteq \mathbb R$ which do not have all square roots of positive numbers, yet are closed under $d$?

A: edit: Look what I found:
Wiki

The field
$$\mathbb{Q}(\sqrt{p} \mid p \in \mathbb{P})$$
might be a good candidate.
At least, all fields closed under $d$ must contain this field.

A: Consider the tower of fields
$K_0:=\mathbb{Q}$,
$K_{i+1}:=K_i(\sqrt{x^2+y^2}| x,y\in K_i)$,
$K:=\bigcup_i K_i$.
Then $K$ is closed under $d$ and contains $1+\sqrt 5$ but not $\sqrt{1+\sqrt 5}$, as I have found by following the Pythagorean fields Wikipedia link given by @Dirk in his answer: If $\sqrt{1+\sqrt 5}$ were in $K$ then $1+\sqrt 5$ would be a sum of two squares in some extension $K_i$, and then it would be so in an extension of $\mathbb{Q}(\sqrt 5)$, which implies that it is a sum of squares in $\mathbb{Q}(\sqrt 5)$, which is impossible because that would entail that $1-\sqrt 5$, which is negative, is also a sum of squares in $\mathbb{Q}(\sqrt 5)$.
The details can be found in Chapter 5 of the book Geometric constructions by Martin. The relevant results are Theorems 5.10-5.15.
Similarly, $\sqrt 2\in K$ but $\sqrt[4]2\not\in K$, and more in general, this is true for any positive number which is not a sum of squares in the first extension in which it appears.
Geometrically, numbers in $K$ correspond to constructible points by ruler and dividers. Hence $\sqrt[4]2$ is constructible by rule and compass but not by rule and dividers.


text:
Q: My Issue with Google Authentication I have been using the old version of Google Calendar GData API (v1, v2)  since November 2011 in my ASP.NET Applications, allowing Users to retrieve and/or create Calendar Events after submitting their usernames and passwords , and this was working perfectly till 17th of November 2014 just before Google decided to shut down this version of API as announced Calendar GData API / Google Calendar Connectors deprecation
Now I am stuck with the new version of Google APIS Calendar (v3) which forces me to use different scenario of Authentication Process instead of the Traditional one.  I don't mind at all using this version of Calendar API as it supports all the needed features but now i don't know how to handle multiple users authentication to use their User Client's ID and Secret which are registered per each user Code Console.
So my question is : Is there any way to let user sign in with his/her normal credentials (Either by Username/Password or Google+ Sign UP feature) and bypassing the process of creating API Project, Enabling the needed APIs and creating new User credentials inside the Console through ASP.net code?
Any Sample code made in C# ASP.net is highly appreciated .
EDIT: Here is my code of Authentication I use
public static CalendarService Authenticate()
        {
            CalendarService service;
            GoogleAuthorizationCodeFlow flow;
            string json_File = System.Configuration.ConfigurationManager.AppSettings["Authentication_Path"];
            string store_path = System.Configuration.ConfigurationManager.AppSettings["FileStore_Path"];
            string url = System.Configuration.ConfigurationManager.AppSettings["Authent_URL"];

            using (var stream = new FileStream(json_File, FileMode.Open, FileAccess.Read))
            {
                flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
                {
                    DataStore = new FileDataStore(store_path),
                    ClientSecretsStream = stream,
                    Scopes = new[] { CalendarService.Scope.Calendar }
                });
            }
            var uri = url;

            var result = new AuthorizationCodeWebApp(flow, uri, uri).AuthorizeAsync("TRAININGCALENDAR", CancellationToken.None).Result;
            if (result.Credential == null)
            {
                GoogleCalendar_Bus.Main_Authentication(url, "", "");
            }
            // The data store contains the user credential, so the user has been already authenticated.
            service = new CalendarService(new BaseClientService.Initializer
            {
                ApplicationName = "Calendar API Sample",
                HttpClientInitializer = result.Credential
            });
            if (result.Credential != null)
            {
                service = new CalendarService(new BaseClientService.Initializer
                {
                    ApplicationName = "Calendar API Sample",
                    HttpClientInitializer = result.Credential
                });
            }

            return service;
        }

A: No you need to use Oauth2. When they authenticate you just save the refresh token this will allow you to then get a new access token and you will have access again. You will need to make your own implementation of Idatastore to store these refresh tokens in the database.
The code for creating an implementation of a Idatastore that stores to the Database is to extensive to post here but you can see a basic example here:  DatabaseDataStore.cs
Then you can use it like this.
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    new ClientSecrets { ClientId = _client_id
                                       ,ClientSecret = _client_secret }
                    ,scopes
                    ,Environment.UserName
                     ,CancellationToken.None
                     ,new DatabaseDataStore(@"LINDAPC\SQL2012", "LindaTest", "test123", "test", "test")).Result;

Update:  Now that I can see your code.

*

*Make sure you have the latested .net client lib.  Google.Apis.Calendar.v3 Client Library

*your code is using FileDataStore this is what you will need to change. You need to make your own implementation of Idatastore similar to the one I have created DatabaseDatastore.

Your code looks different from how I normally do it.
string[] scopes = new string[] {
        CalendarService.Scope.Calendar  ,  // Manage your calendars
        CalendarService.Scope.CalendarReadonly    // View your Calendars
            };

            try
            {
                // here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData%
                UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = clientId, ClientSecret = clientSecret }
                                                                    , scopes
                                                                    , userName
                                                                    , CancellationToken.None
                                                                    , new FileDataStore("Daimto.GoogleCalendar.Auth.Store")).Result;

                CalendarService service = new CalendarService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "Calendar API Sample",
                });
                return service;
            }
            catch (Exception ex)
            {

                Console.WriteLine(ex.InnerException);
                return null;

            }

This may be due to the fact that you aren't using the most up to date client lib, you can find a sample console application for Google Calendar here unfortunately it also uses FileDatastore you will have to edit it to use DatabaseDataStore.  The authentication sample project can be found here Google-Dotnet-Samples/Authentication/ it shows how you can create your own implementation of Idatastore.
I am still working on the tutorial to go along with that sample project I hope to have it completed soon.


text:
Q: wostringstream, Ascii, Unicode, Win32 and integer concatenation to string I am writing a library that uses Win32 APIs, and I would like to be able to compile it for both ASCII and Unicode (wide character is the type), and I am generating an internal class name (read: WinAPI "class") that I am appending an integer to a string to to create unique class names for various windows functions.
The definitions of the variables used:
LPCTSTR lpszClassName;    //  This is char* if ASCII, wchar_t* if Unicode.
#ifdef UNICODE
std::wostringstream Convert;
#else
std::ostringstream Convert;
#endif

The function in question:
void Base::MakeClassName () {
#ifdef _DEBUG_
    cerr << "Base::MakeClassName() called\n";
#endif
static int name_mod = 0;
name_mod++;
lpszClassName = TEXT("Win32WinNo");
Convert << lpszClassName << name_mod;
lpszClassName = Convert.str().c_str();

#ifdef _DEBUG_
    cerr << "Generated class name = " << lpszClassName << "\n";
#endif
}

In ASCII, I get Generated class name = Win32WinNo1
In Unicode, I get a hex value. Which suggests to me the wide character wostringstream is not doing what I want. Either way, CreateWindow doesn't seem to like it (program hangs, if I debug it, it crashes.)
I am not 100% familiar with stringstream, and going by the limited documentation, it returns a 'string' object, but I need a pointer to a C style string for LPCTSTR, so thus, the Convert.str().c_str().  What I am getting is not working right, and If I try TEXT("Win32WinNo1") in my RegisterClass and CreateWindow calls, it works, but this returned string from above is junk.
What am I doing wrong? I am also concerned if it is not appending the integer to the string.  does wostringstream covert the integer to wchar_t?

A: You output to cerr, which is still a narrow stream. It will likely display the pointer value of lpszClassName and not the wide string it points to.

A: ostringstream::str returns a copy of the string object currently associated with the string stream buffer. c_str points to a buffer internal to that temporary string. lpszClassName is a dangling pointer as soon as this temporary string goes out of scope.
This is probably the reason why your program crashes/hangs.

A: I think you need to surround your string-literals with _T() so they will be chars or wchar_ts depending on your UNICODE settings.
For example _T("Hello World").


text:
Q: Understanding focus on divs I feel like I understand focus():

*

*When trying to focus on a form element, like input, it "just works", so long as the document is ready.

*When trying to focus on a non-form element, like div, you must add a tabindex attribute.

*
*

*tabindex adds the ability to tab to an element in precedence order (higher number the better), 0 and up. However, there's a special value, -1, that explicitly removes the element from the tab order.

*When calling focus programmatically, do so within a setTimeout.

*
*

*Be sure to make a setTimeout value large enough that it waits for display animations to finish, but not so late that the user has time to do other things, like click or type elsewhere.

Pretty simple, really, right? But no. It just doesn't work for me.
My specific use-case is that I have a key-nav-enabled widget that, if you hit the right key, opens a pop-over modal widget. It works great. But I can't get that modal widget to take focus. That modal widget that has no form inputs (just some text and a close link). I've added keydown/up/press events to the modal widget, I've added tabindex to various nodes and tried to focus them, but the original widget still gets the keyboard events.
DOM-wise, the modal widget, despite being new'd up within the keynav widget, is attached to the DOM at the body level, so it's not like the keyboard events are bubbling up through my modal dialog and should be stopPropagation'd, it's never getting those events.
What this means is that if you hit another key before you click in the modal widget, it opens a different modal dialog underneath the first modal dialog!
I really hope I'm missing something about focusing divs, because I have several pieces of functionality I'd like to implement that just aren't working due to (I believe) focus requests simply being ignored.
Help! What am I missing?

A: In the specific case I was sleuthing out, I effectively had a typo.
I was doing this, which wasn't working:
 setTimeout(lang.hitch(this, this.domNode.focus), 100);

But this worked:
 setTimeout(function() { this.domNode.focus() }, 100);

That said, I've had a number of issues with focus that regularly make me dread ever having to use it programmatically.
Hopefully though, the list of tips in the question will be helpful to someone.


text:
Q: Uncaught TypeError: Cannot read property 'style' of null, como lo puedo solucionar? Tengo un Iframe donde llamo a Iframe.vue desde Javascript sip_progresivo.js y lo carga en Index.vue pero al realizar la funcion de  getEstado_pantalla sale el error Uncaught TypeError: Cannot read property 'style' of null, no entiendo porque lo muestra como style null, si existe el elemento al que quiero aplicarle el style. como podría solucionarlo?.
Este es mi codigo de javascript sip_progresivo
function getEstado_pantalla(suma) {
  if (suma == 1) {

             document.getElementById('cupcake1').style.display = "none";
             document.getElementById('cupcake2').style.display = "flex";
             document.getElementById('cupcake3').style.display = "none";
             document.getElementById('cupcake4').style.display = "none";
             document.getElementById('colgar').style.display = "block";
             document.getElementById('pausa').style.display = "none";
             document.getElementById('silenciar').style.display = "none";
             document.getElementById('salir').style.display = "block";
             document.getElementById("fame_load").style.display = "block";
             document.getElementById("fame_data").style.display = "none";
            if (activo == false){
                console.log("entro a 1");
                clearInterval(myVar);
            $("#peer").val("sip:55" + telefono +'@' + ip);
            cargar_sicast();
                setTimeout(function(){
               $('#call').click();
                     document.getElementById('call').click();
                    document.getElementById("numero").innerHTML = "LLAMANDO ...";
                }, 3000);
            }
}

export function cargar_sicast(){
   console.log("ENTRO A IFRAME");
             document.getElementById("fame_load").style.display = "none";
             document.getElementById("fame_data").style.display = "block";
   var src = "/gestion-telefonica/progresivo/"+id_cliente+"/"+id_cartera+"/"+telefono+"/"+id_telefono+"/"+id_progresivo+"/"+id;

   var ifr='' ;

   console.log(ifr);
    document.getElementById("idFicha").innerHTML = ifr; // Aqui para llamar a iframe.vue
}

Aquí es donde se muestra el iframe en index.vue

Buscando . . .

Llamando . . .

Finalizando . . .

Back Ffice

En el Iframe.vue guarda datos y oculta el iframe, luego realiza la funcion de estado_progresivo que llama a getEstado_pantalla.
    formSubmit(e) {
      // stop here if form is invalid
      this.v$.$touch();
      this.Guardar_GestionTelefonica();
      console.log(this.submitted)
      if (this.submitted == true) {
         const formData = new FormData(e.target);
         const data = Array.from(formData.entries()).reduce((memo, [key, value]) => ({
            ...memo,
            [key]: value,
         }), {});
         console.log(data);
         // GuardarGestionTelefonicaFormData(data) ;
         GuardarGestionProgresivoFormData(data);
         this.getHgestiones();
         const Toast = Swal.mixin({
            toast: true,
            position: 'bottom-end',
            showConfirmButton: false,
            timer: 2000,
            timerProgressBar: true,
            didOpen: (toast) => {
               toast.addEventListener('mouseenter', Swal.stopTimer)
               toast.addEventListener('mouseleave', Swal.resumeTimer)
            }
         })
         Toast.fire({
            icon: 'success',
            title: 'Se guardo correctamente',
         })

         this.ocultarIframe(); // Para ocultar el iframe
      } else {
         const Toast = Swal.mixin({
            toast: true,
            position: 'bottom-end',
            showConfirmButton: false,
            timer: 2000,
            timerProgressBar: true,
            didOpen: (toast) => {
               toast.addEventListener('mouseenter', Swal.stopTimer)
               toast.addEventListener('mouseleave', Swal.resumeTimer)
            }
         })
         Toast.fire({
            icon: 'error',
            title: 'Error al guardar',
         })
      }
    },

   ocultarIframe(){
      parent.document.getElementById('fame_data').style.display="none";
      parent.document.getElementById('fame_load').style.display="block";
      //parent.location.reload();
      this.estadoProgresivo(4);
   },


text:
Q: FTP to SFTP in shell scripting This script is to connect to different servers and copy a file from a loaction defined.
It is mandatory to use sftp and not ftp.
#!/usr/bin/ksh -xvf

Detail="jyotibo|snv4915|/tlmusr1/tlm/rt/jyotibo/JyotiBo/        jyotibo|snv4915|/tlmusr1/tlm/rt/jyotibo/JyotiBo/"

password=Unix11!
c_filename=import.log
localpath1=`pwd`
for i in $Detail
        do

                echo $i
                UserName=`echo $i | cut -d'|' -f1`
                echo $UserName
                remotehost=`echo $i | cut -d'|' -f2`
                echo $remotehost
                remote_path=`echo $i | cut -d'|' -f3`
                echo $remote_path
                {
                echo "open $remotehost
                user $UserName $password
                lcd $localpath1
                cd $remote_path
                bi
                prompt
                mget $c_filename
                prompt
                "
                } |ftp -i -n -v 2>&1

        done

I want to do the similar thing using sftp instead of ftp.

A: The solution i got is below:
#!/usr/bin/ksh -xvf

Detail="jyotibo|snv4915|/tlmusr1/tlm/rt/jyotibo/JyotiBo/|import.log     jyotibo|snv4915|/tlmusr1/tlm/rt/jyotibo/JyotiBo/|impor
t_1.log"

for i in $Detail
        do
                echo $i
                remote_path=`echo $i | cut -d'|' -f3`
                file_Name=`echo $i | cut -d'|' -f4`
                echo "cd $remote_path" > .jyoti.batch.dat
                echo "get $file_Name" >> .jyoti.batch.dat
                echo "bye" >> .jyoti.batch.dat
                UserName=`echo $i | cut -d'|' -f1`
                echo $UserName
                remotehost=`echo $i | cut -d'|' -f2`
                echo $remotehost
                sftp -b .jyoti.batch.dat $UserName@$remotehost
         done
rm -f  .jyoti.batch.dat


text:
Q: How to associate metadata with many different types of controls in WPF? I have a bunch of controls that may or may not be enabled based on errors in other controls.  When a control is disabled, I want to give the user an explanation of why it is currently disabled.  However, I am already using ToolTip for help text.  So I thought I would make error messages appear in a static text box when the user mouses over a grayed-out component.
Simplified xaml:
<StackPanel Margin="10 10 10 10">
    <TextBox x:Name="thtkDirTextBox" ToolTip="yadda yadda help text"/>
    <TextBox x:Name="tououDatTextBox" ToolTip="yadda yadda help text"/>
    <ComboBox x:Name="touhouExeSelector" ToolTip="yadda yadda help text"/>
    <ComboBox x:Name="stageSelector" ToolTip="yadda yadda help text"/>
    <ComboBox x:Name="sceneSelector" ToolTip="yadda yadda help text"/>
    <GroupBox Header="Errors">
        <TextBox IsEnabled="False" TextWrapping="Wrap" Width="200" FontSize="10" Height="50">
            Mouse over an item that's grayed out and the reason why will appear here.
        </TextBox>
    </GroupBox>
    <StackPanel Orientation="Horizontal" HorizontalAlignment="Right">
        <Button Content="Save as..." ToolTip="yadda yadda help text"></Button>
        <Button Content="Quick Play" ToolTip="yadda yadda help text"></Button>
    </StackPanel>
</StackPanel>

Crucially, in order for this to work, each component will need to be associated with a custom piece of metadata to hold its error message.  (Different controls may have different reasons for being grayed out!)
I read about DependencyProperties, but it seems that using them requires one to subclass a control.  If I have to make subclasses of TextBox, ComboBox, and Button, then I'll end up with duplicated code across three different incompatible DependencyProperties.  (also, virtually all examples of them involve the use of Triggers, which I don't think can help me here?)
I see there is also a Tag property.  Is this a fair usage of the property?  What if I later find that I need another Tag property?  Should I just assume that this probably won't happen?  (Or maybe if it does ultimately come to that, perhaps it is not unreasonable to e.g. serialize JSON objects into Tag in order to store multiple attributes?)
What should I do here?

Additional details:
I am using ReactiveUI to propagate information from one control to another.  For each control that can be grayed out, the ViewModel ultimately constructs an IObservable whose items are either some value needed by the control (e.g. an IEnumerable<string> with choices for a ComboBox, or perhaps just a Unit as a proof of validity for a button), or an error message.
Given one of these observables, I can easily OneWayBind a ObservableAsPropertyHelper of type bool to the control's IsEnabled property, and hope to do something similar for the error message.  If I were to use ToolTips for this, it would be fairly simply:
// ViewModel
this.stageSelectorErrorMessage =
    this.stageSelectorEithers
    .Select(either => either.Error) // string on failure, null on success
    .ScheduleOn(RxApp.MainThreadScheduler)
    .ToProperty(this, x => x.StageSelectorErrorMessage);

// View
this.WhenActivated(disposableRegistration => {
    // ...
    this.OneWayBind(this.ViewModel,
        viewModel => viewModel.StageSelectorErrorMessage,
        view => view.stageSelector.ToolTip
    ).DisposeWith(disposableRegistration);
})

I haven't yet decided how to hook up the mouseover events. (haven't gotten that far)

A:
I see there is also a Tag property. Is this a fair usage of the property?

A better approach would be to create a strongly typed attached dependency property that you can set on any element. Just define a static class where you register the property:
public static class Metadata
{
    public static readonly DependencyProperty InfoProperty = DependencyProperty.RegisterAttached(
          "Info",
          typeof(string),
          typeof(Metadata),
          new FrameworkPropertyMetadata(null));

    public static void SetInfo(UIElement element, string value) => element.SetValue(InfoProperty, value);

    public static string GetInfo(UIElement element) => (string)element.GetValue(InfoProperty);
}

You can set it on any UIElement like this:
<TextBox IsEnabled="False" TextWrapping="Wrap" Width="200" FontSize="10" Height="50"
             local:Metadata.Info="Mouse over an item that's grayed out and the reason why will appear here.">
</TextBox>

You get the value programmatically using the GetInfo method:
string info = Metadata.GetInfo(theControl);


text:
Q: Django: filter JSONField with multiple nested arrays I have a JSONField, called metadata on my model in Django.
The data in that fields might looks something like this
{
    "vis": {
        "plots": [
            // some objects here
            {
                "id": 1,
                "x": "foo",
                "y": "bar",
                "externalData": [
                    // some objects here
                    {
                        "x": "fa",
                        "y": "so",
                        "source": {
                            "name": "FINDME",
                            "location": "some other address"
                        }
                    },
                    // some more objects here
                ]
            },
            // some more objects here
        ],
        "somethingElse": []
    },
    "moreStuff": {}
}

I want to be able to filter models that have "name": "FINDME" in an externalData object (at any index), inside a plots object (also at any index).
I initially tried
MyModel.objects.filter(metadata__vis__plots__externalData__source__name='FINDME')

No good. Then I tried
MyModel.objects.filter(metadata__vis__plots__externalData__source__contains={'name':'FINDME'})

No good. Then I tried
MyModel.objects.filter(metadata__vis__plots__externalData__contains=[{'source': {'name':'FINDME'}}])

Still no luck. Finally, I tried
MyModel.objects.filter(metadata__vis__plots__contains=[{'externalData':[{'source': {'name': 'FINDME'}}]}])

Still no hits.
Clearly, I am doing this all wrong.
Any ideas?
EDIT: I've added some comments in the JSON to make it clear that I don't only have one object in each of my arrays. I am trying to find a 'plot' at an arbitrary index and an 'externalData' at an arbitrary index that contains that "source": {"name": "FINDME"}.

A: The structure of your contains needs to match the JSON, beginning with the first array.  Each level of array in your JSON needs to be represented in the contains=
It is easier to show than to say.  Like this:
MyModel.objects.filter(
     metadata__vis__plots__contains=[{'externalData': [{'source': {'name': 'FINDME'}}]}]
)


text:
Q: Google Cloud Function failed with timeout I have a Pub/Sub triggered cloud function that calls an API end-point and logs the message. But I am not seeing all log messages being logged in console except everything right before calling API.
Once the API is called I am logging the response, and exception messages in case of any error.
It is logging: Function execution took 120015 ms. Finished with status: timeout  Earlier the default timeout was set to 60 sec, later I increased it to 120 sec. Still the problem persist.
I am not understanding the issue here since it is working locally without any issues.
Here I have custom module to log messages to Winston and GCP console (it doesn't have any issue and working fine).
Code calling the API module:
const console = require('./logging-utils');
const portal_api = require('./api-utils');

exports.triggerPortalNotifier = async (event, context) => {
  try {
    /*
    .....
    */

      console.metadata.cloudFunction = cf_name;
      console.metadata.requestId = requestId;
      console.metadata.organizationId = organizationId;
      console.metadata.instanceId = instanceId;

      console.logMessage(`Event received with payload: some message`);
      var payload = {
        //payload to API
      }
      var response = await portal_api.notifyPortal(payload);
      console.logMessage(`Response received from portal API is: ${JSON.stringify(response.data)}`);

    }
    else {
      throw new Error(`Invalid message received: ${_message}`);
    }
  }
  catch (error) {
    console.logMessage(`Portal API failed with exception: ${error}`);
    throw new Error(`${error.message}`);
  }
}

Code that make API request (using axios module)
    require('dotenv').config();
const axios = require('./axios-instance');
const console = require('./logging-utils');

const nextgen_api = {
  notifyPortal: async (payload) => {
    try {
      const config = {
        headers: {
          'Authorization': process.env.PORTAL_AUTHORIZATION_TOKEN,
          'Content-Type': "application/json",
          'Accept': "application/plain"
        }
      }
      console.logMessage(`Input paylod for API end-point: ${process.env.PORTAL_API} => ${JSON.stringify(payload)}`)
      const response = await axios.post(process.env.PORTAL_API, JSON.parse(JSON.stringify(payload)), config);
      console.logMessage(`Response from API: ${JSON.stringify(response.data)}`);
      return response;
    }
    catch (err) {
      if (err.response && err.response.status !== 200) {
        console.logMessage(`API call failed with status code: ${err.response.status} `);
        throw new Error(`API call failed with status code: ${err.response.status} `);
      }
      else {
        console.logMessage(`API call failed with ${err.stack}`);
        throw new Error(`API call failed with status code: ${err.stack} `);
      }
    }
  }
}

module.exports = my_api;

Message Response from API: ${JSON.stringify(response.data)} is not being logged.
Any help here is appreciated.


text:
Q: ActionLink to pass a input value from a different table cell to controller method I'm working in MVC.
I have a table with a bunch of rows. One cell contains an 'Order' button, and a different cell contains a numeric input where the user can specify the quantity of the item he wants to buy? How do I pass through the quantity value in my ActionLink from the input cell? The issue here is not in finding a text value, but rather finding the text value of a specific row

Table Cells
        <input id="itemQuantity" type="number" value="1" min="1" max="@item.QuantityInStock" size="10" class="universalWidth"/>
        @Html.ActionLink("Order", "OrderTuckShop", new { id = item.IngredientId, quanity = ???}, new { @class = "btn btn-success universalWidth" })

Method Call
public ActionResult OrderTuckShop(Guid? id, int quantity)

A: You cannot add the value of the textbox in your ActionLink() method because its razor code, and that is parsed on the server before its sent to the client. In order to respond to client side events you need to use javascript/jquery.
Create a manual link and add the IngredientId as a data- attribute and add an additional class name to use as a selector

    Order

In addition, remove the id="itemQuantity" in the input (duplicate id attributes are invalid html) and add a class name as a selector
<input class="quantity" type="number" ... />

Then include the following script to read the value of the input and make a redirect
var baseUrl = '@Url.Action("OrderTuckShop")';
$('.order).click(function() {
    var id = $(this).data('id');
    var quantity = $(this).closest('tr').find('.quantity').val();
    location.href = baseUrl + '?id=' + id + '&quanity=' + quanity;
});

However, the name of the method suggests you perhaps should be making a POST, not a GET?


text:
Q: Sparkfun's Uberboard HELP I bought the Sparkfun's Uberboard a while back and I was trying to run the "Bootloader Tutorial" I followed all the instructions, got the FW.SFE file, but when the Uberboard resets it does not load the code. I got the following:

SparkFun USB Bootloader v1.1 Boot up
  complete No USB Detected Failed
  Reading Header opening filesystem
  failed Root open "UART0 setup...ing
  firmware...

The "Failed reading header" what does it means? help, anyone? :S

A: From the sparkfun website:
HOW TO USE THE BOOTLOADER INCLUDED ON YOUR BOARD ---
Make sure you add the following to the Makefile: change build: elf hex lss sym to build: elf hex lss sym FW.SFE
--- insert this --- FW.SFE: main.elf @echo @echo $(MSG_FLASH) $@ $(OBJCOPY) -O binary $< $@
--- after this block ---
Create final output file (.bin) from ELF output file.
%.bin: %.elf @echo @echo $(MSG_FLASH) $@ $(OBJCOPY) -O $(FORMAT) $< $@
and in the common folder change the following text in the file: LPC2138-ROM.ld change ROM (rx) : ORIGIN = 0x00000000, LENGTH = 512k to ROM (rx) : ORIGIN = 0x00010000, LENGTH = 380k
Otherwise it will won't write the file. Since the bootloader is sitting at 0x00000000.
I burned a few hours and brain cells on these issues. So, I hope it helps you!


text:
Q: Java - Replace existing objects in heap memory I am using Spring + Hibernate in my java web application. I read in the web that spring and hibernate will use more memory than usual. Frequently I am running out of memory.  So I tried to profile my tomcat by using jvisualvm.  When I see in memory, objects are keep on adding (not replacing existing objects).
For example: if I am loading a list of product objects (1000 objects in the list), then 1000 product objects will be added in heap memory.  If I refresh the data grid again it is adding 1000 objects in heap memory, like that it is keep on increasing (see the image).  is there a way to Replace existing objects in heap memory instead of keep on adding?

A: No, you cannot replace an object on heap. What you can do is to remove all references to that object and delete it from the list, and Java's Garbage Collector will destroy the object.
See this link on Garbage Collection: http://javabook.compuware.com/content/memory/how-garbage-collection-works.aspx


text:
Q: Error in effectfun and parres for Gibbs Area Interaction model I am using spatstat v.1.59-0 to build some point process models, but I am having problems with some of the validation tools, specifically effectfun and and the residual plot parres
The components of the model are rings_pp which consists of point locations for 52 archaeological sites, and elev which is a DEM converted to a spatstat pixel image. I am trying to evaluate the fit of a Gibbs point process model with an Area Interaction parameter (AreaInter) and elev
I fit the model to the data using the following code:
rr1 <- data.frame(r=seq(100, 2000, by=50))
p1 <- profilepl(rr1, AreaInter, rings_pp~elev, aic=T)
ppm5 <- as.ppm(p1)
Everything seems to be working fine (e.g., other diagnostics show the model is a reasonable fit to the data) except when I try to use effectfun and parres to evaluate the effect of the elevation covariate, they wont work.
parres gives the error Error in m[, d$relevant, drop = FALSE] : (subscript) logical subscript too long When I traceback the error I get the following:
`> trace(parres(ppm5, "elev"))
Error in m[, d$relevant, drop = FALSE] :
  (subscript) logical subscript too long
> traceback()
4: effectFun.can(x)
3: effectFun(xxx)
2: parres(ppm5, "elev")
1: trace(parres(ppm5, "elev"))`

effectfun works when se.fit=FALSE but will not work when se.fit=TRUE and gives the following error: Error in quadform(mm, vc) : ncol(x) == nrow(v) is not TRUE When I traceback the error I get the following:
`> trace(plot(effectfun(ppm5, "elev", se.fit=T)))
Error in quadform(mm, vc) : ncol(x) == nrow(v) is not TRUE
> traceback()
8: stop(simpleError(msg, call = sys.call(-1)))
7: stopifnot(ncol(x) == nrow(v))
6: quadform(mm, vc)
5: predict.ppm(orig.model, locations = fakeloc, covariates = fakecov,
   se = se.fit)
4: predict(orig.model, locations = fakeloc, covariates = fakecov,
   se = se.fit)
3: effectfun(ppm5, "elev", se.fit = T)
2: plot(effectfun(ppm5, "elev", se.fit = T))
1: trace(plot(effectfun(ppm5, "elev", se.fit = T)))`

When I fit an inhomogeneous model ppm1 <- ppm(rings_pp, ~elev) both effectfun and parres work fine and show a good fit (though using the residual K function Kres suggest the model isn't accounting for clustering). So it seems to be something with how I've fit the Gibbs AreaInter model.
Any advice would be much appreciated.

A: Thanks again for a clear question.
This is a bug, which can be demonstrated by the simple example
fit <- ppm(cells ~ x, AreaInter(0.07))
plot(effectfun(fit, se.fit=TRUE))
plot(parres(fit))

I will investigate and fix it soon.
Postscript: this has now been fixed in the development version of spatstat (version 1.59-0.020) available on the GitHub repository
.


text:
Q: \MongoDB\BSON\Regex in aggregation pipeline - Convert regex from Python to PHP I'm trying to match some input parameters in my API call using the newer Regex library in PHP, but it's not working so far. I'm using string interpolation to achieve this, but its returning any results. Here is my code:
$regex = new \MongoDB\BSON\Regex ("^{$this->device_id}:", 'i');

$pipeline = [
      [
        '$match' => [
        '_id' => $regex,

      ]]

My document _id are of the type 'london_10:2016-10-05 09' which is the device_id:datehour.
When I var_dump the (string)$regex I get the following, which appears to be working:
string(15) "/^london_10:/i"

The issue is that when adding this to the pipeline, it returns an empty collection. I have equivalent code which is confirmed working but written in Python, and I need to rewrite it in PHP:
    pipeline = [
        {
            '$match': {
                "_id": re.compile("^%s:" %(self.device_id) )
            }
        }
    ]

A: The original code in the question is actually correct - I found that the problem wasn't in this part of my pipeline, but further downstream.


text:
Q: Returning NaN or throwing an exception? I have a function that gets a sample (an std::vector<double>) as input and computes the average of the sample: what is the best way to handle the empty input vector case?
My first idea is to throw an exception like in this snippet:
double average(const std::vector<double>& sample)
{
   size_t sz = sample.size();
   if (sz==0) throw std::exception("unexpected empty vector");

   double acc = 0;
   for (size_t i=0; i<sz; ++i) acc += sample[i];
   return acc/sz;
}

But I think another solution could be to return NaN:
double average(const std::vector<double>& sample)
{
   size_t sz = sample.size();
   if (sz==0) return std::numeric_limits<double>::quiet_NaN();

   double acc = 0;
   for (size_t i=0; i<sz; ++i) acc += sample[i];
   return acc/sz;
}

I like the exception because it shows where the problem happened while if I get a NaN in a final result of a long computation I will have more difficulties to understand where the NaN was born. Anyway with the NaN I like the possibility of returning a "special" double to signal something unexpected happened.
Is there any other way of cope with the empty vector?
Thank you.

A: I DO think that mathematically the NaN would be more correct. In the end it's 0.0/0. Had it been a direct division, what would have happened?
Be aware that about C++ and exceptions there are holy wars. For example read this: To throw or not to throw exceptions?

A: I would leave the behavior undefined.
Just code it for the non-empty case and let the caller think about using it correctly. Probably you won't call it for empty vectors anyway as the check for the empty input will probably be done earlier.

A: Your understanding for using exceptions is correct and you should go ahead with that approach. Exceptions are meant for this purpose (throw when exceptional condition happens).
In this case, suppose if you return NaN, then every time you call the function average() you have to make sure that, you are putting an extra check which takes care of NaN scenario.
[Note: On top of that, make sure that the condition (sz == 0) is not a very frequently happening scenario. IMO, I won't use exceptions if they are thrown frequently.]

A: I would throw, just to keep on the safe side and make sure the error is detected immediately and not, as you said, after a while.
in fact in this specific use case you can return 0 if it make sense to say 0 is the average of "nothing".
what we do usually is to validate parameters as soon as we get inside the method and in case we throw ArgumentNullException or OutOfRangeException if really the method was designed to only be called with non null and properly filled arguments.


text:
Q: How to configure openwrt openvpn bridge I am trying to use my openwrt router to connect to my home network and i can connect to the vpn server but i need to forward or bridge the vpn so everything that comes through the router either through the wired switch or the wifi then routed through the vpn.
More simply clients ---> router (vpn client) ---> vpn server.
It doesnt matter if i can access resources on my home network with it just that its tunneled through my home network so i appear to be using my home IP address. Im also unsure whether to use tap or tun. Any help would be appreciated.
By the way im using all command line because i have a 4mb flash router so i had to build a custom image without the gui so i could fit openvpn.
I have some firewall rules setup to try and foward the traffic but i think what i need is probably a bridge since im using tap currently. I also have redirect-gateway-def1 in my openvpn config file. I guess what i am asking is how to create a bridge for my purposes.
my current etc/config/firewall file contains these lines which pertain to the vpn.
config zone
option name 'VPN_client1'
option masq '1'
option input 'ACCEPT'
option forward 'REJECT'
option output 'ACCEPT'
list network 'VPN_client1'

config forwarding
option dest 'lan'
option src 'VPN_client1'

config forwarding
option dest 'VPN_client1'
option src 'lan'

From the computer hooked up to the router it can ping the router and thats it.
btw this question was kicked off serverfault so im posting it here.
Btw my openvpn server is running on ddwrt on my home router using tun.

A: So, from what I understand, you already have an OpenVPN server up and running.
As for tun and tap: Both server and clients need to use the same configuration. If you do not need Ethernet Bridging, use tun, because it introduces less overhead.
First, we'll update your network configuration to include the VPN interface:
config interface 'vpn'
        option ifname 'tun0'
        option proto 'none'

This is required for integrating the VPN connection into OpenWrt's network system. Of course, if you're using tap, you'll have to change the interface to tap0.
Next, optionally, remove the following lines from /etc/config/firewall:
config forwarding
        option src              lan
        option dest             wan

This ensures that no LAN traffic ever leaves the router over the regular internet uplink. This is not required, of course.
In the same file, add a new zone and configure forwarding:
config zone
        option name             vpn
        list   network          'vpn'
        option input            REJECT
        option output           ACCEPT
        option forward          REJECT
        option masq             1

config forwarding
        option src              lan
        option dest             vpn

Using MASQUERADE and tun makes this configuration easy, because the VPN server does not need to know about the routers clients and we also do not need bridging, reducing overhead. The forwarding section allows LAN traffic to be routed over your VPN connection.
Up next is your VPN configuration. There are some things to keep in mind.
Since we explicitly specified the interface we expect the VPN connection to use, we'll have to do the same in your VPN configuration:
dev tun0

It seems you already have it, but for others, again—we need to redirect traffic through the VPN connection. OpenVPN already offers a great option for this:
redirect-gateway def1

This option also ensures that your VPN server can still be reached.
If your OpenVPN configuration contains the following line, remove it:
persist-tun

After making these changes, reboot your router. Remember: If you removed the forwarding section, you won't be able to access the internet now.
Now, start OpenVPN:
/etc/init.d/openvpn start

If everything works fine now, you can permanently enable OpenVPN:
/etc/init.d/openvpn enable

Do keep in mind though: OpenVPN depends on the date and time being correct to check whether certificates are valid. Your router probably doesn't have a real time clock, meaning it starts at Jan 1 1970 every time. It then depends on internet NTP servers to get the current date and time. This means that OpenVPN will not connect until this is completed, because your certificates are not valid on Jan 1 1970.


text:
Q: Reach to array member using pointer I trying reach to array member using pointer.
Array's first member adress is 23fe20 ;
When I write '1' the program must show me to 23fe24 (because 23fe20+4*1=23fe24) but not working this way. Program output is : 23fe30..
I can use *(pointer+i) for reach to array member but I want reach with adress. How can I do that? Sorry for my english, thanks a lot :'(
int main(int argc, char *argv[]) {
int array[5]={46,85,111,1976,2};
int *pointer,indices;
pointer=array;
int i=0;

printf("Array members : ");
for(i=0;i<=4;i++){
    printf("%d ",array[i]);
}
printf("\n\n Array's First member' : %x\n\n",&*pointer);

printf("Which array member do you want to reach? ");
scanf("%d",&indices);

printf("\n Your member adress : %x",pointer+sizeof(int)*indices);

return 0; }

A: The address you calculate using sizeof(int) is already done by the compiler for you. So your calculation make it point to elsewhere (as the same calculation is done twice). You can simply add a integral type to a pointer to get access to an element.
So do:
printf("\n Your member adress : %p",(void*) (pointer+indices));

You should also use %p in the other place where you print address.

A: The reason for the behavior you see is that in C, pointers have a type, and addition is defined to add that many members, not bytes.
Actually, the syntax array[i] is the same as *(array+i).
Thus, you either have to remove the multiplication by sizeof(int), or, if you really wanted to explore arithmetic on adresses, make pointer a char * instead, because a character is one byte.
Example:
char *cp;
int *ip;
ip = array;
cp = (char *) ip;
printf("%p\n%p\n", ip + 1, cp + 1);

would print, assuming array is at address 23fe20:
23fe24
23fe21

(Assuming that sizeof(int) == 4)


text:
Q: Tracking Scrolling Virtual Page Views in GA Update: Looking into making sure script does not cache events, search has not gone well at all so far.
I am using the script below to track virtual page views in GA, the site has a very long homepage we are tracking this on. The problem I am having is that once the user scrolls down to a lower section, it does not register as a new page view if they scroll back up (making it a maximum of 1 view per page). Any help with this would be greatly appreciated. I am using jQuery and the script below does send/track.
This script is in addition to the Universal Analytics code being implemented just before the  tag. The first code below is the normal Analytics code, which is needed to run the debugger properly because that is where the account is define. The second script is the one that I am having the issue with.
Normal UA script (located in the head tags):
<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
  ga('create', 'UA-123456-1', 'auto');
  ga('require', 'displayfeatures');
  ga('send', 'pageview');
</script>

Script for scrolling virtual page views:
<script language="javascript">

// Predefined variable
Frequency = 10;

//Tracking and Sending
_frequency = Frequency;
_repetition = 100 / Frequency;
var _scrollMatrix = new Array();
for (ix = 0; ix < _repetition; ix++) {
    _scrollMatrix[ix] = [_frequency, 'false'];
    _frequency = Frequency + _frequency;
}
$(document).scroll(function (e) {
    for (iz = 0; iz < _scrollMatrix.length; iz++) {
        if (($(window).scrollTop() + $(window).height() >=      $(document).height()
* _scrollMatrix[iz][0] / 100)  && (_scrollMatrix[iz][1]== 'false')) {
            _scrollMatrix[iz][1] = 'true';
            ga('send', 'pageview', _scrollMatrix[iz][0]+'%' );
        }
    }
 });

</script>

A: You script creates an array of arrays with threshold values ranging from 10 to 100 as index, as determined by the "repentance" variable (this does not mean what you think it means; you mean "repetitions", unless you are really sorry for writing this script). One of the values for each element if your array of the array is a boolean "false".
This boolean value is evaluated in the loop inside the document.scroll function. If the value is "false" the pageview is executed, and the variable is set to "true". Happens in this bit:
if (($(window).scrollTop() + $(window).height() >=      $(document).height()
* _scrollMatrix[iz][0] / 100)  && (_scrollMatrix[iz][1]== 'false')) {
            _scrollMatrix[iz][1] = 'true';

That means the next time around the boolean for _scrollMatrix[iz][1] is "true" and the if branch is no longer executed.
If you want to fire the Google Analytics code regardless you can remove the boolean value and the part where it's evaluated. So your script would look like this:
<script language="javascript">

// Predefined variable
Frequency = 10;

//Tracking and Sending
_frequency = Frequency;
_repentance = 100 / Frequency;
var _scrollMatrix = new Array();
for (ix = 0; ix < _repentance; ix++) {
    _scrollMatrix[ix] = [_frequency];
    _frequency = Frequency + _frequency;
}
$(document).scroll(function (e) {
    for (iz = 0; iz < _scrollMatrix.length; iz++) {
        if (($(window).scrollTop() + $(window).height() >=      $(document).height() * _scrollMatrix[iz][0] / 100)  ) {
            ga('send', 'pageview', _scrollMatrix[iz][0]+'%' );
        }
    }
 });

</script>

While you say that the script is tracking I have to point out that the resulting GA code is actually wrong. Your tracking calls look like this:
ga("send", "pageview", "10%")
ga("send", "pageview", "20%")
...

You cannot simply put in the naked percentage as an argument to that function and hope that it gets recorded somewhere (Edit oops, my bad. Of course the third parameter works as virtual pagename, so that bit is alright if you want the percentage as pagename).
Since your script executes the loop on every scroll event it actually sends dozens of ga calls, and the computed percentages do not relate to the actual scroll position of the user (it simply sends all values from 10-100% for each scroll event). Plus looping on every scroll event makes this horribly expensive in terms of browser ressources. And of course you have a quota of hits per second and hits per sessions, and your script will hit those quotas pretty quickly.
I would frankly recommend that you abandon your script and use one of the existing tested solutions. The jQuery scrollDepth plugin is quite nice and you should be able to adapt it to your needs (more easily than rewriting your own).


text:
Q: No Windows Phone Custom Control Template in Visual Studio? I can't see any such template so how does one develop such control ?
How do I put the control in the toolbox ? Does it use attributes like winform ?

A: Are you talking about a UserControl?  They work the same as any other silverlight UserControl.

A: I suspect your looking to create a custom control. Here's a walkthrough.
Snowfall (User Control Sample) : Windows Phone 7 Tutorials : Compiled Experience


text:
Q: Cannot add 2 blocks with phtml to one layout.xml file I have a page served up by the controller landing_index_index that brings in a couple of blocks to serve phtml. Now, when I bring in just one block:
<referenceContainer name="content">
        <block class="Vendor\Module\Block\Landing" name="landing" template="landing_page.phtml" />
    </referenceContainer>

Everything is just fine. But when I bring in multiple, like this:
<referenceContainer name="content">
        <block class="Vendor\Module\Block\Landing" name="landing" template="landing_page.phtml" />
    </referenceContainer>

    <referenceContainer name="root">
        <block after="content" class="Vendor\Module\Block\Footer" name="landing" template="usfrienbr_footer.phtml" />
    </referenceContainer>

The first block no longer displays at all. If I do footer first and then the main page, only the main page will show. What am I doing that is causing this overwrite? Is it the name? If I change that I get a crash, because I think the name is supposed to correspond to the routes right?

A: Because your two custom block have the same name name="landing", please change the name like below
<referenceContainer name="content">
    <block class="Vendor\Module\Block\Landing" name="landing_page" template="landing_page.phtml" />
</referenceContainer>

<referenceContainer name="root">
    <block after="content" class="Vendor\Module\Block\Footer" name="usfrienbr_footer" template="usfrienbr_footer.phtml" />
</referenceContainer>