text:
Q: Datagrid, Merge/Combine rows, cells and columns I'm trying to acomplish exactly what this question is requesting, but unfortunately the code sample that was provided as the answer is gone, and I'm also not using WPF Toolkit, here the question that he did:

I am trying to Merge cells in WPF toolkit datagrid .I am trying to do something as shown in the image below.We can do this in Winforms datagrid.But how to do this using WPF toolkit datagrid ?.Or is there any alternative controls..?
Can we do this using listview or listbox..? Or is there any free
  controls available which have this functionality ?

I found several answers that manage to do this with the DataGridView control, but I do not want to use Form objects in a WPF project, is there a way to acomplish this?

A: Recource
<Window.Resources>
    <Color x:Key="customBlue"  A="255"   R="54" G="95" B="177"  />
    <SolidColorBrush x:Key="customBlueBrush" Color="{StaticResource customBlue}"></SolidColorBrush>
    <SolidColorBrush x:Key="customBlueBrushOpacity" Color="LightGray" Opacity="0.11"></SolidColorBrush>
    <Style x:Key="calcyListbox"  TargetType="ListBox">
        <Setter Property="SnapsToDevicePixels" Value="True"/>
        <Setter Property="OverridesDefaultStyle" Value="True"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="ListBox">
                    <Grid >
                        <Grid.RowDefinitions>
                            <RowDefinition Height="35"></RowDefinition>
                            <RowDefinition></RowDefinition>
                        </Grid.RowDefinitions>
                        <Grid Grid.Row="0" Height="30"  VerticalAlignment="Top" Background="{StaticResource customBlueBrush}">
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition/>
                                <ColumnDefinition/>
                                <ColumnDefinition/>
                                <ColumnDefinition/>
                                <ColumnDefinition/>
                            </Grid.ColumnDefinitions>
                            <TextBlock Text="Manufacturer" FontSize="14" FontFamily="Segoe Ui Dark" Foreground="White" SnapsToDevicePixels="True" HorizontalAlignment="Center" VerticalAlignment="Center" ></TextBlock>
                            <TextBlock Text="Name" FontSize="14" FontFamily="Segoe Ui Dark" Foreground="White" SnapsToDevicePixels="True"  HorizontalAlignment="Center" VerticalAlignment="Center" Grid.Column="1"></TextBlock>
                            <TextBlock Text="CPU" FontSize="14" FontFamily="Segoe Ui Dark"  Foreground="White" SnapsToDevicePixels="True"  HorizontalAlignment="Center" VerticalAlignment="Center"  Grid.Column="2"></TextBlock>
                            <TextBlock Text="RAM" FontSize="14" FontFamily="Segoe Ui Dark"  Foreground="White" SnapsToDevicePixels="True"  HorizontalAlignment="Center" VerticalAlignment="Center"  Grid.Column="3"></TextBlock>
                            <TextBlock Text="Price" FontSize="14" FontFamily="Segoe Ui Dark"  Foreground="White" SnapsToDevicePixels="True"  HorizontalAlignment="Center" VerticalAlignment="Center"  Grid.Column="4"></TextBlock>
                        </Grid>
                        <Border Grid.Row="1" SnapsToDevicePixels="True"  Background="Transparent" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="0">
                            <ScrollViewer x:Name="ScrollViewer"  Padding="{TemplateBinding Padding}" Background="{TemplateBinding Background}" BorderBrush="Transparent" BorderThickness="0">
                                <ItemsPresenter />
                            </ScrollViewer>
                        </Border>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
    <Style x:Key="noStyleToListboxItem" TargetType="ListBoxItem">
        <Setter Property="SnapsToDevicePixels" Value="True"/>
        <Setter Property="OverridesDefaultStyle" Value="True"/>
        <Setter Property="FocusVisualStyle" Value="{x:Null}"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="ListBoxItem">
                    <Border>
                        <ContentPresenter></ContentPresenter>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</Window.Resources>

xaml
<ListBox  MaxHeight="300" ItemsSource="{Binding ManufacturerList}" Background="{StaticResource customBlueBrushOpacity}"  x:Name="ManufacturerListBox" ScrollViewer.VerticalScrollBarVisibility="Auto" Style="{StaticResource calcyListbox}" ItemContainerStyle="{StaticResource noStyleToListboxItem}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition/>
                    <ColumnDefinition Width="4*"/>
                </Grid.ColumnDefinitions>
                <TextBlock Text="{Binding Company}" HorizontalAlignment="Center" VerticalAlignment="Center"/>
                <Border BorderThickness="0,0,0,1" BorderBrush="Black" ></Border>
                <ListBox Grid.Column="1" BorderThickness="1,0,1,1" Background="{StaticResource customBlueBrushOpacity}" HorizontalContentAlignment="Stretch" ItemsSource="{Binding Models}">
                    <ListBox.ItemTemplate>
                        <DataTemplate>
                            <Grid>
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition/>
                                    <ColumnDefinition/>
                                    <ColumnDefinition/>
                                    <ColumnDefinition/>
                                </Grid.ColumnDefinitions>
                                <Border BorderThickness="0,0,1,0" BorderBrush="Black" Margin="-2" Grid.Column="0"></Border>
                                <Border BorderThickness="0,0,1,0" BorderBrush="Black" Margin="-2" Grid.Column="1"></Border>
                                <Border BorderThickness="0,0,1,0" BorderBrush="Black" Margin="-2" Grid.Column="2"></Border>
                                <TextBlock Text="{Binding Name}" HorizontalAlignment="Center" VerticalAlignment="Center" Grid.Column="0"/>
                                <TextBlock Text="{Binding CPU}" HorizontalAlignment="Center" VerticalAlignment="Center"  Grid.Column="1"/>
                                <TextBlock Text="{Binding Ram}" HorizontalAlignment="Center" VerticalAlignment="Center"  Grid.Column="2"/>
                                <TextBlock Text="{Binding price}" HorizontalAlignment="Center" VerticalAlignment="Center"  Grid.Column="3"/>
                            </Grid>
                        </DataTemplate>
                    </ListBox.ItemTemplate>
                </ListBox>
            </Grid>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

c#
        InitializeComponent();
        List<Manufacturer> ManufacturerList = new List<Manufacturer>();

        ManufacturerList.Add(new Manufacturer()
        {
            Company = "DEll",
            Models = new List<Model>(){new Model(){CPU = "T7250", Name = "Inspiron1525", price =234434 , Ram= "2048 MB" },
                                       new Model(){CPU = "T5750", Name = "Studio 1535", price =234443 , Ram= "2048 MB" },
                                       new Model(){CPU = "T5780", Name = "Vastro 1510", price =234434 , Ram= "2048 MB" },}
        });

        ManufacturerList.Add(new Manufacturer()
        {
            Company = "Lenovo",
            Models = new List<Model>(){new Model(){CPU = "T1230", Name = "l123", price =23546454 , Ram= "1024 MB" },
                                      new Model(){CPU = "T1230", Name = "l1423", price =2346456 , Ram= "1024 MB" },
                                      new Model(){CPU = "T1230", Name = "ldf123", price =2344646 , Ram= "1024 MB" },}
        });

        ManufacturerListBox.ItemsSource = ManufacturerList;

public class Manufacturer
{
    public string Company { get; set; }
    public List<Model> Models { get; set; }
}

public class Model
{
    public string Name { get; set; }
    public string Ram { get; set; }
    public double price { get; set; }
    public string CPU { get; set; }
}

A: For a merged cell, bind its Margin and set it to a negative value equal to the sum width/height of the associated merged cells - then the cell will spill across and on top the neighboring cells.
    <Style TargetType="DataGridCell">
        <Setter Property="BorderThickness" Value="{{Binding BorderThickness[5], Mode=OneWay}}"/>
        <Setter Property="Margin" Value="{{Binding CellMargins[5], Mode=OneWay}}"/>
        <Setter Property="Block.TextAlignment" Value="Center"/>
    </Style>

The bindings are indexed because CellMargins is an ObservableCollection of Thickness. The viewmodel is row-level, so each column binds to a different index.
Before this gets downvoted, let me say this can lead to some undesirable visual quirks. Getting this to work perfectly requires a bit of code-behind, such as:
The cell margins' negative values need to be updated whenever a column width changes, so I handled the datagrid's LayoutUpdated event, where I iterated through the columns, measured their current ActualWidths and updated the margins accordingly. I likewise update the BorderThickness to show/hide cell borders as needed. Disabling the selection highlight for cells that are "hidden" is another trick.
Note this means keeping track of what cells (i.e., which row viewmodels and column indices) you want merged separately in code-behind.
This method is complicated and probably not the easiest for every situation, but I found it useful for my purposes. I needed a Datagrid where the user could merge/unmerge cells and create/delete columns, similar to Excel. Furthermore, I wanted to stick with DataGridTextColumns (instead of custom TemplateColums) because of their built-in functionality (recognized keyboard edit commands, copy/paste, etc.)


text:
Q: How do I make flutter_inappwebview load youtube page with video on pause? I have been trying to follow the network abuse policy, which I don't know much about, any way you guys can help me understand this would be apreciated.
I am trying to get the YouTube link to open but to not start playing video, I have already solved the problem where the video would keep playing on the background using Flutter_inappwebview instead of Flutte_webview but don't know how to keep it from playing at start. I am also not sure if there is other thing that I need to change to follow the policys of YouTube and Play Console.
This my code
class PodcastTab extends StatefulWidget {
  @override
  _PodcastTabState createState() => _PodcastTabState();
}

class _PodcastTabState extends State<PodcastTab> with WidgetsBindingObserver {
  InAppWebViewController webView;

