text:
Q: How to prove that a sequence is Cauchy How do I show if $x_n = \frac{n^2}{n^2 -1/2}$ is a Cauchy sequence? (using the definition of Cauchy sequence)
My attempt: A sequence is Cauchy if $ \forall \epsilon>0$ $ \exists N \in \mathbb N$ $\forall m,n \geq N$ :|$x_n -x_m$|$\leq \epsilon$
|$x_n -x_m|=|\frac{n^2}{n^2 -1/2} -\frac{m^2}{m^2 -1/2}$| $\leq|\frac{n^2}{n^2 -1/2}-1|+|1-\frac{m^2}{m^2 -1/2}|= 1/2|\frac{1}{n^2 -1/2}|+1/2|\frac{1}{m^2 -1/2}|$
$1/2|\frac{1}{n^2 -1/2}| \leq \epsilon$ and also $1/2|\frac{1}{m^2 -1/2}| \leq \epsilon$
So $1/2|\frac{1}{n^2 -1/2}|+1/2|\frac{1}{m^2 -1/2}| \leq 2 \epsilon$
if we choose $N \in \mathbb N$ such that $N >\sqrt{\frac{\epsilon}{2}+\frac{1}{2}}$

A: Easier:
$$x_n = \frac{1}{1-\frac{1}{2n^2}} \stackrel{n \to \infty}\longrightarrow 1$$
and convergent sequences are Cauchy sequences.

A: Your penultimate line is unnecessary. You actually want $N>\sqrt{\frac{1}{2\epsilon}+\frac12}$ to ensure $|x_n-x_m|<2\epsilon$. Usually, we'd instead prove $|x_n-x_m|<\epsilon$ is achievable, with $\min\{m,\,n\}>\sqrt{\frac{1}{\epsilon}+\frac12}$.

A: In this case, you can easily conclude that it is Cauchy because it converges for $n \rightarrow \infty$

A: The definition you posted is correct. Note though that
$$
x_n
 = \frac{n^2}{n^2-1/2}
 = 1 + \frac{1/2}{n^2-1/2},
$$
and it's clear this is a sequence which decreases to $1$, so $x_{n+1} < x_n$ for all $n$. (You could at this point claim that since the sequence is convergent, it is also Cauchy, but if you need a proof from the fundamentals, read on).
Assuming $N<m<n$,
$$
\begin{split}
\left|x_m - x_n\right|
 &= x_m - x_n \\
 &= \left(1 + \frac{1/2}{m^2-1/2} - 1 - \frac{1/2}{n^2-1/2}\right) \\
 &= \frac12 \left(\frac{1}{m^2-1/2} - \frac{1}{n^2-1/2}\right) \\
 &= \frac12
    \left(\frac{n^2 - m^2}
               {\left(m^2-1/2\right)\left(n^2-1/2\right)}\right) \\
 &\le \frac12
    \left(\frac{n^2}
               {\left(m^2-1/2\right)\left(n^2-1/2\right)}\right) \\
 &\le \frac{1/2}{m^2-1/2} \left(\frac{n^2}{n^2-1/2}\right)\\
 &\le \frac{1/2}{m^2-1/2} \left(1 + \frac{1/2}{n^2-1/2}\right)\\
 &\le \frac{1}{m^2-1/2}\\
 &\le \frac{1}{N^2}.
\end{split}
$$
Can you find what $N$ you need to pick in terms of $\epsilon$ to have that expression $< \epsilon$ in the end?


text:
Q: How to expose properties of a WPF DataTemplate? I have a data template that I use in many pages, the data template contains a few buttons, I want to hide some of these buttons by triggers (I mean setting the IsEnabled Property of these buttons in the page where I use this DataTemplate).
In other words, I would even like to set in style triggers/setters a property 'ButtonXIsEnabled', 'ButtonYIsEnabled' as part of the DataTemplate settable from the ListBox where I use this DataTemplate.
I really hope I am clear enough, please leave comments for any further details.
Any discussion will be really appreciated!
Thanks in advance.

A: Basically this depends on what object your using for your datatemplate.  Instead of using some ButtonYIsEnabled, etcs.  Try to use some words that fit better in to your domain model.
For example say you have a list of customers, and some of those customers have the ability to purchase discounted products.  Then add a property to your Customer called CanPurchaseDiscountedProducts, and use that property in your DataTemplate
<DataTemplate TargetType="{x:Type local:Customer}">
  <!-- Other Items -->
  <Button Content="Purchase Discounted Products" x:Name="discounts" Visibility="Hidden" />
  <DataTemplate.Triggers>
    <DataTrigger Binding="{Binding CanPurchaseDiscountedProducts}" Value="True">
      <Setter TargetName="discounts" Property="Visibility" Value="Visible"/>
    </DataTrigger>
  </DataTemplate.Triggers>
</DataTemplate>

A: A WPF data template is a view of a certain object type... how you want an instance of ObjectTypeX to look. The data template can bind to properties on the underlying instance.
So if you have a ButtonXIsEnabled property on your instance, you can bind the corresponding Button's Visibility property to the instance property. The button would be shown or hidden based on the value in the underlying object.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Reactjs make infinity carousel I'm new in React. I need to make infinity carousel without backing scroll when all elements from list run out. For example we got list [1,2,3,4] and now is element 4 and click to button to right i must to add new element (1) after element 4, than 2, 3, 4, 1, 2, 3,... And similar into left. But I don't want to install another library and packages.
Something like that. Thank you


text:
Q: How can I speed up loading data in Oracle tables? I have some very large tables (to me anyway), as in millions of rows.  I am loading them from a legacy system and it is taking forever.  Assuming hardware is ok that is fast.  How can I speed this up?  I have tried exporting from one system into CSV and used Sql loader - slow.  I have also tried a direct link from one system to another so there is no middle csv file, just unload from one load into another.
One person said something about pre-staging tables and that somehow could make things faster.  I don't know what that is or if it could help.  I was hoping for input.  Thank you.
Oracle 11g is what is being used.
update:  my database is clustered so I don't know if I can do anything to speed things up.

A: What you can try:

*

*disabling all constraints and only enabling them after the load process

*CTAS (create table as select)

What you really should do: understand what is you bottleneck. Is it network, file I/O, checking constraints ... then fix that problem. For me looking at the explain plan is most of the time the first step.

A: As Jens Schauder suggested, if you can connect to your source legacy system via DB link, CTAS would be the best compromise between performance and simplicity, as long as you don't need any joins on the source side.
Otherwise, you should consider using SQL*Loader and tweaking some settings. Using direct path I was able to load 100M records (~10GB) in 12 minutes on a 6 year old ProLaint.
EDIT: I used the data format defined for the Datamation sort benchmark. The generator for it is available in the Apache Hadoop distribution. It generates records with fixed width fields with 99 bytes of data plus a newline character per line of file. The SQL*Loader control file I used for the numbers quoted above was:
OPTIONS (SILENT=FEEDBACK, DIRECT=TRUE, ROWS=1000)
LOAD DATA
INFILE 'rec100M.txt' "FIX 99"
INTO TABLE BENCH (
BENCH_KEY POSITION(1:10),
BENCH_REC_NBR POSITION(13:44),
BENCH_FILLER POSITION(47:98))

A: What is the configuration you are using?
Does the database where the data is imported have something like a standby database coupled to it? If so, it is very likely to have a configuration with force_logging enabled?
You can check this using
SELECT FORCE_logging from v$database;

It can also be enabled at tablespace level:
SELECT TABLESPACE_name,FORCE_logging from DBA_tablespaces

If your database is running ith force_logging, or your tablespace has force_logging, this will have impact on the import speed.
If this is not the case, check if archivelog mode is enabled.
SELECT LOG_mode from v$database;

If so, it could be that the archives are not written fast enough. In that case increase the size of the online redolog files.
If the database is not running archivelog mode, it still has to write to the redo files, if not using direct path inserts. In that case, check how quick the redo's can be written. Normally, 200GB/h is very well possible, when indexes are not playing a role.
Important is to find what link is causing the lack of performance. It could be the input, it could be the output. Here I focused on the output.


text:
Q: I need to display a certain row from a file i need to get text from selected line from Txt file and print it on JLabel object
I am learning Java and I do not have anyone who can help me with this code, thank everyone who will help
if you need more code from my project, I can send it
public int check(String filename, String str)
    {
        int row=0;
        try{
        FileReader fr=new FileReader(filename);
        BufferedReader br=new BufferedReader(fr);
        while(br.ready())
        {
            if(br.readLine().equals(str))
            {
               br.close();
               return row;

            }
            row=row+1;
        }
        br.close();
        return -1;
        }
        catch(Exception e)
        {
            JOptionPane.showMessageDialog(this, "Error");
        }
        return -1;
    }

------------------------------------------------------------------------------------------------------

    String str=jComboBoxAdminPUsers.getSelectedItem().toString();
        System.out.println(str);
   int a=check("Pass.txt", str);
   int b=check("Email.txt", str);
   try{
   FileReader fr=new FileReader("Pass.txt");
   BufferedReader br=new BufferedReader(fr);
   String pass="";
   for (int i=0;i<=a;i++)
         pass=br.readLine();
   jLabelPassword.setText(pass);
      br.close();

   FileReader fr1=new FileReader("Email.txt");
   BufferedReader br1=new BufferedReader(fr1);
   String email="";
   for (int i=0;i<=b;i++)
         email=br1.readLine();
   jLabelEmail.setText(email);
      br1.close();
   }
   catch(Exception e)
   {

   }


text:
Q: Example of a convergent series for which integral test fails? Is there example of a convergent series for which integral test fails or can not be applied?
Just wondering if integral test is the silver bullet of convergence tests, or are there any series that any of the other tests can determine convergence but integral test fails?
Of course by convergence we mean classical convergence, not Cesàro summable series that do not have a classical sum.

