text:
Q: How to plot massive subplots elegantly with matplotlib in Python? I am doing machine learning and I have a DataFrame with more than 200 columns.
I am trying to plot each columns with a single sub-histograms in a big chart.
However, I am now having trouble with the style.
To make an example, assume a dataframe with 100 columns:
df = pd.DataFrame(np.random.randn(1234,100))

Out[94]:
            0         1         2   ...        97        98        99
0     0.227933 -0.934809  1.245618  ...  0.183019  1.094679 -0.700376
1    -1.552202  0.354364  1.760722  ... -1.721636 -0.496572 -0.313080
2    -0.541565  1.655707  1.088710  ... -1.184670 -2.001252 -1.050429
3     0.238195 -0.108591 -0.050451  ... -0.302628  0.288851  0.338153
4     0.457096  0.203172  0.471098  ... -1.027933  0.374829  0.169761
5    -0.001841  1.011984 -0.431907  ...  0.258545  1.605582  0.760974
6     1.471813 -0.098398  0.714360  ...  0.703606  1.044807 -0.412672
7     1.059184 -2.149349  0.562838  ... -2.437435  1.737460 -1.024770
8    -0.896903 -0.508237 -0.068818  ... -0.297863 -0.384948 -0.579373
9     0.758799 -0.693295 -1.159272  ...  0.234178  0.032233  0.697570
10    0.675474 -0.352852  0.260396  ... -0.188973  0.523143  1.018925
11   -1.181557 -1.344497 -1.412222  ... -0.321479  0.067915  0.669999
12    0.672136 -0.330293 -0.196936  ...  1.260385 -1.236806  0.681533
13    0.140299  0.504153  1.071389  ...  1.405158 -0.094521  1.721735
14    0.181808  0.742402 -0.326770  ... -1.398279 -0.656203  0.580988
15    0.774710 -0.491283  1.372789  ... -1.404231 -0.126589  0.269563
16   -0.810371 -1.126111  0.302669  ...  1.113741 -1.021419  0.377687
17   -0.275810 -1.949190 -2.071974  ...  1.034045  1.015850  0.637097
18   -0.726322 -0.307625  0.704000  ... -0.835547 -0.008488  0.648393
19   -0.120899  1.101081  0.505107  ... -0.407943  0.429991  0.818632
20    0.480182 -0.978485  2.203976  ...  0.173605  0.997255 -0.776093
21    3.644270 -1.459632 -1.489905  ...  0.498239 -1.621092 -0.620479
22   -0.881719  0.052045  0.278912  ... -1.455999  0.607180 -0.882525
23   -0.705938 -1.891938 -0.754146  ...  0.173924  0.566448 -0.438995
24    0.023259  0.279602  0.260847  ... -0.045225  0.226867  0.467748
25    1.471445 -0.655969  0.562600  ... -1.319302 -0.441864  0.218756
26   -1.290618 -0.298832 -0.487050  ... -1.203545  0.541088 -0.116866
27    1.643755  0.653025  0.249342  ... -1.223990  0.290089  0.005852
28   -2.605484  0.424496 -1.281222  ...  0.123490  1.353371  0.634363
29   -0.449753 -1.135369  0.800035  ...  1.636977 -0.299558 -1.593589
       ...       ...       ...  ...       ...       ...       ...
1204  0.367236 -0.496249  0.638197  ... -0.005895 -1.010969 -2.224020
1205 -0.018760 -0.217639 -1.212887  ... -1.192913  1.069104 -0.293956
1206 -0.665659 -0.593877  0.092854  ...  1.439034  0.485228  1.423196
1207  1.248896  1.003573  0.084656  ...  1.381297 -0.062409  0.663831
1208  1.449891  1.782664 -0.634846  ...  0.455383  1.214181  0.897387
1209  0.375230 -0.058600 -0.351712  ... -1.010911 -0.609472  0.138377
1210  1.226543  1.379220 -0.934771  ...  1.748498 -0.124114 -0.850524
1211 -1.545769  1.238527  1.396890  ...  0.409140  0.669806  1.957392
1212 -0.900113 -0.153754  0.302294  ...  0.610643 -0.148486  0.489769
1213 -0.185048 -1.269445  0.419378  ... -0.142677  0.366322  1.696444
1214  0.534094 -0.782849 -0.284366  ... -1.054251 -1.537188  0.562177
1215 -0.178500  0.210884  0.182022  ... -0.209546  2.206681  0.509346
1216 -0.335233 -3.032272 -0.797425  ... -1.477771 -0.082340  0.042482
1217  1.317906  0.787575  0.460959  ... -0.538162 -2.051323 -1.028799
1218  0.574316 -1.036290  1.166396  ...  0.361653 -0.132850  1.096488
1219  1.403475  2.204577 -0.775761  ...  0.223978  1.894171 -1.218972
1220  0.076612 -0.013123 -0.783453  ... -0.677839  1.016566  1.796378
1221 -1.400581  0.327359  1.055722  ...  1.810790  0.021424 -0.246043
1222 -1.447060  2.538317  0.439193  ...  0.495636 -1.760769 -0.628957
1223 -0.870338  1.818412  0.798017  ... -0.933465 -1.090436 -0.410563
1224 -1.423078  0.131146  1.197407  ... -1.982966 -0.953694  0.427993
1225  1.377813 -1.809781 -0.002360  ... -0.538392 -0.021987  0.387233
1226  1.795981  1.314450 -0.345786  ... -0.076487  0.101984  0.582052
1227  0.380336 -0.252359 -0.573491  ...  1.266275 -0.691479  0.253323
1228  0.233902  0.131575  1.377134  ...  1.927273  0.209263  0.017895
1229  0.870897 -0.443010 -0.978864  ...  0.553497  0.862721  0.475816
1230 -1.458877 -0.409397  1.191692  ... -0.687324  0.349970 -0.144902
1231 -1.631386 -0.132206  2.812334  ... -1.142442  0.262944 -1.496118
1232  0.270174  1.458061  0.033355  ... -1.267695  0.584439  1.565823
1233 -2.620657 -1.451272 -1.571154  ...  1.016622 -0.381059  0.256811

[1234 rows x 100 columns]

So each column is regarded as a random variable with 1234 samples.
Now I've come up with the code for plotting as:
rows = 10
cols = 10
figure, ax = plt.subplots(rows, cols, figsize=(cols,rows))
axes = ax.flatten()
for i in range(100):
        axes[i].hist(df.iloc[:, i], bins=10, density=True)
        axes[i].set_title(str(i+1)+' th Graph')
        print(f'\r{i+1}/100', end='')

for ax in axes.flat:
    ax.label_outer()

plt.savefig('./hists.png', dpi=300)

which gives me a graph of:

What should I do to further make it graph more elegant and readable? Thanks in advance!

A: I've successfully tweaked the graph a little bit:

codes:
figure, ax = plt.subplots(20, 10, figsize=(13,20), gridspec_kw={'hspace': 0.6, 'wspace': 0.3})
axes = ax.flatten()
for i in range(200):
    # plot the histogram, with bins=20, black border with width 0.4, alpha 0.9
    axes[i].hist(df.iloc[:, i], bins=20, edgecolor='black', linewidth=0.4, alpha=0.9)
    # Tick Params, make the tick label size smaller, and closer (pad) to the plot
    axes[i].tick_params(axis='both', which='major', labelsize=4, pad=1)
    # adjust the x,y tick amount
    axes[i].locator_params(nbins=8, axis='both')
    # subplot title
    axes[i].set_title(str(i+1)+'th Feature', fontsize=5, pad=2)

    print(f'\r{i+1}/200', end='')

## This eliminates graph labels of those in between
#for ax in axes.flat:
#    ax.label_outer()

plt.savefig('./hists1.png', dpi=300)


text:
Q: how to reference external jars inside jsp file I have  four jsp files. Some of it using JDBC jar file.
And I put all of it in folder webapps/hello like this.
index.jsp
login.jsp
userloginmid.jsp
userstatus.jsp

/WEB-INF/
--------/lib/postgres ....jar

But it's not work.
I got exception : java.lang.ClassNotFoundException: org.postgresql.Driver
I don't want to use ECLIPSE or something like this.
Just text editor.
Thank.

redpajama_set_name: RedPajamaStackExchange


text:
Q: set the size of a string object Need to read some data directly into a string and pass it to other functions. But I don't know how to set the size after copying data into it.
string s;
s.reserve(10000);
int n = recv(sock, s.c_str(), 10000);
//how to set the s to have size/length n?
proc(s);

I understand that I can allocate a buf of 10000 bytes and save data to it and then create a string object from the buf, but it's not as efficient.
UPDATE1
This question is about the difference of methods reserve() or resize(). This is about using a string with enough space as a buffer to store some bytes from, say, network socket.
UPDATE2
I just need to make the following code snippet work. Of course, the s.resize(n) will zero out the content written into the space reserved for this string object. Need a way to get it working.
#include <stdio.h>
#include <string>
using namespace std;

int main (int argc, char *argv[]) {
    string s;
    s.reserve(100);
    int n = sprintf((char*)(s.c_str()), "hello %f\n", 45.32);
    printf("n=%d\n", n);
    s.resize(n);
    printf("%s\n", s.c_str()); //expect to print hello 45.32
    return 0;
}

UPDATE3
Doing resize() may work sometimes, but not working always.
As the following code snippet shows, the second printf() should have printed 25 characters, but it only printed 16.
    #include
    #include
    using namespace std;
int main (int argc, char *argv[]) {
    string s;
    s.resize(20);
    int n = sprintf((char*)(s.c_str()), "helo %f\n", 45.32);
    printf("n=%d\n", n);
    //s.length = n;
    s.resize(n);
    printf("%ld %p %s\n",  s.size(), s.data(), s.data());
    n = sprintf((char*)(s.c_str()), "hello world!!! %f\n", 45.32);
    printf("n=%d\n", n);
    s.resize(n);
    printf("%ld %p %s\n",  s.size(), s.data(), s.data());
    return 0;
}


text:
Q: TabBar without changing state of first tab and refresh second tab I have a widget TabBar on the main page with two tabs - page1() and page2(). In page1() I have DropdownSearch and in Page2() ListView. When I choose something on Page1, I can see it on Page2 (I use AutomaticKeepAliveClientMixin). But when I come back to Page1, my DropdownSearch resets. How I can save the state on the first page and not reset the chosen value in my Dropdown?
I used also AutomaticKeepAliveClientMixin but with bool get wantKeepAlive => false; but it doesn't work
class Page1 extends StatefulWidget {

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

class _Page1State extends State<Page1>
    with AutomaticKeepAliveClientMixin<Page1> {

   ...
 @override
 Widget build(BuildContext context) {
    super.build(context);

  return Center(
  child:
   DropdownSearch<Object>(
            mode: Mode.MENU,
            isFilteredOnline: true,
            showClearButton: true,
            items: list,
            showSearchBox: true,

            dropdownSearchDecoration: InputDecoration(
              contentPadding: EdgeInsets.symmetric(horizontal: 14),
              labelText: "Choose",
              hintText: "something",
            ),

            //autoValidate: true,
            validator: (u) =>
            u == null ? "field is required " : null,

            onChanged: (data) {
              if(data != null) {
                print(data);
              }
            },
          ),
      )
   )
  ...

  @override
  bool get wantKeepAlive => false;
}

class Page2 extends StatefulWidget {

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

class _Page2State extends State<Page2>
    with AutomaticKeepAliveClientMixin<Page2> {

...

  @override
  bool get wantKeepAlive => true;
}

A: I have 100% working and reusable solution for this:) You can keep this is as a separate file:
import 'package:flutter/material.dart';

class KeepPageAlive extends StatefulWidget {
  const KeepPageAlive({
    Key? key,
     this.child,
  }) : super(key: key);