  @override
  void initState() {
    WidgetsBinding.instance.addObserver(this);
    super.initState();
  }
  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    print('state = $state');
    if (webView != null) {
      if (state == AppLifecycleState.paused) {
        webView.pauseTimers();
        if (Platform.isAndroid) {
          webView.android.pause();
        }
      } else {
        webView.resumeTimers();
        if (Platform.isAndroid) {
          webView.android.resume();
        }
      }
    }
  }
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          elevation: 0.0,
          backgroundColor: Colors.grey[900],
          leading: FlatButton(
            child: new Icon(
              Icons.arrow_back_ios_rounded,
              color: Colors.yellow,
            ),
            onPressed: () {
              Navigator.pop(context);
            },
          ),
        ),
        body: Container(
          child: Column(
            children: <Widget>[
              Expanded(
                child: InAppWebView(
                  initialUrl:
                      "https://www.youtube.com/watch?v=R4sB74NJzcY&list=PLCxoHXWd63cwaD2ceIZGZU4QfkA0C0Tb_",
                  initialHeaders: {},
                  initialOptions: InAppWebViewGroupOptions(
                    crossPlatform: InAppWebViewOptions(
                      debuggingEnabled: true,
                    ),
                  ),
                  onWebViewCreated: (InAppWebViewController controller) {
                    webView = controller;
                  },
                  onLoadStart:
                      (InAppWebViewController controller, String url) {},
                  onLoadStop:
                      (InAppWebViewController controller, String url) {},
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I loop over Json data? This is my json structure.
[
    [
      {
       "nos": 0,
        "name": "A S MUSIC AND DANCE A CULTURAL ORGANIZATION",
         "unique_id": "AN/2020/0259067",
         "reg_details": [
                      {
                        "registered_with": "Registrar of Societies"
                      },
                      {
                        "type_of_ngo": "Registered Societies (Non-Government)"

This is working fine.
 String jsonString = await _loadANgoAsset();
    final jsonResponse = json.decode(jsonString);
    String name = jsonResponse[0][0]['name'];
    debugPrint("Name of NGO is $name");

But when I want to loop throug a key of various entities of data using this code:
   List<dynamic> allNamesOfNGO = jsonResponse[0][0]['name'];
    allNamesOfNGO.forEach((allNamesOfNGO) {
      (allNamesOfNGO as Map<String, dynamic>).forEach((key, value) {
        print(key);
        (value as Map<String, dynamic>).forEach((key2, value2) {
          print(key2);
          print(value2);
        });
      });
    });

The following error occurs:
E/flutter ( 4683): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: type 'String' is not a subtype of type 'List<dynamic>'

Help please!

A:  List<dynamic> allNamesOfNGO = jsonResponse[0][0]['name'];

This line tries to assign name of first ngo(String) to allNamesOfNGO(List), which results in the above error.
To overcome this error, replace the above code with this:
List<dynamic> allNamesOfNGO = jsonResponse[0];
allNamesOfNGO.forEach((allNamesOfNGO) {
  (allNamesOfNGO as Map<String, dynamic>).forEach((key, value) {
    print(key);
    print(value);
    if(key == "reg_details") {
      value.forEach(regDetail) {
        print(regDetail);
      });
    }
  });
});

You don't need innermost forEach loop as you have already got the key, value pair before that loop. In the innermost forEach loop, you are trying to loop through individual key like nos, name and unique_is(which is either a string or an int) which isn't possible.
Value of reg_details is a list. So you can loop through it, but for that you have to check if key == "reg_details".

A: because you declare it as String and then loop it as dynamic .try

List<string>

instead of

List<dynamic>.


text:
Q: Extension method binding for explicit interface implementation I have been playing with extension methods in order to add some capabilities to existing interfaces. When I implement interface members implicitly, compiler chooses the interface member implementation instead of extension method as it is stated in this MSDN page.
However, when I try explicit implementation, it seems that extension method is selected instead of implemented member of the interface.
//My interface and extension method for this interface
interface IExt
{
    void Extended(int e);
}

public static int Extended(this yapboz.IExt ext, int e)
{
    return e + 1;
}

When I implement the given Extended method explicitly (CExt below), it doesn't bind.
class CExt : IExt
{
    void IExt.Extended(int e)
    {
        throw new NotImplementedException();
    }
}

After this implementation it returns integer value instead of throwing an exception!
However, when I implement the interface member implicitly (see below), then my code throws the exception.
class CExt : IExt
{
    public void Extended(int e)
    {
        throw new NotImplementedException();
    }
}

A: Explicit implementations have to be called through the interface. So
IExt c = new CExt();
c.Extended(1);

will bind to the explicit interface implementaion since the variable is of the interface type,  but
CExt c = new CExt();
c.Extended(1);

Will bind to the extension method since there is no public Extended method on the CExt type itself.
So that's why it behaves the way it does.  However I would note that it's not a good idea to add extension methods that are the same as existing interface methods.  Extension methods are used to extend interfaces and classes, not to add an implementation to an existing interface method.


text:
Q: Windows 7 network drive to Linux filesystem via PuTTY I'm trying to establish a remote ssh connection to a Linux filesystem from Windows 7.
The purpose is to be able to enable Windows programs (like OneNote) to write files to the Linux box, so they can be stored there instead of on the local machine.
So I used this stackoverflow question which leads me to this tutorial since I am using PuTTY to establish the SSH connection.
A few things stick out at me in that tutorial however.
1)  He seems to be connecting to the server on port 22:

(source: cam.ac.uk)
But in the 2 pictures before that, he has destination port 139 on his server

(source: cam.ac.uk)
Is that wrong?  To get any response out of my server at all, I leave tunnel source port 139, and set tunnel destination port 22, not 139.
2)  The main problem I encounter after establishing the SSH connection (a normal putty window opens, and I log in with my Linux username/pass), is with attempting to map the network drive.
Really I don't know what the 2nd name means (after \\127.0.0.1\WHATISTHIS) in

I thought connecting to \\127.0.0.1\foldername was the deal, but it appears no.
Also shouldn't I specify \\127.0.0.1:139 to make sure it goes to the SSH tunnel?
3)  Finally I find even if I do manage to apparently hit the server at \\127.0.0.1\, it doesn't recognize any of the login credentials that I could possibly have set up

Credentials for the Windows machine don't work, credentials for the Linux box don't work.

A: Have you considered alternatives to PuTTY? See my answer to a related question on Super User:

A quick search for "windows sshfs" turned up Dokan and ExpanDrive.
I have never tried Dokan, but it appears to be a one-man open source project.
ExpanDrive is a commercial product, going for $39.95 at this writing. I installed the 30-day free trial, and it has worked really well. I mounted one of my servers over SSH and it looks and acts like any other network drive.


text:
Q: I get "UserWarning: Port 8787 is already in use" when use AutoSklearn, Why would AutoSklearn use ports? Here is my code
automl = autosklearn.classification.AutoSklearnClassifier(
include={'feature_preprocessor': ["no_preprocessing"],
 },
exclude={ 'classifier': ['random_forest']},
time_left_for_this_task=60*10,
per_run_time_limit=60*1,
memory_limit = 1024 * 10,
n_jobs=-1,
metric=autosklearn.metrics.f1_macro,
        )

clf = OneVsRestClassifier(automl, n_jobs=-1)

clf.fit(X_train, y_train)

when I try to fit I get this error
/home/user/.local/lib/python3.8/site-packages/distributed/node.py:180: UserWarning: Port 8787 is already in use.
Perhaps you already have a cluster running?
Hosting the HTTP server on port 42433 instead
  warnings.warn(
Killed

why AutoSKlearn asking for dask and how to fix this error??

A: Auto-sklearn uses Dask for parallel optimization, which is controlled by the n_jobs argument, as explained in more detail here. The warning message you're seeing occurs when you're starting a new Dask cluster when there is already one in use. One option to remove the warning is to guard the code, as shown in the example in the above link, by placing your code within if __name__ == '__main__':.


text:
Q: Preventing a spring boot service from failing on startup with Redis not present We have a number of services that use spring boot (v1.2.3) and Spring Data Redis using the spring-boot-starter-redis dependency.
Also we are using spring session and its corresponding redis dependency
        <dependency>
            <groupId>org.springframework.session</groupId>
            <artifactId>spring-session</artifactId>
            <version>1.0.0.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.session</groupId>
            <artifactId>spring-session-data-redis</artifactId>
            <version>1.0.0.RELEASE</version>
            <type>pom</type>
        </dependency>

If the redis server is not started or cannot be reached then the service issues a fail and aborts startup.
Is it possible to allow the service to not fail on startup?  What do I need to setup in order to do so?
NOTE: I tracked the critical failure down and it is in the Redis support for Spring Session.  A failure thrown here ripples up to cause the service to failure out.  Is it possible to have a fallback to a regular session if connectivity to redis is failed?
RedisHttpSessionConfiguration.java at line 156
 public void afterPropertiesSet() throws Exception {
     >>>   RedisConnection connection = connectionFactory.getConnection();

Stack trace is as follows:
2015-06-02 17:20:00.214  WARN 67248 --- [           main] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'enableRedisKeyspaceNotificationsInitializer' defined in class path resource [org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfiguration.class]: Invocation of init method failed; nested exception is org.springframework.data.redis.RedisConnectionFailureException: Cannot get Jedis connection; nested exception is redis.clients.jedis.exceptions.JedisConnectionException: Could not get a resource from the pool
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1566) ~[spring-beans-4.1.5.RELEASE.jar:4.1.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539) ~[spring-beans-4.1.5.RELEASE.jar:4.1.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476) ~[spring-beans-4.1.5.RELEASE.jar:4.1.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303) ~[spring-beans-4.1.5.RELEASE.jar:4.1.5.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.1.5.RELEASE.jar:4.1.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299) ~[spring-beans-4.1.5.RELEASE.jar:4.1.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194) ~[spring-beans-4.1.5.RELEASE.jar:4.1.5.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755) ~[spring-beans-4.1.5.RELEASE.jar:4.1.5.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757) ~[spring-context-4.1.5.RELEASE.jar:4.1.5.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480) ~[spring-context-4.1.5.RELEASE.jar:4.1.5.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118) [spring-boot-1.2.2.RELEASE.jar:1.2.2.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:686) [spring-boot-1.2.2.RELEASE.jar:1.2.2.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:320) [spring-boot-1.2.2.RELEASE.jar:1.2.2.RELEASE]
    at com.cisco.services.rpil.MicroServiceApplication.main(MicroServiceApplication.java:47) [classes/:na]
Caused by: org.springframework.data.redis.RedisConnectionFailureException: Cannot get Jedis connection; nested exception is redis.clients.jedis.exceptions.JedisConnectionException: Could not get a resource from the pool
    at org.springframework.data.redis.connection.jedis.JedisConnectionFactory.fetchJedisConnector(JedisConnectionFactory.java:140) ~[spring-data-redis-1.4.2.RELEASE.jar:1.4.2.RELEASE]
    at org.springframework.data.redis.connection.jedis.JedisConnectionFactory.getConnection(JedisConnectionFactory.java:229) ~[spring-data-redis-1.4.2.RELEASE.jar:1.4.2.RELEASE]
    at org.springframework.data.redis.connection.jedis.JedisConnectionFactory.getConnection(JedisConnectionFactory.java:57) ~[spring-data-redis-1.4.2.RELEASE.jar:1.4.2.RELEASE]
    at org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration$EnableRedisKeyspaceNotificationsInitializer.afterPropertiesSet(RedisHttpSessionConfiguration.java:156) ~[spring-session-1.0.0.RELEASE.jar:na]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1625) ~[spring-beans-4.1.5.RELEASE.jar:4.1.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1562) ~[spring-beans-4.1.5.RELEASE.jar:4.1.5.RELEASE]
    ... 13 common frames omitted
Caused by: redis.clients.jedis.exceptions.JedisConnectionException: Could not get a resource from the pool
    at redis.clients.util.Pool.getResource(Pool.java:42) ~[jedis-2.5.2.jar:na]
    at redis.clients.jedis.JedisPool.getResource(JedisPool.java:84) ~[jedis-2.5.2.jar:na]
    at redis.clients.jedis.JedisPool.getResource(JedisPool.java:10) ~[jedis-2.5.2.jar:na]
    at org.springframework.data.redis.connection.jedis.JedisConnectionFactory.fetchJedisConnector(JedisConnectionFactory.java:133) ~[spring-data-redis-1.4.2.RELEASE.jar:1.4.2.RELEASE]
    ... 18 common frames omitted
Caused by: redis.clients.jedis.exceptions.JedisConnectionException: java.net.ConnectException: Connection refused
    at redis.clients.jedis.Connection.connect(Connection.java:150) ~[jedis-2.5.2.jar:na]
    at redis.clients.jedis.BinaryClient.connect(BinaryClient.java:71) ~[jedis-2.5.2.jar:na]
    at redis.clients.jedis.BinaryJedis.connect(BinaryJedis.java:1783) ~[jedis-2.5.2.jar:na]
    at redis.clients.jedis.JedisFactory.makeObject(JedisFactory.java:65) ~[jedis-2.5.2.jar:na]
    at org.apache.commons.pool2.impl.GenericObjectPool.create(GenericObjectPool.java:836) ~[commons-pool2-2.2.jar:2.2]
    at org.apache.commons.pool2.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:434) ~[commons-pool2-2.2.jar:2.2]
    at org.apache.commons.pool2.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:361) ~[commons-pool2-2.2.jar:2.2]
    at redis.clients.util.Pool.getResource(Pool.java:40) ~[jedis-2.5.2.jar:na]
    ... 21 common frames omitted
Caused by: java.net.ConnectException: Connection refused
    at java.net.PlainSocketImpl.socketConnect(Native Method) ~[na:1.8.0_25]
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:345) ~[na:1.8.0_25]
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206) ~[na:1.8.0_25]
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188) ~[na:1.8.0_25]
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) ~[na:1.8.0_25]
    at java.net.Socket.connect(Socket.java:589) ~[na:1.8.0_25]
    at redis.clients.jedis.Connection.connect(Connection.java:144) ~[jedis-2.5.2.jar:na]
    ... 28 common frames omitted