A: No, there isn't. As long as you can apply the integral test, then it has to work: if $f : [0, \infty) \to [0, \infty)$ is decreasing, then the series $\sum f(n)$ converges iff the improper integral $\int_0^\infty f(t) dt$ converges. This isn't, say, like the root test or the ratio test that can be inconclusive, even when you can apply it (when $\lim a_{n+1}/a_n = 1$ or $\limsup |a_n|^{1/n} = 1$).
But there are two caveats here. First, this only works for nonnegative, decreasing functions $f$. If your function takes negative values, or if it is not decreasing, then you cannot apply the integral test. In that sense, it is not a "silver bullet". Another caveat is that you need to compute an integral to apply the test (or at least determine if it's convergent), and this is not always easy or even feasible. Determining whether $\int_0^\infty f(t) dt$ converges can be just as hard as determining if $\sum f(n)$ converges.
But if you satisfy the hypotheses and if you can determine an explicit antiderivative or otherwise determine the convergence of the integral, then the integral test is a powerful tool.


text:
Q: replace accents when getting thetvdb series I'm trying to replace accent mark so I can search properly at my rss:

*

*TVDB name: Cómo vender drogas online (a toda pastilla)

*RSS title name: Como vender drogas online (a toda pastilla)

and I want to match this so it can be replaced, but isn't working
manipulate:
  - title:
      replace:
        regexp: 'á'
        format: 'a'
  - title:
      replace:
        regexp: 'é'
        format: 'e'
  - title:
      replace:
        regexp: 'í'
        format: 'i'
  - title:
      replace:
        regexp: 'ó'
        format: 'o'
  - title:
      replace:
        regexp: 'ú'
        format: 'u'

My config.yml:
  tv:

    thetvdb_lookup:
      language: es

    configure_series:
      from:
        thetvdb_list:
          username: '{? TvDB.username ?}'
          account_id: '{? TvDB.account_id ?}'
          api_key:  '{? TvDB.api_key ?}'
          strip_dates: yes

    set:
      path: {? path.externaldrive ?}

I want to replace accent mark like this:
á = a
So I can search properly


text:
Q: 'No shipping information available' in Sales Order admin For few orders, shipping description in admin order grid shows

'No shipping information available'.

I am using the magestore onestep checkout. All I've found is that some orders have an empty shipping_description column in sales_flat_quote_address and 'sales_flat_order' table, where as shipping_method column is always correct. I tried to reproduce the same problem,but till now I haven't found any pattern yet.
I'd appreciate any help.


text:
Q: Getting Boolean from Getter value according to getter identifier I need to enable/disable a  according to the field of the database "estadopdf".
I got this, but disable all rows:
boolean est_habilitado = ord.getEstadopdf() == 1? false:true;

And my xhtml:
<p:commandLink ajax="false" value="PDF" class="icon-file-pdf"
               actionListener="#{ordenRetiroBean.exportpdf(ord)}"
               disabled="#{ordenRetiroBean.est_habilitado}">
</p:commandLink>

I need to make a condition that disable the <p:commandLink> from the bean.
The logic i guess, can be
1.- Get the id from that row ordenRetiroentity.getCod_OrdenRetiro
2.- ask this ord.getEstadopdf() == 1? false:true
3.- return a boolean on my method.
4.- give the boolean to my attribute "disable"

A: Since you say "disables all rows" I guess the commandLink is part of for example a datatable row.
So maybe all links are disabled because you're using the managed bean name and not the "var" (which is the row) like in
<h:dataTable value="#{userData.employees}" var="employee">

Look here for example: https://www.tutorialspoint.com/jsf/jsf_display_datatable.htm
You're condition in this example could be
disabled="#{employee.disablePdfLink}"

In case this doesn't help, please specify your problem more detailed and/or post more code.


text:
Q: Binary search not working for all test cases I'm trying to implement a recursive binary search in Java, however, it it not working for all test cases. I am doing a Hacker rank challenge, and it is not showing me the test cases I've missed. When I test it with my own cases, it always tests successfully. I don't know what I'm missing.
import java.util.Arrays;

public class Project {
    public static void main(String [] args){
        int[] arr = {1,2,4,7,9,10,11};

        Arrays.sort(arr);

        String x = findNumber(arr, 10);
        System.out.println(x);
    }

     private static String findNumber(int[] arr, int k) {
             int arrLength = arr.length - 1;

             int mid = Math.round(Math.abs((arrLength) / 2));
             if (arrLength >= mid){
                 if (arr[mid] == k) {
                     return "YES";
                 }

                 else if (arr[mid] > k) {
                     int[] newArr = Arrays.copyOfRange(arr, 0, mid);
                     return findNumber(newArr, k);
                 }

                 else if (arr[mid] < k) {
                     int[] newArr = Arrays.copyOfRange(arr, mid + 1, arrLength + 1);
                     return findNumber(newArr, k);
                 }
             }

        return "NO";
     }
}

Can anyone see what I'm doing wrong?

A: You're coding too much and thinking not enough.
First, the base case.  If the array is of zero length, return "NO". You can't find k in a zero-length array.
Now the recursive case. The array has at least 1 element. Think of it as split it into 3 parts: a single element that's roughly in the middle plus two additional subarrays of length zero or more.  You always have a middle element because the array has at least one element.
The index computation int mid = a.length / 2 will work fine to locate the middle. (Dump the rounding and absolute value.) The remaining sub arrays have index ranges 0..mid-1 and mid+1..a.length-1.
With mid, you can immediately check to see if a[mid] is a match. If it is return "YES".
Otherwise you'll need to figure out in which subarray k lies and search that recursively.
DON'T make a copy to build the subarray. Use the List method subList(from, to). This needs only constant space. It's just a view into the input array, not a copy into new memory.  Much more efficient.
To use subList, your algorithm will need to accept a List rather than a native Java array.
Note that subList's second parameter is exclusive, so the recursive calls will be on a.sublist(0, mid) or a.sublist(mid+1, a.length).
Note that the two subarray alternatives are always shorter than a. This guarantees that your algorithm will eventually terminate, i.e. not recur infinitely. If you shorten the array at each recursive call, you must eventually get to the base case, which always returns.
You'll need to work out some additional details, but not many.


text:
Q: Get warning in debug mode but not in release mode (do I get undefined behavior?) I have a little bit strange situation. I am compiling on some device.
If I compile in Release mode, e.g.
makeCore projectname release exe

All is fine. If I compile in debug mode:
makeCore projectname debug exe

I get following warning:
src/administration.c: In function 'SetIp':
src/administration.c:1409: warning: implicit declaration of function 'InputIp'

Q: Does this mean in the release mode it is safe to use my application?
Why is this behaviour? What to do? I am using the binary compiled in release mode, should I be worried?
Edit: Should I maybe first check out which C standard this compiler conforms to, if it is pre C89 then I should not worry because it is not undefined behaviour right?
Edit2: My ultimate question is if I am trigerring undefined behaviour and how to check whether I am or not trigerring undefined behaviour? I am not sure whether my compiler implements C89 or C90 etc.. Maybe I should ask vendors whether it is undefined behaviour what I did above?
UPDATE:
This is function signature:
s32 InputIp(s32 line, u8 * text, s32 otherline, u8 *IP, u8 coordx, s32 coordy);

This is how it is called:
s32 res = InputIp(someconstant, u8pointer, otherconstant, otheru8pointer, integer1, integer2);

final question: Since I get this warning in the first place, can I be sure I am using compiler which uses C89? Otherwise it would be error? Am I right?

A: There are a couple of possible reasons why you get a difference.

*

*Lower compiler warning level in release build.

This is the most probable reason.

*Conditional code.

Something like this could be the cause:
`#ifndef DEBUG`

`#include "ip.h"`

`#endif`

Note that implicit declaration is a warning you should take seriously as it can hide bugs. I suggest that you add forward declarations where needed.

A: You should not rely on implicit declarations, but if InputIp is defined as int InputIp(); you should be fine.

A: In C89, if the function is prototyped like this (and this prototype is visible at the point of the function body, or the function body uses the same prototype):
s32 InputIp(s32 line, u8 * text, s32 otherline, u8 *IP, u8 coordx, s32 coordy);

and assuming u8 is an 8-bit type, then calling this function without a prototype in scope causes undefined behaviour.
The rule in this situation (calling prototyped function without a prototype in scope) is that all arguments and return value must remain unchanged under the default argument promotions.  Link to related thread
Those promotions, which are the same ones applied to arguments matching ... in variadic functions, are:

*

*Any integral type of lower rank than int is promoted to int

*float is promoted to double

*All other types remain unchanged

So, the u8 would be changed to int by the default argument promotions.
In C99 calling a function without a declaration in scope is ill-formed.

I strongly recommend fixing the code so that the function is called with a prototype in scope.

A: Trying to provide punctual answers:

*

*Does this mean in the release mode it is safe to use my application: The warning means the compiler cannot find the InputIp function prototype. No differences in the run-time behavior of your application (caused by this warning) are expected between the two binary flavors. You should fix it by following the suggestion at 3.

*Why is this behaviour: It seems that the compiler flags are adjsted in Makefile according to the parameters passed by you to make ...

*What to do?: Add the missing function prototype for InputIp and rebuild your application.

*I am using the binary compiled in release mode, should I be worried?: There should be no run-time differences triggered by your issue between the app compiled in debug mode and the one compiled in release mode. You should follow the suggestion at 3

*Should I maybe first check out which C standard this compiler conforms to:  C89/C90 standards have nothing to do with your issue.


text:
Q: Trying to 7-Zip individual files via Batch File The following code runs without error, but doesn't actually zip the files. I can't figure out my bug in the code line that begins "%ZipProgram%".
@echo off

:: Get the current directory.
set CurrDir=%cd%

:: Find the 7-Zip program.
set ZipProgram="C:\Program Files\7-Zip\7z.exe"
if not exist %ZipProgram% (
    set ZipProgram="C:\Program Files (86)\7-Zip\7z.exe"
)
if not exist %ZipProgram% (
    set ZipProgram="C:\Program Files\Easy 7-Zip\7z.exe"
)
if not exist %ZipProgram% (
    set ZipProgram="C:\Program Files (86)\Easy 7-Zip\7z.exe"
)

:: %%n is the variable n specified in a batch file. From a command line it would be %n.
:: /D specifies loop through Directory names only.
FOR /D %%n in ("%CurrDir%\*.*") DO (
    %ZipProgram% u -y -t7z "%%n.7z" "%%n" -r -x!*.tmp
)

pause


text:
Q: Incrementing a string subscript number in Javascript Good day! I want to increment a subscript in a div it name, like "#jstree1", "#jstree2"... etc. I know iterations and incrementing values are a solution. But with this kind of structure, I can't figure out how.
<script src= '@routes.Assets.at("dist/libs/jquery.js")' type="text/javascript"></script>
<script src= '@routes.Assets.at("dist/jstree.min.js")' type="text/javascript"></script>
<script>
  $(function () {
    var i = 0;

    // 6 create an instance when the DOM is ready
    $('#jstree'+i).jstree({
          "core" : {
                "animation" : 0,
                "check_callback" : true,
                "themes" : { "stripes" : true }
              },
              /*"plugins" : [
                "search", "unique",
                "state", "types"
              ]*/
              "plugins" : [
                            "contextmenu", "dnd", "search",
                            "state", "types", "core", "json_data", "ui", "crrm"
                          ]
    });

    i++;

    var to = false;
    var k = 0;
    $('#plugins4_q').keyup(function () {
      if(to) { clearTimeout(to); }
      to = setTimeout(function () {
        var v = $('#plugins4_q').val();
        $('#jstree'+k).jstree(true).search(v);
      }, 250);
    });
    k++;

  });

  </script>

  }

I need to increment the div jstree for displaying the tree and making the search bar to work but it doesn't work. So I'm thinking to assign the variable to any number, if possible. Please help me fix this. Thank you very much.

A: Ummm.... Yes! In Javascript any number can be assigned to a variable.
i = 10;
x = 1.5;

... etc.

A: Yes you can assign any numbers but when you doing some logical operation make sure to use strict notations.
===/!==