  final Widget? child;

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

class _KeepPageAliveState extends State<KeepPageAlive>
    with AutomaticKeepAliveClientMixin {
  @override
  Widget build(BuildContext context) {
    super.build(context);

    return widget.child!;
  }

  @override
  bool get wantKeepAlive => true;
}

and you need to just wrap your tab_page widget with this class:
Column(
          children: [
            SimpleTabBar(
              tabController: _tabController,
              tabTitles: [
                LocaleKeys.byCargo.tr(),
                LocaleKeys.byCar.tr(),
                LocaleKeys.byCompany.tr(),
              ],
              onTabTapped: onTabTapped,
            ),
            Flexible(
              child: PageView(
                controller: _pageController,
                onPageChanged: onPageChanged,
                children: [
                  KeepPageAlive(child: SearchCargoPostsLayout()),
                  KeepPageAlive(child: SearchTruckPostsLayout()),
                  KeepPageAlive(child: SearchCompaniesLayout()),
                ],
              ),
            ),
          ],
        ),


text:
Q: Problema ao utilizar o Identity em API ASP .NET Core Boa tarde, estou tentando utilizar o Identity na minha API, porém estou com algum erro que acredito ser de injeção de dependência.
Fiz toda a configuração necessária, conectei com o banco, gerei os Migrations, porém quando tento injetar as classes SignInManager e UserManager do Microsoft.AspNetCore.Identity na minha Controller, estou tomando um erro de ArgumentNullException na Startup, assim como imagem abaixo.

O erro da entender que a aplicação não esta conseguindo acessar a string dentro do appsettings, porém para aplicar os Migrations está funcionando.
Se eu remover SignInManager e UserManager da Controller o erro para de ocorrer. Segue implementações:
Startup:
services.AddDbContext<AppDbContext>(options =>
            options.UseSqlServer(configuration.GetConnectionString("DefaultConnection")));

services.AddIdentity<IdentityUser, IdentityRole>()
            .AddEntityFrameworkStores<AppDbContext>()
            .AddDefaultTokenProviders();

AppDbContext:
namespace Identity.API.Data
{
  public class AppDbContext : IdentityDbContext
  {
    public AppDbContext(DbContextOptions<AppDbContext> options) :
    base(options) {}
  }
}

appsettings (saiu meio desformatado):
{
  "ConnectionStrings": {
    "DefaultConnection":
    "Server= (localdb)\\mssqllocaldb;Database=MyDb;
      Trusted_Connection=True;MultipleActiveResultSets=true"
  }
}

Controller (estou testando um método simples GET):
namespace Identity.API.Controllers
{
   [ApiController]
   [Route("auth")]
   public class AuthController : Controller
   {
     public readonly SignInManager<IdentityUser> SignInManager;
     public readonly UserManager<IdentityUser> UserManager;

     public AuthController(
        SignInManager<IdentityUser> signInManager,
        UserManager<IdentityUser> userManager)
     {
        SignInManager = signInManager;
        UserManager = userManager;
     }

    [HttpGet]
    public string Get()
    {
        return "Deu certo";
    }
  }
}

A: Se estiver usando o asp.net core 3.1
O Startup:
services.AddIdentity<IdentityUser, IdentityRole>().AddEntityFrameworkStores<MeuDbContext>();

Veja se você tem instalado
<PackageReference Include="Microsoft.AspNetCore.Identity" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.Identity.Stores" Version="3.1.7" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="3.1.11" />


text:
Q: Tab doesn't expand the path when using $_ to access the previously typed path Consider the following scenario:
I've used ls to list the contents of a directory, and I've used Tab to find the right directory, so I don't know the full path. And it's a potentially long path, so I don't want to type it again. Now I'm trying to choose and, for example, copy a single file from that directory into another directory. But to choose the file, the Tab functionality doesn't work after I've typed $_.
As an example,

I'm trying use to Tab so that it suggests the contents of a directory, but it doesn't work after I've typed cp $_/. How can I do that?

A: zsh
When you type cp $_Tab (note there is neither space nor / after _), the shell is able to expand $_; but most likely there are more variables that start with _ and the shell cannot be sure you're not after one of them; therefore you will get a list of variables (try it). To expand $_ immediately you need to inform the shell the name of the variable/parameter is already complete:
cp ${_}Tab
The braces work in a similar way as in ${foo}bar. You explicitly terminate the name with } so whatever follows (e.g. bar) is not a part of it. In case of ${_} the shell understands there is no missing (i.e. yet to be typed) part of the name so ${_} means $_ for sure and it can be expanded as such.
After ${_} gets expanded, the experience with Tab should be as you expect.

bash
(Originally the question was tagged bash and I answered accordingly. The tag is no more but I decided to keep this part.)
After you type cp $_, hit Ctrl+Alt+e to expand the special parameter. After it's expanded, Tab will work.
Note the keystroke expands more than variables and parameters. E.g. if your cp is an alias then it will be expanded as well. The expanded line will be expanded again (if applicable) when you hit Enter. In some circumstances such double expansion may be undesired. Compare this answer of mine, the part where Ctrl+Alt+e is mentioned.


text:
Q: Changing order of Android default photo gallery - SDK/ADT I am trying to set a specific order in the default photo gallery for an Android app (or at least a 'this image shows first' type script). I have tried modifying and saving the image to update a last-modified-date attribute, however, it seems to be a bit more complicated than that. What i need, is some clarification on how the images are handled to populate the default gallery.
a few questions i can't answer:
Are the images in the default photo gallery ordered by a last-modified-date or an added-date attribute?
Or is there a gallery file (XML or equivalent) that specifies the specific order?
Do different manufacturers (htc, samsung, lg, etc) have unique ways they order their galleries or call their images?


text:
Q: .htaccess file not working on php website http://www.example.com/questions.php?scid=6

I want to make this url as:
http://www.example.com/general-knowledge_questions-answers_indian-constitution-1

what code i have to use in my .htaccess file

A: Use redirect code in .htacess
//301 Redirect Old File
Redirect 301 http://www.example.com/questions.php?scid=6 http://www.example.com/general-knowledge_questions-answers_indian-constitution-1


text:
Q: python generator returning ndarray I'm having the following odd behavior with a generator that returns a numpy array. In the real application, I am using scipy.sparse to implement an iterative linear algebra solver: The below is a stripped down version. I have the following:
import numpy as np

def iterable(n):

  nc = np.array([0,0,0])
  yield nc

  while nc[0] < n:
    nc += 1
    yield nc

  raise StopIteration

When i try and populate a list with the output
iter = iterable(4)

print list(iter)

I get
$ python itertest.py
[array([4, 4, 4]), array([4, 4, 4]), array([4, 4, 4]), array([4, 4, 4]), array([4, 4, 4])]

i.e., the result of the final 'yield' repeated n times. If I change the yield nc to yield nc.tolist() then I get the expected result. If possible I would like to avoid that as I will end up having to re-make the array. What's going on?
Thanks in advance!

A: You only create one ndarray.  When you do nc += 1, you modify it in place.  So the later iterations modify the same array already yielded, and then yield it again.
You can see this by printing out the generated arrays one at a time:
>>> it = iterable(3)
>>> x = next(it)
>>> print x
[0 0 0]
>>> y = next(it)
>>> print y
[1 1 1]
>>> print x   # x changed!
[1 1 1]
>>> x is y
True

You can see that the second iteration changes the object that was yielded on the first iteration, because they are the same object.
To fix it, change your nc += 1 line to nc = nc + 1.  This will create a new array on each iteration.


text:
Q: How to Limit Size of Radius With d3.js I'm sure the solution is straight forward, but I'm trying to find out how to limit the range of radius when I plot circles onto a geomap.  I have values that range in size significantly, and the larger values end up covering a significant amount of the map.
d3.csv("getdata.php", function(parsedRows) {

    data = parsedRows
    for (i = 0; i < data.length; i++) {
      var mapCoords = this.xy([data[i].long, data[i].lat])
      data[i].lat = mapCoords[0]
      data[i].long = mapCoords[1]
    }

    vis.selectAll("circle")
    .data(data)
    .enter().append("svg:circle")
    .attr("cx", function(d) { return d.lat })
    .attr("cy", function(d) { return d.long })
    .attr("stroke-width", "none")
    .attr("fill", function() { return "rgb(255,148,0)" })
    .attr("fill-opacity", .4)
    .attr("r", function(d) { return Math.sqrt(d.count)})
  })

This is what I have right now.

A: You'll probably want to use d3 scales by setting the domain (min/max input values) and the range (min/max output allowed values). To make this easy, don't hesitate to use d3.min and d3.max to setup the domain's values.
d3.scale will return a function that you can use when assigning the r attribute value. For example:
var scale = d3.scale.linear.domain([ inputMin, inputMax ]).range([ outputMin, outputMax ]);
vis.selectAll("circle")
  // etc...
  .attr( 'r', function(d) { return scale(d.count) });


text:
Q: KeyPress to detect 'Enter' blocks any data entry on an Input text field Beginner with React and I am bumping into an issue. I have a profile page where the user can change each field (First name, Email, etc.) and once 'Enter' is pressed, it saves that particular field (redux/axios/promise).
The problem I have is that when I use onKeyPress/Down/Up as event trigger, it blocks any data entry. Meaning, i cannot type anything in the field, as if it was read-only or blocked. If I use onChange, it works.
class Account extends Component {

    constructor( props ) {
        super(props);

        this.handleChange = this.handleChange.bind(this);
    }

    handleChange(e) {

        if( e.key == 'Enter' ) { // this is detected (i console.logged it)

            e.preventDefault(); // also tried without these
            e.stopPropagation(); // also tried without these

            // this is triggered but the text field doesn't change so it updates nothing
            this.props.setUserKvPair( e.target.name, e.target.value );
        }
    }

    render() {

        return (

                            Email Address
                            <input
                                type="text"
                                name="email"
                                className="form-control"
                                value={this.props.user.email}
                                onKeyDown={this.handleChange} />

                            First Name
                            <input
                                type="text"
                                name="first_name"
                                className="form-control"
                                value={this.props.user.first_name}
                                onKeyPress={this.handleChange} />

        );
    }

}

const mapStateToProps = ( state ) => {
    return {
        user: state.user.data,
        properties: state.properties.data,
    }
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators(userActions, dispatch);
}

export default connect( mapStateToProps, mapDispatchToProps )(Account);

Basically, everything works but it's just that the value of the text input doesn't change unless I use onChange.
How can I remove that blockage/readonly on the field?

A: How can you write something in the input with a value and without onChange?
value={this.props.user.email} without onChange this mean your input is read only
https://jsfiddle.net/69z2wepo/84207/

A: I recommend using a form for this as it grants free onEnter functionality without having to wire up a bunch of different event handlers. Also, I suggest using Controlled Components which does make use of the onChange handler but caches all input values in the component state. This makes using the data extremely easy.
See below code for an example
import React, { Component } from "react";

class SomeComponent extends Component {
    constructor() {
        super();

        this.state = {
            text_1: "",
            text_2: ""
        };

        this.submitHandler = this.submitHandler.bind(this);
    }

    submitHandler(e) {
        e.preventDefault();

        const { text_1, text_2 } = this.state;

        console.log(text_1, text_2);
    }