text:
Q: Grouping by LIKE operators I have a small database in Access which has information about customers.
In this database, the original creators had specified a Primary Key (let's call this ID).
There's also a column for (as you've guessed) customer names.
On this report that I'm working on, what I essentially want is similar customer names grouped into one row.
Like for example if I have the following sets of customers:
Malaysia
Malaysia Airlines
Malaysia Pipeline
Note that these are all the same customers but the IDs are different (as you can assume....ID is an auto incremented field...1,2,3).
I'm not sure if this is possible..or if I'd have to write some VBA to capture this.
Any suggestions?

A: This should do the trick.  This will eliminate all of the rows where the name has a more concise version of itself somewhere in the table (i.e. where another name exists that is a substring of the name being eliminated).  Since this works by deletion, I'm putting everything in a temp table first to protect your original data.
select * into #tmp from your_table

delete t1
    from #tmp t1
    inner join #q t2 on t1.[name] like '%' + t2.[name] + '%' and t1.[name] <> t2.[name]

select * from #tmp

You can then use this temp table as a kind of master list and, if need be, join to and group the original table, like this:
select t1.[name], count(*) - 1 as number_of_aliases, sum(t2.number_of_passengers) as number_of_passengers, avg(t2.avg_ticket_price) as avg_ticket_price
    from #tmp t1
    left join your_table t2 on t1.[name] like '%' + t2.[name] + '%'
    group by t1.[name]
    order by t1.[name]

...or get a simple listing all of the aliases, like this:
select t1.[name], t2.[name]
    from #tmp t1
    left join your_table t2 on t1.[name] like '%' + t2.[name] + '%'
    order by t1.[name], t2.[name]

I hope this helps.


text:
Q: ReportExecutionService.Render() - missing hyperlink from report column I am working on peace of code where, rendering a report using ReportExecutionService.Render() method. I have passed following parameters to this method;
string format = "EXCELOPENXML";
string devInfo = @"False";
Report contains one column with hyperlink, but after rendering the report with Render method, output file is missing that hyperlink. If I export same  report from report viewer to excel, resulting excel has the hyperlink on that column.
What can be the possible issue for missing hyperlink? Do i need to specify any particular format (i tried same thing with HTML, PDF formats as well but no luck)? Is there any workarround to get the hyperlink into the rendered report using ReportExecutionService.Render()?


text:
Q: UI not updating after deleting one element from array list I am writing a chat application. On click of a button I am trying to remove selected friend from list And its working properly but on removing the friend the UI is not getting updated
  private void removeFriend(String remfri) {
       removefri = remfri;

            {
                try {
                    Constants.connection.getRoster().setSubscriptionMode(Roster.SubscriptionMode.accept_all);
                    Constants.connection.getRoster().createEntry(removefri, removefri, null);

                    Collection<RosterEntry> entries = Constants.connection.getRoster().getEntries();
                    for (RosterEntry entry : entries)
                    {
                        System.out.println("name..."+entry.getUser()+"...type.."+entry.getType());
                        if(entry.getType()==ItemType.none)
                        {
                            Presence unsubscribe = new Presence(Presence.Type.unsubscribe);
                            unsubscribe.setTo(removefri);
                            Constants.connection.sendPacket(unsubscribe);

                           // usersList.clear();
                            usersList.remove(removefri);
                            Log.d("removed"," the best friend " + removefri);

Pasting code for refrence :http://pastie.org/8744959

A: Use adapter.notifyDataSetChanged(); after removal


text:
Q: spring boot application deployment failed on jboss eap 7 I am not able to deploy the my Spring BOOT REST Application on JBOSS EAP 7 Server.
However, its running fine after deployment on  Apache Tomcat 8 Server.
Application Main Class:
@SpringBootApplication(scanBasePackages= {"org.nic"})
@PropertySource(value="classpath:database.properties")
public class PopulationApplication extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(PopulationApplication.class);
    }

    public static void main(String[] args) throws Exception {
        SpringApplication.run(PopulationApplication.class, args);
    }

}

pom.xml
  <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <start-class>org.nic.PopulationApplication</start-class>
        </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

         <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
        </dependency>

        <!-- <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency> -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <scope>provided</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

It's throwing the following error at server logs
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.web.servlet.filter.OrderedHttpPutFormContentFilter]: Factory method 'httpPutFormContentFilter' threw exception; nested exception is java.lang.VerifyError: Failed to link com/fasterxml/jackson/databind/type/ReferenceType (Module "deployment.nhpmapi-0.0.1-SNAPSHOT.war:main" from Service Module Loader): Cannot inherit from final class
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:579)
    ... 35 more

My Server environment only had JBOSS EAP 7.
I had research to solve the issue but could not find any success.
I had last option to remove Spring BOOT configuration into order to run on JBOSS EAP 7

A: I had the exact same problem and struggled for two days. Finally found a solution!
java.lang.VerifyError is usually caused when there is inconsistency of classes. As shown in the error message, it's caused by com.fasterxml.jackson.core.jackson-databind
Since Jboss has its internal Jackson module, and its version is different from your application specified.
To solve the problem, add jboss-deployment-structure.xml and put it under src/main/webapp/WEB-INF:

<?xml version='1.0' encoding='UTF-8'?>
<jboss-deployment-structure xmlns="urn:jboss:deployment-structure:1.1">
    <deployment>
        <exclusions>
            <module name="com.fasterxml.jackson.core.jackson-annotations" />
            <module name="com.fasterxml.jackson.core.jackson-core" />
            <module name="com.fasterxml.jackson.core.jackson-databind" />
            <module name="com.fasterxml.jackson.datatype.jackson-datatype-jdk8"/>
            <module name="com.fasterxml.jackson.datatype.jackson-datatype-jsr310"/>
            <module name="com.fasterxml.jackson.jaxrs.jackson-jaxrs-json-provider" />
            <module name="org.jboss.resteasy.resteasy-jackson2-provider" />
            <module name="org.slf4j" />
        </exclusions>
    </deployment>
</jboss-deployment-structure>

It will avoid implicit dependencies and solve the problem.
Found the answer here and here and here thanks to them!
For more information: Causes of getting a java.lang.VerifyError
What is jboss-deployment-structure.xml
Module Dependencies

A: It seems like Spring is not able to instantiate beans from the WAR. Can you check classes inside are visible and are loaded properly?
Seems like class loading issue.


text:
Q: How do you conduct regression analysis using SPSS when there is more than one dependent variable? How do you conduct a regression analysis in SPSS using 1 predictor variable (personality score) and 8 dependent variables (stigma scores to 8 different case studies)?
I have tried to use this process as seen in previous posts:
Analyze - general linear model - multivariate - list the 8 DVs as the outcome variables box and the IV (personality) in the covariates box
Although this saves me from doing 8 separate linear regressions - I cannot get full output this way.
I have clicked on the options box and selected parameter estimates but there is no checkbox for regression or R values. Does anyone know how to get the FULL output using this multivariate technique?

A: The technique is called "Multivariate regression" (not to be confused with multiple regression, which is simply a regression with multiple predictors). Googling leads to this document on IBM support site. If you have AMOS as a part of your SPSS license, you can create a structural equation model in SPSS with these variables.


text:
Q: writing a method body as Expression<> I want to convert a logic inside a method as a Expression, so that i could store that and when required could compile it for execution.
The method has flow like
1) takes a parameter
2) does a 'FirstOrDefault' on a collection property on passed in parameter
3) Calls some method on a repository class
4) some if conditions
5) creation/instantiation of some field
etc etc. In all a complex method which does lots of things.
Question : Is there any article/resource which could show me this with an example.
Thanks