because following bugs can be happened
var number = 1.2;
if(number == "1.2") == > TRUE
if(number == 1.2) == > TRUE
if(number == 1) ==> TRUE


text:
Q: Как заменить сразу несколько символов на разные значения в строке (java) import java.util.Scanner;
public class zamena {
    public static void main(String[]args){
        Scanner scn = new Scanner(System.in);
        System.out.println("Введите ваш текст на английском: ");
        String a = scn.nextLine();
        String n = a.replace('q', 'й');
        String n1 = a.replace('w', 'ц');
        System.out.println("Вывод: ");

A: ...
String n = a.replace('q', 'й').replace('w', 'ц');
System.out.println("Вывод: " + n);


text:
Q: d3.event's x and y coordinates are incorrect while showing tooltip I am trying to display a tooltip on the horizontal bar chart. This tooltip does not work properly if I scroll down the page a bit.
This works fine if the bar chart is in view and there is no need to scroll. But if I add more elements above the chart, as I scroll down tooltip goes higher from the mouse pointer.
Please help me in resolving this issue.
Here is the code:

//Ignore test data
var birthData = [{
    "year": 1967,
    "month": "January",
    "births": 31502
  },
  {
    "year": 1967,
    "month": "February",
    "births": 26703
  },
  {
    "year": 1967,
    "month": "March",
    "births": 28853
  },
  {
    "year": 1967,
    "month": "April",
    "births": 26958
  },
  {
    "year": 1967,
    "month": "May",
    "births": 28591
  },
  {
    "year": 1967,
    "month": "June",
    "births": 29545
  },
  {
    "year": 1967,
    "month": "July",
    "births": 30086
  },
  {
    "year": 1967,
    "month": "August",
    "births": 30947
  },
  {
    "year": 1967,
    "month": "September",
    "births": 32338
  },
  {
    "year": 1967,
    "month": "October",
    "births": 32296
  },
  {
    "year": 1967,
    "month": "November",
    "births": 30326
  },
  {
    "year": 1967,
    "month": "December",
    "births": 28994
  }
]

//d3 code
var minYear = d3.min(birthData, function(d) {
  return d.year;
});
var maxYear = d3.max(birthData, function(d) {
  return d.year;
});
var width = 600;
var height = 600;
var barPadding = 30;
var numBars = 12;
var barWidth = 10;

var maxBirths = d3.max(birthData, function(d) {
  return d.births;
});

var xScale = d3.scaleLinear()
  .domain([0, maxBirths])
  .range([0, width]);

var tooltip = d3.select('body').append('div').classed('tooltip', true);

var g = d3.select('svg')
  .attr('width', width)
  .attr('height', height)
  .selectAll('g')
  .data(birthData.filter(function(d) {
    return d.year === minYear;
  }))
  .enter()
  .append('g')
  .attr('transform', 'translate(40, 40)');

g.append('rect')
  .attr('width', function(d) {
    return xScale(maxBirths);
  })
  .attr('height', barWidth)
  .attr('x', 0)
  .attr('y', function(d, i) {
    return (barWidth + barPadding) * i;
  }).attr('fill', 'grey');

g.append('rect')
  .attr('width', function(d) {
    return xScale(d.births);
  })
  .attr('height', barWidth)
  .attr('x', 0)
  .attr('y', function(d, i) {
    return (barWidth + barPadding) * i;
  }).attr('fill', 'blue')
  .classed('original', true);

g.append('text')
  .attr('x', 0)
  .attr('y', function(d, i) {
    return (barWidth + barPadding) * i;
  })
  .text(function(d) {
    return d.month;
  });

g.on('mousemove', showToolTip)
  .on('mouseout', hideToolTip)
  .on('touchstart', showToolTip)
  .on('touchend', hideToolTip);

function hideToolTip() {
  tooltip
    .style('opacity', 0);
}

function showToolTip(d) {
  tooltip
    .style('opacity', 1)
    .style('left', d3.event.x + 'px')
    .style('top', d3.event.y + 'px')
    .text(d.month + ': ' + d.births)
};
svg,
input {
  margin: 0 auto 10px;
  display: block;
}

.tooltip {
  opacity: 0;
  position: absolute;
  pointer-events: none;
  background-color: lightblue;
  border: 8px solid blue;
  border-radius: 8px;
  padding: 15px;
}
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>D3 Birth Chart</title>
  <link rel="stylesheet" href="style.css">

Dashboard

  <svg>
  </svg>

A: Instead of d3.event.x and d3.event.y use d3.event.pageX and d3.event.pageY. event.pageX:

returns the X (horizontal) coordinate (in pixels) at which the mouse was clicked, relative to the left edge of the entire document. This includes any portion of the document not currently visible.

The same goes for pageY.
Here is your code with that change:

//Ignore test data
var birthData = [{
    "year": 1967,
    "month": "January",
    "births": 31502
  },
  {
    "year": 1967,
    "month": "February",
    "births": 26703
  },
  {
    "year": 1967,
    "month": "March",
    "births": 28853
  },
  {
    "year": 1967,
    "month": "April",
    "births": 26958
  },
  {
    "year": 1967,
    "month": "May",
    "births": 28591
  },
  {
    "year": 1967,
    "month": "June",
    "births": 29545
  },
  {
    "year": 1967,
    "month": "July",
    "births": 30086
  },
  {
    "year": 1967,
    "month": "August",
    "births": 30947
  },
  {
    "year": 1967,
    "month": "September",
    "births": 32338
  },
  {
    "year": 1967,
    "month": "October",
    "births": 32296
  },
  {
    "year": 1967,
    "month": "November",
    "births": 30326
  },
  {
    "year": 1967,
    "month": "December",
    "births": 28994
  }
]

//d3 code
var minYear = d3.min(birthData, function(d) {
  return d.year;
});
var maxYear = d3.max(birthData, function(d) {
  return d.year;
});
var width = 600;
var height = 600;
var barPadding = 30;
var numBars = 12;
var barWidth = 10;

var maxBirths = d3.max(birthData, function(d) {
  return d.births;
});

var xScale = d3.scaleLinear()
  .domain([0, maxBirths])
  .range([0, width]);

var tooltip = d3.select('body').append('div').classed('tooltip', true);

var g = d3.select('svg')
  .attr('width', width)
  .attr('height', height)
  .selectAll('g')
  .data(birthData.filter(function(d) {
    return d.year === minYear;
  }))
  .enter()
  .append('g')
  .attr('transform', 'translate(40, 40)');

g.append('rect')
  .attr('width', function(d) {
    return xScale(maxBirths);
  })
  .attr('height', barWidth)
  .attr('x', 0)
  .attr('y', function(d, i) {
    return (barWidth + barPadding) * i;
  }).attr('fill', 'grey');

g.append('rect')
  .attr('width', function(d) {
    return xScale(d.births);
  })
  .attr('height', barWidth)
  .attr('x', 0)
  .attr('y', function(d, i) {
    return (barWidth + barPadding) * i;
  }).attr('fill', 'blue')
  .classed('original', true);

g.append('text')
  .attr('x', 0)
  .attr('y', function(d, i) {
    return (barWidth + barPadding) * i;
  })
  .text(function(d) {
    return d.month;
  });

g.on('mousemove', showToolTip)
  .on('mouseout', hideToolTip)
  .on('touchstart', showToolTip)
  .on('touchend', hideToolTip);

function hideToolTip() {
  tooltip
    .style('opacity', 0);
}

function showToolTip(d) {
  tooltip
    .style('opacity', 1)
    .style('left', d3.event.pageX + 'px')
    .style('top', d3.event.pageY + 'px')
    .text(d.month + ': ' + d.births)
};
svg,
input {
  margin: 0 auto 10px;
  display: block;
}

.tooltip {
  opacity: 0;
  position: absolute;
  pointer-events: none;
  background-color: lightblue;
  border: 8px solid blue;
  border-radius: 8px;
  padding: 15px;
}
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>D3 Birth Chart</title>
  <link rel="stylesheet" href="style.css">

Dashboard

  <svg>
  </svg>


text:
Q: Cisco ASA: How to free memory without reboot? How can I free up some memory in our Cisco ASA 5510 without rebooting it?
We urgently need to free memory otherwise it will crash, but we can't reboot it in the next 2 days.

A: First figure out what is eating up your memory
sh mem detail
sh proc detail

Something like this could bring the memory down but might not be what you desire.  Also remember logging takes memory I belive.
clear conf threat-detection


text:
Q: Getting min and max values from an array - Java import java.util.Scanner;

public class Sales {
  public static void main(String[] args) {
    int[] sales;
    sales = getSales();
    printSales(sales);
    printSummary(sales);
  }

  private static int[] getSales() {
    Scanner input = new Scanner(System.in);
    int[] temp;
    System.out.print("Enter the number of salespeople: ");
    temp = new int[input.nextInt()];

    for (int i = 0; i < temp.length; i++) {
      System.out.print("Enter sales for salesperson " +
                       (i + 1) + ": ");
      temp[i] = input.nextInt();
    }
    return temp;
  }

  private static void printSales(int[] s) {
    System.out.println();
    System.out.println("Salesperson   Sales");
    System.out.println("-----------   -----");
    for (int i = 0; i < s.length; i++) {
      System.out.printf("%6d%12d\n", i + 1, s[i]);
    }
  }

  private static void printSummary(int[] s) {
    int sum      = 0;
    int max_sale = 0;  // Salesperson with the most sales
    int min_sale = 0;  // Salesperson with the least sales

    for (int i = 0; i < s.length; i++)  {
      sum = (s[i] + sum);
      if (s[i] > max_sale)
        max_sale = s[1];
      else if (s[i] > min_sale)
        s[i] = min_sale;
    }
    System.out.println();
    System.out.println("Total sales:  " + sum);
    System.out.println("Average sales: " + (double)sum / s.length);
    System.out.println("Salesperson " + (max_sale + 1) +
                       " had the maximum sale with "   +
                       s[max_sale]);
    System.out.println("Salesperson " + (min_sale + 1) +
                       " had the minimum sale with "   +
                       s[min_sale]);
  }
}

The purpose of the application is to take the number of salespeople as input, along with their sales and then display individual sales, total sales, and average. That is working fine, but it's also supposed to display which salesperson had the max and minimum sales and what they were (lines 51 - 54). At the moment, any time the max is greater than the number of salespeople I get an ArrayIndexOutOfBoundsException and for whatever reason can't figure it out.

A: 1 - Modify your for loop to get the max and min without modifying the array
2 - Try to print max and min instead of printing sum[max] and some[min] (which can throws IndexOutOfBoundsException)
3 - min_sale should be greater than 0, actually a value enough large (because you can have only positive values in your array)
To summarize :
    int sum      = 0;
    int max_sale = Integer.MIN_VALUE;  // Salesperson with the most sales
    int min_sale = Integer.MAX_VALUE;  // Salesperson with the least sales

    for (int i = 0; i < s.length; i++){
          sum = (s[i] + sum);
          if (s[i] > max_sale)
            max_sale = s[i];
          else if (s[i] < min_sale)
            min_sale = s[i];
    }

System.out.println("Salesperson " +
                       " had the maximum sale with "   +
                       max_sale);
System.out.println("Salesperson " +
                       " had the minimum sale with "   +
                       min_sale);

A: the specific problem that's causing your error is here,
System.out.println("Salesperson " + (max_sale + 1) +
                   " had the maximum sale with "   +
                   s[max_sale]);
System.out.println("Salesperson " + (min_sale + 1) +
                   " had the minimum sale with "   +
                   s[min_sale]);

you're using your result as though it were an index
change it to the following
System.out.println("Salesperson " + (max_sale + 1) +
                   " had the maximum sale with "   +
                   max_sale);
System.out.println("Salesperson " + (min_sale + 1) +
                   " had the minimum sale with "   +
                   min_sale);

A:  if (s[i] > max_sale)
    max_sale = s[1];
  else if (s[i] > min_sale)
    s[i] = min_sale;

Here you are trying to assign the value in s[1] to max_sales. whereas you should be assigning max_sale = i. and the if condition should be
if(s[i] > s[max_sale] )

Updated code:
for (int i = 0; i < s.length; i++)
{
  sum = (s[i] + sum);
  // Finds the index of the sales person with best sales
  if (s[i] >= s[max_sale])
    max_sale = i;
  // If this sales person is not the best, then check if he is last
  else if (s[min_sale] > s[i])
    min_sale = i;
}


text:
Q: How to get firebase child snapshot value back to work? var test = String()

func fetchUser() {
 let currentUserUid = Auth.auth().currentUser?.uid

    Database.database().reference().child("users").child(currentUserUid!).child("test").observeSingleEvent(of: .value) { (snapshot) in

        self.test = snapshot.value as! String
   })
}

I want to add the snapshot value to my variable.
But it is crashing, although my firebase concept is perfect and fitting to the code.
What could be the reason?
Console structure:

*

*users

*

*iBagi96IMGbd2k6wUtXjPs0gmNq1.  <--- currentUserUid

*

*test: testValue

The error i get: Could not cast value of type 'NSNull' (0x10dd86de0) to 'NSString' (0x10b2485d8).
In addition i would like to add that i once renamed the child name from "test" to sth else and it worked afterwards for a short time. Than the error occured again.

A: There are a number of typo's in the code in the question but it's kinda correct.
The biggest issue is the handling of optionals - they are being force-unwrapped when you should be treating them as optionals to protect your code.
so this
let currentUserUid = Auth.auth().currentUser?.uid

would be better as
guard let user = Auth.auth().currentUser else {return}
let uid = user.uid

But working with your code, here's an update that reads the value from that node as a string and prints it out.
var test = String()

func readUserString() {
    let currentUserUid = "iBagi96IMGbd2k6wUtXjPs0gmNq1"
    let usersRef = self.ref.child("users")
    usersRef.child(currentUserUid).child("test").observeSingleEvent(of: .value, with: { snapshot in
        let test = snapshot.value as! String
        print(test) //prints "testValue"
    })
}


text:
Q: Javascript function that returns two different types of variables depending on input? I'm trying to follow the rule and avoid repeating the same code.
I have this single function but depending on the input I want it to either return an array of objects or an object (not an array of just one object)
e.g.(the actual function is much longer and more elaborate than this one obviously, there are just the last few lines after a much longer calculation)
function (nameParameter, ageParameter, inputType)
{
  if (inputType === "asObject")
  {
    var x = {};
    x.name = nameParameter;
    x.age = ageParameter;
    return x;
  }
  else if (inputType === "asArray")
  {
    var y = [];
    y.push(nameParameter);
    y.push(ageParameter);
    return y;
  }
};

Is this possible and if so is it good practice? Is there some other way around it?
Otherwise I'll have to create two distinct function with almost the exact same code.

A: Yes; that will work fine.
Javascript is not strongly-typed;  functions can return whatever they want, whenever they want.

A: You can simplify your code by declaring the object and array with the values already set, but in my opinion if you have this strict type of coding it is not necessary to keep this function... Anyway, here is a simplified version:
function (nameParameter, ageParameter, inputType) {
    var ret;
    if (inputType === "asObject") {
        ret = {
            name: nameParameter,
            age: ageParameter
        };
    } else if (inputType === "asArray") {
        ret = [nameParameter, ageParameter];
    }
    return ret;
};

I left it without name and with a semicolon at the end because I guess it has been declared through a variable.

A: Don't do this. Implement one version and add a wrapper function that converts the the other format you may want. That way the caller always gets consistent behaviour, and theres still no code duplication.
function asObject(nameParameter, ageParameter)
{
    //Lots of work here.
    var x = {};
    x.name = nameParameter;
    x.age = ageParameter;
    return x;
};

function asArray(nameParameter, ageParameter)
{
  //Just defer to the other version and repack its response.
  var o = asObject(nameParameter, ageParameter);
  var y = [o.nameParameter,o.ageParameter ];
  return y;
}

A: if ( typeof inputType == 'object') {
  //object part of code
} else {
  //array part of code
}


text:
Q: JSON.parse converting to a string instead of passing into array Yallo, I am at ends as to why notes = JSON.parse(notesString) is converting my array to a string instead of passing my json strings into the array. I tested by checking the typeof before and after. I understand why push cannot be used because it's no longer an array. but I don't know the solution.
Code
// array to store notes in
var notes = [];

// note JSON object
var note = {
    title: title,
    body: body
};

try {
    // read pre-existing content of notes-data.json file
    var notesString = fs.readFileSync('notes-data.json');

    // store pre-existing data as the notes array, passing as
    // JSON
    console.log("notesString: " + typeof notesString)
    console.log("notes before parse: " + typeof notes)

    notes = JSON.parse(notesString)

    console.log("notes after parse:" + typeof notes)
} catch (e) {

}

// add note to notes array
notes.push(note)

// store content of notes array in notes-data.json as a string
fs.writeFileSync('notes-data.json', JSON.stringify(notes));

This is my JSON
"[{\"title\":\"herp\",\"body\":\"derp\"},{\"title\":\"herp\",\"body\":\"derp\"}]"

Output
notesString: object
notes before parse: object
notes after parse:string
C:\Visual Studio 2015\Projects\Note_App_NodeJS\Note_App_NodeJS\notes.js:32
    notes.push(note)
          ^

TypeError: notes.push is not a function

Resolved
sorry people I don't know what was going on but I should have validated my output/input first. I don't know why it was formatted in that manner and it's formatted in the correct json format since, when converting to stingify then parsing back. I am using Visual Studio with the Nodejs extension so perhaps that had something to do with it.

A: It is a string because of the outer quotes. If you remove those, your JSON is not valid. You must format it according to the JSON rules. All the keys must be strings, and values can be only primitives, like strings, numbers, booleans, arrays or other JSON objects.
Format your JSON like
[
    {
        "title": "herp",
        "body":"derp"
    },
    {
        "title":"herp",
        "body":"derp"
    }
]

Here you can see some examples: http://json.org/example.html

A:
sorry I should have been more specific at the momment it contains
"[{\"title\":\"herp\",\"body\":\"derp\"},{\"title\":\"herp\",\"body\":\"derp\"}]"

That is the JSON expression of a string, which is why you get a string when you parse it.
The string happens to contain a nested set of JSON which is the array you are looking for.
Extract that array from the string and put that in the file.
[{"title":"herp","body":"derp"},{"title":"herp","body":"derp"}]


text:
Q: How to check whether a clone of an element exists in the document -- Jquery/JavaScript I have some draggable elements in the DOM, which if dropped become draggable disabled. Now there can be only one element in the droppable at a time. So if the user drags another draggable and drops it, the previous dropped element must get removed from the droppable and the currently dragged element must replace it in the droppable.
How can I do this??
This is my draggable:
$('#draggable').draggable({
  helper: "clone",
  revert: 'invalid',
  containment: '#drag-drop-wrapper',
  appendTo: '#doc-container'
});

And my droppable
$('#droppable').droppable({
  accept: ".session",
  drop: function(event,ui){
    //Need the code to replace old dropped item with new dropped item
  }
});

Please help.
Thanks in advance.


text:
Q: Normalizing team leader Each user is on exactly one team. A team has exactly one user in the team_lead role. How can we normalize this in the database? Examples in pseudo-SQL:
Strategy 1:
table user:
id       int  pk
team_id  int  fk references team(id)
is_lead  int  //1 or 0

table team
id            int  pk

Problem: Multiple users on one team could be marked as the team lead
Strategy 2:
table user:
id       int  pk
team_id  int  fk references team(id)

table team
id            int  pk
team_lead_id  int  fk references user(id)

Problem: There is no guarantee the referenced team lead is actually a member of that team
Is there any way to normalize this in the database design, or do we have to use constraints or enforce on the front-end?

A: There's a (standard SQL) way of getting the guarantees you want, but I'm afraid mySQL 5.7 is not able to handle it. My example has been tested on PostgreSQL.
You can define your users table this way:
-- Schema for everything
CREATE SCHEMA teams ;

-- Users
CREATE TABLE teams.users
(
  user_id integer NOT NULL PRIMARY KEY,
  team_id integer,
  CONSTRAINT users_team_id_user_id_key UNIQUE (user_id, team_id)
);

Then, have your teams have be defined in the following fashion:
-- Teams have one team_lead
CREATE TABLE teams.teams
(
  team_id integer NOT NULL PRIMARY KEY,
  team_lead_id integer NOT NULL,

  -- This constraint ensures that 'team_lead_id' is a 'user_id', and
  -- this user is actually a member of the team
  CONSTRAINT teams_team_lead_id_fkey FOREIGN KEY (team_lead_id, team_id)
      REFERENCES teams.users (user_id, team_id) MATCH FULL
      ON UPDATE RESTRICT ON DELETE RESTRICT
      DEFERRABLE INITIALLY DEFERRED
);

By using a composite foreign key constraint you actually make sure that the user you are checking for, is actually a member of the team.
After this second table has been defined, you can now add the foreign key constraint users.team_id -> teams.team_id:
-- The 'team_id' on users is a
ALTER TABLE teams.users
  ADD CONSTRAINT users_team_id_fkey FOREIGN KEY (team_id)
      REFERENCES teams.teams (team_id) MATCH SIMPLE
      ON UPDATE RESTRICT ON DELETE RESTRICT
      DEFERRABLE INITIALLY DEFERRED ;

Note that both tables are referrrig to each other. You have circular references.
Being this the case: the constraints must be checked at the end of a transaction, not just at the end of a statement. In the case of PostgreSQL, they need to be defined DEFERRABLE and INITIALLY DEFERRED (this is what mySQL cannot handle). You need to enter data for the first team (table teams) and its team leader (table users) all in one transaction, or, otherwise, there's no way to satisfy both FOREIGN KEY constraints:
Let's assume these are 'user 1' and 'team 5':
BEGIN TRANSACTION ;
INSERT INTO teams.users (user_id, team_id)      VALUES (1, 5) ;
INSERT INTO teams.teams (team_id, team_lead_id) VALUES (5, 1) ;
COMMIT TRANSACTION ;

Unfortunately, mySQL 5.7 documentation about foreign key constraints states:

[...] InnoDB checks foreign key constraints immediately; the check is not deferred to transaction commit. According to the SQL standard, the default behavior should be deferred checking. That is, constraints are only checked after the entire SQL statement has been processed. Until InnoDB implements deferred constraint checking, some things are impossible, such as deleting a record that refers to itself using a foreign key.

MariaDB documentation about FKs doesn't have mentions about deferrability.

A: It's not at all complicated. You already must have a cross reference/intersection table for the m-m User-Team relationships:
create table TeamPlayers(
  TeamID   int  not null references Teams( ID ),
  PlayerID int  not null referneces Users( ID ),
  constraint PK_TeamPlayers primary key( TeamID, PlayerID ),
  constraint UQ_TeamPlayers_Player unique( Playerid )
);

The FK constraint is typical of such tables. It assures the same player cannot be listed more than once for the same team.
The Unique constraint assures the same player cannot be listed more than once across all teams.
You would think that the Unique constraint renders the PK superfluous. Not really.
Though it can be placed in a separate table, the team leader is an attribute of the team so I'll show it as part of the Teams table:
create table Teams(
  ID    int  auto_generate primary key,
  ...
  Lead  int,
  ...,
  constraint FK_TeamsLeader( ID, Lead )
    references TeamPlayers( TeamID, PlayerID )
);

By referencing the FK to the intersection table, we guarantee that the team leader is a user already defined as a player on the team.
So you guarantee that each user is on exactly one team and a team has exactly one user in the team_lead role and that user is one that is playing on the team..


text:
Q: Flutter - image change with onPressed (not in a button) i'm new in the game of StackOverflow and of flutter and try to write an app for web.
Maybe it is a simple problem, but i don't know how to do it.
I've the problem, that i don't know how to change a image, which i've displayed.
My target is 3 buttons, which can change an image above them.
One of the images could be displayed or at the begin replaced with a placeholder, it's unimportant.
Maybe in the code are some unnecessary function, ignore them.
It would be very nice, if you could help me.
Image
import 'package:flutter/material.dart';

void main() {
  runApp(StarCounter());
}

class StarCounter extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Screen',
      theme: ThemeData(
        primarySwatch: Colors.orange,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Screen'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  var _itemImage = Image.asset("Screenshot1.png");

  tmpFunction() {
    Container(
      child: _itemImage,
      width: 500,
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Container(
              child: Placeholder(
                fallbackWidth: 500,
              ),
            ),
            Text(
              'Wählen Sie den gewünschten Button aus:',
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                FlatButton(onPressed: tmpFunction, child: Text("Button 1")),
                FlatButton(onPressed: tmpFunction, child: Text("Button 2")),
                FlatButton(onPressed: tmpFunction, child: Text("Button 3")),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

A: Each button will change image you can change user asset image or network image
import 'package:flutter/material.dart';
void main() {
runApp(StarCounter());
}

class StarCounter extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
  title: 'Screen',
  theme: ThemeData(
    primarySwatch: Colors.orange,
    visualDensity: VisualDensity.adaptivePlatformDensity,
  ),
  home: MyHomePage(title: 'Screen'),
  );
  }
  }

   class MyHomePage extends StatefulWidget {
   MyHomePage({Key key, this.title}) : super(key: key);

   final String title;

    @override
   _MyHomePageState createState() => _MyHomePageState();
     }

    class _MyHomePageState extends State<MyHomePage> {
       var _itemImage = [
        Image.network("https://i.picsum.photos/id/203/200/300.jpg?
        hmac=mJaqsySlyEjr8fLBHytyVCUyqlfPSxqXePXEIhZZi_Y"),
        Image.network("https://i.picsum.photos/id/14/200/200.jpg?hmac=bwQwH7-
        0RPCqUVkFzd3hFhc6yDfC6_e7vgaKXZ7vFOA"),
        Image.network("https://picsum.photos/id/870/200/300?grayscale&blur=2")];

        int index =0;

        tmpFunction() {
        Container(
        child: _itemImage[index],
        width: 500,
        );
        }

       @override
       Widget build(BuildContext context) {
       return Scaffold(
        appBar: AppBar(
        title: Text(widget.title),
       ),
       body: Center(
       child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[

         Container(
         child: _itemImage[index],
         width: 500,
         ),
        Text(
          'Wählen Sie den gewünschten Button aus:',
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            FlatButton(onPressed: (){

             setState(() { index = 0;});
            }, child: Text("Button 1")),
            FlatButton(onPressed: (){
               setState(() { index = 1;});

            }, child: Text("Button 2")),
            FlatButton(onPressed: (){
               setState(() {  index = 2;});

            }, child: Text("Button 3")),
          ],
           ),
          ],
         ),
           ),
        );
        }
       }


text:
Q: How to disable Install-Recommends for snap? I am using APT::Install-Recommends in /etc/apt/apt.conf and it works well to let me only install what I actually intended to install. Without even limiting my options when manually later choosing to accept recommendations.
This does not seem to apply to packages installed via snap, which has now during automatic updates installed openprinting/cups and brlin/hunspell-dictionaries-1-7-2004. I would like to review newly added non-dependencies, or at least keep unattended additions limited to Canonical-supported software.
What are my options to configure snapd to restrain itself in this regard?


text:
Q: Page Transition Style Like Flipboard on Windows Phone 8 I'm searching how to create the flip effect on a wp8 application like the Flipboard style : www.flipboard.com.
could you help me how to proceed to create this effect?
Thanks.

A: I would recomment using Telerik's SlideView control. You can set a Flip transition. You can download the Telerik sample application and try it out. The phone controls are only $99. Even better is to use Nokia Developer Offers. You get Telerik's phone controls, as well as Infragistics controls, a DevCenter account and BugSense tracking for $99. I know it's not free, but how much is your time worth creating all the controls you get from this?
NOTE: I am not affiliated with any of the above companies.

A: Look here: How to Perform a Card Flip Animation
I have told how to make FlipAnimation, un projections menu there are also other effects that affect XYZ axes - your effect is quite simple.
But if you wan't a whole page transition then i think you should NOT use pages, but use different Views on one page.


text:
Q: Custom event on each ref within for loop Vuejs I have a loop of data and have a modal for each loop

It's a bootstrap modal and to each of them I want to bind an event whenever I close the modal
 mounted(){
   Object.keys(this.$refs).map((val) => $(this.$refs[val]).on("hidden.bs.modal",
 this.doSomethingOnHidden))
  }

I don't seem to access the object properly

A: First thing, your ref is not dynamic, it's a string. So make it dynamic by binding this using the bind (v-bind or :) operator.
Second thing, mustaches cannot be used inside HTML attributes, so {{loop.index}} won't work.
Here is the demo-

new Vue({
  el: "#app",
  mounted() {
    Object.keys(this.$refs).map((val) => console.log(val))
  }
})

  <div v-for="index in 5" :ref="`vuemodal-${index}`">
    It's a bootstrap modal and to each of them I want to bind an event whenever I close the modal


text:
Q: Getting NPE NullPointerException in PageFactory (Selenium+Java) I'm trying to implement Page Factory pattern for my testing framework, but I'm getting NPE while trying to reach or interact with elements. BTW, I'm using Spring Dependency Injection for sharing WebDriver instance among tests (instead of constructor), so I implemented PageFactory initElements() inside non-static block to be able to reach it.
BTW, without PageFactory (without @FindBy and with commented By items) it works perfect.
Here is my code of PO.class:
@Component
public class HomePage extends BasePage {
  @Autowired
  private DatabasesPage databasesPage;
  @Autowired
  private UserAccountsPage userAccountsPage;

  public static Logger log = LogManager.getLogger(HomePage.class.getName());
  private String themeLabelColorHex = "#235a81";
  private Select themeList;

 /* private By databasesHeaderButton = By.cssSelector("#topmenu > li:nth-child(1)"),
             userAccountsHeaderButton = By.cssSelector("#topmenu > li:nth-child(4)"),
             languagesDropdown = By.id("sel-lang"),
             themeDropdown = By.name("set_theme"),
             themeLabel = By.xpath("//*[@id='li_select_theme']//a");*/

  @FindBy(how = How.CSS, css = "#topmenu > li:nth-child(1)")  private WebElement databasesHeaderButton;
  @FindBy(how = How.CSS, css = "#topmenu > li:nth-child(4)")  private WebElement userAccountsHeaderButton;
  @FindBy(how = How.ID, id = "sel-lang") private WebElement languagesDropdown;
  @FindBy(how = How.NAME, name = "set_theme") private WebElement themeDropdown;
  @FindBy(how = How.XPATH, xpath = "//*[@id='li_select_theme']//a") private WebElement themeLabel;

  {
    PageFactory.initElements(driver,this);
    System.out.println("**************** THIS IS A NON-STATIC FIELD REACHED BY DEP INJ ****************");
  }

  public HomePage openUp() {
    String propertiesPath = get(System.getProperty("user.dir"),
      "src", "main", "java", "base", "configuration", "config.properties").normalize().toString();

    try {
      Properties properties = new Properties();
      properties.load(new FileInputStream(propertiesPath));
      String url = properties.getProperty("url");

      driver.get(url);
    }
    catch ( IOException e) {
      log.error("Properties file is not found");
      log.error("\n " + ExceptionUtils.getStackTrace(e));
    }

    return this;
  }

  public DatabasesPage goToDatabasesPage() {
    databasesHeaderButton.click();
    return databasesPage;
  }

  public UserAccountsPage goToUserAccountsPage() {
    userAccountsHeaderButton.click();
    return userAccountsPage;
  }

  public HomePage changeLanguage(String langValue) {
    try {
      Select langList = new Select(languagesDropdown);
      String currentLang = langList.getFirstSelectedOption().getAttribute("value");
      if (langValue.equalsIgnoreCase(currentLang)) log.warn("Desired language is already selected!");
      else langList.selectByValue(langValue);
    }
    catch (Exception e) {
      log.error("\n" + ExceptionUtils.getStackTrace(e));
    }

    return this;
  }

  public HomePage changeTheme(String themeValue) {
    try {
      themeList = new Select(themeDropdown);
      String currentTheme = themeList.getFirstSelectedOption().getAttribute("value");

      if (themeValue.equalsIgnoreCase(currentTheme))
        log.warn("Desired theme is already selected!");
      else {
        themeList.selectByValue(themeValue);
        driver.navigate().refresh();
        themeLabelColorHex = "#0000ff";
      }
    }
    catch (Exception e) {
      log.error("\n" + ExceptionUtils.getStackTrace(e));
    }

    return this;
  }

  public HomePage setDefaultTheme() {
    themeList = new Select(themeDropdown);
    themeList.selectByValue("pmahomme");
    themeLabelColorHex = "#235a81";
    return this;
  }

  public boolean isLanguageChanged() {
    return true; // TO DO
  }

  public boolean isThemeChanged() {
    String RGBColor = themeLabel.getCssValue("color"); // I'm getting NPE here somehow
    String HexColor = Color.fromString(RGBColor).asHex();

    return HexColor.equalsIgnoreCase(themeLabelColorHex);
  }

}

Here is my Test method:
@Test
  @Description("Change website theme")
  public void changeWebsiteTheme() {
    homePage.openUp().changeTheme("original");
    assertThat(true).isEqualTo(homePage.isThemeChanged()); // and it fails here but it didn't perform previous step - changeTheme();

    homePage.setDefaultTheme();
    assertThat(true).isEqualTo(homePage.isThemeChanged());
  }

enter code here

A: to initiate the PageFactory which is written in constructor, it has to be initiated by create the object of the class.
this helped me to achieve this.


text:
Q: SSL Using Only Python Flask Is there any way to serve a SSL site using the Python Flask (no apache/nginx frontend) framework with the two following caveats?

*

*Nothing additional can be compiled on the host (testing on a base Xubuntu 14.04 image, python 2.7.6 is the default interpreter).

*No privileges on the local host available, so no packages can be installed to the system

I am using VirtualEnv to set up the requirements and then running a standalone Flask application from within the VirtualEnv environment.
As best I can tell, this is not possible.

*

*This guy ran into the same problem (requires Python 2.7.9, which violates requirement 1 and, as best as I can tell, nothing has 2.7.9 installed by default): http://www.sadafnoor.com/blog/ssl-https-from-python-flask/

*This workaround requires pyOpenSSL to be installed which breaks because of a missing package: http://flask.pocoo.org/snippets/111/, resolution to install pyopenssl: https://askubuntu.com/questions/499714/error-installing-scrapy-in-virtualenv-using-pip
In summary, my goal is to serve a Python Flask site over HTTPS without requiring the installation or compilation of any other programs (self signed cert if desired). Installing via the VirtualEnv pip command is fine, but no host level packages via apt-get or the like.
I have tried several methods unsuccessfully (http://kracekumar.com/post/54437887454/ssl-for-flask-local-development and http://flask.pocoo.org/snippets/111/).
Am I missing something or am I just going to have to install a web server front end to handle SSL?
Thanks!

A: In the end, as best as I could tell, I have to install some things via apt-get to get this working on a default install of Xubuntu 14.04:
sudo apt-get install python-dev libssl-dev libffi-dev


text:
Q: How do I make widgets reusable in Flutter? I'm attempting to use the Flutter DropdownMenu with different parameters on the same page, however I'm unsure how to structure the code.
If I want to use a list other than ['One', 'Two', 'Free', 'Four'] how would I setup the widget to take different parameters without having to copy and paste the widget everytime?
This is the sample code from the docs:
String dropdownValue = 'One';

@override
Widget build(BuildContext context) {
  return DropdownButton<String>(
    value: dropdownValue,
    icon: Icon(Icons.arrow_downward),
    iconSize: 24,
    elevation: 16,
    style: TextStyle(
      color: Colors.deepPurple
    ),
    underline: Container(
      height: 2,
      color: Colors.deepPurpleAccent,
    ),
    onChanged: (String newValue) {
      setState(() {
        dropdownValue = newValue;
      });
    },
    items: <String>['One', 'Two', 'Free', 'Four']
      .map<DropdownMenuItem<String>>((String value) {
        return DropdownMenuItem<String>(
          value: value,
          child: Text(value),
        );
      })
      .toList(),
  );
}

A: Create a method that returns a DropdownButton.
  Widget createDropdownButton({
    String value,
    List<String> items,
    ValueChanged<String> onChanged,
  }) {
    return DropdownButton<String>(
      value: value,
      icon: Icon(Icons.arrow_downward),
      iconSize: 24,
      elevation: 16,
      style: TextStyle(color: Colors.deepPurple),
      underline: Container(
        height: 2,
        color: Colors.deepPurpleAccent,
      ),
      onChanged: onChanged,
      items: items.map<DropdownMenuItem<String>>((String value) {
        return DropdownMenuItem<String>(
          value: value,
          child: Text(value),
        );
      }).toList(),
    );
  }

  String dropdownValue1 = 'Two';
  String dropdownValue2 = '3';

  @override
  Widget build(BuildContext context) {
    return Column(children: [
      createDropdownButton(
          value: dropdownValue1,
          items: ['One', 'Two', 'Free', 'Four'],
          onChanged: (String newValue) {
            setState(() {
              dropdownValue1 = newValue;
            });
          }),
      createDropdownButton(
          value: dropdownValue2,
          items: ['1', '2', '3', '4'],
          onChanged: (String newValue) {
            setState(() {
              dropdownValue2 = newValue;
            });
          }),
    ]);
  }

A: Instead creating a function which creates the widget tree, consider creating your own widget for the DropdownButton. This should yield a performance benefit in most cases, see this answer for an explantion why this is the case.
You could create your widget like this:
class MyDropdownButton extends StatelessWidget {
  const MyDropdownButton({
    Key key,
    @required this.value,
    @required this.labels,
    @required this.onChanged,
  }) : super(key: key);

  final String value;
  final List<String> labels;
  final ValueChanged<String> onChanged;

  @override
  Widget build(BuildContext context) {
    return DropdownButton<String>(
      value: value,
      icon: Icon(Icons.arrow_downward),
      iconSize: 24,
      elevation: 16,
      style: TextStyle(
        color: Colors.deepPurple
      ),
      underline: Container(
        height: 2,
        color: Colors.deepPurpleAccent,
      ),
      onChanged: onChanged,
      items: Cost [
        for (final label in labels)
           DropdownMenuItem<String>(
             key: ValueKey(label),
             value: value,
             child: Text(value),
           )
      ],
    );
  }
}

Then you can use it like this:
return MyDropdownButton(
  value: dropdownValue,
  labels: ["one", "two", "three"],
  onChanged: (label) {
    setState(() {
       dropdownValue = label;
    });
  },
);


text:
Q: Query on two DataTable to find duplicate rows I have an excel sheet which i am uploading to sqlserver table using sqlbulkcopy, i have applied an index on database table so that duplicate entries are ignored but i also want to display the duplicate entries which were ignored in a grid view.
  protected void Button1_Click(object sender, EventArgs e)
{
    string strFileType = System.IO.Path.GetExtension(FileUpload1.FileName).ToString().ToLower();
    string strFileName = FileUpload1.PostedFile.FileName.ToString();

    FileUpload1.SaveAs(Server.MapPath("~/Import/" + strFileName + strFileType));
    string strNewPath = Server.MapPath("~/Import/" + strFileName + strFileType);

        string excelConnectionString = String.Format(@"Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source="+strNewPath +"; Extended Properties=Excel 8.0;");

    //string excelConnectionString = String.Format(@"Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=C:\\myFolder\\Book1.xls;" + "Extended Properties=Excel 8.0;");

        // Create Connection to Excel Workbook
        using (OleDbConnection connection = new OleDbConnection(excelConnectionString))
        {
            connection.Open();
            OleDbCommand command = new OleDbCommand("Select ID,Data FROM [Sheet1$]", connection);
            OleDbCommand command1 = new OleDbCommand("select count(*) from [Sheet1$]",connection);

            //Sql Server Table DataTable
            DataTable dt4=new DataTable();
            SqlCommand cmd4 = new SqlCommand("select id,data from ExcelTable", con);
            try
                {
                    SqlDataAdapter da4 = new SqlDataAdapter(cmd4);
                    da4.Fill(dt4);//sql table datatable
                 }
                catch { }

            //excelsheet datatable
            DataTable oltlb = new DataTable();
          OleDbCommand olcmd = new OleDbCommand("select id,data from [Sheet1$]", connection);
          try
          {
              OleDbDataAdapter olda = new OleDbDataAdapter(olcmd);
              olda.Fill(oltlb); //excel table datatable
          }
          catch { }

    var matched = (from table1 in dt4.AsEnumerable()
                         join table2 in oltlb.AsEnumerable() on
                       table1.Field<int>("ID") equals table2.Field<int>("ID")
                         where table1.Field<string>("Data") == table2.Field<string>("Data")
                         select table1);
          DataTable dthi5 = new DataTable();
          dthi5 = matched.CopyToDataTable();

          GridView1.DataSource = dthi5;
          GridView1.DataBind();
            GridView1.DataSource = matched.ToList();

ERROR:
Specified cast is not valid.
table1.Field("ID") equals table2.Field("ID")

A: It would appear that the ID field in one of your tables is not an int.
Rather than one or both of us guessing, try inspecting the data type of the first column in both tables (oltlb and dt4) to see which has the non-integer data type.  It may in fact be both.
Here's the thing:  even if the value of a string is a numeric literal, you can't cast a string to an int.  You'd have to use Int32.Parse or Convert.ToInt32 to convert.  So if one of your tables has a string type for the ID column, you would express it like this:
table1.Field<int>("ID") equals Convert.ToInt32(table2.Field<string>("ID"))

If both of the tables have a string ID field, you could just express it this way:
table1.Field<string>("ID") equals table2.Field<string>("ID")


text:
Q: Update textfield after input I'm trying to write a GUI with several JTextFields. Two of the fields are for float values. I already have the fields ignoring any non-numerical inputs via a formatter, but I also want the text in the text field to update to a float value if an integer is inputted (i.e. "5" changes to "5.00"). I tried to update the text field using a setText() command from within an event, but the displayed value is not changing. I want the text to change once focus is lost on the text field.
The code is very long, so I will include the relevant snippet.
        heightField.addFocusListener(new FocusAdapter() {
        @Override
        public void focusLost(FocusEvent arg0) {
            heightDone = !heightField.getText().trim().equalsIgnoreCase("");

            //This is the problem code//
            if(UF.isInt(heightField.getText().trim()))
                heightField.setText(heightField.getText().trim().concat(".00"));

            System.out.println(heightField.getText());
            heightFormat = UF.isFloat(heightField.getText().trim());
            isDone();
        }

    });

A: maybe you need to refresh the frame after the change on the textField :
frame.repaint();


text:
Q: How to run all pytest tests with extra function calls using class I have a base class called BaseTest which all my test cases are inheriting from.
Each TestCase have X tests and a method - different_configuration()
Instead of creating test_xyz and test_xyz_different for each test (which means to double my tests in the code, and even more if I'll have x different configurations)
Is there a way to make the base class have something or even a fixture which per existing test will create/run another test but will call self.different_configuration() at the beginning.
EXTRA INFO -
I have a dict as an attribute which has configurations and, there's one configuration, which for each test I'd like to test both available options.
self.different_configuration() just changes the configuration value before the test itself.
Illustration -
    def test_x(self):
        self.run_and_verify()

    def test_x_different_configuration(self):
        self.different_configurations()
        self.run_and_verify()

So for each existing test I create another test with this function call at the beginning, isn't there a cleaner way to achieve it?

A: You can parametrize a fixture.
You will have to extract your configuration values from the dictionary to a list, though, to use it on the params argument.
import pytest

@pytest.fixture(scope="module", params=[config1, config2])
def different_configuration(request):
    return request.param

Then, on your test, you can use each configuration value somehow to change the configuration as you want:
def test_x(self, different_configuration):
    self.different_configurations(different_configuration)
    self.run_and_verify()

Or something like that.


text:
Q: Should we downvote answers to obvious duplicate questions? According to the accepted answer to Should one downvote answers to off-topic questions?, downvoting answers to an obvious off-topic question is appropriate, with the purpose of not encouraging people in asking them.
Does this apply to obvious duplicate questions as well?
I came across this question:
StatusBar bug in iOS7?
Now, if you know a bit about the specific topic, you will also know that the status bar behavior change in iOS 7 generated a LOT of questions in the last couple of months.
The search query "[ios7] status bar" currently generates 585 results, all being pretty much about the same issue.
I feel like answering this kind of questions is not adding any value. Also I'm afraid the OP won't receive the message that they should put research effort before posting a question and in this specific case it's really trivial to find tons of useful information.
That being said, I also left a comment about this, liking to the search query above and marked the question as a duplicate. Nonetheless a few minutes later answers started to appear.
Is is appropriate to "punish" this answers by downvoting them, or should I just move on and hope that the question is closed soon?

A: It's never appropriate to use voting as punishment, that just distorts the meaning of votes on SE.
Vote based on the quality, accuracy and helpfulness of the answer.  The purpose for voting is to allow good answers to float to the top.
Of course, there's no one to police you on this but your own conscience.
Remember, that if you're voting based on the appropriateness of the question, that the question may get edited into good form, but you'll never be notified.  So the downvote will stay there, when the reason for your punishment has gone away.  Also remember that answers get put on before the question is closed, so the answerers may not have any idea it's a dupe, they're just excited to help someone out.

A: After having heard several points of view (thank y'all for sharing) here's my contribute to the discussion.
As Servy said

you should vote based on whether an answer is useful or not useful [...]
The definition of "useful" is left intentionally vague and open to interpretation.

So what's my definition? Josh Caswell said about it

I prefer to take a holistic interpretation of the "useful" criterion for answers, to wit, "Is this answer 'useful' in the context of the entire site?"

and also

I do support the downvoting of answers when they don't constitute high-quality additions to our knowledge archive when considered as a whole

I'm with Josh on this.
I think just looking at how likely is the answer to help the OP is just part of the story and I typically take a broader context into consideration when voting.
Concerning the specific case, as I said in response to Lance Roberts

If you consider the topic with some domain knowledge about iOS and StackOverflow in general, it's not a helpful answer. If it has original content, it has a better fit as an answer to the original question; if it doesn't then it's not helpful as it provide much less information than the answers to the original question.

The point here is to help, and to help as much people as possible. As I said in the comments to the answer

This topic is sooo common, that a tremendous amount of people will come to StackOveflow looking for help. Scattering good pieces of information around several duplicate questions can maybe help the single OPs, but it's surely going to hurt future visitors.

To wrap it up,
Is the answer helpful to the OP?
Maybe. Or maybe a link to a much more complete answer (+143 votes) to the same question (+150 votes) would have been more beneficial.
Is the answer helpful to future visitors?
No. It's rephrasing information already present elsewhere on SO and, in case it adds any original content, it will probably never be found as much more popular questions on the subject exist.
Is the answer helpful to the iOS SO community?
No. It's been two months and we've been answering about the goddamn status bar every single day. It's quite enough.
Is the answer helpful to the SO community in general?
No. Seriously, we don't need people to think it's ok to post duplicate questions without putting some research effort before and neither we need people thinking that scattering information is helpful.

That being said, I took the decision of downvoting the answer, explaining my reasons to the author with a comment.

A: I think you're right to bring this up, and your comment on the question you've linked was spot-on.
Given the constant streams of low-quality, low-effort questions and answers that I see during the times I'm most active on SO, I prefer to take a holistic interpretation of the "useful" criterion for answers, to wit, "Is this answer 'useful' in the context of the entire site?"
Does it provide information in a more understandable way than existing posts? Of course some repetition with different wording helps search, but there's a line past which the material can start to get smeared out. Finding the bit you need becomes a hunt through many questions, just like the old sifting of endless forum threads that SO is supposed to obviate. Therefore, I think one should ask: does an answer to this question make info easier to find, or are we past the tipping point?
See also Gordon's excellent answer to "Is it my responsibility to search for duplicates & vote to close before answering?" -- answering massively duplicated questions actually makes the site worse.
Thus, while I don't think it's justified in all cases, I do support the downvoting of answers when they don't constitute high-quality additions to our knowledge archive when considered as a whole.

A: You are allowed to vote however you want, based on whatever criteria you want, with the exception of voting fraud (which this clearly is not).
The general guideline (based on the tooltip) is that you should vote based on whether an answer is useful or not useful.  If you feel that the answer is not being useful because it is providing an answer to an obvious duplicate, feel free to downvote it.  If you feel that the answer is useful despite being an answer to an obvious duplicate, you can upvote it.  The definition of "useful" is left intentionally vague and open to interpretation.


text:
Q: How to put my url images into carousel? I am getting URL images from API. I have stored the UR images into string. Here my problem I want to display that into carousel. I don't know how to do this. Below is my code that I have tried.
for(int i=0;i<hotelIMAges.count;i++ )
{
    NSDictionary *images=[hotelIMAges objectAtIndex:i];
    NSString *Images= [images objectForKey:@"Imagepath"];
    [ImageARRAy addObject:Images];
} //Here I have stored all the images into string..(https://***.jpg)

Carousel *carousel = [[Carousel alloc] initWithFrame:CGRectMake(0, 0,300, 262)];
[carousel setImages:ImagesARRAy];

A: You just need to process asynchronously as your current approach can be a synchronous request and blocks the main thread until that download is complete.
Consider using SDWebImage and the UIImageView extension it adds to manage the image download and display. It also supports a placeholder image that you can supply to indicate that the download is in progress.
If your using any third party carousel check for asynchronous methods to display the images.I believe setImages: method must be for images that are stored locally inside app. Do let me know if you have any queries.
----EDITED----
Your Carousel is using synchronous method to display which blocks the main thread.
You can use SDWebImage for your purpose.
For this you need to download SDWebImage for asynchronous downloading of image.  You can download SDWebImage from link below.
You can use it in your Carousel.h class as
#import <SDWebImage/UIImageView+WebCache.h>

modify your setup method with below line.
[imageView sd_setImageWithURL:[NSURL URLWithString:self.images[i]]
         placeholderImage:[UIImage imageNamed:@"placeholder.png"]];

For details refer github page of SDwebpage. DO let me know if you have any queries.
https://github.com/rs/SDWebImage#using-asynchronous-image-downloader-independently


text:
Q: Find cached image with Signature Android glide im using this code because every time the image change on the server i want to download the latest.
 Glide.with(yourFragment)
 .load(yourFileDataModel)
 .signature(new StringSignature(new ObjectKey(System.currentTimeMillis()))
 .into(yourImageView);

But there is a problem here. If internet connection goes out (or smt) glide cant find the image in disk cache and will show an error. How can i find the cached image using signature?

A: You are using wrong key for signature. System.currentTimeMillis() changes in each milli seconds. What you want to do is provide some key which will only change when the image changes. You'll have to do something like this. You can ask for image.getUpdatedAt() from the server.
GlideApp.with(context)
        .load(glideUrlCacheKey)
        .signature(new ObjectKey(image.getUpdatedAt()))
        .into(holder.customerImage);

A: This answer might helpful for you
Glide.with(mContext)
  .load(urlProfile)
  .apply(RequestOptions.signature(new StringSignature(...))
      .diskCacheStrategy(DiskCacheStrategy.NONE))
  .into(imageView);

Use the signature by applying RequestOptions
Useful link: http://bumptech.github.io/glide/doc/options.html#requestoptions

A: for offline work store the url of the image in sqllite and check if internet connection is not active give glide the url from sqllite


text:
Q: Should I back up an SQL database to file or another DB? I want to run a daily back up of an SQL database. I was thinking I would do this to another DB (primarily to act as a safeguard against my own mistakes or user errors), but all the scripts that I've found do it to a file.
Is it advisable to backup to another database, and if the data's stored as a file on the server, won't having unencrypted data there create a security risk? Is there a good encryption method, should it all be encrypted in the DB? Is there a good script out there for doing this?
Any help would be much appreciated!
Ben

A: I would recommend backing up to files rather than another DB unless that DB has some form of version control, otherwise you risk copying errors/bad data into the new DB.

A: You don't generally backup to another DB. You could mirror the data in another DB, which explains why all the scripts you found deal with files.
You could always store the backups in a secure location, that would make them as secure as a normal DB that is password protected.
Having your DB output to a file is preferred because it becomes much more portable than carting a DB around.


text:
Q: Getting the error The origin server did not find a current representation for the target resource or is not willing to disclose that one exists Getting the error origin server did not find a current representation for the target resource or is not willing to disclose that one exists.

A: Your dispatcher servlet does not where to dispatch the request. Issue is your controller bean is not created/working.
Even I faced the same problem. Then added the following under mvc-config.xml
<mvc:annotation-driven/>
<context:component-scan base-package="com.nsv.jsmbaba.teamapp.controller"/>

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix"><value>/WEB-INF/view/</value></property>
    <property name="suffix"><value>.jsp</value></property>
</bean>


text:
Q: Display Duplicate Records (TSQL) I am really struggling with an SQL query to return only duplicate rows, for example:
EMPLOYEE_ID   STORE_NO   REGION
2531047     1671         E05
2544970     1254         W09
2566618     1625         E01
2566618     1635         E01
2566618     1835         E01

Should look like:

EMPLOYEE_ID   STORE_NO   REGION
2566618     1625         E01
2566618     1635         E01
2566618     1835         E01

The above was acheived by the following:
SELECT
   E.EMPLOYEE_ID,
   E.STORE_NO,
   S.REGION
FROM
   [USICOAL].[dbo].[EMPLOYEE_STR_ASGN] AS E
RIGHT JOIN
   [USICOAL].[dbo].[STORE] AS S ON E.STORE_NO = S.STORE_NO
ORDER BY EMPLOYEE_ID, REGION

I have tried various options but can only find a way to remove these duplicates, not display them only... Can anyone advise if the above is even possible?
Thanks in advance,
Charley.

A: SELECT * FROM stuff st
WHERE EXISTS (
        SELECT 1 FROM stuff xx
        WHERE xx.employee_id = st.employee_id
        GROUP BY xx.employee_id
        HAVING COUNT(*) > 1
        )
        ;

A: SELECT
   E.EMPLOYEE_ID,
   E.STORE_NO,
   S.REGION
FROM
   [USICOAL].[dbo].[EMPLOYEE_STR_ASGN] AS E
RIGHT JOIN
   [USICOAL].[dbo].[STORE] AS S ON E.STORE_NO = S.STORE_NO
JOIN
   ( SELECT EMPLOYEE_ID
       FROM [USICOAL].[dbo].[EMPLOYEE_STR_ASGN]
      GROUP BY EMPLOYEE_ID
     HAVING COUNT(*) > 1 ) DUPS
 ON DUPS.EMPLOYEE_ID = E.EMPLOYEE_ID
ORDER BY E.EMPLOYEE_ID, REGION

And the right join could just be a join
If there is > 1 employee there is > 0 employee


text:
Q: Increasing the size of the title of a plotly graphic I'm using plotly 4.5.2.
Here is how I do to change the size of the title of the plot, by using titlefont=list(size=30) in layout():
library(plotly)
x <- 0:10
y <- 0:10
dd <- transform(expand.grid(x=x, y=y), z=x+y)
dd1 <- data.frame(x=x, y=y)
pp <- plot_ly() %>%
  layout(title="Hello", titlefont=list(size=30)) %>%
  add_trace(data=dd, x=~x, y=~y, z=~z, type="heatmap") %>%
  add_trace(data=dd1, x=~x, y=~y, type="scatter", mode="lines", showlegend=FALSE)

But then the title is not correctly rendered when it is too big:

Is it a bug, or am I doing something bad ?

A: You can set a graph size manually. Try the following:
pp %>% layout(autosize = F, height = 500, margin = list(l=50, r=50, b=100, t=100, pad=4))
Title is visible now


text:
Q: Create a installer with inno setup and postgreSQL in Windows X64 I've created an installer for my application that also installs postgreSQL.
The first question:
What is the best way to configure my database, I mean, is it better to use the postgres default user account? Or should I create a new user. Also is it better to use default public schema or should I create a new schema? As one can see, I'm seeking the best practices to use databases. Also, what kind of care do I need to take with possible already installed versions of postgreSQL from any other application?
The second question:
How to create a user using the installer?
I'm trying to create a new user different from the default user but how can I set a password for this user? I would like to do this without prompting the user in a command shell.
If it's helpful, I will happily post any of my code!

A: Let's go for some points that you've asked in your question.

What is the best way to configure my database, I mean, is it better to use the postgres default user account?

That doesn't matter at all as long as you have defined a strong password for the user to install it you will be good.

is it better to use default public schema or should I create a new schema?

That will depends on your software. If you want to have everything well defined and organized on the use of the database go on, create a schema to your system. If your system will be the only one using PostgreSQL why botter? Read this answer on this matter from DBA forum PostgreSQL and default Schemas

Also, what kind of care I might to take with possible already installed versions of postgreSQL of any other application?

That's a trick one and the very first problem you will have. I find out the hard way that you can't install PostgreSQL database if you already have one previously installed. Not even if you uninstall it (in this case you have to delete all associated registries from windows registry of PostgreSQL).
My advice here is that you put a message on your installer that your system needs a fresh install of PostgreSQL on the target machine and it can't have a previously installed one on it otherwise the install will fail. I know that sucks, but I couldn't find anything to do here. One other thing that I did was to add a note on the installer messages to the user that if He still want to install the system on that machine He would have to contact the "support" to do it manually.

How to create a user using the installer?

From here I will add some commands to you install PostgreSQL in unattended mode.

I'm trying to create a new user different from default user but how to set a password to this user?

The command you will need to install PostgreSQL with a user different from the default one will be:
postgresqlInstallFile[withversion].exe --mode unattended --superaccount super_user_name --superpassword yourStrongPassowordHere

It would be great here if you could ask for the password on your installer program and use a variable within above command.
That alone will install the database with a user defined by you. Here is the documentation about all parameters for PostgreSQL Unattended Install
The second problem is regarding the database of you system. The best course of action I could find was to make a Dump file from the database that I need to install (this database would be empty, with just the structure), added this dump file to the installer so I could import it to the fresh installation of the database.
The problem with this approach is you can't create a database or restore it to PostgreSQL without entering the password for the super account. What I did was

*

*Add messages to the user that He should pay attention to the installer messages and steps so he can't get it wrong

*After installing PostgreSql database comes the step to create the database so I use the command:

[path_for_postgresq]/createdb.exe -U user_you_created -W -E UTF8 -O user_you_created "NameOfYourDatabase"

*

*Before I run the above command I showed a message to the user that he will see a prompt screen asking for a password, so He have to enter it and hit Enter. You can't add it as a parameter (PostgreSQL says it is for security measures)

*After the database creation it is time to import the dump that I've added on the installer so I used:
[path_for_postgresq]/pg_restore -U user_you_created -c -d NameOfYourDatabase DumpFileOfYourDatabase.backup
Once again, before this command I showed a message to the user asking to enter the password for the database restore command.
Here I will add the code I made for the NSIS installer. Just the PostgreSQL part of it. There are a lot more on my installer you may need something more.
;--------------------------------
;Include Modern UI
!include "MUI.nsh"
;Include Process checker
!include nsProcess.nsh
;Include ZipDLL
!include zipdll.nsh
; include for some of the windows messages defines
!define ALL_USERS
!include winmessages.nsh

;--------------------------------
;General Configuration
    Name "Name of your Installer"
    OutFile "fileNameOfYourInstaller.exe"

    ShowInstDetails "show"

    InstallDir $PROFILE\FolderWhereToInstallYourSystem

    ; Request application privileges for Windows Vista
    RequestExecutionLevel admin

    ; HKLM (all users) vs HKCU (current user) defines
    !define env_hklm 'HKLM "SYSTEM\CurrentControlSet\Control\Session Manager\Environment"'
    !define env_hkcu 'HKCU "Environment"'

;--------------------------------
;Interface Settings
    !define MUI_ABORTWARNING

;--------------------------------
;Pages
    !insertmacro MUI_PAGE_DIRECTORY
    !insertmacro MUI_PAGE_INSTFILES

;--------------------------------
;Languages
    !insertmacro MUI_LANGUAGE "English"

Function .onInit
    SetOutPath $TEMP
    # the plugins dir is automatically deleted when the installer exits
    InitPluginsDir
    File /oname=re.bmp re.bmp  #here is an image for a splash screen of the installer

    splash::show 2000 re

    Pop $0  ; $0 has '1' if the user closed the splash screen early,
            ; '0' if everything closed normally, and '-1' if some error occurred.
FunctionEnd

Function verifyInstallationDIR
    IfFileExists $INSTDIR PathGood
        MessageBox MB_OK "The chosen directory is not valid for installation.$\r$\nPlease start again and inform a valid path."
        Quit ;if $INSTDIR wasn't created the installer will close
    PathGood:
FunctionEnd

Section
    SetOutPath $TEMP
    CreateDirectory $INSTDIR

    #Message to the user to PAY ATTENTIOM
    MessageBox MB_OK "Please carefully read all messages through installation steps!"

    Call verifyInstallationDIR
    #Files needed to the installer
    File "resources\DatabaseDumpFile.backup"
    File "resources\postgresql-9.3.9-3-windows-x64.exe"

    #Call postgresql installation in an unattended mode
    ExecWait 'postgresqlInstallFile[withversion].exe --mode unattended --superaccount super_user_name --superpassword yourStrongPassowordHere'

    Postgresql_Running_Check:
        ; is app.exe process running? result is stored in $R0
        ${nsProcess::FindProcess} "postgres.exe" $R0
        ${If} $R0 > 0
            MessageBox MB_RETRYCANCEL|MB_ICONEXCLAMATION "PostgreSQL process is not running yet. Wait 30 seconds and click Retry or Cancel to cancel installation." /SD IDCANCEL IDRETRY Postgresql_Running_Check
            Quit
        ${EndIf}

    ;Create the database
    MessageBox MB_OK "The System DataBase will be created. A console window will appear asking for a password. Please when it happens type:$\r$\n$\r$\nyourStrongPassowordHere"
    ExecWait '$PROGRAMFILES64\PostgreSQL\9.3\bin\createdb.exe -U user_you_created -W -E UTF8 -O user_you_created "NameOfYourDatabase"'

    MessageBox MB_OK "The System Installer will import the configuration data to the database. It will ask again for the password. Please when it happens type:$\r$\n$\r$\nyourStrongPassowordHere"
    ExecWait '$PROGRAMFILES64\PostgreSQL\9.3\bin\pg_restore -U user_you_created -c -d NameOfYourDatabase DatabaseDumpFile.backup'

SectionEnd

Hope it helps.


text:
Q: where are agrregation pipeline executed/Computed Are they computed on node js or server or the in the Mongodb server like the RDBMS stored procedures and postgres fuctions work

A: Aggregation pipleines are executed on mongoDB server/cluster side , but there is stages executed on data nodes , there is stages executed on routing nodes (mongoses).


text:
Q: SQL SUM AND GROUP BY (MS SQL) Following Setup:
PredDate                    WtSumLoc
2017-02-16 00:00:00.000     1360.139000
2017-02-16 00:00:00.000     399.444000
2017-02-28 00:00:00.000     400.000000
2017-02-28 00:00:00.000     8231.046000
2017-02-28 00:00:00.000     400.000000
2017-03-01 00:00:00.000     1118.055000
2017-04-15 00:00:00.000     400.000000
2017-04-15 00:00:00.000     2488.699000
2017-04-28 00:00:00.000     1555.556000
2017-04-28 00:00:00.000     1555.252000
2017-06-30 00:00:00.000     432.704000

I try to sum and Group by this Table by doing:
SELECT

MONTH(PredDate) 'Month',
sum(WtSumLoc) as 'sum'

FROM Table

GROUP BY PredDate
ORDER BY Month

And i get the following result:
Month   sum
2       1759.583000
2       9031.046000
3       1118.055000
4       2888.699000
4       40.000000
4       3110.808000
6       432.704000

Why are those not grouped up? Where is this 40.000 coming from?

A: ANSI SQL compliant solution is to wrap the month extraction part up in a derived table, and GROUP BY its result:
select "Month", sum(WtSumLoc) as 'sum'
from
(
    SELECT MONTH(PredDate) 'Month', WtSumLoc
    FROM Table
) dt
GROUP BY "Month"
ORDER BY Month

ANSI SQL uses double quotes to delimit identifiers, e.g. "Month". SQL Server does also support square brackets, like [Month]. Single quotes are for string literals.

A: Because you're grouping by date thus receiving distinct dates, but outputing month of these dates - thus for two distinct dates in the same month you're receiving two distinct records.
You have to change your query to something like
SELECT

MONTH(PredDate) 'Month',
sum(WtSumLoc) as 'sum'

FROM Table

GROUP BY    MONTH(PredDate)
ORDER BY Month

A: SELECT

MONTH(PredDate) 'Month',
sum(WtSumLoc) as 'sum'

FROM Table

GROUP BY MONTH(PredDate)
ORDER BY Month

You must also group it by MONTH(PredDate)


text:
Q: Kali linux taking super long to boot I just installed kali linux ubuntu 64bit and its stuck on the dragon booting logoenter image description here
and its just stuck for like 5 hours

A: If it gets hung up on boot, one option is to try again, after making sure it has a boot device connected to the Mainboard