    render() {
        return (
            // Using a form gives free on 'Enter' functionality
            <form onSubmit={this.submitHandler}>
                {/* Controlled Component 1 */}
                <input
                    type="text"
                    value={this.state.text_1}
                    onChange={e => this.setState({ text_1: e.target.value })}
                />

                {/* Controlled Component 2 */}
                <input
                    type="text"
                    value={this.state.text_2}
                    onChange={e => this.setState({ text_2: e.target.value })}
                />
            </form>
        );
    }
}


text:
Q: IPTables: Get UID of incoming network traffic I want to be able to log all my network traffic for all apps on Android. Currently I am using iptables for that purpose which generates me log messages like this:
In case of outgoing packets everything is fine and I get the uid of the sending application
Rule: iptables -A OUTPUT -j NFLOG
Logs: IN= OUT=pdp0 SRC=10.179.120.240 DST=173.252.102.16 LEN=52 PROTO=TCP SPT=49541 DPT=443 UID=10093

However, for incoming packages I only get the destination port (DPT) and there is no matching to receiving apps.
Rule: iptables -A INPUT -j NFLOG
Logs: IN=pdp0 OUT= SRC=173.252.102.16 DST=10.179.120.240 LEN=81 PROTO=TCP SPT=443 DPT=49541

Is that something iptables can cover? If not, how can I get the App that receives a packet over network?

A: The traffic passes iptables before it end up in local processing by daemons/servers/..., so iptables does not know the owner (UID) of a packet in INPUT chains.
See http://de.wikipedia.org/wiki/Datei:Netfilter-packet-flow.svg

A: To get an application list you could generate a list of applications dynamicly using netstat -tulpen or ss -tulpen and link that data with with your iptables logs from INPUT chains.


text:
Q: how to stop repeat click to post ajax in jquery I use django create a website .and i just write a vote page ,when people click ,it will post data via jquery ajax .it work well
here is the code
<!doctype html>

  <meta charset="utf-8">
  <title>vote</title>