A: What's wrong with MSDN? You can find examples here (at the bottom of the page):
http://msdn.microsoft.com/en-us/library/bb397951.aspx
Something like this:
static Expression<Action<IEnumerable<int>>> BuildExpression()
{
    ParameterExpression param1 = Expression.Parameter(typeof(IEnumerable<int>), "param1");
    Expression<Func<IEnumerable<int>, int>> firstOrDefault = collection => collection.FirstOrDefault();
    Expression body = Expression.Condition(
        Expression.LessThan(
            Expression.Invoke(firstOrDefault, param1),
            Expression.Constant(10)),
        Expression.Call(
            typeof(Console).GetMethod("WriteLine", new [] { typeof(string) }),
            Expression.Constant("Less")),
        Expression.Call(
            typeof(Console).GetMethod("WriteLine", new [] { typeof(string) }),
            Expression.Constant("Greater or equal"))
        );
    return Expression.Lambda<Action<IEnumerable<int>>>(body, new[] { param1 });
}


text:
Q: Static Routing in Express.js returning 404 Error I'm trying to create routing for different pages of my website, using express.js.
When going to 127.0.0.1:8080, it loads the index.html page fine, however, when I go to 127.0.0.1:8080/questionaire, it comes back with a 404 error and doesn't load questionaire.html. I thought that using the line:
app.use(express.static('client', { extensions: ['html'] }));

meant that this would be possible, however, it doesn't work. If there is a better way to do this then fixing the solution, inform me please.
Directory
client
-- index.html
-- index.js
-- questionaire.html
-- questionaire.js
svr.js
viewapi.js

svr.js
'use strict';

const express = require('express');
const app = express();

const view_api = require('./viewapi');

app.use(express.static('client', { extensions: ['html'] }));

const api = require('./api');

app.use('/view', view_api); // routing to api which will get data in form of JSON

app.listen(8080);

A: I just tried your setup and loading questionare.html worked fine for me. Did you receive any other errors from the Express server when you tried to load the page? I'm asking because I'm not sure what the contents are inside viewapi.js so when I tested it, I didn't have that file.
However, to answer this:

If there is a better way to do this then fixing the solution, inform me please.

it's good practice to separate the assets that you serve (html, css, js, images, etc.). For example, you could create sub-folders inside your client folder and put your static files in the appropriate folder.
You can also find examples and better documentation here: https://expressjs.com/en/starter/static-files.html


text:
Q: Stop moving other nodes while dragging one node in D3 forceSimulation I made a D3 forced-directed graph by d3.forceSimulation() and attached the drag function. While clicking one node, I don't want other nodes to move accordingly. Now I can freeze the node being dragged by setting the d.fx and d.fy as the following:
function dragended(d) {
    if (!d3.event.active) simulation.alphaTarget(0);
    d.fx = d.x;
    d.fy = d.y;
}

Is it possible to freeze all the other nodes while dragging one node?

A: Thanks @rioV8 for the hint! I tried to fix the other nodes while dragging one node.
node.call(d3.drag()
    .on('start', dragstarted)
    .on('drag', dragged)
    .on('end', dragended))

function dragged(d) {
    d.fx = d3.event.x;
    d.fy = d3.event.y;
    fix_nodes(d);
}

// Preventing other nodes from moving while dragging one node
function fix_nodes(this_node) {
    node.each(function(d){
        if (this_node != d){
            d.fx = d.x;
            d.fy = d.y;
        }
    });
}

Demo is here: https://jsfiddle.net/casbie/21dvjcgn/

A: Here's a solution that allows flexible manipulation on the forces of the simulation during dragging:
let tempForces = {};

const modifyForces = (simulation) => {
    tempForces = {};
    // For example, I want to temporarily remove the "link" and "charge" forces during dragging.
    (["link", "charge"]).forEach((forceName) => {
        tempForces[forceName] = simulation.force(forceName);
        simulation.force(forceName, null);
    });
    // You may modify your forces here. Store them to 'tempForces' if you'd like to restore them after dragging.
};

const restoreForces = (simulation) => {
    for (let [name, force] of Object.entries(tempForces)) {
        simulation.force(name, force);
    }
    tempForces = {};
};

And then call modifyForces() and restoreForces() when dragging starts and ends respectively. (Adapted from this observable)
const start = function(event) {
    modifyForces(simulation); // Modifying
    if (!event.active) {
        simulation.alphaTarget(0.1).restart();
    }
    event.subject.fx = event.subject.x;
    event.subject.fy = event.subject.y;
};

const drag = function (event) {
    event.subject.fx = event.x;
    event.subject.fy = event.y;
};

const end = function (event) {
    restoreForces(simulation); // Restoring
    if (!event.active) {
        simulation.alphaTarget(0);
    }
    event.subject.fx = null;
    event.subject.fy = null;
};

const dragBehavior = d3.drag()
    .on("start", start)
    .on("drag", drag)
    .on("end", end);

node.call(dragBehavior);


text:
Q: Advice on Setup I started my first data analysis job a few months ago and I am in charge of a SQL database and then taking that data and creating dashboards within Power BI. Our SQL database is replicated from an online web portal we use for data entry. We do not add data ourselves to the database but instead the data is put into tables based on the data entered into the web portal. Since this database is replicated via another company, I created our own database that is connected via linked server. I have built many views to pull only the needed data from the initial database( did this to limit the amount of data sent to Power BI for performance). My view count is climbing and wondering in terms of performance, is this the best way forward. The highest row count of a view is 32,000 and the lowest is around 1000 rows.
Some of the views that I am writing end up joining 5-6 tables together due to the structure built by the data web portal company that controls the database.

A: My suggestion would be to create a Datawarehouse schema ( star schema ) keeping as principal, one star schema per domain. For example one for sales, one for subscriptions, one for purchase, etc. Use the logic of Datamarts.
Identify your dimensions and your facts and keep evolving that schema. You will find out that you will end up with a much fewer number of tables.
Your data are not that big so you can use whatever ETL strategy you like.
Truncate load or incrimental.


text:
Q: How to dewarp an image taken by 360 fisheye lense? I was wondering, how the following is achieved (hopefully efficiently).
Turning this:

to this:

I have seen methods to dewrap (for example Circular Fisheye Image dewarp to flat image), but none of them target the case above.
EDIT
I managed to get camera matrix, distortion coefficients, rotation and translation vectors using the following line of code
ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1],None,None)

and then undistorting with:
dst = cv2.undistort(img, mtx, dist, None, None)

but i got garbage..


text:
Q: Check NTP trigger service with testinfra I have a service which triggers time update every 30 seconds on a linux system.Just running ntp is unfortunatetly not an option.
To make sure it's working properly I checked it with testinfra like that
assert host.service("mytimesynch").is_eanbled

but that's only half of the storry as the service runs for a second so is_running is not a valid test.
How to properly check if the service ended succesfully ?
Preferably with testinfra


text:
Q: The ring of $k[z_0, z_1, z_2, \ldots]/(z_{i+1}z_j - z_{i}z_{j+1})$ Let $A = k[z_0, z_1, z_2, \ldots]$ be the polynomial ring in countably many variables over a field $k$.  Let $I$ be the ideal generated by the polynomials $z_{i+1}z_j - z_{i}z_{j+1}$ and let $R = A/I$.
I'm trying to get a better sense of $R$.  For starters I thought it would be good to check that $R$ is a domain but already I'm struggling to formalize the proof.
One way I was thinking to pursue it was to first check that the homogeneous components of degree $d > 1$ of $R$ are freely generated as $k$-vector spaces by the elements $\bar{z}_0^{d-1} \bar{z}_i$ but I didn't like the way the proof was looking for $d > 2$.  Anyway, this approach is already unsatisfactory for me because I'm also interested in quotients of $k[z_0, z_1, z_2, \ldots]$ by homogeneous quadratic ideals that look like $I$ but are generated by $n$-sums of instead of $2$-sums.

A: Intuitively, if we let $z_1/z_0 = y$, then we find $z_i = z_0 y^i$ in $A/I$.
This suggests that we define a morphism $\varphi \colon A \to k[x,y]$ by $z_i \mapsto xy^i$.
It is easy to see that $I \subseteq \ker \varphi$. Conversely, let $f \in \ker \varphi$. Applying the relations in $I$, the polynomial $f$ is equivalent mod $I$ to some polynomial $g$ of the form
$$ h(z_0) + \sum_{i = 1}^n z_i g_i(z_0).$$
The fact that $g \in \ker \varphi$ then clearly implies $g = 0$, hence that $f \in I$. Thus $\ker \varphi = I$, and we have
$$A/I \approx k[x, xy, xy^2, \dots] = k \oplus xk[x,y].$$


text:
Q: Change option DHCP/BOOTP in dhcp reservation I'm using C# (Visual Studio 2010) to programmatically create a DHCP reservation.
I've used the information in this post to get the DHCPOBJECTS.DLL. Connecting to the DHCP server works well. I'm also able to create a new reservation or enumerate through existing reservations.
class CDHCP
{
    private Manager dhcpmgr;
    private Server dhcpsrvr;

    public CDHCP()
    {
        dhcpmgr = new Manager();
        dhcpsrvr = dhcpmgr.Servers.Connect("192.168.1.3");
    }

    public void create_reservation(string sName, string sAddress, string sDescription, string sMAC)
    {
        Reservation DHCPReservation = dhcpsrvr.Scopes["192.168.1.0"].Reservation.CreateNew();

        DHCPReservation.Name = sName;
        DHCPReservation.UniqueID = sMAC;
        DHCPReservation.Address = sAddress;
        DHCPReservation.Comment = sDescription;

        DHCPReservation.Update();
    }

    public void get_reservations()
    {
        List<Reservation> reservations = new List<Reservation>();

        for(int i = 1; i <= dhcpsrvr.Scopes.Count; i++)
        {
            for(int j = 1; j <= dhcpsrvr.Scopes[i].Reservations.Count; j++)
            {
                reservations.Add(dhcpsrvr.Scopes[i].Reserations[j]);
            }
        }
    }
}

Unfortunately when creating a new reservation the supported type is always set to "both". In our network we have to use only DHCP.
Anyone knows how to set the supported type to DHCP via the DHCPOBJECTS.DLL?
EDIT:
Okay it seems that I'm not able to change this option via DHCPOBJECTS.DLL.
Now I will try to realize this via the microsoft dhcp server management api


text:
Q: Is it possible that the Android translucent navigation bar "stains" the navigation drawer? Due to some "Full Screen" requirements of a screen, I'm temporarily hiding the status and navigation bars when showing a window and, when done, I'm showing them again. This goes pretty well but it leaves me with this weird situation:

On the left, we see the bottom of the navigation drawer before hiding and showing the translucent navigation bar and
on the right, we see how it looks after the operation. It looks as though the translucent bar left a stain on the navigation drawer! If wondering, if I use a different navigational system (eg. 2- or 3-button), the stain is as big as the new navigation bar:

The methods used to hide and show the system UI (status and navigation bars):
    /**
     * Use this method to (temporarily) hide the status bar and the navigation bar
     */
    private fun hideSystemUI() {
        window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)
        window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION)
        window.decorView.apply {
            systemUiVisibility = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_FULLSCREEN or View.SYSTEM_UI_FLAG_IMMERSIVE
        }
    }

    /**
     * Restore the status and navigation bars
     */
    fun showSystemUI() {
        window.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION)
        window.decorView.apply {
            systemUiVisibility =
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    View.SYSTEM_UI_FLAG_VISIBLE or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR or View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR
                } else {
                    View.SYSTEM_UI_FLAG_VISIBLE or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
                }
        }
    }

The situation persists until I restart the Activity that hosts the drawer.


text:
Q: What is the best way to only display some of the html elements in the ng-repeat loop I want to use an ng-if inside an ng-repeat (as described in this question):
However, I want to display a row in a table if and only if the if condition holds. In the answers to the question above, you will get empty div tags where the if condition does not hold. This does not cause much of a problem with divs, but when doing the same with tables, you do not want to have div (or span) tags inbetween tr tags.
Is there another tag or directive that I could use?

A: If you just want to hide these elements, you can consider using ng-show instead of ng-if.
Maybe you can also add the ng-show in the ng-if tag to hide it when empty.
Now, if you do not want to render the content at all, I think the only solution is to remove these elements from your collection in your controller

A: A better idea is to use a (custom) filter.
That way, only the needed rows are generated, in stead of hiding/removing existing ones.
I just made a plunk for another question, that showed how to use a filter:
the relevant line is this one:

you can use a object directly in your code like this:

If you put that line in the sample I linked in, you can see how that would work out!
Does this help you?

A: you can use ng-show.its works for show and hide tags.if you don't want to angular compile inside the tag you can use ng-if.


text:
Q: Php, simple locking against all request to have one I have a big cron (rebuild a cache) which requires to exclude all other request and hold them or stop them. So only one request should be running at one time.
Can this work out?
$f = fopen("lockfile", 'w+');
if (flock($f, LOCK_EX | LOCK_NB))
{
    sleep(10); // doing the work
}
else
{
    echo 'Come back later!';
}

may this work, even for Windows and Linux? No concurrencing threads then?

A: If it's really necessary to block clients while the cache is rebuilding, avoid the file locks and just create a file during maintenance, have the clients check for it, and delete it when done.
cron.php
<?php
//..
touch('/path/to/lockfile.dat');
//.. do work
unlink('/path/to/lockfile.dat');

other clients
<?php

if (file_exists('/path/to/lockfile.dat')) {
    die('Under maintenance, please check back shortly.');
}


text:
Q: How do I completely remove phpmyadmin? I messed up my phpmyadmin, I haven't logged in phpmyadmin for a while and as a result I forgot my password.
I decided to purge PHPMyAdmin:
sudo apt-get purge phpmyadmin

I did get some error messages asking for my password, but I forgot that, so I just pressed ignore, after that, I installed phpmyadmin again:
sudo apt-get install phpmyadmin

But now, when I logging to my phpmyadmin, I get a 404 not found error page!?

How do i completely remove phpmyadmin?

A: You might want to try sudo dpkg-reconfigure phpmyadmin

A: You have to remove total.  I mean sudo apt-get purge phpmyadmin*


text:
Q: A way to implement assignment by 'new' There are three way to use keyword 'new'.
First is the normal way. Suppose Student is a class.
Student *pStu=new Student("Name",age);

Second way . Only ask for the memory space without calling the constructor.
Student *pArea=(Student*)operator new(sizeof(student));//

Third way is called 'placement new'. Only call the constructor to initialize the meomory space.
new (pArea)Student("Name",age);

So, I wrote some code below.
class Student
{
private:
    std::string _name;
    int _age;
public:
    Student(std::string name, int age):_name(name), _age(age)
    {
        std::cout<<"in constructor!"<<std::endl;
    }
    ~Student()
    {
        std::cout<<"in destructor!"<<std::endl;
    }
    Student & assign(const Student &stu)
    {
        if(this!=&stu)
        {
            //here! Is it a good way to implement the assignment?
            this->~Student();

            new (this)Student(stu._name,stu._age);

        }
        return *this;
    }
};

This code is ok for gcc. But I'm not sure if it would cause errors or it was dangerous to call destructor explicitly. Call you give me some suggestions?

A: The problem with a "replacement-assignment" is that it's not exception safe. Consider this simplified, generic approach:
struct Foo
{
    Foo & operator=(Foo const & rhs)
    {
        if (this == &rhs) { return *this; }

        ~Foo();
        ::new (this) Foo(rhs);   // may throw!
    }

    // ...
};

Now if the copy constructor throws an exception, you're in trouble. You've already called your own destructor, so the inevitable next destructor call will cause undefined behaviour. You also cannot change the order of operations around, since you don't have any other memory.
I actually asked about this sort of "stepping on a landmine" behaviour in a question of mine.

A: Your suggestion is a major anti-pattern: if the new terminates
with an exception, you'll get undefined behavior, and if someone
tries to derive from your class, all sorts of weird things may
occur:
DerivedStudent a;
DerivedStudent b;
a = b;      //  Destructs a, and reconstructs it as a Student

and when a goes out of scope, it is the destructor of
DerivedStudent which will be called.
As a general rule, if you have to test for self-assignment, your
assignment operator is not exception safe.
The goal of this idiom, of course, is to avoid code duplication
between the copy constructor and the assignment operator, and to
ensure that they have the same semantics.  Generally, the best
way to do this is to use the swap idiom, or something similar:
Student&
Student::operator=( Student const& other )
{
    Student tmp( other );
    swap( tmp );
    return *this;
}

void
Student::swap( Student& other )
{
    myName.swap( other.myName );
    std::swap( myAge, other.myAge );
}