 vote

Everything works well, and I just found the problem. I can not stop repeatedly click vote.
If I click repeatedly
 vote
it repeate show up the pop_up message,"i already voted ,do not vote again."
so i thought ,i may solve the problem by remove the class post_up  ,in this way ,people can not activate ajax post function
so i add $(this).removeClass();
  $(function(){

    $(".post_up").click(function(){
        $(this).removeClass();
        $.ajax({
            url:"/article/{{post.id}}/vote_up/",
            type:'post',
            success:function(msg){
                var beforevote = $(".btn").text();
                if (msg==0){
                    $(".pop_up_vote").empty().text("thanks,i get your vote!").show(300).delay(7000).hide(300);
                      };
                      if (msg==1){
                    $(".pop_up_vote").empty().text("you already voted,do not need vote again").show(300).delay(7000).hide(300);
                };
        })

})

When I remove the class, I still have the problem regarding ajax. How could I fix it?

A: Try this : http://api.jquery.com/one/.
$('.post_up').one('click', function () {

You can re-bind the same handler once Ajax is done :
$('.post_up').one('click', function handler() {
    var el = this;
    $.ajax({
        url: '/article/{{post.id}}/vote_up/',
        type: 'post',
        success: function (msg) {
            $(el).one('click', handler);

Here is a demo : http://jsfiddle.net/wared/CVm37/.

A: I think the problem is that the behaviour is already set for the link, so removing the class won't do anything
try this instead
$(".post_up").unbind("click");


text:
Q: Getting an error when running node js and mongodb. Working fine but getting an error in the console I am getting an error like this
    at new NodeError (node:internal/errors:387:5)
    at ServerResponse.setHeader (node:_http_outgoing:603:11)
    at ServerResponse.header (D:\web development\todolist-v2-starting-files\node_modules\express\lib\response.js:767:10)
    at ServerResponse.send (D:\web development\todolist-v2-starting-files\node_modules\express\lib\response.js:170:12)
    at done (D:\web development\todolist-v2-starting-files\node_modules\express\lib\response.js:1004:10)
    at tryHandleCache (D:\web development\todolist-v2-starting-files\node_modules\ejs\lib\ejs.js:257:5)
    at View.exports.renderFile [as engine] (D:\web development\todolist-v2-starting-files\node_modules\ejs\lib\ejs.js:482:10)    at View.render (D:\web development\todolist-v2-starting-files\node_modules\express\lib\view.js:135:8)
    at tryRender (D:\web development\todolist-v2-starting-files\node_modules\express\lib\application.js:640:10)
    at Function.render (D:\web development\todolist-v2-starting-files\node_modules\express\lib\application.js:592:3)

Here is my code
const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");

const app = express();

app.set('view engine', 'ejs');

app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static("public"));

mongoose.connect("mongodb://localhost:27017/toDoListDB",function(err){
  if(err)
    console.log("Here is the error");
  else
    console.log("Successfully connected to MongoDB");
});

const itemsSchema  = new mongoose.Schema({
  name:String
});

const Item = mongoose.model("Item",itemsSchema);

const item1 = new Item({
  name: "Complete this course"
});

const item2 = new Item({
  name: "Complete RPA course"
});

const item3 = new Item({
  name: "Learn Programming"
});

const defaultArray = [item1, item2, item3];

app.get("/", function(req, res) {
  let check=false;
  Item.find(function(err,item){
    if(err)
      console.log("Error in finding ");
    else{
      if(item.length==0){
        Item.insertMany(defaultArray,function(err){
          if(err)
            console.log("Error in inserting ");
          else
            console.log("Successfully saved");
        });
        if(check==false){
          res.redirect("/");
          check=true;
        }
      }
      res.render("list", {listTitle: "Today", newListItems: item});
    }
  })

});

app.post("/", function(req, res){
  const itemName = req.body.newItem;
  if(itemName!=""){
    const item = new Item({
      name: itemName,
    });
    item.save();
  }
  res.redirect("/");
});

app.get("/work", function(req,res){
  res.render("list", {listTitle: "Work List", newListItems: workItems});
});

app.get("/about", function(req, res){
  res.render("about");
});

app.listen(3000, function() {
  console.log("Server started on port 3000");
});

Here the thing is I am getting the correct output on the web page, but in the console, there was an error. I am trying to handle that but getting the same error, no matter how I tried. Can somebody tell me why I am getting an error like this! I already included check variable in order to handle this error, but didn't work. Any help would be appreciated.
Thanks in Advance


text:
Q: How do I access subscription data when using MonitoringMode.Sampling? I'm trying to find out how to use Eclipse Milo, and finding out how subscriptions go. I can easily get any MonitoringMode.Reporting mode subscription to work, but when I use Sampling it doesn't call the callback method (as expected). According to the docs it's supposed to "queue" up the values without calling the callback, but I can't find any place I can access that queue or anything similar. The UaMonitoredItem doesn't have anything in its interface that looks like it, neither does the request.
It's probably something obvious, but what am I doing wrong?
Thank you in advance!

A: Answered in the GitHub repo discussions, but for posterity:

MonitoringMode.Sampling simply means the server continues to sample the underlying but does not report the values to the client.
The queued values are not available to you. If you change back to MonitoringMode.Reporting then they would be the first values reported for that item.


text:
Q: What is the argument for never forcing a push in a DVCS (Mercurial)? I always preach never to force push anything, because that adds ambiguity to the repository server.
In this specific example, we collaborate with a customer and they "skip a step" and force push instead of appropriately pulling and merging. This takes the ambiguity of what code is good, what code is bad, out of their working directory and into the server. Two heads on this branch, which one do I use, etc. I am looking to use a hook to disallow force pushing, I just didn't want to lock down that ability if there was a good use case for it.
We are relatively new (2 or 3 years) to DVCS, moving from SVN previously. What are the arguments for not doing a force push in a DVCS?  What exceptions exist for this hard and fast rule?

A: The main reason not to force a push is that it forces everyone else to do rebases or force pulls, and any outstanding branches will not merge cleanly.  Also, when beginners don't really understand how to use DVCS yet, a force push is usually a sign that you forgot a step, like doing a pull or merge first, and you can accidentally lose history or even committed code.
There are some teams who force push regularly as a matter of course.  They just build it into their regular workflow.  For example, a team that works on one subsystem of the Linux kernel might diverge from the "mainline" but regularly force a push to get itself back synced up.  I think you have to have a fairly disciplined and DVCS-experienced team for this to work well, though.

A: This is written from a git perspective, since the force push isn't unique to Mercurial
There are commands which allow you to change your repo local repo. git commit --amend, rebase are two of the more common things that people do to modify their own repo history. This is perfectly acceptable.  I've often done a git commit --amend after forgetting to include the tracking number for github in the message.  But its not without peril (as the documentation says)

Ahh, but the bliss of rebasing isn't without its drawbacks, which can be summed up in a single line:
Do not rebase commits that you have pushed to a public repository.

The thing is that the public repo should be append only.  You append commits as you create them.  Rewriting the public rep causes all sorts of headaches and causes everyone who has pulled form it to have to adjust their own repos to match.
There are certainly times when you will need to force a push.  If you really need to modify that last commit (oppose there was a password in there), or worse, you need to go back and find old files that contain sensitive data.
git push --force is a tool.  It is a very heavy handed tool that allows you to do quite a bit of rewriting of history, but it is still a tool (people have written even bigger tools yet titled bfg for cleaning repos).  To say 'never force a push' ignores all those times when you do need to rewrite the history.

In this specific example, we collaborate with a customer and they "skip a step" and force push instead of appropriately pulling and merging. This takes the ambiguity of what code is good, what code is bad, out of their working directory and into the server. Two heads on this branch, which one do I use, etc. I am looking to use a hook to disallow force pushing, I just didn't want to lock down that ability if there was a good use case for it. So far I haven't seen one yet.

The problem that is ebbing encountered, however, is not one with the tool.  It is a problem with the people using the tool.  If they don't have the... maturity... to handle a force push correctly, then by all means take it away from them.  They likely don't need it, don't know when they should use it, or are aware of the problems that it causes.  Forcing them to use a proper workflow will certainly mean more work for them... it will also mean less work for you cleaning up.  On the balance, its likely that using a better workflow will reduce the overall work done and make things cleaner.  Once they are fully aware of how to use the tool, and the proper way the workflow works, then let them have the unfettered toolchain again.


text:
Q: Find Last Field in Row and Subtract Previous I have an Excel spreadsheet that keeps track of word count in various reports. It has a list of projects, a date, and a word count for each date.
Basically:
Title    | Date        | Words | Date       | Words | Date       | Words
Report 1 | 07/20/2015  | 100   | 07/21/2015 |150    | 07/23/2015 | 140
Report 2 | 07/20/2015  | 200   | 07/24/2015 |300    |            |
Report 3 | 07/20/2015  | 10    | 07/23/2015 |100    | 07/24/2015 | 160

I have another sheet that keeps track of words written for each day.
Ex:
Date       | Words
07/20/2015 | 310
07/21/2015 | 50
07/22/2015 | 0
07/23/2015 | 80
07/24/2015 | 160

Right now, I'm updating the second sheet manually. What I want the sheet to do is to find the dates that match column A of sheet 2 for each project, subtract it from the word count of the previous record, and add them together for each day.
I tried doing it using VLookup, but I don't think that's going to work. I know it's probably going to be some convoluted combination of formulas but I'm having a hard time finding a place to start. Any suggestions for how I should tackle this?

A: Try SUMIF function. Your example would be like this:
=SUMIF(Sheet1!B2:B4, Sheet2!A2, Sheet1!C2:C4) + SUMIF(Sheet1!D2:D4, Sheet2!A2, Sheet1!E2:E4) + SUMIF(Sheet1!F2:F4, Sheet2!A2, Sheet1!G2:G4)

More about this function on Office Support.

A: There's a way to do that, but you have to predefine a limited range for your data (You CAN make that very very large).
Suppose you define the range to be Sheet1!A1:ZZ99999. What you do is use a SUMIF with the range being all the rows, and all the columns except the LAST one (so A1:ZY99999), the criteria is your date (A2, A3 and so on in Sheet2), and the sum range is all the rows and all the columns except the FIRST one (so B1:ZZ99999). Since the ranges are unaligned, the contents of each cell determines whether the cell next to it is included in the summation. From that you subtract the value from the cell above.
The formula is =SUMIF(Sheet1!A1:ZY99999, A3, Sheet1!B1:ZZ99999)-B3.


text:
Q: add dynamic field near his parent field? In my web page I am using Add Dynamic Field Functionality  by using jQuery.
I am adding a new div by clicking on an existing div:

divA1

DivB1

DivC1

By clicking on the parent div I am creating a new dynamic div

DivA2

It is coming at the end of the all div's like that.

divA1

DivB1

DivC1

DivA2

But I need it alongside the parent div like this:

divA1

DivA2

DivB1

DivC1

This is my jQuery code:
    newTextBoxDiv = $(document.createElement('div'))
     .attr("id", text).attr("class", 'test0 ' + text);
    newTextBoxDiv.html('

');
}

newTextBoxDiv.appendTo("#contents");

contents is id of main div

A: Try this
JS Code
 $('.divA').on('click', function(){
      $(this).after('
').next().attr('class', 'divA2').text('divA2');
 });

Demo: http://jsfiddle.net/mhn3q/11/

A: As your question stating, according to that.
You can try this
$("div").on("click", function(){
    var  _this = $(this);
    var className = this.className;
    _this.after($('
').addClass(className).html("New Html"));

});

and
DivC1
  should be as
DivC1

check this quick DEMO

A: user $("your div selector").after("new div element");
http://api.jquery.com/after/

A: Try this. It should give you exactly (I hope) what you want:
http://jsfiddle.net/zjcHf/1/


text:
Q: Convergence integral causal function I have an exercise where there is the following given:

*

*$f$ is a causal function.

*$f$ is Laplace transformable:$\int_{0}^{\infty} f(t)e^{-zt}
   \, dt = L(z) $ with $Real(z)> -1$
I have to determine if the integral : $\int_{-\infty}^{\infty}f(t)$ is convergent or not.
First thing that popped in my head was that if $\int_{-\infty}^{\infty}f(t)\leq \int_{0}^{\infty} f(t)e^{-zt}
   \, dt$ then of course it integral is convergent.
The problem is that I'm not sure if this is always true for all z where $Real(z)>-1$. If it's not true I have no idea on how to determine if the integral is convergent or not. Anyone who knows if my idea was good and how to prove it? If it's nog the right way to handle this problem how to do it then? Thanks in advance !

A: If you know that $\int_0^\infty f(t)\,e^{-zt}\,dt$ converges for $\operatorname{Re}(z) > -1$, you can just take $z=0$ to see that $\int_0^\infty f(t)\,dt$ converges, and since $f$ is causal, this is the same as $\int_{-\infty}^\infty f(t)\,dt$.


text:
Q: OpenVPN: Transporting a connection from that 'other' OS? After finally making the change from windows to Ubuntu, one needed function remains unfulfilled - a needed connection via OpenVPN to a distant location.
I have all the files from the previously working configuration that match those at the other end, but have not been able to get the right info into the right places to make it work.
Posting at the OpenVPN forum has brought only nastiness in return from folks who use that place to promote their commercial agendas.
Given the state of things at present, visiting that location to make changes is not a viable option.
I am hoping very much that someone else here has made this change before & will kindly guide me so that I may have a working connection again.
Thanks for any helpful replies.

A: I posted my query here as I thought it was as simple as closing the gap in moving an OpenVPN connection from windows to Ubuntu.
That idea proved to be incorrect.
It turns out that it is a version mismatch between what Ubuntu is using now vs. what the PC at the distant location is using, that is an older version which I must travel there to update manually.
Since I cannot travel there in the present craziness, it must wait for me to do that.
In the meantime it is fortunate that I had the foresight to install the free version of Anydesk there such that I can access all EXCEPT for the OpenVPN server, and I am still able to fire up the old windows box here if I desperately need to use that connection.
The info I needed to identify that mismatch was provided at the server s/w site by a user who knew the correct & specific things to check in finding why my present OS could not log in.
Oversimplification=>
It is just too new !!


text:
Q: How do I store an instance variable across multiple actions in a controller? Say I want to store some variable in my controller.  I want to initialize it in one action, increment it in another, and read it in yet another.  Just declaring this variable with @foo doesn't work because @foo dies after the action that created it is rendered.
I do not want this variable to be stored in a model.
Is there a way to preserve this variable besides storing it in a session?
It seems like I've run into this simple problem a few times, and I want to know the best way to go about solving it.

A: You could make use of the built in Rails.cache mechanism to store the value but as mentioned in the first answer you'd have to key it off something like the user_id.  This is a nice way to go since you can back it with different storage mechanisms.
Rails.cache.write(:foo)
# in later action
Rails.cache.read(:foo)

One other thing you could look at is the flash hash, which provides a keep method to make the flash value last more than one subsequent request.
So in action 1 you could create the value:
flash[:foo] = some_value
flash.keep(:foo)

In action 2 you can access it, and call keep again if you want it to stay alive for more subsequent actions.
flash[:foo] #use it for something
flash.keep(:foo) # keep it for another request

It's a bit of a tricky thing to do cleanly within the context of http requests.

A: Not really. Each call to a controller action is stateless. Nothing is available after the controller action finishes. A new controller instance is created for each request, and then discarded at the end of the request.
If you don't want to store it in the session, or database model, you don't have many options if you're wanting that variable to be specific to a particular session.
If it is global across all sessions, you could put it in a @@class_variable rather than an @instance_variable, but that can get messy once you start having multiple Rails processes (each which will have their own copy of it), or if you're running in threadsafe mode, you can end up with nasty concurrency bugs.
I guess you could look at something like memcached, but you'd still need to key that to some user_id or other session marker (unless it's global)

A: I too am wondering why you are against using session? If you don't like working with session directly in your actions, you could emulate a surviving @foo instance variable with filters. Something like this maybe?
class FooController < ApplicationController
  before_filter :load_foo
  after_filter :save_foo

  private
    def load_foo
      @foo = session[:foo] || 0
    end

    def save_foo
      session[:foo] = @foo
    end

end

Your actions will the be able to manipulate the value through the @count instance variable and this will be automatically persisted to session.

A: If it's a simple count or string, I think the best solution is to store it in the session.  That way it will be there if you are using multiple web servers.
Why are you against using a session for this?

A: Don't worry, sessions won't bite.
Also, the session is probably the best way to do this.


text:
Q: Looking for a cause of random EAccessViolation in SysUtils.Format / System.Move I'm (users of my application are) experiencing weird EAccessViolation errors with a piece of code having no bad programming logic. The DisplayData function simply sets the caption of a label - no compile time errors, no bad data send to the SysUtils.Format() function.
MadExcept call stack looks like:
main thread ($1860):
00406a33 +067 MyApp.exe System            137   +0 Move
00452c9e +13e MyApp.exe System.SysUtils            AddBuf
0045365d +931 MyApp.exe System.SysUtils            WideFormatBuf
004528c0 +014 MyApp.exe System.SysUtils            FormatBuf
00452ab4 +0c0 MyApp.exe System.SysUtils            FmtStr
004529d2 +00e MyApp.exe System.SysUtils            Format
004529b7 +01b MyApp.exe System.SysUtils            Format
00b3aa55 +185 MyApp.exe mainunit     1506  +14 TMainForm.DisplayData

The error does not appear always, the function can be called few times (same parameters) and no error, then an error at random times.
I'm guessing there's some issue with memory here (there is enough available memory) - but have no idea how to help the user - or where to look for the cause.
Any ideas to what could be happening here ?

... as asked by David to show the real code, here goes:
TRadioButton(rgOperation.Controls[Integer(SelectedItem.Operation)]).Caption :=
TRadioButton(rgOperation.Controls[Integer(SelectedItem.Operation)]).Caption +
Format(' %s',[SelectedItem.History.OperationOn.TargetStr]);

Where:
rgOperation is a TRadioGroup. There are 4 radio buttons in the group.
SelectedItem.Operation is an enum (0..3). SelectedItem.History.OperationOn.TargetStr is a string. Nothing in a call to SelectedItem.History.OperationOn is nil.

A: If
Format('%s', [SelectedItem.History.OperationOn.TargetStr])

leads to an access violation inside Format then the only reasonable conclusion to draw is that
SelectedItem.History.OperationOn.TargetStr

is invalid. So, perhaps SelectedItem.History.OperationOn are all valid, but TargetStr is invalid. That's perhaps not so likely because I presume that TargetStr is a string and you have to work pretty hard to corrupt string variables.
More likely is that SelectedItem or History or OperationOn is invalid. Perhaps one of these refer to an object that has been destroyed and re-used by the memory manager. Your use of the stale reference could then lead to the error you observe.
You may well find that the full FastMM memory manager running in full debug mode helps identify the fault. If you are using an object after it has been destroyed, then full debug FastMM very likely will identify that for you.


text:
Q: segmentation fault on end of function below you can find my full code (yes, I've changed this to make it buildeable for tests and short)
It basically has to read file /var/log/messages and write on teste.txt only the IP addresses it finds
It works well, but it never print the "parte 8\n" after run the function (check function main())
It always run the code well, print everything, except what has after function
#include <stdio.h>
#include <string.h>
#include <netinet/ip.h>
#include <arpa/inet.h> // htons e inet_addr
#ifndef __FAVOR_BSD
#   define __FAVOR_BSD
#endif
#include <netinet/udp.h>
#include <netdb.h>
#include <netinet/in.h>
#include <string.h>

#include <sys/types.h>
#include <ifaddrs.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>

#define RANDOM() (int) random() % 255 +1

char * RetornaStringEntreStrings( char * primString, char * segString, char * stringao)
{
    char * posPrim = strstr(stringao, primString);
    if(posPrim <= 0)
    {
        return "";
    }
    posPrim += strlen(primString);

    char * posSeg = strstr(posPrim, segString);

    char * retorno;
    memcpy(retorno, posPrim, posSeg-posPrim);
    retorno[posSeg-posPrim] = 0;
    return retorno;
}

int ExisteIPnoArquivo(char *ip, char *arquivoNome)
{
    FILE *arquivo = fopen(arquivoNome, "r");
    char buffer[128];

    if(arquivo != NULL)
    {
        while(fgets(buffer, 128, arquivo))
        {
            if(strcmp(ip, buffer) == 0)
            {
                fclose(arquivo);
                return 1;
            }
        }
        fclose(arquivo);
        return 0;
    }
    else
        printf("Nao foi possivel abrir o arquivo.\n");

    return 0;
}

void EscreverArquivo(char * string, char * arquivoNome)
{
    FILE *arquivo = fopen(arquivoNome, "a+");

    if(arquivo == NULL)
    {
        printf("Erro na abertura do arquivo!");
    }
    else
    {
        fprintf(arquivo, "%s", string);
        fclose(arquivo);
    }
}

void SalvarLogsArquivo(char * arquivoNome)
{
    FILE *arquivo = fopen("/var/log/messages", "r");
    char buffer[512];

    // testa se o arquivo foi aberto com sucesso
    if(arquivo != NULL)
    {
        while(fgets(buffer, 512, arquivo))
        {
            char * IP = RetornaStringEntreStrings("SRC=", " ", buffer);
            if(strlen(IP) < 7)
                continue;

            strcat(IP, "\n");
            if(ExisteIPnoArquivo(IP, arquivoNome) == 0)
            {
                printf("Adicionando IP: %s", IP);
                EscreverArquivo(IP, arquivoNome);
            }
            else
                printf("IP ja encontrado: %s", IP);
        }
        fclose(arquivo); // libera o ponteiro para o arquivo
    }
    else
        printf("Nao foi possivel abrir o arquivo.");

    printf("End of Function (segmentation fault below will happen below)\n");
}

int main()
{
    SalvarLogsArquivo("teste.txt");
    printf("After function, it doesn't run cuz it gets segmentation fault before\n");
}

A: This is the cause
char * retorno;
memcpy(retorno, posPrim, posSeg-posPrim);

You didn't allocate memory for retorno, you need to with malloc(). Example
retorno = malloc(posSeg - posPrim + 1);
if (retorno != NULL)
{
    memcpy(retorno, posPrim, posSeg - posPrim);
    retorno[posSeg - posPrim] - '\0';
}

A: In your function RetornaStringEntreStrings() you copy data to an uninitialized pointer which might segfault (in general it's undefined behavior):
 char * retorno;
 memcpy(retorno, posPrim, posSeg-posPrim);


text:
Q: May I use a root user to expose the python bottle application to the Internet? I made a WEB application using Bottle and want to publish it. I decided to use paste for the web server because official document said it's the easiest way.
In order to let the web server process listen on the port 80, the process must be launched by the root user. I'm not a security expert and can not judge that it's safe to use the root user for launching an application that is exposed to the internet directly.
Shall I avoid using root user in such a situation ?

A: No.
Do not run your web server as root.

Shall I avoid using root user in such a situation?

Yes, avoid running as root.

In order to let the web server process listen on the port 80

Your web server does not need to listen on port 80. One common way to structure this is to put a proxy (like a load balancer) in front of your web server. Your server listens on a non-privileged port (e.g. 8000); the load balancer (which is listening on port 80) forwards all requests to your server.
The accepted answer (which does not actually answer your question) merely mentions chroot, but I suggest that you not worry about that. Running as a non-privileged user is a much more important safeguard than using chroot. I would consider chroot to be secondary to your initial, quite legitimate, concerns over running as root.

A: It is recommended to create an chrooted environment with an restricted user.
Over here you can find a howto on how to create a chrooted environment www.howtogeek.com/441534/how-to-use-the-chroot-command-on-linux/amp/


text:
Q: Brownian motion on a $\mathbb{Z}$-cover Let $(M,g)$ a smooth closed Riemannian manifold with non trivial first homology group $H^1(M,\mathbb{R})$. Any element of  $H^1(M,\mathbb{Z})$ will define a riemannian $\mathbb{Z}$-cover of $M$ denoted by $M_{\mathbb{Z}}$. Let us fix a base point $x_0$ on $M_{\mathbb{Z}}$ and consider the Brownian motion starting at $x_0$ and a ball $B$ of radius $C >0$ of center $x_0$.

Question. Does the probability of such a process to come back in the ball $B$ in time $t$ is like $\sqrt{t}$ ?

As it is true for $\mathbb{R}$ endowed with the flat metric I wish the same result holds also in this set up. A $\mathbb{Z}$-cover should look like $\mathbb{R}$ in large scale.


text:
Q: Sample Autocovariance Suppose that we have a wide sense stationary process $X_t$.
Without loss of generalization assuming that mean is 0, lag one covariance is $\mathbb{E}[X_t X_{t-1}]$.
In order to estimate the covariance, I use the sample version:
$$\frac{1}{N}\sum_1^N X_t X_{t-1}$$
What's bothering me here is the consecutive products i.e. $X_t X_{t-1}$ and $X_{t-1} X_{t-2}$ are not independent due to the shared $X_{t-1}$ component.
It looks like this is a mean of non-IID samples.
Question: Is this something to worry about?
What are some issues to be careful about (especially for the small sample case)?

A: We need the stochastic process $\{Z_t\} = \{X_tX_{t-1}\}$ to have a constant mean  and be "ergodic for the mean".
If these properties hold then the Birkhoff–Khinchin Ergodic Theorem states that
$$\frac 1T \sum Z_t \to_p \mu_z = \text{Cov}(X_t,X_{t-1})$$
Let $\gamma_k \equiv E(X_tX_{t-k})$ . If
$$\sum_{k=0}^{\infty} |\gamma_k|< +\infty$$
then the process $\{X_t\}$ is ergodic for the mean.
Assume that it is. Then continuous transformations of $\{X_t\}$ are also ergodic for the mean. Then (to be a little pedantic), $W_t \equiv LX_t = X_{t-1}$ is ergodic for the mean because the transformation induced by the lag operator is continuous. Also, multiplication and addition are continuous transformations. Then
$$Z_t = X_t \cdot W_t = X_tX_{t-1}$$
is ergodic for the mean.
Moreover, $\{Z_t\}$ has a constant mean since
$$E(Z_t) = E(X_tX_{t-1}) = \text{Cov}(X_t,X_{t-1}) = \gamma_1$$
which is constant and does not depend on the index $t$, due to $\{X_t\}$ being covariance-stationary.
So for asymptotic consistency of the sample covariance, the essential condition is the absolute summability condition on the autocovariance series of $\{X_t\}$.
I note that the fact that autocovariances of $\{X_t\}$ "do not depend on the index only on the distance", does not make them absolutely summable. We can conceive of a situation (although perhaps counter-intuitive both from a space-perspective and from a time-perspective), in which as the distance increases, the autocovariance increases also.


text:
Q: Parsing xml with StAX: not getting a large content tag I am using StAX to parse my xml file, the problem is that when the tag content is large, StAX is not able to give me the whole content.
Here is a part of my xml doc, the content of payload tag is so much more larger, can't print it all in SOF:
<payload>{\"id\": \"ENTITY24\",\"attr1\": {\"type\": \"sensor\",\"type\": \"type1\",\"value\": \"val1\",\"metadata\": {}}}</payload>

Here is a part of my code parsing it:
if(startElement.getName().getLocalPart().equals("payload")){
    xmlEvent = xmlEventReader.nextEvent();
    if(xmlEvent.isCharacters()){
       setPayload(xmlEvent.asCharacters().getData());
    }
}

Any idea why StAX is not able to give the whole tag content?
Thanks and best regards.

A: You should either concatenate all isCharacters events between other events or set the IS_COALESCING property.
Just like with SAX, STAX may offer you one single run of characters as multiple events.


text:
Q: What is the "regional Pokémon" for south America? The question: What are the regional Pokemon? does not address South America (hereby referred as SA), basically because at the time of the posting the game had not launched in South America (SA).
The question linked above was posted before South America launch, and does not address if the north america Pokémon can be caught in South America too. Therefore, not a duplicate.
Tauros is the Pokémon for North America? Is it the same for SA?
If not, is there any hard evidence of some of the "regional" Pokémon being caught in SA?

A: Here are the regional Pokémon in Pokémon Go.
It shows Mr Mime in Europe, Tauros in the Americas, Farfetch'd in Asia and Kangaskhan in Australia.
To clarify, South America has the same regional Pokémon as North America.


text:
Q: Analytical functions: enumerate, order I have added 2 columns through analytical functions with the next information:

*

*A column -position- that enumerates the encounters of each user, ordered chronologically.

*A column -cost- containing the sum of the costs of the different services created for that encounter.
But I could not solve the next issues:

*

*The column 'cost' is not sorted chronologically for each user.

*At column 'position', it shows the total number of encounters, but I would
that it were from 1 until the total.

Here is both table and data for testing:
CREATE TABLE users (
  user_id INT PRIMARY KEY,
  name CHARACTER VARYING(50)
);

CREATE TABLE orders_catalog (
    order_code INT PRIMARY KEY,
    order_desc CHARACTER VARYING(50) NOT NULL,
    cost REAL NOT NULL
);

CREATE TABLE encounter (
    encounter_id INT PRIMARY KEY,
    user_id INT NOT NULL,
    encounter_type CHARACTER VARYING(50) NOT NULL,

    CONSTRAINT FK_encounter FOREIGN KEY (user_id) REFERENCES users(user_id)
);

CREATE TABLE orders (
    order_id INT PRIMARY KEY,
    order_code INT NOT NULL,
    encounter_id INT NOT NULL,
    created_dt TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT FK_orders_catalog FOREIGN KEY (order_code) REFERENCES orders_catalog (order_code),
    CONSTRAINT FK_orders_encounter FOREIGN KEY (encounter_id) REFERENCES encounter(encounter_id)
);
--

INSERT INTO users(user_id, name) VALUES(1, 'Peter');
INSERT INTO users(user_id, name) VALUES(2, 'Charles');
INSERT INTO users(user_id, name) VALUES(3, 'Eva') ;
INSERT INTO users(user_id, name) VALUES(4, 'John');
INSERT INTO users(user_id, name) VALUES(5, 'Helene');

INSERT INTO orders_catalog(order_code, order_desc, cost) VALUES (10000, 'Painting', 100.34);
INSERT INTO orders_catalog(order_code, order_desc, cost) VALUES (10001, 'Painting', 214.11);
INSERT INTO orders_catalog(order_code, order_desc, cost) VALUES (10002, 'Painting', 214.11);
INSERT INTO orders_catalog(order_code, order_desc, cost) VALUES (10003, 'Spare part', 181.03);
INSERT INTO orders_catalog(order_code, order_desc, cost) VALUES (10004, 'Sheet metal', 168.18);
INSERT INTO orders_catalog(order_code, order_desc, cost) VALUES (10005, 'Sheet metal', 240.02);
INSERT INTO orders_catalog(order_code, order_desc, cost) VALUES (10006, 'Sheet metal', 240.02);
INSERT INTO orders_catalog(order_code, order_desc, cost) VALUES (10007, 'Electricity', 146.85);
INSERT INTO orders_catalog(order_code, order_desc, cost) VALUES (10008, 'Spare part', 162.13);
INSERT INTO orders_catalog(order_code, order_desc, cost) VALUES (10009, 'Electricity', 140.02);
INSERT INTO orders_catalog(order_code, order_desc, cost) VALUES (10010, 'Electricity', 180.02);

INSERT INTO encounter(encounter_id, user_id, encounter_type) VALUES(100,1,'appointment');
INSERT INTO encounter(encounter_id, user_id, encounter_type) VALUES(101,2,'appointment');
INSERT INTO encounter(encounter_id, user_id, encounter_type) VALUES(102,3,'appointment');
INSERT INTO encounter(encounter_id, user_id, encounter_type) VALUES(103,4,'urgent');
INSERT INTO encounter(encounter_id, user_id, encounter_type) VALUES(104,5,'urgent');
INSERT INTO encounter(encounter_id, user_id, encounter_type) VALUES(105,1,'appointment');
INSERT INTO encounter(encounter_id, user_id, encounter_type) VALUES(106,2,'appointment');
INSERT INTO encounter(encounter_id, user_id, encounter_type) VALUES(107,3,'waiting');
INSERT INTO encounter(encounter_id, user_id, encounter_type) VALUES(108,4,'urgent');
INSERT INTO encounter(encounter_id, user_id, encounter_type) VALUES(109,5,'waiting');
INSERT INTO encounter(encounter_id, user_id, encounter_type) VALUES(110,1,'waiting');

INSERT INTO orders(order_id, order_code, encounter_id, created_dt) VALUES (1000,10000,100,'2009-06-16 09:12');
INSERT INTO orders(order_id, order_code, encounter_id, created_dt) VALUES (1001,10001,101,'2009-06-16 09:12');
INSERT INTO orders(order_id, order_code, encounter_id, created_dt) VALUES (1002,10002,102,'2009-06-16 09:12');
INSERT INTO orders(order_id, order_code, encounter_id, created_dt) VALUES (1003,10003,103,'2009-12-03 09:50');
INSERT INTO orders(order_id, order_code, encounter_id, created_dt) VALUES (1004,10004,104,'2010-02-24 12:21');
INSERT INTO orders(order_id, order_code, encounter_id, created_dt) VALUES (1005,10005,105,'2010-03-27 23:54');
INSERT INTO orders(order_id, order_code, encounter_id, created_dt) VALUES (1006,10006,106,'2010-03-22 12:43');
INSERT INTO orders(order_id, order_code, encounter_id, created_dt) VALUES (1007,10007,107,'2010-02-24 12:21');
INSERT INTO orders(order_id, order_code, encounter_id, created_dt) VALUES (1008,10008,108,'2010-03-04 08:55');
INSERT INTO orders(order_id, order_code, encounter_id, created_dt) VALUES (1009,10009,109,'2010-03-06 09:25');
INSERT INTO orders(order_id, order_code, encounter_id, created_dt) VALUES (1010,10010,110,'2010-03-22 11:18');

And here is the query that I tried:
SELECT
  u.user_id,
  name,
  COUNT (e.encounter_type) OVER (
    PARTITION BY u.user_id
  ) AS position,
  SUM (c.cost) OVER (
    PARTITION BY o.encounter_id ORDER BY o.created_dt DESC
  ) AS cost
FROM
  users u
INNER JOIN
  encounter e USING (user_id)
INNER JOIN
  orders o USING (encounter_id)
INNER JOIN
  orders_catalog c USING (order_code)
ORDER BY user_id;

But the output is not what I expect:
1   "Peter" 3   180.02
1   "Peter" 3   240.02
1   "Peter" 3   100.34
2   "Charles"   2   240.02
2   "Charles"   2   214.11
3   "Eva"   2   214.11
3   "Eva"   2   146.85
4   "John"  2   181.03
4   "John"  2   162.13
5   "Helene"    2   168.18
5   "Helene"    2   140.02

Since I would want something like:
1   "Peter" 1   100.34
1   "Peter" 2   240.02
1   "Peter" 3   180.02
...

FIDDLE

A: ROW_NUMBER is a btter choice, for what you want

SELECT
  u.user_id,
  name,
  ROW_NUMBER() OVER (
    PARTITION BY u.user_id
  ) AS position,
  SUM (c.cost) OVER (
    PARTITION BY o.encounter_id ORDER BY o.created_dt DESC
  ) AS cost
FROM
  users u
INNER JOIN
  encounter e USING (user_id)
INNER JOIN
  orders o USING (encounter_id)
INNER JOIN
  orders_catalog c USING (order_code)
ORDER BY user_id;

user_id | name    | position | cost
------: | :------ | -------: | :-----
      1 | Peter   |        1 | 180.02
      1 | Peter   |        2 | 240.02
      1 | Peter   |        3 | 100.34
      2 | Charles |        1 | 240.02
      2 | Charles |        2 | 214.11
      3 | Eva     |        1 | 214.11
      3 | Eva     |        2 | 146.85
      4 | John    |        1 | 181.03
      4 | John    |        2 | 162.13
      5 | Helene  |        1 | 168.18
      5 | Helene  |        2 | 140.02

db<>fiddle here


text:
Q: Interface that enforces a constructor signature Why does class C
class C implements N, M {
  constructor(public a: number) {}
}

not satisfy the the interfaces M or N?
interface M {
  constructor(a: number)
}
interface N {
  new(a: number)
}

How do I write an interface that C satisfies?


text:
Q: Supermicro X7DVA Not Recognizing More Than 4GB of RAM We've got several Supermicro servers that we're trying to upgrade the RAM on so that we can run virtual servers on them, but only a few of them took the RAM upgrade that we performed. We double-checked to make sure that the RAM was all in the proper slots and that the RAM itself wasn't bad. We also flashed the bios to the most recent version to make sure that wasn't the problem, but to no avail. A large number of our servers just won't see more than 4GB of RAM. The ones that do don't have any apparent differences to the ones that don't, so we're completely stumped.
Any ideas or suggestions anyone can give will be extremely helpful.

A: You're running a 32bit OS, so I believe you'll need to install the specific PAE kernel, or install a 64bit version of your OS to enable the OS to address more than 4Gb of RAM:
yum install kernel-PAE
I would advise 64bit OS rather than 32Bit+PAE as it handles >4GB of memory far better, but if you can't do a re-install PAE should at least enable you to use the RAM.

A: Have you tried setting the BIOS 4GB PCI Hole Granularity to 1GB?  Also make sure you are using pairs in channels 1A-2A, 1B-2B and so on.
When I say 1A-2A that means slots 1 and 4.  This board has the slots going in order: 1A, 1B, 1C, 2A, 2B, 2C.  If you use 2 sticks you can use either 1A-2A or 1A-1B configuration.  When using 3 sticks: 1A, 1B, 1C.  When 4 or 6 you must pair up the memory banks: 1A-2A, 1B-2B, 1C-2C


text:
Q: Undo all new commits in a branch Unintended I pull a remote branch feature1 into development
1. git checkout development
2. git pull origin feature1

The branch development is ahead of origin/development by N commits. I can't push changes to origin/development. After pull, I tried run merge --abort but it did not work.
Is there a way to undo all new changes (commits to push) in a branch in particular?

A: Issue the following command while branch development is checked out:
git reset --hard origin/development

This will reset your local development branch to point to the same commit as origin/development (the commit you were on before pull).
Precautions:  Do not use the --hard option if you have local uncommitted changes you wish to keep.
If you have unpushed commits on your local development branch you wish to keep you should use the commit id of the latest commit on development instead of origin/development.

A: git reset should help you out. you can roll back commits on your branch.
Assuming the merge was clean and you just have a linear history, then executing this from the development branch:
git reset --hard HEAD~N

will undo the latest N commits on the development branch. Just be careful since the --hard will throw them away and they'll be gone forever if the commits aren't backed up on another branch. But it sounds like you already have those N commits on the feature branch.


text:
Q: Problems to understand the definition of the level of significance $\alpha$ I'm having problems to understand the definition of the level of significance $\alpha$. I thought I knew what $\alpha$ is but I realized I don't.
When I stated to study statistics by myself I read this introductory book and everything was fine, the definition is very clear. He says on page 290:

You're probably wondering, how small does a p-value have to be for us
to achieve statistical significance? If we agree that a p-value of
$0.0001$ is clearly statistically significant and a p-value of $0.50$ is not, there must be some point between $0.0001$ and $0.50$ where we cross
the threshold between statistical significance and random chance. That
point, measuring when something becomes rare enough to be called
"unusual," might vary a lot from person to person. We should agree in
advance on a reasonable cutoff point. Statisticians call this cutoff
point the significance level of a test and usually denote it with the
Greek letter $\alpha$ (alpha). For example, if $\alpha = 0.05$ we say we are doing
a $5\%$ test and will call the results statistically significant if the
p-value for the sample is smaller than $0.05$. Often, short hand
notation such as $P < 0.05$ is used to indicate that the p-value is less
than $0.05$, which means the results are significant at a $5\%$ level.

Now, I'm studying about statistical inference, a more advanced subject, and I realized there are some concepts that don't exactly have the same definition as I studied before. The level of significance is an example.
I'm reading this book and on page 352 he introduces the Neyman-Pearson lemma as a method to find the UMP test.

Example:
On the basis of a random sample of size $1$ from the p.d.f. $f(x;
 \theta)=\theta x^{\theta-1},\ 0 < x < 1\ (\theta > 1)$:
For $\theta_1>\theta_0$ , the cutoff point is calculated by:
... $C=(1−\alpha)^{\frac{1}{\theta_0}}$
For $\theta_1<\theta_0$ , we have:
... $C = \alpha^{\frac{1}{\theta_0}}$

So in this second book, the cutoff point is not necessarily $\alpha$, I'm confused.
MY ATTEMPT TO UNDERSTAND WITH THE HELP OF THE ANSWERS
The alpha is predetermined, but it doesn't mean I can't have a smaller rejection region. Then I end up having a smaller rejection region using NP lemma with the same level of significance alpha. Some introductory books let the cutoff point to be $\alpha$ by standard (why?), that's the reason of my confusion, I can shrink the rejection region keeping the value of $\alpha$. Can someone say if I'm right?

A: First remember that you are dealing with simple hypothesis (both simple).
Applying NP Lemma you get that the critical region is
$$\frac{ \theta_0x^{\theta_0-1} }{ \theta_1x^{\theta_1-1}   }\leq k$$
$$x^{\theta_0-\theta_1}\leq k^*$$
Now it is easy to observe that

*

*if $\theta_0>\theta_1$ the critical region can be viewed as $x\leq  c$ and thus, by definition of $\alpha$ you get

$$\int_0^c \theta_0x^{\theta_0-1}dx=\alpha\rightarrow c=\alpha^{1/\theta_0}$$

*

*if $\theta_0<\theta_1$ with similar reasoning (that I left to you as an exercise) the critical region can be viewed as $x\geq c$ that is $c=(1-\alpha)^{1/\theta_0}$

In these formulas $\alpha$ is the given significance level. Usually $5\%$ for a significant test or $1\%$ for a high significant test

Definition of $\alpha$
$$\alpha=\mathbb{P}[\mathbf{x}\in C|H_0]$$
Where $C$ is the critical region calculated with NP Lemma

I suggest you to read Casella Berger or Mood Graybill Boes that are two reference textbook for these arguments

A: You are misunderstanding what "cutoff" means in the context of the Neyman-Pearson lemma. It is referring to a cutoff of the likelihood ratio in the test, not as a cutoff of what $p$-values are small enough to be significant.

A $p$-value (of some results) represents the probability under the null hypothesis of getting results at least as extreme/unusual as your current results. The idea is that seeing results that are unusual under the null hypothesis should be evidence to reject the null hypothesis. To decide how small a $p$-value is small enough to be significant, you must set a significance level, say $\alpha = 0.05$; if your $p$-value is smaller than $\alpha$, this indicates that your data is unusual under the null, so you reject the null.
Comparing $p$-values against $\alpha$ guarantees that your Type I error is $\le \alpha$: if the null is true, the probability that your test is wrong is $\le \alpha$. More generally, this is how you should be thinking about significance levels: as Type I error (probability that a test rejects the null if null is true). This is important for likelihood ratio tests, where there aren't $p$-values being computed anywhere.

"Cutoff" in Neyman-Pearson
In this context, you are forming a test based on a statistic called the likelihood ratio $\Lambda(x) = \frac{L_1(\theta \mid x)}{L_0(\theta \mid x)}$. (I am following your textbook's convention of putting the null in the denominator.)
The test is of the form

reject $H_0$ if $\Lambda(x) >C$
do not reject $H_0$ if $\Lambda(x) < C$

for some cutoff $C$. (I'm ignoring the case where the likelihood ratio equals $C$ for simplicity.) The intuition is that if the data $x$ seem to support the alternative hypothesis, the numerator of the likelihood ratio would be large so we would lean toward rejecting; likewise if the data $x$ seem to support the null, the denominator would be large and we would lean toward not rejecting. This is $C$ is what the "cutoff" is in the Neyman-Pearson example. It is not a cutoff for what $p$-values are small enough to be significant.
How do we choose the cutoff?
If $C$ is large, then you reject less often (leading to small Type I error); if $C$ is small you reject more often (leading to large Type I error). If you have set a significance level, then you must set $C$ large enough to avoid a large Type I error. The example you are reading is solving for the smallest $C$ that keeps the Type I error below $\alpha$.


text:
Q: Why doesn't OpenGL draw a polygon in this code? Here is the simplest code, but it does not represent anything. That isn't possible. Everything seems to be absolutely correct. However, I only see a black background. It used to work all the time, but now it doesn't. The color is correct and the blue triangle should be visible. But nothing.
Code:
#include <iostream>
#include <chrono>
#include <GL/glut.h>

using namespace std;

constexpr auto FPS_RATE = 60;
int windowHeight = 600, windowWidth = 600;

void init();
void displayFunction();
void idleFunction();
double getTime();

double getTime()
{
    using Duration = std::chrono::duration<double>;
    return std::chrono::duration_cast<Duration>(
        std::chrono::high_resolution_clock::now().time_since_epoch()
        ).count();
}

const double frame_delay = 1.0 / FPS_RATE;
double last_render = 0;

void init()
{
    glutDisplayFunc(displayFunction);
    glutIdleFunc(idleFunction);
    glClearColor(0.0, 0.0, 0.0, 0.0);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluOrtho2D(-windowWidth / 2, windowWidth / 2, -windowHeight / 2, windowHeight / 2);
}

void idleFunction()
{
    const double current_time = getTime();
    if ((current_time - last_render) > frame_delay)
    {
        last_render = current_time;
        glutPostRedisplay();
    }
}

void displayFunction()
{
    glClear(GL_COLOR_BUFFER_BIT);

    glBegin(GL_POLYGON);
    glColor3i(0, 0, 1);

    glVertex2i(-50, 0);
    glVertex2i(50, 0);
    glVertex2i(0, 50);
    glVertex2i(100, 50);

    glEnd();
    glutSwapBuffers();
}

int main(int argc, char* argv[])
{
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
    glutInitWindowSize(windowWidth, windowHeight);
    glutInitWindowPosition((GetSystemMetrics(SM_CXSCREEN) - windowWidth) / 2, (GetSystemMetrics(SM_CYSCREEN) - windowHeight) / 2);
    glutCreateWindow("Window");
    init();
    glutMainLoop();
    return 0;
}

A: The issue is glColor3i.
When you would use
glColor3f(0, 0, 1.0f);

then you would see a full blue colored polygon. But when you want to use glColor3i, then the color has to be set to
glColor3i(0, 0, 2147483647); // 2147483647 == 0x7fffffff

to get a polygon with the same blue color.
When you use the the version of glColor with integral signed arguments, like glColor3b, glColor3s or glColor3i, then the full range of the integral value is mapped to the floating point range [-1.0, 1.0]. So for glColor3i the integral values in range [−2.147.483.648, 2.147.483.647] are mapped to [-1.0, 1.0] (See Common integral data types).
The unsigned version of glColor like glColor3ub, glColor3us or glColor3ui maps the integral values to the range [0.0, 1.0]. e.g glColor3ub maps the arguments from [0, 255] to [0.0, 1.0].


text:
Q: Google Chrome sends 2 requests to every controller/ razor page For some reason, Google Chrome sends 2 requests to every webpage on my solution. I originally experienced this issue on an MVC web application but then I made a test project without using MVC and this continued to happen.
This does not happen with Edge or Internet Explorer.
Did anybody experience the same problem and how did you go about it?
Most of my research pointed in the direction of having an href="#" tag that would cause the browser to reload the page but this is not the case in my situation.
This normally would not be an issue, but it seems to be causing the AntiForgeryRequestToken to not get validated

A: 2 requests means the total SAME requests or an 'OPTIONS' method and a normal medthod?
if you are in the second situation, you will need use IIS/ngnix to Url Rewrite to make sure your chrome Url and your ajax request url are in the same domain.


text:
Q: Generate alphanumeric unique numbers I want to generate alphanumeric unique numbers but the format should be like this
that should be starts from AA001 to AA999 after that AB001 to AB999 .... BA001 to BA999 end with ZZ999. if i give the input is
  1 = result AA001
 999  = result AA999
 1000 = result AB001

any one can help this ?

A: Complete solution (see it running):
function formatNum1000($num) {
  $tail =       $num % 1000;
  $head = (int)($num / 1000);
  $char1 = chr(ord('A') + (int)($head / 26));
  $char2 = chr(ord('A') +      ($head % 26));

  return sprintf('%s%s%03d', $char1, $char2, $tail);
}

function formatNum999($num) {
  $tail =      (($num - 1    ) % 999) + 1;
  $head = (int)(($num - $tail) / 999);
  $char1 = chr(ord('A') + (int)($head / 26));
  $char2 = chr(ord('A') +      ($head % 26));

  return sprintf('%s%s%03d', $char1, $char2, $tail);
}

$ns = array(1, 500, 999, 1000, 1998, 1999, 2000, 25974, 25975, 25999, 26000, 675324, 675999);
foreach($ns as $n) {
  $formatted1000 = formatNum1000($n);
  $formatted999  = formatNum999 ($n);
  echo "Num: $n => $formatted1000 / $formatted999\n";
}

Note: you need to make sure that the input number is within the valid range (0...675999 when including 000-numbers, 1...675324 otherwise)
Note: answer revised, missed the point earlier that 000 is not allowed

A: How about:
$start = 'AA997';
for($i = 0; $i < 5; $i++) {
    $start++;
    if (substr($start, 2) == '000') continue;
    echo $start,"\n";
}

output:
AA998
AA999
AB001
AB002


text:
Q: Disable output buffering Is output buffering enabled by default in Python's interpreter for sys.stdout?
If the answer is positive, what are all the ways to disable it?
Suggestions so far:

*

*Use the -u command line switch

*Wrap sys.stdout in an object that flushes after every write

*Set PYTHONUNBUFFERED env var

*sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
Is there any other way to set some global flag in sys/sys.stdout programmatically during execution?

If you just want to flush after a specific write using print, see How can I flush the output of the print function?.

A: # reopen stdout file descriptor with write mode
# and 0 as the buffer size (unbuffered)
import io, os, sys
try:
    # Python 3, open as binary, then wrap in a TextIOWrapper with write-through.
    sys.stdout = io.TextIOWrapper(open(sys.stdout.fileno(), 'wb', 0), write_through=True)
    # If flushing on newlines is sufficient, as of 3.7 you can instead just call:
    # sys.stdout.reconfigure(line_buffering=True)
except TypeError:
    # Python 2
    sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)

Credits: "Sebastian", somewhere on the Python mailing list.

A: You can also run Python with stdbuf utility:
stdbuf -oL python <script>

A: Yes, it is.
You can disable it on the commandline with the "-u" switch.
Alternatively, you could call .flush() on sys.stdout on every write (or wrap it with an object that does this automatically)

A: From Magnus Lycka answer on a mailing list:

You can skip buffering for a whole
python process using python -u
or by
setting the environment variable
PYTHONUNBUFFERED.
You could also replace sys.stdout with
some other stream like wrapper which
does a flush after every call.
class Unbuffered(object):
   def __init__(self, stream):
       self.stream = stream
   def write(self, data):
       self.stream.write(data)
       self.stream.flush()
   def writelines(self, datas):
       self.stream.writelines(datas)
       self.stream.flush()
   def __getattr__(self, attr):
       return getattr(self.stream, attr)

import sys
sys.stdout = Unbuffered(sys.stdout)
print 'Hello'

A: One way to get unbuffered output would be to use sys.stderr instead of sys.stdout or to simply call sys.stdout.flush() to explicitly force a write to occur.
You could easily redirect everything printed by doing:
import sys; sys.stdout = sys.stderr
print "Hello World!"

Or to redirect just for a particular print statement:
print >>sys.stderr, "Hello World!"

To reset stdout you can just do:
sys.stdout = sys.__stdout__

A: You can create an unbuffered file and assign this file to sys.stdout.
import sys
myFile= open( "a.log", "w", 0 )
sys.stdout= myFile

You can't magically change the system-supplied stdout; since it's supplied to your python program by the OS.

A: You can also use fcntl to change the file flags in-fly.
fl = fcntl.fcntl(fd.fileno(), fcntl.F_GETFL)
fl |= os.O_SYNC # or os.O_DSYNC (if you don't care the file timestamp updates)
fcntl.fcntl(fd.fileno(), fcntl.F_SETFL, fl)

A: It is possible to override only write method of sys.stdout with one that calls flush. Suggested method implementation is below.
def write_flush(args, w=stdout.write):
    w(args)
    stdout.flush()

Default value of w argument will keep original write method reference. After write_flush is defined, the original write might be overridden.
stdout.write = write_flush

The code assumes that stdout is imported this way from sys import stdout.

A: This relates to  Cristóvão D. Sousa's answer, but I couldn't comment yet.
A straight-forward way of using the flush keyword argument of Python 3 in order to always have unbuffered output is:
import functools
print = functools.partial(print, flush=True)

afterwards, print will always flush the output directly (except flush=False is given).
Note, (a) that this answers the question only partially as it doesn't redirect all the output. But I guess print is the most common way for creating output to stdout/stderr in python, so these 2 lines cover probably most of the use cases.
Note (b) that it only works in the module/script where you defined it. This can be good when writing a module as it doesn't mess with the sys.stdout.
Python 2 doesn't provide the flush argument, but you could emulate a Python 3-type print function as described here https://stackoverflow.com/a/27991478/3734258 .

A: Variant that works without crashing (at least on win32; python 2.7, ipython 0.12) then called subsequently (multiple times):
def DisOutBuffering():
    if sys.stdout.name == '<stdout>':
        sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)

    if sys.stderr.name == '<stderr>':
        sys.stderr = os.fdopen(sys.stderr.fileno(), 'w', 0)

A: (I've posted a comment, but it got lost somehow. So, again:)

*

*As I noticed, CPython (at least on Linux) behaves differently depending on where the output goes. If it goes to a tty, then the output is flushed after each '\n'
If it goes to a pipe/process, then it is buffered and you can use the flush() based solutions or the -u option recommended above.

*Slightly related to output buffering:
If you iterate over the lines in the input with
for line in sys.stdin:
...
then the for implementation in CPython will collect the input for a while and then execute the loop body for a bunch of input lines. If your script is about to write output for each input line, this might look like output buffering but it's actually batching, and therefore, none of the flush(), etc. techniques will help that.
Interestingly, you don't have this behaviour in pypy.
To avoid this, you can use
while True:
   line=sys.stdin.readline()
...

A: I would rather put my answer in How to flush output of print function? or in Python's print function that flushes the buffer when it's called?, but since they were marked as duplicates of this one (what I do not agree), I'll answer it here.
Since Python 3.3, print() supports the keyword argument "flush" (see documentation):
print('Hello World!', flush=True)

A: def disable_stdout_buffering():
    # Appending to gc.garbage is a way to stop an object from being
    # destroyed.  If the old sys.stdout is ever collected, it will
    # close() stdout, which is not good.
    gc.garbage.append(sys.stdout)
    sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)

# Then this will give output in the correct order:
disable_stdout_buffering()
print "hello"
subprocess.call(["echo", "bye"])

Without saving the old sys.stdout, disable_stdout_buffering() isn't idempotent, and multiple calls will result in an error like this:
Traceback (most recent call last):
  File "test/buffering.py", line 17, in <module>
    print "hello"
IOError: [Errno 9] Bad file descriptor
close failed: [Errno 9] Bad file descriptor

Another possibility is:
def disable_stdout_buffering():
    fileno = sys.stdout.fileno()
    temp_fd = os.dup(fileno)
    sys.stdout.close()
    os.dup2(temp_fd, fileno)
    os.close(temp_fd)
    sys.stdout = os.fdopen(fileno, "w", 0)

(Appending to gc.garbage is not such a good idea because it's where unfreeable cycles get put, and you might want to check for those.)

A: The following works in Python 2.6, 2.7, and 3.2:
import os
import sys
buf_arg = 0
if sys.version_info[0] == 3:
    os.environ['PYTHONUNBUFFERED'] = '1'
    buf_arg = 1
sys.stdout = os.fdopen(sys.stdout.fileno(), 'a+', buf_arg)
sys.stderr = os.fdopen(sys.stderr.fileno(), 'a+', buf_arg)

A: Yes, it is enabled by default. You can disable it by using the -u option on the command line when calling python.

A: In Python 3, you can monkey-patch the print function, to always send flush=True:
_orig_print = print

def print(*args, **kwargs):
    _orig_print(*args, flush=True, **kwargs)

As pointed out in a comment, you can simplify this by binding the flush parameter to a value, via functools.partial:
print = functools.partial(print, flush=True)


text:
Q: Angular Firebase Getting Zoneaware with Promisses I don't understand why I'm getting a Zoneaware with this code. Can anybody help me?
Here is the rational:
Step 1 get the data as an array and then map it and call step 2.
Step 2 get the ID executorID from the step1 and return an object.
Step 3 get the users data and return an object. Please ignore the ELSE, that's for something else.
So the idea is that in the end I get a complete object.
// Step 1 get the data as an array and then map it and call step 2.
getPanic(checkID: string) {
    return this.db.firestore.collection(`${this.PATH}`).where('checkId', '==', checkID).get()
        .then(data => {
            return data.docs.map(async d => {
                const panicObj = {id: d.id, ...d.data() } as any;
                panicObj.actions = await this.getActions(panicObj.id);
                return panicObj;
            });
        })
        .catch((err) => console.log(err));
}

// Step 2 get the ID executorID from the step1 and return an object,
getActions(panicID: string) {
    return this.db.firestore.collection(`${this.PATH}${panicID}/actions`).get()
            .then(data => {
                return data.docs.map(async d => {
                    const actionObj = d.data();
                    actionObj.executorData = await this.userService.getUser(actionObj.executor, true);
                    return actionObj;
                });
            })
            .catch((err) => console.log(err));
}

// Step 3 get the users data and return an object. Please ignore the ELSE, that's for something else.
getUser(uid, asPromise?: boolean) {
    if (asPromise) {
        return this.db.firestore.doc(`users/${uid}`).get()
                .then(uData => {
                    return uData.data();
                })
                .catch((err) => {
                    console.log(err);
                    return err;
                });
    } else {
        return this.db.doc<Interviewers>(`users/${uid}`).valueChanges();
    }
}


text:
Q: How to write single line scala codes? I'm new to Scala and I've written a piece of code that takes employee file(empId, name, age, salary, department) as an input and prints out the department and the total salary in the department.
It is a novice code. How to I shorten the code? Please help
Code:
object UsingCollectionMaps {
  def main(a: Array[String]) {
    val filename = "Employee.txt"
    var map = collection.mutable.Map[String,Long]()
    var sal: Long = 0
    for (line <- Source.fromFile(filename).getLines()) {
      val fields = line.split(",")
      if (map.contains(fields(4))) {
        map.put(fields(4), (map(fields(4)) + fields(3).toLong))
      } else {
        map.put(fields(4), fields(3).toLong)
      }
    }
    println(map)
  }
}

A: I would try to avoid those mutable structures and also to make sense of this file, properly part it to a case class.
After that, the use of groupBy and sum.
import scala.io.Source

case class Employee(empId: String, name: String, age: Int,
                    salary: Long, department: Int)

Source.fromFile("someFile.txt")
      .getLines()
      .map( _.split(",") )
      .map( l => Employee(l(0), l(1), l(2).toInt,
                          l(3).toLong, l(4).toInt) )
      .toSeq
      .groupBy( _.department )
      .mapValues( _.map( _.salary ).sum )

A: You could use the .groupBy method to create a Map of 'Departement' -> 'Employees' and then sum their salaries:
object UsingCollectionMaps {
  def main(a:Array[String]){
    val filename = "Employee.txt"
    val lines = io.Source.fromFile(filename).getLines().toList
    val map = employees.map(_.split(","))
                       .groupBy(_(4))  // Group by the fourth element of the arrays
                       .mapValues(_.map(_(3).toLong).sum) // Map an employeeList to their salaries and sum them
    println(map)
  }
}

A: This isn't considerably shorter, but does take a more functional approach:
import collection.immutable.Map
import io.Source

object UsingCollectionMaps {
  def main(args: Array[String]) {
    println(
      Source.fromFile("Employee.txt").getLines()
        .foldLeft(Map.empty[String, Long])({
          case (totals, line) =>
            val fields = line.split(",")
            val department = fields(4)
            val salary = fields(3).toLong
            totals.updated(department,
              totals.getOrElse(department, 0L) + salary)
        })
    )
  }
}


text:
Q: Localization in a custom Laravel Package My service provider of my custom package has the following lines in the boot() method:
$this->loadTranslationsFrom(__DIR__.'/../resources/lang', 'name');
$this->publishes([
            __DIR__.'/../resources/lang' => resource_path('lang/vendor/name'),
        ], 'lang');

I ran the php artisan vendor:publish command and the packages/vendorname/packagename/resources/lang/de.json file was successfully copied to the project.
The translation is not working. I tried copying to the /lang/vendor/name/ folder as well.
When I move my de.json file manually to /lang then the translation is working. To there is no issue with the file itself.
I tried to clear all caches already.

A: I am not sure why, But, it seems that Laravel just loads only the JSON translation files of the main project and the first package in the Vendor folder.
My solution is:

*

*for loading the JSON translation files from your package, you have to
use loadJsonTranslationsFrom in your package's service provider:
class CustomeServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the package services.
     *
     * @return void
     */
    public function boot()
    {
        $this->loadJsonTranslationsFrom(__DIR__.'/../resources/lang');
    }
}

*In your JSON file you can use your package name as a prefix for every key. for example, if your package name is MyPackage, your en.json file
looks like:
{
  "MyPackage::email": "Email",
  "MyPackage::username": "Username",
  ...
}

*You can use some helper functions of Laravel to load your translation keys:
trans('MyPackage::email'); // returns "Email"
OR
__('MyPackage::username'); // returns "Username"

You can follow the links below for more information:
https://laracasts.com/discuss/channels/laravel/loadjsontranslationsfrom-does-not-load-all-json-translation-files
https://github.com/laravel/framework/issues/17923
Laravel 5 loadJsonTranslationsFrom method does not load all JSON translation files from packages
https://github.com/nWidart/laravel-modules/pull/412
https://github.com/laravel/framework/pull/20599


text:
Q: Upgrade Outdated Python Packages by PIP in PowerShell in One Line How to upgrade outdated Python packages by PIP in PowerShell in one line?
A few days ago,  I created an issue in pypa / pip, to ask why package names could not be passed as object in PowerShell by
pip list --outdated | Select-Object Package

The developer advised to use
py -m pip list --outdated --format=json | ConvertFrom-JSON

Now it seems that
((pip list --outdated --format=json | ConvertFrom-JSON).name | Out-String).replace("`r`n"," ")

outputs outdated packages split in space:
idna ipykernel ipython jedi jupyter-client jupyterlab jupyterlab-server lxml Pillow setuptools```

pip install ((pip list --outdated --format=json | ConvertFrom-JSON).name | Out-String).replace("`r`n"," ")

does not work:

ERROR: Invalid requirement: 'idna ipykernel ipython jedi jupyter-client jupyterlab jupyterlab-server lxml Pillow setuptools'

However, if I use Write-Output:
Write-Output "pip install -U" ((pip list --outdated --format=json | ConvertFrom-JSON).name | Out-String).replace("`r`n"," ")

it outputs
pip install -U
idna ipykernel ipython jedi jupyter-client jupyterlab jupyterlab-server lxml Pillow setuptools

which is split into two lines and cannot be executed by Invoke-Expression.
If I use Write-Host:
Write-Host "pip install -U" ((pip list --outdated --format=json | ConvertFrom-JSON).name | Out-String).replace("`r`n"," ") | Invoke-Expression

It just outputs normally but doesn't execute:
pip install -U idna ipykernel ipython jedi jupyter-client jupyterlab jupyterlab-server lxmlPillow setuptools```

It's acceptable to do this in two lines:
$od = ((pip list --outdated --format=json | ConvertFrom-JSON).name | Out-String).replace("`r`n"," ")
Write-Output "pip install -U $od" | Invoke-Expression

But, just for my curiosity, can this be written in one line?


text:
Q: What is the best word describing the nature of expiring in a short amount of time, connoting "losing public attention"? Is there an adjective that describes the nature of expiring, connoting a sense of losing public attention, in a very short amount of time? For example,

In a fast-paced era, news articles are ____.
During the 1990s, compared with traditional technologies, computer  technologies are ___; for example, a new generation of CPU technologies usually comes out every one to two years.

(I thought about "perishable," but it does not seem connoting "losing public attention.")

A: I think a better word for this would be evanescent:

evanescent adj
  1. vanishing; fading away; fleeting.
  2. tending to become imperceptible; scarcely perceptible.
Dictionary.com

Right on both counts.

A: I like the word fleeting for this:

: passing swiftly : TRANSITORY
  // … the often fleeting nature of fame and fortune …
  — Tom Sinclair

So:

In a fast-paced era, news articles are fleeting.

Of course, the referenced transitory would also work, depending on the style of speech to be conveyed.

A: I know there's an accepted answer, but another word that comes to mind (a synonym of fleeting) is ephemeral.
lasting a very short time
// ephemeral pleasures

A: It's a phrase rather than a word, so aplogies on that but you could describe it as a "flash in the pan"
Def: something that happened only once or for a short time and was not repeated:

A: One could use short-lived.

not living or lasting long

A: To add one more option, I like waning

wane verb (used without object), waned, wan·ing
  1. to decrease in strength, intensity, etc.:
  "Her enthusiasm for the cause is waning"
  2. to decline in power, importance, prosperity, etc.:
  "Colonialism began to wane after World War II"
  3. to draw to a close; approach an end:
  "Summer is waning."

Dictionary.com

A: I'd go with Disposable:

Adjective
  designed for or capable of being thrown away after being used or used up:
  disposable plastic spoons; a disposable cigarette lighter.

As, in my opinion, that captures the idea best. When everything becomes disposable – news, information, items, culture – they also become worthless.

A: I thought of faddish

fad noun
  : a practice or interest followed for a time with exaggerated zeal : CRAZE

Of course that also denotes a quick entrance to the limelight, which may not be what you're going for.

A: I would also use the word "Obsolescent". So,
In a fast-paced era, news articles are obsolescent.
From Wikitionary:

Adjective
  Obsolescent (comparative more obsolescent, superlative most
  obsolescent)
  1.In the process of becoming obsolete, but not obsolete yet.

From Wikipedia:

Obsolescence (noun) is the state of being which occurs when an object,
  service, or practice is no longer wanted even though it may still be
  in good working order. ... Typically, obsolescence is preceded by a
  gradual decline in popularity.

A: Answers have not all been related to computer technology, so I add "a one-day wonder".
The Collins Dictionary has this

a one-day wonder
  or a nine-day wonder
something or someone that is interesting, exciting, or successful for only a very short time, and does not have any lasting value

It certainly does describe some technology though I would not like to name one.

A: Transient could work here, particularly for the computer example as it occurs more often in computing nomenclature and is keyword in the Java programming language, used to indicate that an item data is short-lived and not intended to be saved to a long term storage medium through a process known as serialization.
For a multi-word answer (and I do think the "in the public mind" aspect of this question generally tends towards multi-words) I quite like here today, gone tomorrow