(One final, unrelated point.  In practice, you're going to run
into conflicts with names which begin with an underscore.  In
general, it's best to avoid leading or trailing underscore.)

A:
But I'm not sure if it would cause errors or it was dangerous to call destructor explicitly. Call you give me some suggestions?

The code as you wrote it has three major drawbacks:

*

*it is difficult to read

*it is optimized for the uncommon case (always performs the self assignment check although you rarely perform self assignment in practice)

*it is not exception safe
Consider using the copy and swap idiom:
Student & assign(Student stu) // pass stu by value, constructing temp instance
{                             // this is the "copy" part of the idiom
    using namespace std;
    swap(*this, stu); // pass current values to temp instance to be destroyed
                      // and temp values to *this
    return *this;
} // temp goes out of scope thereby destroying previous value of *this

This approach is exception-safe if swap doesn't throw and it has two potential drawbacks:

*

*if Student is part of a class hierarchy (has virtual members) creating a temporary instance will be more costly.

*in the case of self assignment the implementation should be a no-op (or a self equality test), but in that case it will create an extra object instance. The self-assignment case is very rare.


text:
Q: How do i get result which is bigger than an avg ( avg that i don't have )? I am very new to PostgreSQL and to this website. I need your help with this, please.
I need to get all months with more than average rain amount.
I tried this but its not working, may anyone explain?
Select month, rain from weather
where rain > avg(rain)
group by month , rain;

Thanks a lot.

A: Try this
SELECT month FROM (SELECT month, avg(rain) avg_rain FROM weather GROUP BY month) a
CROSS JOIN
(SELECT avg(rain) rain FROM weather) b
WHERE avg_rain > rain

A: WITH rain_avg_by_month AS (
  SELECT month, AVG(rain) AS rain_avg
  FROM weather
  GROUP BY month
), total_rain_avg AS (
  SELECT AVG(rain_avg)
  FROM rain_avg_by_month
)
SELECT month
FROM rain_avg_by_month, total_rain_avg
WHERE rain_avg_by_month.rain_avg > total_rain_avg.avg
;

A: select * from (
    select
            month,
            rain,
            avg(rain) over() avg_rain
        from weather
    ) t
    where rain > avg_rain;

Here we assume there is one record per month. First query (the nested one) gives us all months and corresponding rain values along with average rain value (we use window function avg over all records in set). Then the outer query gives us what we need: months where rain value is greater than average rain value.


text:
Q: Numpy Typehint with nptyping and Array in PyCharm I try to use numpy with nptyping's Array to do my typehinting.
I tried the following:
enemy_hand: Array[float, 48] = np.zeros(48)

I get an typerror:

Expected Type 'Array[float, Any]', got 'ndarray' instead

as far as I understand from this: https://pypi.org/project/nptyping/ thats how it should look.

A: nptyping is currently useless for static analysis. Quoting a post by the library's developer on its issue tracker,

mypy is just not supported by nptyping (yet)

I wouldn't put much hope in that "yet". NumPy's dtype and shape handling is very hard to fit into the typing/mypy static type model, and nptyping's own design decisions are a poor fit for NumPy itself. For example, it doesn't look like the dev ever considered arrays that aren't 2D, so Array[str, 3] represents a 2D array with 3 rows and unspecified columns instead of a 3-element 1D array. All the implementation is in terms of rows and columns, too.
As far as I can tell, the only real functionality nptyping has is isinstance checks, and even that's buggy.


text:
Q: How to custom the color of each bar of a bar chart in flutter? I am new to flutter and try to build a bar chart with different colors. I use the chart dependency provided by google.
https://google.github.io/charts/flutter/gallery.html
However, I find I could only change the color of all bars. Is there anyway I could custom the color of one specific bar?
I have searched online and no such information are posted.

A: To expand on what Hemanth is referring to, colorFn is a property that takes a function that returns a color.
So if you do something like:
colorFn: (_, __) => charts.MaterialPalette.blue.shadeDefault

You're going to be returning the same color for every segment in the series.
To set different colors for individual segments within a series you can do something like this:
class ExampleSegment {
  final String segment;
  final int size;

  ExampleSegment(this.segment, this.size);
}

static List<charts.Series<ExampleSegment, String>> _createSampleData() {
  final blue = charts.MaterialPalette.blue.makeShades(2);
  final red = charts.MaterialPalette.red.makeShades(2);
  final green = charts.MaterialPalette.green.makeShades(2);

  final data = [
    new ExampleSegment('First', 100),
    new ExampleSegment('Second', 100),
    new ExampleSegment('Third', 100),
    new ExampleSegment('Fourth', 100),
  ];

  return [
    new charts.Series<ExampleSegment, String>(
        id: 'Segments',
        domainFn: (ExampleSegment segment, _) => segment.segment,
        measureFn: (ExampleSegment segment, _) => segment.size,
        data: data,
        colorFn: (ExampleSegment segment, _) {
          switch (segment.segment) {
            case "First":
              {
                return blue[1];
              }

            case "Second":
              {
                return red[1];
              }

            case "Third":
              {
                return green[1];
              }

            case "Fourth":
              {
                return blue[0];
              }

            default:
              {
                return red[0];
              }
          }
        }
      ),
  ];
}

A: There is a colorFn property taken by the Series with which you can specify a stroke.
Check this out!
Hope that helps!


text:
Q: Label Not Showing Progress Bar % VB.Net I am trying to get a Label to show the % of the Progress bar in a Windows Form using VB.Net 2019 but for some reason, the label is not updating.
If I substitute the Label for the Forms text then it works but I cant see why using the Label will not work.
I must be missing something obvious but I cannot see what!
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    ProgressBar.Visible = True
    For i As Integer = 0 To 10
        Dim percent As Integer = i * 10
        ProgressBar.Value = percent
        Label1.Text = percent & "%" '<-- This does not show the %
        Me.Text = percent & "%" '<-- This does show the %
        Thread.Sleep(100)
    Next
    ProgressBar.Visible = False
End Sub

A: Refreshing the label did the trick.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    ProgressBar.Visible = True
    For i As Integer = 0 To 10
        Dim percent As Integer = i * 10
        ProgressBar.Value = percent
        Label1.Text = percent & "%"
        Label1.Refresh() '<--This updated the Label
        Thread.Sleep(100)
    Next
    ProgressBar.Visible = False
End Sub

A: You can also use Task.Delay
Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    ProgressBar.Visible = True
    For i As Integer = 0 To 10
        Dim percent As Integer = i * 10
        ProgressBar.Value = percent
        Label1.Text = percent & "%"
        Await Task.Delay(500)
    Next
    ProgressBar.Visible = False
End Sub


text:
Q: Why is my post request returning a 405 error? I'm trying to make a post request to firebase via my vue app and i keep getting this error image
I'm running a webpack server and the website is on localhost:8080 however I also have a live version hosted on hostinger this is the site http://arestate.online/ and when I click on add new blog, after filling out the details and clicking post it throws the CORS error too.
I've added and modified a .htaccess file to include this  IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
/IfModule>  (with the tags closed properly, I just modified them so they would show up on stack overflow)
IF anyone could offer me assistance that would be superb!

A: You have to define which methods can be used by the remote origin with the 'Access-Control-Allow-Methods' header, example:

Access-Control-Allow-Methods: OPTIONS, HEAD, GET, POST

See https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

A: I think is better if you use the firebase Lib from npm. REST API of firebase Database is extrem ineficcent because it downloads many unuseful data and you need to keep in mind that firebase bills the amount of downloaded data. But you don't specify which module you are using. It would be also great if you post the code.


text:
Q: Topology for sets in $\mathbb{R^2}$ and $\mathbb{R^3}$ I have a question regarding topology of sets in $\mathbb{R^2}$ and $\mathbb{R^3}$. The question is as follows:
For each $A \subset \mathbb{R^3}$, we define $P(A) \subset \mathbb{R^2}$ by \begin{equation} P(A) := \{(x,y)\  |\ \exists\ z \in \mathbb{R}: (x,y,z) \in A\}.\end{equation}
I have the following statements:
"If A is open (in $\mathbb{R^3}$), then $P(A)$ is open (in $\mathbb{R^2}$)."
"If A is closed (in $\mathbb{R^3}$), then $P(A)$ is closed (in $\mathbb{R^2}$)."
"If A is compact (in $\mathbb{R^3}$), then $P(A)$ is compact (in $\mathbb{R^2}$)."
I think that the first statement is true, but I am in doubt about the second one. I was thinking of a set $A = \{(x,y,z)\  | \ x^2 + y^2 < 1, -1 \leq z \leq 1\}$, but I am now sure whether I am going in the correct direction. Could anyone help me out? Thanks in advance!

A: Have a look at the classical projection function:
$$\pi:\mathbb{R}^3\to\mathbb{R}^2$$
$$\pi(a,b,c)=(a,b)$$
and note that
$$P(A)=\pi(A)$$
where on the right side is the image of $A$ via $\pi$.

*

*Now the first statement is equivalent to the statement that the projection is an open map which is true.

*Second statement is not true. Generally projections are not closed maps. For example take
$$A=\bigg\{\big(0, x, \frac{1}{x}\big)\ \bigg|\ x>0\bigg\}$$
This set is closed, however $\pi(A)=\big\{(0,x)\ \big|\ x>0\big\}$ is not.

*

*The third statement is true because $\pi$ is continous so the image of a compact set is compact. Note that $A$ from the previous example is not compact.

A: The general def'n of the Tychonoff-product topology on $S(J)=\prod_{j\in J}S_j$ when each $S_j$ is a top'l space is that it is the weakest  topology such that  for each $a\in J$ the projection $p_a(\;(x_j)_{j\in J}\;)=x_a$ is continuous.
Any $A\subset S(J)$  is open in this topology iff the following holds: For each $x=(x_j)_{j\in J}\in A$, there exists $A(x)=\prod_{j\in J}B_j \subset A$ such that (I)... $x\in A(x)$, and (II)... each $A_j$ is open in $S_j$ and  (III)... $\{j\in J: A_j\ne S_j\}$ is finite.
It follows that if $K\subset J$ and $P_K(\;(x_j)_{j\in J}\;)=(x_k)_{k\in K}$ then $P_K$ is a continuous open mapping from $S(J)$ to $S(K)=\prod_{k\in K}S_k.$ (A function is called an open mapping iff the image of each open set is open.)
In particular, when $J$ is finite then $A$ is open  in $S(J)$ iff for each $x=(x_j)_{j\in J}\in A$ there exists $A(x)=\prod_{j\in J}A_j\subset A$ with $x\in A(x)$, where each $A_j$ is open in $S_j.$ And hence  if $K\subset J$ then the image $P_K(A)$ satisfies $P_K(x)\in \prod_{k\in K}A_k\subset P_K(A),$ so $P_K(A)$ is open in $S(K)$.
For example, in your Q we have $J=\{1,2,3\}$ and $K=\{1,2\}$ and each $S_j=\mathbb R.$  Let $A$ be open in $S_J=\mathbb R^3.$ For any $(x,y,z)\in A\subset S(J)$  there exist open subsets $A_1,A_2,A_3$ of $\mathbb R$ such that $(x,y,z)\in A_1\times A_2\times A_3\subset A .$  So $(x,y)\in A_1\times A_2\subset P_K(A)$. This holds for every $(x,y,z)\in A$  so $P_K(A)$ is open in $S(K)=\mathbb R^2.$


text:
Q: How to create and access multiple children of the root node in Firebase Database? I need to access the books field in the database. I have created a fragment with a recyclerview that displays the books. What I needed in the app is that each user should be able to request only one book. So I created another node directly under the root node as "users", but after adding the "users" node the recyclerview is not working properly. This is how the database looks after adding "users". Database Snapshot
Here is the Before Recyclerview:
Before Adding users field
Here is the After RecyclerView:
After Adding users field
Here is the exported json code from firebase database.`
{
  "books" : {
    "BOOK 1 BY AUTHOR 1": {
      "author" : "Author 1",
      "category" : "CLASSICAL",
      "description" : "",
      "image" : "NO_IMAGE",
      "requested" : "NO",
      "requester" : "NO_ONE",
      "title" : "Book 1"
    },
    "BOOK 2 BY AUTHOR 2" : {
      "author" : "Author 2",
      "category" : "SPIRITUALITY",
      "description" : "",
      "image" : "NO_IMAGE",
      "requested" : "NO",
      "requester" : "NO_ONE",
      "title" : "Book 2"
    },
    "BOOK 3  BY AUTHOR 3" : {
      "author" : "author 3",
      "category" : "ADVENTURE",
      "description" : "",
      "image" : "NO_IMAGE",
      "requested" : "NO",
      "requester" : "NO_ONE",
      "title" : "book 3 "
    }
  },
  "user" : {
    "User1" : {
      "requestedBook" : "no"
    },
    "User2" : {
      "requestedBook" : "yes"
    }
  }
}

`This is the fragment code.
    package club.bms.keshav.readersreserve.fragments;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;

import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.util.ArrayList;
import java.util.List;

import club.bms.keshav.readersreserve.NewBookAttributes;
import club.bms.keshav.readersreserve.R;
import club.bms.keshav.readersreserve.dataHelper.Book;
import club.bms.keshav.readersreserve.dataHelper.BooksAdapter;

public class HomeFragment extends Fragment{
    private static final String TAG = "HomeFragment";
    RecyclerView.LayoutManager mLayoutManager;
    RecyclerView recyclerView;
    List<Book> bookList = new ArrayList<>();
    BooksAdapter adapter;
    private ChildEventListener childEventListener;
    private ProgressBar progressBar;
    private DatabaseReference databaseReference;
    public HomeFragment() {
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setHasOptionsMenu(true);
        Log.d(TAG, "onCreate: ");
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable final ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.activity_recyclerview_declaration, container, false);
        view.setBackgroundResource(R.color.white);
        Log.d(TAG, "onCreateView: background color set");
        recyclerView = view.findViewById(R.id.recycler_view);
        progressBar = view.findViewById(R.id.progress_bar_home_fragment);
        recyclerView.setVisibility(View.GONE);
        progressBar.setVisibility(View.VISIBLE);
        final Context context = view.getContext();
        FloatingActionButton fab = (FloatingActionButton) view.findViewById(R.id.add_book_fab);

        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(context, NewBookAttributes.class));
            }
        });

        mLayoutManager = new GridLayoutManager(view.getContext(), 2, GridLayoutManager.VERTICAL, false);

        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        Log.d(TAG, "onCreateView: recyclerview set without adapter");
         databaseReference = FirebaseDatabase.getInstance().getReference();
         databaseReference.keepSynced(true);
        Log.d(TAG, "onCreateView: database ref created");
        childEventListener = new ChildEventListener() {
            @Override
            public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
                Log.d(TAG, "onChildAdded: ");
                getAllBooks(dataSnapshot, context);
            }

            @Override
            public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
                Log.d(TAG, "onChildChanged: ");
                getAllBooks(dataSnapshot, context);
            }

            @Override
            public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {
                taskDeletion(dataSnapshot, context);
            }

            @Override
            public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {

            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        };
            databaseReference.addChildEventListener(childEventListener);
        Log.d(TAG, "onCreateView: added listener");
         return view;
    }

    private void taskDeletion(DataSnapshot dataSnapshot, Context context) {

        for(DataSnapshot snapshot: dataSnapshot.getChildren())
        {
            Book book = snapshot.getValue(Book.class);
            Book tempBook = new Book();
            tempBook.setAuthor(book.getAuthor());
            tempBook.setTitle(book.getTitle());
            tempBook.setDescription(book.getDescription());
            for(int i=0;i<bookList.size();i++)
            {
                Book b = bookList.get(i);
                if(b.getAuthor().equals(tempBook.getAuthor()) && b.getTitle().equals(tempBook.getTitle()))
                {
                    bookList.remove(i);
                }
            }
        }
        adapter = new BooksAdapter(context, bookList);
        adapter.notifyDataSetChanged();
        recyclerView.setAdapter(adapter);
        Log.d(TAG, "taskDeletion: adapter set");

    }

    private  void getAllBooks(DataSnapshot dataSnapshot, Context context) {

       bookList.clear();
        Book book;
        for(DataSnapshot dataSnapshot1: dataSnapshot.getChildren()) {
            book = dataSnapshot1.getValue(Book.class);
            bookList.add(book);
        }
        adapter = new BooksAdapter(context, bookList);
        recyclerView.setAdapter(adapter);
        progressBar.setVisibility(View.GONE);
        recyclerView.setVisibility(View.VISIBLE);
        Log.d(TAG, "getAllBooks: adapter set");
        }

    @Override
    public void onDetach() {
        super.onDetach();
        databaseReference.removeEventListener(childEventListener);
        Log.d(TAG, "onDetach: removed listener");
    }
}

When I add the "users" node programmatically, the card view becomes empty, and on clicking the card view, it gives NullPointerException.
Here is the code for the RecyclerView Adapter
    package club.bms.keshav.readersreserve.dataHelper;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;

import java.util.List;

import club.bms.keshav.readersreserve.ConstantFields;
import club.bms.keshav.readersreserve.GlideApp;
import club.bms.keshav.readersreserve.R;
import club.bms.keshav.readersreserve.Single_Book_Activity;

class   RecyclerViewHolder extends RecyclerView.ViewHolder implements View.OnLongClickListener, View.OnClickListener {
    public TextView mAuthor, mTitle, mCategory;
    public ImageView mBookImage;
    //public TextView btn, mauthor;

    private ItemClickListener itemClickListener;

    public RecyclerViewHolder(@NonNull View itemView) {
        super(itemView);
        mAuthor = itemView.findViewById(R.id.textV_book_author);
        mTitle = itemView.findViewById(R.id.textV_book_title);
        mBookImage = itemView.findViewById(R.id.image_for_book);
        mCategory = itemView.findViewById(R.id.textV_book_category);
        //        mStatus = itemView.findViewById(R.id.textV_book_status);
        itemView.setOnClickListener(this);
        itemView.setOnLongClickListener(this);

    }

    public void setmBookImage(String path, final Context context)
    {
        if(path == null || path.equals(ConstantFields.NO_IMAGE))
        {
            Glide.with(context)
                    .load(R.drawable.default_book_cover)
                    .into(mBookImage);
        }
        else{
            StorageReference storageReference = FirebaseStorage.getInstance().getReference().child("images/" + path + "/" + path + " cover");

            GlideApp.with(MyApp.getAppContext())
                    .load(storageReference)
                    .apply(new RequestOptions()
                            .placeholder(R.drawable.rolling_placeholder)
                            .error(R.drawable.default_book_cover)
                    )
                    .into(mBookImage);
        }

    }

    public void setItemClickListener(ItemClickListener itemClickListener) {
        this.itemClickListener = itemClickListener;
    }

    @Override
    public void onClick(View v) {
        itemClickListener.onClick(v, getAdapterPosition(), false);
    }

    @Override
    public boolean onLongClick(View v) {
        itemClickListener.onClick(v, getAdapterPosition(), true);
        return true;
    }
}

public class BooksAdapter extends RecyclerView.Adapter<RecyclerViewHolder> {
    private Context mContext;
    private List<Book> bookList;
    private Book book;
    private ItemClickListener itemClickListener = new ItemClickListener() {
        @Override
        public void onClick(View view, int position, boolean isLongClicked) {
            if (isLongClicked) {

//                AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
//                builder.setMessage("DELETE");
//                AlertDialog dialog = builder.create();
//                dialog.show();

                //DO SOMETHING
            } else {
                Intent intent = new Intent(mContext, Single_Book_Activity.class);
                Bundle args = new Bundle();
                book = bookList.get(position);
                args.putSerializable("bookObject", book);
                intent.putExtras(args);
                mContext.startActivity(intent);
            }
        }
    };

    public BooksAdapter(Context mContext, List<Book> bookList) {
        this.mContext = mContext;
        this.bookList = bookList;
    }

    @NonNull
    @Override
    public RecyclerViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.book_list_row, parent, false);
        return new RecyclerViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerViewHolder holder, int i) {
        book = bookList.get(i);
        holder.mAuthor.setText(book.getAuthor());
        holder.mTitle.setText(book.getTitle());
        holder.mCategory.setText(book.getCategory());
        holder.setmBookImage(book.getImage(), mContext);
        holder.setItemClickListener(itemClickListener);
    }

    @Override
    public int getItemCount() {
        return bookList.size();
    }

}

Is there any other way using which, I can apply the one user, one book rule?
On changing the code to
      databaseReference = FirebaseDatabase.getInstance().getReference().child(ConstantFields.CHILD_BOOK);
         bookRef = databaseReference.child(ConstantFields.CHILD_BOOK);
bookRef.addChildEventListener(...);

I can add the books successfully to the desired position in the database(I have no idea how), but OnChildAdded() or onChildChanged() method does not get called, hence the progress bar keeps on displaying infinitely, and the books are not displayed

A: Check your database reference.
database = FirebaseDatabase.getInstance.getReference

this will check the whole of your database.
Your child event listener should check to database.child("books")
DatabaseReference db = FirebaseDatabase.getInstance.getReference
dbBooks = db.child("books")
dbBooks.addChildEventListener(new ChildEventListener{
}

A: I think JJ Swart's answer is right, problem here is your BookReference refererences to whole of your data instead of only your "books's data". Can you show us your Exception info to see what's really your error after you changes the reference to "books".


text:
Q: Not able to run Tests in VS code I am fairly new to programming( 1st year CompSci). I decided to write my java code in VSCode. I Have a test file but whenever i try to run the test i get the following errors in the Debug Console:-
Unrecognized option: -ea,--enable-preview

Error: Could not create the Java Virtual Machine.

Error: A fatal exception has occurred. Program will exit.

I have a "lib" folder in the folder containing my java and test file which contains the junit-platform-console-standalone-1.5.2.jar
If I click on Debug Test , I get a popup error saying
"Failed to launch debuggee VM. Reason: com.sun.jdi.connect.VMStartException: VM did not connect within given time: 10000ms"

Any Ideas on how to fix this please?
Thank You.

A: I had a silimar error, the problem was that the path where my project was in the workspace had blank spaces, for example:
C:\Users\user\my workspace\proyect ----solution----> C:\Users\user\myWorkspace\proyect

A: Fixed it myself. Apparently something wasn't correctly configured in my VSCode installation.
I just  reinstalled it along with the java extensions and everything works fine now


text:
Q: Custom Membership Provider Umbraco Issues I'm looking to use a custom membership provider to authenticate Umbraco members against an Active Directory however I'm having issues with adding the additional provider into the web.config file.
When I add the extra string in to reference the AD provider all of my Umbraco macros fail with the "Error loading MacroEngine" error. Below is my string, are there any obvious problems with it?
<add name="MyADMembershipProvider"
type="System.Web.Security.ActiveDirectoryMembershipProvider, System.Web,
Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
connectionStringName="LDAPConnection" connectionUsername="DOMAIN\USER"
connectionPassword="REMOVED" connectionProtection="None" />

LDAP connection string:
<add name="LDAPConnection" connectionString="LDAP://SERVER.DOMAIN.co.uk:389/DC=DOMAIN,DC=co,DC=uk" />

Thanks for any help you can offer, really at a stuck point with this!


text:
Q: Как быстрее всего заполнить DataTable (для DataGridView)? Конкретным новичком себя назвать не могу, раньше уже с С# дело имела, как и с DataGridView (дальше DGV), но раньше до скорости загрузки данных дела не было (данных было мало, да и сами БД по структуре были достаточно простые), а вот сейчас стал вопрос ускорения загрузки данных в DGV. Скажу сразу, что в коде не использую запросы SQL, в качестве БД использую Firebase.
Сейчас использую такую конструкцию:
Формирование столбцов таблицы:
            dt.Columns.Add("ID");
            dt.Columns.Add("КЗ");
            dt.Columns.Add("ДЗ");
            dt.Columns.Add("Студент");
            dt.Columns.Add("Дисципліна");
            dt.Columns.Add("Тип");
            dt.Columns.Add("Дата");
            UploadTable();

Собственно сама загрузка данных в DGV (вернее, код автоматического обновления таблицы после создания/обновления/удаления оценок):
            List<BLL.DTOs.MarkDTO> temp = marksService.GetMarksByInstitute(institute);
            dt.Rows.Clear();

            foreach (var elem in temp)
            {
                DataRow row = dt.NewRow();
                row["ID"] = elem.ID;
                row["КЗ"] = elem.Short_Value;
                row["ДЗ"] = elem.Long_Value;
                row["Студент"] = studentsService.GetFIOByID(elem.Student_ID);
                row["Дисципліна"] =
                disciplinesService.GetNameById(elem.Discipline_ID);
                row["Тип"] = elem.Type;
                row["Дата"] = elem.Date;

                dt.Rows.Add(row);
            }

            DataView dataView = new DataView(dt);
            dataGridView1.DataSource = dataView;

При такой конструкции загрузка 20-25 записей занимает около 12-14 секунд, что явно многовато, учитывая, что записей по плану будет явно больше чем 20. Немного изменив код:
            dt.Columns.Add("ID");
            dt.Columns.Add("КЗ");
            dt.Columns.Add("ДЗ");
            dt.Columns.Add("Студент");
            dt.Columns.Add("Дисципліна");
            dt.Columns.Add("Тип");
            dt.Columns.Add("Дата");
            dataGridView1.DataSource = dt;
            UploadTable();

List<BLL.DTOs.MarkDTO> temp = marksService.GetMarksByInstitute(institute);
            dt.Rows.Clear();
            foreach (var elem in temp)
            {
                DataRow row = dt.NewRow();
                row["ID"] = elem.ID;
                row["КЗ"] = elem.Short_Value;
                row["ДЗ"] = elem.Long_Value;
                row["Студент"] = studentsService.GetFIOByID(elem.Student_ID);
                row["Дисципліна"] = disciplinesService.GetNameById(elem.Discipline_ID);
                row["Тип"] = elem.Type;
                row["Дата"] = elem.Date;

                dt.Rows.Add(row);
            }

получаю примерно те же результаты (разве что, записи появляются не сразу в таблице, а постепенно по одной, что, конечно, интересно наблюдать, но все равно это долговато).
Понимаю, что, скорее всего, решение простое, но я реально пока не знаю что делать. Очень хочется, что бы результаты прогружались достаточно быстро (в пределах 3 секунд, в идеале).
Иными словами, есть список оценок (второй фрагмент кода, переменная temp), и нужно быстро перенести его в DGV.
Функция UploadTable - это как раз тот второй кусок кода.
Данные сервисы получают данные с одной и той же удаленной БД (я упоминала Firebase).
Я тоже сначала проверила именно сервисы, но их я уже изменила, и они запросы выполняют достаточно быстро.
Основная проблема - именно с отрисовкой самой таблицы. Вариантом присвоения списка свойству DataSource я воспользовалась, и теперь таблица прогружается и обновляется реально быстро (1-2 секунды) даже при большом кол-тве данных, но появилось два нюанса - столбцы переименовались с нормальных названий на названия полей, и значения в строках повторяет в точности значения объектов в списке.
Вопрос с названиями столбцов решился (топорно, правда, но работает) - я просто в коде создаю столбцы.
dataGridView1.Columns.AddRange(
        new DataGridViewTextBoxColumn() { Name = "clmID", HeaderText = "ID", DataPropertyName = "ID" },
        new DataGridViewTextBoxColumn() { Name = "clmShortValue", HeaderText = "КЗ", DataPropertyName = "Short_Value" },
        new DataGridViewTextBoxColumn() { Name = "clmLongValue", HeaderText = "ДЗ", DataPropertyName = "Long_Value" },
        new DataGridViewTextBoxColumn() { Name = "clmStudent", HeaderText = "Студент", DataPropertyName = "Student_ID" },
        new DataGridViewTextBoxColumn() { Name = "clmDiscipline", HeaderText = "Дисципліна", DataPropertyName = "Discipline_ID" },
        new DataGridViewTextBoxColumn() { Name = "clmType", HeaderText = "Тип", DataPropertyName = "Type" },
        new DataGridViewTextBoxColumn() { Name = "clmDate", HeaderText = "Дата", DataPropertyName = "Date" },
        new DataGridViewTextBoxColumn() { Name = "clmTeacher", HeaderText = "Викладач", DataPropertyName = "Teacher_ID" }
        );

Что до основной проблемы (скорость), то да, обращений действительно много (и там циклы, что замедляет работу). Решение вижу в Linq, так что буду рефакторить остальной код приложения.


text:
Q: Am i doing it in right wat? predict stock price I prepared csv file with the input data for neural network, and csv file where i can test my neural network. The results are not satisfactory. I was trying increase/decrease size of input data. Probably i missing something and i would be glad if someone can some tips etc. Here is my encog code:
    //input data
    File file = new File("path to file");
    CSVFormat format = new CSVFormat('.', ',');
    VersatileDataSource source = new CSVDataSource(file, false, format);
    VersatileMLDataSet data = new VersatileMLDataSet(source);
    data.getNormHelper().setFormat(format);

    ColumnDefinition wig20OpenN = data.defineSourceColumn("wig20OpenN", 0, ColumnType.continuous);
    (...)

    ColumnDefinition futureClose = data.defineSourceColumn("futureClose", 81, ColumnType.continuous);

    data.analyze();
    data.defineSingleOutputOthersInput(futureClose);
    EncogModel model = new EncogModel(data);

    //TYPE_RBFNETWORK, TYPE_SVM, TYPE_NEAT, TYPE_FEEDFORWARD <- this type of method i was trying
    model.selectMethod(data, MLMethodFactory.TYPE_SVM);
    model.setReport(new ConsoleStatusReportable());

    data.normalize();

    model.holdBackValidation(0.001, true, 10);
    model.selectTrainingType(data);
    MLRegression bestMethod = (MLRegression)model.crossvalidate(20, true);
    // Display the training and validation errors.
    System.out.println( "Training error: " + model.calculateError(bestMethod, model.getTrainingDataset()));
    System.out.println( "Validation error: " + model.calculateError(bestMethod, model.getValidationDataset()));
    NormalizationHelper helper = data.getNormHelper();

    File testingData = new File("path to testing file");
    ReadCSV csv = new ReadCSV(testingData, false, format);
    String[] line = new String[81];
    MLData input = helper.allocateInputVector();
    while(csv.next()) {
            StringBuilder result = new StringBuilder();

            for(int i = 0; i <81; i++){
            line[i] = csv.get(i);
        }

            String correct = csv.get(81);
            helper.normalizeInputVector(line,input.getData(),false);
            MLData output = bestMethod.compute(input);
            String irisChosen = helper.denormalizeOutputVectorToString(output)[0];

            result.append(Arrays.toString(line));
            result.append(" -> predicted: ");
            result.append(irisChosen);
            result.append("(correct: ");
            result.append(correct);
            result.append(")");

            System.out.println(result.toString());
        }

        // Delete data file and shut down.
        filename.delete();
        Encog.getInstance().shutdown();

What i was trying so far is to change the MLMethodFactory, but had problems here, only TYPE_RBFNETWORK, TYPE_SVM, TYPE_NEAT, TYPE_FEEDFORWARD this type works fine, for example if i changed it to TYPE_PNN i had following exception:
Exception in thread "main" org.encog.EncogError: Please call selectTraining first to choose how to train.

Ok i know from documentation that i should use this method:
selectTraining(VersatileMLDataSet dataset, String trainingType, String trainingArgs)

But the string type for traningtype and triningArgs is confusing.
And last question what about saving the neural after traning to file, and loading it to check on the traning data? As i would like to have this separately.
Edit: I forgot the size of the input data is 1500.

A: I see that you not satisfied with your results, but it is relatively fine. I propose you to consider adding scaling to your training. You have 81 columns, and in your input row I see data like 16519.1600, also 2315.94, and even -0.6388282285709328. For neural network it is hard to adjust weights correctly for such different inputs.
P.S. scaling is also normalizing of columns!. As usually in books is described normalizing of rows, but normalizing of columns is also important.


text:
Q: Exploding tensor after using Dataset and .batch I have a numpy array of shape (100,4,30). This represents 100 samples of 4 samples of encodings of length 30. The 4 samples, per row, are related.
I want to get a TensorFlow dataset, batched, where related samples are in the same batch.
I'm trying to do:
first, use np.vsplit to get a list of length 100, where each element in the list is a list of the 4 related samples.
Now if I call tf.data.Dataset.from_tensor_slices(...).batch(1) on this list of lists, I get a batch that contains a tensor of shape (4,1,30).
I want this batch to contain 4 tensors of shape (1,30).
How can I achieve this?

A: I may have missunderstood you, but if you just leave out the "vsplit":
data = np.zeros((100, 4, 30))
data_ds = tf.data.Dataset.from_tensor_slices(data).batch(1)
for element in data_ds.take(1):
    print(element.shape)

you will get:
(1, 4, 30)

(so one batch contains all 4 related encodings).
If you really want the dimensions inside a batch to be 4 times (1, 30) you can do:
data = np.expand_dims(data, axis=2)

before dataset creation.
EDIT:
I think I just understood your question. You want every batch to have 4 elements and those are the related encodings? You can achieve this by:
data = np.swapaxes(data, 0, 1)
data = np.reshape(data, (100*4, -1))
data_ds = tf.data.Dataset.from_tensor_slices(data).batch(4)


text:
Q: How can I fix pitch black self-shadows? I started a new project and all the self-shadows look like in the image below.

How can I fix this?

A: You can change the ambient light of the scene in Window > Lighting > Settings > Environment Light.
I got this from this question on the Unity forum: Shadows Are Too Dark.

A: Based on the direction of your shadows. I think you are using a directional light. If you want your scene to be equally lit or dim with some factor. Ambient Light is the type of light you have to use along with your current Directional or other types of light in your scene. By balancing out between Ambient Light intensity and your scene lights you can get the results you are aiming for.
For detailed documentation:
https://docs.unity3d.com/Manual/lighting-ambient-light.html
https://docs.unity3d.com/Manual/lighting-window.html