text:
Q: Capture output from a mysql select statement using python Using Python2.4 I want to capture output from a mysql command. One caveat is that I need to pipe the SQL statement using an echo.
echo 'SELECT user FROM mysql.user;' | mysql

I see example using call, os.system, popen but what is best to use for my version of python and capturing the output in a tuple.
Thanks

A: The subprocess module is the most flexible tool for running commands and controlling the input and output.  The following runs a command and captures the output as a list of lines:
import subprocess

p = subprocess.Popen(['/bin/bash', '-c', "echo 'select user from mysql.user;' | mysql" ],
    stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

lines = [line for line in p.stdout]

On Windows, bash -c would be replaced with cmd /c.


text:
Q: UIActivityIndicatorView doesn't stop for UIWebView EDIT: I SOLVED IT
I solved it.
I changed:
@property(nonatomic,retain) UIActivityIndicatorView *activityIndicator;

to
@property(nonatomic,retain) IBOutlet UIActivityIndicatorView *activityIndicator;

MY QUESTION:
I am making a simple UIWebView app and I want the indicator to stop spinning when it is done loading the webpage. I checked "hide when done" in the storyboarding interface and I have connected the indicator to the view controller (activityIndicator). It still doesn't stop. In my header file, I have this:
@interface ViewController : UIViewController<UIWebViewDelegate>{
IBOutlet UIBarButtonItem *bBack, *bForward, *toolbarStop, *toolbarRefresh;
IBOutlet UIActivityIndicatorView *_activityIndicator;

BOOL internetOK;
NSTimer *timer;

}
-(void)tryInternet;
-(void)loading;
-(void)startAnimating;
-(void)stopAnimating;
-(void)verifyInternet;
-(IBAction)refresh:(id)sender;
-(IBAction)dontTouchMe:(id)sender;
-(IBAction)refreshWebView:(id)sender;
@property (weak, nonatomic) IBOutlet UIWebView *webview;
@property(nonatomic,retain) UIActivityIndicatorView *activityIndicator;

And in my .m file, I have this:
- (void)webViewDidStartLoad:(UIWebView *)webView {
    [_activityIndicator startAnimating];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    [_activityIndicator stopAnimating];

Why doesn't this work? Do you have any ideas?

A: Try it using following code.
- (void)webViewDidStartLoad:(UIWebView *)webView
{
 [_activityIndicator setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleGray];
 [_activityIndicator setFrame:CGRectMake(200, 10, 20, 20)];
 [self.view addSubview:_activityIndicator];
 [_activityIndicator startAnimating];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
 [_activityIndicator startAnimating];
}

I hope it will work.

A: in your .h file, take both names same, i.e. activityIndicator.
Then in your .m file synthesize it, i.e activityIndicator = _activityIndicator.
And then write the following code -
- (void)webViewDidStartLoad:(UIWebView *)webView
{
 [activityIndicator setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleGray];
 [activityIndicator startAnimating];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
 [activityIndicator stopAnimating];
}

A: I assume that, you have connect delegate to your view controller.
And whenever webViewDidStartLoad delegate of UIWebView called, your animation starts.
I think that, instead of webViewDidFinishLoad method, webViewFailedToLoad method is calling. So, you need to write your code [activityIndicator stopAnimating]; inside that failed method.
Hope, it will be helpful to you.
Cheers!

A: I solved it. I changed:
@property(nonatomic,retain) UIActivityIndicatorView *activityIndicator;

to
@property(nonatomic,retain) IBOutlet UIActivityIndicatorView *activityIndicator;

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to query specific columns from an array with sqlalchemy? I'm building a flask application and need an dict from my database model. The query should filter by user_ids and only query a few rows. I guess the best way is to filter the rows and the use the internal __dict__ object to return my dict. Currently I know how to filter by ids, but I have no idea how to select specific rows. Users.query.filter(Users.id.in_(user_ids)).all()
the array of rows looks like
rows = ["username", "role", "last_seen"]
any ideas how to do that?

A: load_only should do the job:
from sqlalchemy.orm import load_only
rows = ["username", "role", "last_seen"]
session.query(Users).filter(Users.id.in_(user_ids)).options(load_only(*rows)).all()


text:
Q: Beyond Compare - Remove unecessary content (BETWEEN ") I'm comparing two files and I need to ignore everything that is in between ".
Like, File1 "ASD" and File2 "ABCDOOP" = Ignore.

A: You could define an importance rule to mark everything between " as unimportant:
In the example the between " is only an unimportant difference.

The rule works also with multiple unimportant texts in one line:

You can define the rule in Session -> Session Settings. Then the Tab Importance. Then you can add the rule with +. The _text to *"`, the regular expression-checkbox must be marked.


text:
Q: SQLDependency_OnChange-Event fires only one single Time I'm working with SQLDependency to notify me if there is a change in the Database.
After Program Start-Up it works just fine. When I make a first change the Event fires. Wohoo... that's great.
But if I made a second change the event doesn't fire again. I've searched all the web I think but haven't found anything about THIS Problem. Only found problems where the OnChange-Event fires in a Loop.
Can anyone help me?
Here a little code piece:
private void GetStates()
    {
        if (!DoesUserHavePermission())
            return;

        SqlDependency.Stop(con);
        SqlDependency.Start(con);

        using (SqlConnection cn = new SqlConnection(con))
        {
            using (SqlCommand cmd = cn.CreateCommand())
            {
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = "SELECT Bla, Bla2, ..FROM dbo.[BLA3]"

                cmd.Notification = null;
                cmd.Dispose();

                SqlDependency dep = new SqlDependency(cmd);
                dep.OnChange += new OnChangeEventHandler(dep_OnChange);

                cn.Open();

                using (SqlDataReader dr = cmd.ExecuteReader())
                {
                    state.Clear(); //In this Case "state" is a List<string>
                    while (dr.Read())
                    {
                        state.Add(dr.GetString(0) + "|" + dr.GetInt32(3));
                    }
                    dr.Dispose();
                    dr.Close();
                }
            }
        }
    }

my OnChange-Event looks like this:
private void dep_OnChange(object sender, SqlNotificationEventArgs e)
    {
        SqlDependency dep = sender as SqlDependency;
        dep.OnChange -= this.dep_OnChange;

        using (SqlConnection cn = new SqlConnection(con))
        {
            using (SqlCommand cmd = cn.CreateCommand())
            {
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = "SELECT Bla, Bla2, ..FROM dbo.[BLA3]";

                cmd.Notification = null;

                if (e.Type == SqlNotificationType.Change)
                {
                    if (cn.State != ConnectionState.Open)
                    {
                        cn.Open();
                    }

                    using (SqlDataReader dr = cmd.ExecuteReader())
                    {
                        state.Clear(); // Clear and Refill the stringlist "state"
                        while (dr.Read())
                        {
                            state.Add(dr.GetString(0) + "|" + dr.GetInt32(3));
                        }
                    }
                }
                cn.Close();
            }
        }
        this.GetStates(); //to go ahead and wait for a new change
    }

Where is the problem?

A: After changes happened to the database at the first time, you have to execute the command again and re-subscribe to the event.
The following code is working for me.
class Program
{
    static string connectionString = "Server=.;Database=test_sql_dependency;Integrated Security=True;";

    static void Main(string[] args)
    {
        // 1. create database

        // 2. enable service broker by executing this sql command on the database.
        // alter database test_sql_dependency set enable_broker

        // 3. start sql dependency, for some sql server connection string or with queue if you want.

        //var queueName = "myFirstQueue";
        //SqlDependency.Start(connectionString, queueName);
        SqlDependency.Start(connectionString);

        // complete the rest of the steps in seperate method to be able to call it again when you need to
        // re-subscribe to the event again, becuase by default it will be executed only one time

        RegisterSqlDependency();

        Console.WriteLine("Listening to database changes...");
        Console.ReadLine();
    }

    static void RegisterSqlDependency()
    {
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            if (connection.State != System.Data.ConnectionState.Open)
            {
                connection.Open();
            }

            // 4. create a sql command
            // you can't say select *, and also you have to specefy the db owner (dbo.)
            SqlCommand command = new SqlCommand("select Id, Name from dbo.Employee", connection);

            // 5. create dependency and associtate it to the sql command
            SqlDependency dependency = new SqlDependency(command);

            // 6. subscribe to sql dependency event
            dependency.OnChange += new OnChangeEventHandler(OnDependencyChange);

            // 7. execute the command
            using (SqlDataReader reader = command.ExecuteReader())
            {

            }
        }
    }

    static void OnDependencyChange(object sender, SqlNotificationEventArgs e)
    {
        var InsertOrUpdateOrDelte = e.Info;

        //-----------------------------Finally-------------------------
        // after you knew that there is a change happened
        // you have to unsubscribe the event and execute the command again and then re-subscribe to the event

        // 1. unsubscribe the event
        SqlDependency dependency = sender as SqlDependency;
        dependency.OnChange -= OnDependencyChange;

        // 2. re-subscribe to the event and execute the command again
        RegisterSqlDependency();

    }
}

A: In your private void dep_OnChange(object sender, SqlNotificationEventArgs e) method after you unsubscribe the dep_OnChange event you should call the private void GetStates() again, to initialize the dep.OnChange event again.

A: I was running into this issue as well. You need to create a new SqlDependency entity (after unsubscribing the existing one from the OnChange event) and then run a new ExecuteReader command. I got the idea from this post:
http://www.codeproject.com/Articles/12335/Using-SqlDependency-for-data-change-events
This usually makes sense, as once you have been notified of a change you will normally want to re-query the data.

A: Not sure if that is your problem but you dispose the command right after you have created it:
using (SqlCommand cmd = cn.CreateCommand())
{
  ...
  cmd.Dispose();

It looks like a bug.

A: In GetStates() :
SqlDependency.Stop(con);
SqlDependency.Start(con);
these lines should be executed only when registering the sql dependency for first time.
Restrict them when you call the method from OnChange event.

A: Look my friend:
dep.OnChange -= this.dep_OnChange;

you un-fired your event; which is not true;
just delete this line;


text:
Q: Type unknown[] is not assignable to type React.ReactNode import * as React from 'react';
import { List, ListItemButton, ListItemIcon, ListItemText, ListItem} from '@mui/material';
import LightbulbOutlinedIcon from '@mui/icons-material/LightbulbOutlined';
import NotificationsNoneOutlinedIcon from '@mui/icons-material/NotificationsNoneOutlined';
import DeleteOutlinedIcon from '@mui/icons-material/DeleteOutlined';

const mainListItems = () => {
    const navList = [
        { id: 1, name: 'Notes', icon: <LightbulbOutlinedIcon />},
        { id: 2, name: 'Reminders', icon:  <NotificationsNoneOutlinedIcon /> },
        { id: 3, name: 'Bin', icon: <DeleteOutlinedIcon /> },
    ]

    return (
            <List>
                {
                    navList.map( list => (
                        <ListItem key={list.id} disablePadding sx={{display: 'block'}}>
                            <ListItemButton sx={{minHeight: 48, justifyContent: open ? 'initial' : 'center', px: 2.5}}>
                                <ListItemIcon sx={{minWidth: 0, mr: open ? 3 : 'auto', justifyContent: 'center'}}>
                                    {list.icon}
                                </ListItemIcon>
                                <ListItemText primary={list.name} sx={{opacity: open ? 1 : 0}}/>
                            </ListItemButton>
                        </ListItem>
                    ))
                }
            </List>
    )
}

I tried reducing the amount of code by using map to assign icon information. But it shows this error and I can't understand why it happens. Should I assign types to the attributes in the list?
line where error occurs :
navList.map( list => (

Full error message :

Type unknown[] is not assignable to type React.ReactNode ...   Type
unknown[] is not assignable to type ReactElement<any, string |
JSXElementConstructor> | string | number | Iterable |
ReactPortal | boolean     Type unknown[] is not assignable to type
boolean

A: This code runs fine given that there's no problems with any of the imports. The only thing wrong here is that mainListItemsshould be MainListItems as all React components should have names starting with uppercase letters.

A: The error is occurring because TypeScript cannot infer the return type of the map() function, which is an array of unknown type. To resolve this, you can explicitly type the return type of map() by using the ReactNode[] type:
navList.map((list): React.ReactNode => (
  // ...
))

This tells TypeScript that the map() function will return an array of React nodes, which is what is expected by the List component.

A: *

*You need to define a type for your NavItems. Then set the navList to be of type NavItems Array. const navList: NavItem[].

*There is the issue of convention as earlier mentioned; React treats lowercase JSX as React Elements. e.g <div>,<section>, etc. These are the HTML tags look-alikes that come preloaded with react. So whenever React sees a lowercase JSX <mainListItems> in this case, It will attempt to read it as an intrinsic element and fail. THIS IS WHY IT IS IMPORTANT TO FOLLOW THE CONVENTION OF USING the <MainListItems/> naming style for your <Components/>

*Sandbox demo

type NavItem = {
  id: number;
  name: string;
  icon: JSX.Element;
};
const MainListItems = () => {
  const navList: NavItem[] = [
    { id: 1, name: "Notes", icon: <LightbulbOutlinedIcon /> },
    { id: 2, name: "Reminders", icon: <NotificationsNoneOutlinedIcon /> },
    { id: 3, name: "Bin", icon: <DeleteOutlinedIcon /> }
  ];

  return (
    <List>
      {navList.map((list) => (
        <ListItem key={list.id} disablePadding sx={{ display: "block" }}>
          <ListItemButton
            sx={{
              minHeight: 48,
              justifyContent: open ? "initial" : "center",
              px: 2.5
            }}
          >
            <ListItemIcon
              sx={{
                minWidth: 0,
                mr: open ? 3 : "auto",
                justifyContent: "center"
              }}
            >
              {list.icon}
            </ListItemIcon>
            <ListItemText primary={list.name} sx={{ opacity: open ? 1 : 0 }} />
          </ListItemButton>
        </ListItem>
      ))}
    </List>
  );
};

A: Okay, so the first thing that jumps out at me here is the fact that your component's name starts with a lower case letter. Always make sure to use UpperCaseLetters when naming components in React. So change mainListItems to MainListItems.
Second, dont import React like that. Instead of
import * as React from 'react';

import as
import React, {FC, Fragment, ... other imports ...} from "react"

Next, there is no mention of TypeScript but this error seems to be a TypeScript error to me, so go ahead and assign a type to newList.
I tested this on fiddle and it worked fine, go ahead and try it on your end please.
const MainListItems = () => {
    const navList:Array<{ id: number, name: string, icon: JSX.Element }> = [
        { id: 1, name: 'Notes', icon: <LightbulbOutlinedIcon />},
        { id: 2, name: 'Reminders', icon:  <NotificationsNoneOutlinedIcon /> },
        { id: 3, name: 'Bin', icon: <DeleteOutlinedIcon /> },
    ]

    return (
            <List>
                {
                    navList.map( list => (
                        <ListItem key={list.id} disablePadding sx={{display: 'block'}}>
                            <ListItemButton sx={{minHeight: 48, justifyContent: open ? 'initial' : 'center', px: 2.5}}>
                                <ListItemIcon sx={{minWidth: 0, mr: open ? 3 : 'auto', justifyContent: 'center'}}>
                                    {list.icon}
                                </ListItemIcon>
                                <ListItemText primary={list.name} sx={{opacity: open ? 1 : 0}}/>
                            </ListItemButton>
                        </ListItem>
                    ))
                }
            </List>
    )
}

If that doesnt work, and you are not using TypeScript, go ahead and delete package-lock.json and node_modules, and run npx install again to see if that solves your error.


text:
Q: How can I update the Application Loader on MAC OS Catalina 10.15.5? If i check this link https://help.apple.com/itc/apploader/ this is the showed me:

But if i check my Application Loader this is showed me:

Someone knows what is the problem?

A: Application Loader has been replaced.  Use Transporter instead.


text:
Q: React: How can I set my components' render content from outside? I want to do something like this (similar to the Accordion in react bootstrap):
class Foo extends React.Component{
   static Button;
   static Content;

   render(){
      return(

            <Foo.Button/>
            <Foo.Content/>

      );
   }
}

so that I can use it like this:
function App() {
  return (
     <Foo>
        <Foo.Button>

this is in the button

        </Foo.Button>
        <Foo.Content>

this is content

        </Foo.Content>
     </Foo>
  );
}

How can I get this or what do I have to search for an example?

A: You should pass the content you want via props. For example,
 return (
     <Foo>
        <Foo.Button>

{this.props.buttonText}

        </Foo.Button>
        <Foo.Content>

{this.props.content}

        </Foo.Content>
     </Foo>
  );

A: You can do something like this :
class Foo extends React.Component {
  static Button;
  static Content;

  render() {
    return (

        <Foo.Button />
        <Foo.Content />

    );
  }
}

Foo.Button = props => {
  const { children, ...rest } = props;

  <button {...rest}>{children}</button>;
};

Foo.Content = props => {
  const { children, ...rest } = props;

{children}
;
};

export default Foo;


text:
Q: Parse multiple json objects that are in one line I'm parsing files that containt json objects. The problem is that some files have multiple objects in one line. e.g.:
{"data1": {"data1_inside": "bla{bl\"a"}}{"data1": {"data1_inside": "blabla["}}{"data1": {"data1_inside": "bla{bla"}}{"data1": {"data1_inside": "bla["}}

I've made a function that tries parsing a substring when there are no open brackets left, but there may be curly brackets in values. I've tried skipping values with checking the start and end of quotes, but there are also values with escaped quotes. Any ideas on how to deal with this?
My attempt:
def get_lines(data):
    lines = []
    open_brackets = 0
    start = 0
    is_comment = False
    for index, c in enumerate(data):
        if c == '"':
            is_comment = not is_comment
        elif not is_comment:
            if c == '{':
                if not open_brackets:
                    start = index
                open_brackets += 1

            if c == '}':
                open_brackets -= 1
                if not open_brackets:
                    lines.append(data[start: index+1])

    return lines

A: The problem is that you can't reasonably split by any character or sequence of characters, because that sequence could always show up in a string as a field value, for example '{"data1": "}{"}{"data2":"foo"}'.
If we assume that every substring in your file/string that is valid JSON must start with '{' and end with '}' (of course, in the general case we'd also have to deal with '[' and ']' characters), here's a brute force approach:
import json

with open('input.txt') as inp:
    s = inp.read().strip()

jsons = []

start, end = s.find('{'), s.find('}')
while True:
    try:
        jsons.append(json.loads(s[start:end + 1]))
    except ValueError:
        end = end + 1 + s[end + 1:].find('}')
    else:
        s = s[end + 1:]
        if not s:
            break
        start, end = s.find('{'), s.find('}')

for x  in jsons:
    print(x)

Demo:
$ cat input.txt
{"data1": {"data1_inside": "bla{bl\"a"}}{"data1": {"data1_inside": "blabla["}}{"data1": {"data1_inside": "bla{bla"}}{"data1": {"data1_inside": "bla["}}
$ python json_linereader.py
{u'data1': {u'data1_inside': u'bla{bl"a'}}
{u'data1': {u'data1_inside': u'blabla['}}
{u'data1': {u'data1_inside': u'bla{bla'}}
{u'data1': {u'data1_inside': u'bla['}}

Output for s = '{"data1": "}{"}{"data2":"foo"}'
{'data1': '}{'}
{'data2': 'foo'}

I haven't checked this code for all eventualities with unit tests, but the idea should be clear.

A: Simple but less robust version:
>>> import re
>>> s = r'{"data1": {"data1_inside": "bla{bl\"a"}}{"data1": {"data1_inside": "blabla["}}{"data1": {"data1_inside": "bla{bla"}}{"data1": {"data1_inside": "bla["}}'
>>> r = re.split('(\{.*?\})(?= *\{)', s)
['', '{"data1": {"data1_inside": "bla{bl\\"a"}}', '', '{"data1": {"data1_inside": "blabla["}}', '', '{"data1": {"data1_inside": "bla{bla"}}', '{"data1": {"data1_inside": "bla["}}']

This will fail if }{ is contained in a string
As other suggested, you could then try to parse each element. If it's not valid, then we should check this element together with the next one.
Note that r is the result of the code above
accumulator = ''
res = []
for subs in r:
    accumulator += subs
    try:
        res.append(json.loads(accumulator))
        accumulator = ''
    except:
        pass

A: You can use the json raw_decoder! This allows the reading of json strings with extra data after the first json object. An example of usage would be:
>>> dec = json.JSONDecoder()
>>> json_str = '{"data": "Foo"}{"data": "BarBaz"}{"data": "Qux"}'
>>> dec.raw_decode(json_str)
({u'data': u'Foo'}, 15)
>>> dec.raw_decode(json_str[15:])
({u'data': u'BarBaz'}, 18)
>>> dec.raw_decode(json_str[33:])
({u'data': u'Qux'}, 15)

The first part of the tuple is the json object, the second is how much of the string was used when reading it. Therefore a loop like this will allow you to iterate over all the json objects in a string.
dec = json.JSONDecoder()
pos = 0
while not pos == len(str(json_str)):
    j, json_len = dec.raw_decode(str(json_str)[pos:])
    pos += json_len
    # Do something with the json j here

A: Building on Carcophan's answer and Hi-angel's comment I added a check to see if the leftover part of the string is whitespace.  Python strings have a isspace() method so I used that to check.
NOTE: This is python3 -- I think the json library returned a different exception in eariler verisons.
dec = json.JSONDecoder()
pos = 0
results = []
while pos != len(str(json_str)):
    try:
        j, json_len = dec.raw_decode(str(json_str)[pos:])
    except json.decoder.JSONDecodeError as exc:
        if len(results) > 0 and str(json_str)[pos:].isspace():
            break
        raise exc
    else:
        pos += json_len
        results.append(j)

A: Slight improvement over @Carcophan's answer, to handle spaces before, after and between JSON objects:
import json

decoder = json.JSONDecoder()
pos = 0
objs = []
while pos < len(json_str):
    json_str = json_str[pos:].strip()
    if not json_str:
        break  # Blank line case
    obj, pos = decoder.raw_decode(json_str)
    objs.append(obj)

One thing to remember is that JSON objects can be lists, strings, numbers, etc., meaning they don't necessarily start/end with {}. That means the answers here that rely on a string that contains {} for the start/end of JSON objects become unnecessarily limited to dictionaries.
This piece of code deals with any type of JSON object and blank chars (space, tabs, newlines).


text:
Q: C++ ambiguous template instantiation the following gives me ambiguous template instantiation with nvcc (combination of EDG front-end and g++).
Is it really ambiguous, or is compiler wrong?  I also post workaround à la boost::enable_if
template<typename T> struct disable_if_serial { typedef void type; };
template<> struct disable_if_serial<serial_tag> { };

template<int M, int N, typename T>
__device__
//static typename disable_if_serial<T>::type
void add_evaluate_polynomial1(double *R,
                         const double (&C)[M][N], double x,
                         const T &thread) {
    // ...
}

template<size_t M, size_t N>
__device__
static void add_evaluate_polynomial1(double *R,
                                     const double (&C)[M][N], double x,
                                     const serial_tag&) {
    for (size_t i = 0; i < M; ++i)
        add_evaluate_polynomial1(R, C, x, i);
}

// ambiguous template instantiation here.
add_evaluate_polynomial1(R, C, x, serial_tag());

A: AFAIK, the problem is that you have the nontype arguments inconsistently typed (that is, M and N are int here, but size_t there). This means not all template variable assignments from one can be used in the other, which means there is no partial ordering, hence the error message.
Unite the template nontype argument types and it should work.

A: I have tested the code on Clang, GCC and Comeau. Comeau rejects it while GCC and Clang accept it. I think that for both groups of compilers there can be made points

*

*Comeau follows the C++03 rule, which requires an "exact match (so the deduction does not rely on implicit conversions)" for the deduced template arguments. However this specification was horribly underspecified and has been completely rewritten for C++0x.

*Clang and GCC seem to implement the rewritten rule, and this rule better specifies what "exact match" means. This specification goes fine with the different types of the array dimensions.
In any case, if you want to go fine with all compilers, then really go by the accepted answer and change the non-type parameter types to a common type :)


text: Q: How to collect core dumps from unit tests? What is the easiest way to collect core dumps from unit tests job in ci? Tests are run with CTest if important. I can set up kernel_pattern and write the corresponding path in the artifacts, but I still need to copy the executable file of the crashed application with symbols, which is no longer so trivial. Or is there another way to get a dump with symbols at once, without having to look for an executable?


text:
Q: Objects exposed on JSON web-api - how to stop the property names changing case? I have an object model that looks like:
public class Product
{
    public string ProductCode { get; set; }
    public string ProductInfo { get; set; }
}

I'm populating this via Dapper, and exposing it to an angular.js consumer, but the property names in the JSON are coming out as:
{
     "productCode": 1,
     "productInfo": "Product number 1"
}

Note in particular the camel-case. I would like it to match the original declared names, i.e.
{
     "ProductCode": 1,
     "ProductInfo": "Product number 1"
}

How can I do this?

A: Under the hood, it is most likely that the web-API is using JSON.Net as the JSON serialization engine; this means that you can control the output using JSON.Net's attributes, for example:
public class Product
{
    [JsonProperty("ProductCode")]
    public string ProductCode { get; set; }
    [JsonProperty("ProductInfo")]
    public string ProductInfo { get; set; }
}

Without these, JSON.Net uses conventions and configuration - and the usual JSON convention is to use camel-case, hence that is the default. You can also probably change the default configuration, but I would advise against that unless you understand the scope of the impact.

A: Use this code to preserve property names case from changing for Newtonsoft.Json serializer:
services.AddControllers().AddNewtonsoftJson(options=>
{
    options.SerializerSettings.ContractResolver = new DefaultContractResolver() {  };
});

or for System.Text.Json:
services.AddControllersWithViews().AddJsonOptions(options =>
{
    options.JsonSerializerOptions.PropertyNamingPolicy = null;
});


text:
Q: blocking access to my apache server According to this site:
http://httpd.apache.org/docs/2.2/howto/access.html
I need to use something like the script below to block access to my site for everyone except specific ip addresses:
Order deny,allow
Deny from all
Allow from dev.example.com

It's not clear from that site, where I type this script.
I am using Ubuntu 10.04 as my development machine.

A: Write exact IPs or it's starting part including ending dot under allow from and you are done.
Order deny,allow
Deny from all
Allow from 192.168.1.1
Allow from 192.168.1.2
Allow from 10.0.

BTW, belongs to ServerFault.


text:
Q: IOS core plot hide 0-100 part of x axis makes y axis disapear Hiding 0-100 part of x axis, by setting visible range to 0-100, makes y axis disapear
How can I solve this problem?

A: It's likely not disappeared, rather it could be on the left/right of the screen, assuming that both the axes don't intersect at (0,0). If you enable interaction on plot space (plotSpace.allowsUserInteraction = YES;) you might be able to pinch zoom and take a look around if its there or not.
Also, you can try to make the axes 'fixed' by adding constraints to them:
CPTXYAxisSet *axisSet = (CPTXYAxisSet *) self.hostView.hostedGraph.axisSet;

// Configure x-axis
CPTXYAxis *x = axisSet.xAxis;
CPTXYAxis *y = axisSet.yAxis;

x.axisConstraints = [CPTConstraints constraintWithLowerOffset:50];
y.axisConstraints = [CPTConstraints constraintWithLowerOffset:50];


text:
Q: How to do a distinct count in JPA critera API? I would like to do this but with the criteria API instead:
select count(distinct e) from Event e, IN(e.userAccessPermissions) p where p.principal = :principal and p.permission in (:permissions)

Any ideas?

A: You can use countDistinct on CriteriaBuilder
criteriaQuery.select(criteriaBuilder.countDistinct(entityRoot))

A: Use c.distinct(true) on your Query.
See http://relation.to/Bloggers/ATypesafeCriteriaQueryAPIForJPA for more samples.

A: Like this?
Criteria crit = session.createCriteria(Event.class):
crit.createAlias("userAccessPermissions", "p");
crit.add(Restrictions.eq("p.principal", principal);
crit.add(Restrictions.in("p.permission", permissions);
crit.setProjection(Projections.countDistinct("id"));

A:     public long getCount(String xValue){
      EntityManager entityManager = this.getEntityManager();

      CriteriaBuilder cb = entityManager.getCriteriaBuilder();
      CriteriaQuery<Long> criteriaQuery = cb.createQuery(Long.class);
      Root<MyEntity> root = criteriaQuery.from(MyEntity.class);

      criteriaQuery.select(cb.count(criteriaQuery.from(MyEntity.class)));

      List<Predicate> predicates = new ArrayList<>();

      Predicate xEquals = cb.equal(root.get("x"), xValue);
      predicates.add(xEquals);

      criteriaQuery.select(cb.countDistinct(root));
      criteriaQuery.where(predicates.toArray(new Predicate[0]));

      return entityManager.createQuery(criteriaQuery).getSingleResult();

    }

With Spring Data Jpa,  we can use this method:
     /*
     * (non-Javadoc)
     * @see org.springframework.data.jpa.repository.JpaSpecificationExecutor#count(org.springframework.data.jpa.domain.Specification)
     */
    @Override
    public long count(@Nullable Specification<T> spec) {
        return executeCountQuery(getCountQuery(spec, getDomainClass()));
    }


text:
Q: Python Remove line breaks from CSV file When opening my CSV file in Notepad++ it shows the encoding is ANSI, and the line breaks are showing as LF.  I'm trying to remove these line breaks via python, but have not found a solution.  A couple solutions I've tried:
with open(csvTable, 'r') as f:
    raw_csv = f.read()
    clean_csv = raw_csv.strip()

with open(csvTable2, 'w') as f:
    f.write(clean_csv)

And:
data_set = pd.read_csv(data_file,skip_blank_lines=True, encoding='ANSI')
data_set.to_csv(target_file,index=False)

Can someone point me in the right direction?

A: You can (and should) use the csv module for any CSV-related work; beyond allowing you to control the lineterminator, it will also preserve the internal line breaks that may exist inside a "cell".
The following:

*

*opens your input CSV and creates an output CSV, both with the CP-1252 (Windows-1252 or "ANSI") encoding

*the newline="" directive tells the file handlers created by open() not to do anything with newlines as the files are being read and written; the csv module's reader and writer will handle all newline characters

*importantly, newlines inside a cell will be left as is, while the newline at the end of a row (the "line terminator") will be set CRLF with lineterminator="\r\n"
import csv

ANSI = "cp1252"

with (
    open("input.csv", encoding=ANSI, newline="") as f_in,
    open("output.csv", "w", encoding=ANSI, newline="") as f_out,
):
    reader = csv.reader(f_in)
    writer = csv.writer(f_out, lineterminator="\r\n")
    for row in reader:
        writer.writerow(row)

Here's my input.csv:
Col1,Col2
"à
ÿ",1
b,2
c,3

Looking at it from hexdump:
00000000  43 6f 6c 31 2c 43 6f 6c  32 0a 22 e0 0a ff 22 2c  |Col1,Col2."�.�",|
00000010  31 0a 62 2c 32 0a 63 2c  33                       |1.b,2.c,3|
00000019

we can see that we have LF (0a) for the line terminators, and the à and ÿ characters are encoded as e0 and ff, according to CP-1252.
Here's ouptut.csv:
Col1,Col2
"à
ÿ",1
b,2
c,3

Looks to the same to the naked eye; here's how it looks from hexdump:
00000000  43 6f 6c 31 2c 43 6f 6c  32 0d 0a 22 e0 0a ff 22  |Col1,Col2.."�.�"|
00000010  2c 31 0d 0a 62 2c 32 0d  0a 63 2c 33 0d 0a        |,1..b,2..c,3..|
0000001e

We can see:

*

*the à and ÿ are still encoded as e0 and ff, the CP-1252 encoding was kept

*the internal newline between à and ÿ was kept as 0a (LF)

*the line terminators were converted to 0d 0a (CRLF)


text:
Q: Spring Security Oauth: migration from xml to annotations I'm trying to migrate from xml to annotations. But I can't correctly configure endpoint /oauth/token - it doesn't accept my params for POST query.
Request:
curl -X POST -d "grant_type=password&client_secret=secret&client_id=testclient&username=root&password=password" http://localhost:8080/oauth/token

Log:
2014-09-07 16:33:39 DEBUG AntPathRequestMatcher:145 - Checking match of request : '/oauth/token'; against '/oauth/token'
2014-09-07 16:33:39 DEBUG FilterSecurityInterceptor:194 - Secure object: FilterInvocation: URL: /oauth/token; Attributes: [fullyAuthenticated]
2014-09-07 16:33:39 DEBUG FilterSecurityInterceptor:310 - Previously Authenticated: org.springframework.security.authentication.AnonymousAuthenticationToken@9055e4a6: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@957e: RemoteIpAddress: 127.0.0.1; SessionId: null; Granted Authorities: ROLE_ANONYMOUS
2014-09-07 16:33:39 DEBUG AffirmativeBased:65 - Voter: org.springframework.security.web.access.expression.WebExpressionVoter@302753d0, returned: -1
2014-09-07 16:33:39 DEBUG ExceptionTranslationFilter:165 - Access is denied (user is anonymous); redirecting to authentication entry point
org.springframework.security.access.AccessDeniedException: Access is denied
    at org.springframework.security.access.vote.AffirmativeBased.decide(AffirmativeBased.java:83)
    at org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:206)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:115)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)

XML (worked correctly) :
<http pattern="/oauth/token" create-session="stateless"
      authentication-manager-ref="authenticationManager"
      xmlns="http://www.springframework.org/schema/security">
    <intercept-url pattern="/oauth/token" access="IS_AUTHENTICATED_FULLY"/>
    <anonymous enabled="false"/>
    <http-basic entry-point-ref="clientAuthenticationEntryPoint"/>
    <custom-filter ref="clientCredentialsTokenEndpointFilter" before="BASIC_AUTH_FILTER"/>
    <access-denied-handler ref="oauthAccessDeniedHandler"/>
</http>

Annotations version:
@Configuration
@EnableWebSecurity
@EnableAuthorizationServer
public class SecurityConfig {

@Bean
public AuthorizationServerConfigurer authorizationServerConfigurer() {
    return new AuthorizationServerConfigurerAdapter() {
        @Override
        public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
            oauthServer.authenticationEntryPoint(customEntryPoint());
        }

        @Override
        public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
            endpoints.tokenStore(tokenStore());
            endpoints.authenticationManager(authenticationManager());
            endpoints.clientDetailsService(clientDetailsService());
        }

        @Override
        public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
            clients.withClientDetails(clientDetailsService());
        }
    };
}

@Bean
public PasswordEncoder passwordEncoder() {
    return new MD5PasswordEncoder();
}

@Bean
public OAuth2AuthenticationEntryPoint customEntryPoint() {
    OAuth2AuthenticationEntryPoint oAuth2AuthenticationEntryPoint = new OAuth2AuthenticationEntryPoint();
    oAuth2AuthenticationEntryPoint.setRealmName("springsec/client");
    oAuth2AuthenticationEntryPoint.setTypeName("Basic");
    return oAuth2AuthenticationEntryPoint;
}

@Bean
public TokenStoreDao tokenStoreDao() {
    return new TokenStoreDaoImpl();
}

@Bean
public TokenStore tokenStore() {
    MongoTokenStore tokenStore = new MongoTokenStore();
    tokenStore.setTokenStoreDao(tokenStoreDao());
    return tokenStore;
}

@Bean
public AuthenticationManager authenticationManager() throws Exception {
    OAuth2AuthenticationManager oAuth2AuthenticationManager = new OAuth2AuthenticationManager();
    DefaultTokenServices tokenServices = new DefaultTokenServices();
    tokenServices.setTokenStore(tokenStore());
    oAuth2AuthenticationManager.setTokenServices(tokenServices);
    return oAuth2AuthenticationManager;
}

@Bean
public ClientDetailsService clientDetailsService() {
    return new OAuthClienDetailsService();
}

@Bean
public ClientDetailsUserDetailsService clientDetailsUserDetailsService() {
    return new ClientDetailsUserDetailsService(clientDetailsService());
}

@Bean
public AuthenticationProvider authenticationProvider() throws Exception {
    DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
    authenticationProvider.setUserDetailsService(clientDetailsUserDetailsService());
    authenticationProvider.setPasswordEncoder(passwordEncoder());
    authenticationProvider.afterPropertiesSet();
    return authenticationProvider;
}

Any advice?

A: The answer is:
.allowFormAuthenticationForClients();
@Bean
public AuthorizationServerConfigurer authorizationServerConfigurer() {
    return new AuthorizationServerConfigurerAdapter() {
        @Override
        public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
            oauthServer
                    .authenticationEntryPoint(customEntryPoint())
                    .allowFormAuthenticationForClients();
        }


text:
Q: Migration Ninject -> Simple Injector We use Ninject in our project, but have some performance problems. It will be interesting to test the same project with Simple Injector.
Do you know some kind of guides that make the migration easier?

A: As for today there isnt such a guide for the migration Ninject -> Simple Injector.


text:
Q: linux configure 2 NICs to team mode / redundancy mode / switch mode I would like to implement 3 modes of NIC operation to my users, so that they can choose how to use 2 NICs on their machines.
These 3 modes are:

*

*Team mode: (aka) link aggregation, use 2 NICs together in order to get higher total bandwidth.

*Redundancy Mode: only 1 NIC is active, it will switch automatically if the link fails

*Switch Mode: the 2 NICs is like a switch, one port for LAN, another port is able to connect other devices.

How do i achieve these 3 modes? Thanks for your help, even partial answers are greatly appreciated.

A: You Google "Channel Bonding ubuntu" in Google. First link I came up with was https://help.ubuntu.com/community/UbuntuBonding.
In a nut shell -

*

*sudo apt-get install ifenslave

*Check "bonding" module is loaded (ie it exists in /proc/modules, if not, add
to /etc/modules and load manually/reboot)

*Modify network Interfaces to create and use a bond0 device rather then
ethernet device (and enslave the ethernets into the bond)

Example -

auto eth0
iface eth0 inet manual
bond-master bond0

auto eth1
iface eth1 inet manual
bond-master bond0

auto bond0
bond-mode XXXX
bond-miimon 100
bond-lacp-rate 1
bond-slaves none
iface bond0 inet ....
[definition as per eth0 was initially]

Restart networking
bond-mode XXXX refers to the mode you want to use for bonding.  Briefly.
0 = balance-rr (round robin),
1 = active-backup
2 = balance-xor
3 = broadcast
4 = 802.3ad
5 = balance-tlb
6 = balance-alb
Mode 0 and 1 are the easiest to use and don't require any special hardware or fiddle with the routing.


text:
Q: Spark structed streaming window issue I have a problem regrading the window in Spark Structed Streaming. I want to group the data i'm receiving continuously from kafka source in sliding window and count the number of data. The issue is that writestream streams the window dataframe each time there is data coming and update the count of the current window.
I'm using the following code to create the window:
#Define schema of the topic to be consumed
jsonSchema = StructType([ StructField("State", StringType(), True) \
                        , StructField("Value", StringType(), True) \
                        , StructField("SourceTimestamp", StringType(), True) \
                        , StructField("Tag", StringType(), True)
                        ])

spark = SparkSession \
    .builder \
    .appName("StructuredStreaming") \
    .config("spark.default.parallelism", "100") \
    .getOrCreate()

df = spark \
  .readStream \
  .format("kafka") \
  .option("kafka.bootstrap.servers", "10.129.140.23:9092") \
  .option("subscribe", "SIMULATOR.SUPERMAN.TOTO") \
  .load() \
  .select(from_json(col("value").cast("string"), jsonSchema).alias("data")) \
  .select("data.*")

df = df.withColumn("time", current_timestamp())

Window = df \
    .withColumn("window",window("time","4 seconds","1 seconds")).groupBy("window").count() \
    .withColumn("time", current_timestamp())

#Write back to kafka

query = Window.select(to_json(struct("count","window","time")).alias("value")) \
    .writeStream \
    .format("kafka") \
    .option("kafka.bootstrap.servers", "10.129.140.23:9092") \
    .outputMode("update") \
    .option("topic", "structed") \
    .option("checkpointLocation", "/home/superman/notebook/checkpoint") \
    .start()

The windows are not sorted and are updated each time there is a change in count. How can we wait for the end of the window and stream the final count one time. Instead of this output:
{"count":21,"window":{"start":"2019-05-13T09:39:14.000Z","end":"2019-05-13T09:39:18.000Z"},"time":"2019-05-13T09:39:15.026Z"}
{"count":47,"window":{"start":"2019-05-13T09:39:12.000Z","end":"2019-05-13T09:39:16.000Z"},"time":"2019-05-13T09:39:15.026Z"}
{"count":21,"window":{"start":"2019-05-13T09:39:13.000Z","end":"2019-05-13T09:39:17.000Z"},"time":"2019-05-13T09:39:15.026Z"}
{"count":21,"window":{"start":"2019-05-13T09:39:15.000Z","end":"2019-05-13T09:39:19.000Z"},"time":"2019-05-13T09:39:15.026Z"}
{"count":21,"window":{"start":"2019-05-13T09:39:16.000Z","end":"2019-05-13T09:39:20.000Z"},"time":"2019-05-13T09:39:17.460Z"}
{"count":42,"window":{"start":"2019-05-13T09:39:14.000Z","end":"2019-05-13T09:39:18.000Z"},"time":"2019-05-13T09:39:17.460Z"}
{"count":42,"window":{"start":"2019-05-13T09:39:15.000Z","end":"2019-05-13T09:39:19.000Z"},"time":"2019-05-13T09:39:17.460Z"}
{"count":21,"window":{"start":"2019-05-13T09:39:17.000Z","end":"2019-05-13T09:39:21.000Z"},"time":"2019-05-13T09:39:17.460Z"}
{"count":40,"window":{"start":"2019-05-13T09:39:16.000Z","end":"2019-05-13T09:39:20.000Z"},"time":"2019-05-13T09:39:19.818Z"}
{"count":19,"window":{"start":"2019-05-13T09:39:19.000Z","end":"2019-05-13T09:39:23.000Z"},"time":"2019-05-13T09:39:19.818Z"}
{"count":19,"window":{"start":"2019-05-13T09:39:18.000Z","end":"2019-05-13T09:39:22.000Z"},"time":"2019-05-13T09:39:19.818Z"}
{"count":40,"window":{"start":"2019-05-13T09:39:17.000Z","end":"2019-05-13T09:39:21.000Z"},"time":"2019-05-13T09:39:19.818Z"}
{"count":37,"window":{"start":"2019-05-13T09:39:19.000Z","end":"2019-05-13T09:39:23.000Z"},"time":"2019-05-13T09:39:21.939Z"}
{"count":18,"window":{"start":"2019-05-13T09:39:21.000Z","end":"2019-05-13T09:39:25.000Z"},"time":"2019-05-13T09:39:21.939Z"}

I would like this:
{"count":47,"window":{"start":"2019-05-13T09:39:12.000Z","end":"2019-05-13T09:39:16.000Z"},"time":"2019-05-13T09:39:15.026Z"}
{"count":21,"window":{"start":"2019-05-13T09:39:13.000Z","end":"2019-05-13T09:39:17.000Z"},"time":"2019-05-13T09:39:15.026Z"}
{"count":42,"window":{"start":"2019-05-13T09:39:14.000Z","end":"2019-05-13T09:39:18.000Z"},"time":"2019-05-13T09:39:17.460Z"}
{"count":42,"window":{"start":"2019-05-13T09:39:15.000Z","end":"2019-05-13T09:39:19.000Z"},"time":"2019-05-13T09:39:17.460Z"}
{"count":40,"window":{"start":"2019-05-13T09:39:16.000Z","end":"2019-05-13T09:39:20.000Z"},"time":"2019-05-13T09:39:19.818Z"}
{"count":40,"window":{"start":"2019-05-13T09:39:17.000Z","end":"2019-05-13T09:39:21.000Z"},"time":"2019-05-13T09:39:19.818Z"}

The expected ouput wait for the window to be closed based on comparaison between the end timestamp and the current time.


text:
Q: Silverlight grid with a large number of rows and columns I would like to know what is the recommended way of designing a Silverlight page with many controls in it, like a lob application for example. What I think would be simpler, especially if there are many pages to make, is to make a template page with a large number of rows and columns of the same dimension, so that I can visually put every control into the grid. In this way, each control will have something like absolute coordinates, as well as rowspan and columnspan.
Isn't this one the easiest way to design? I think such a layout would also be easier to modify, since if I want to move a textbox from the left to the right side of the screen, I only have to change it's Grid.Column property, without minding all the interactions with the stackpanels and the grids on the right side, like I see in many layouts that are organized with a number of grids and stackpanels.
And can the fact of having a large number of rows and columns decrease the performances?
Thanks for any opinion.

A: You can use a Canvas control if you want to do absolute positioning.


text:
Q: CSS - Placing image next to centered text I'm pretty well versed with HTML and CSS, but I'd like your opinion on this one!

I need to center the text in the arrow, but place a check box next to the centered text. Because of this, I can't user text-align on all of the contents of the arrow, like I normally would. If I include the check in the centering, the anchor point shifts off of the text to include the check, and the text isn't truly centered.
Thanks!

A: Make the check an absolutely positioned span, set as display:block, positioned relative to the text. Check out this jsFiddle for a basic idea. Your HTML may be set up differently:

*

*http://jsfiddle.net/cGG3W/1/

A: Without seeing the code, you could

*

*use text-align:center; on the text in the div.

*place the checkmark in another div and position it where necessary.  You may need to adjust the stack.


text:
Q: Submitting a partial view form within a modal dialog MVC, jQuery Here is my code:

                    <%= Html.ActionLink(item.Comments, "Comments", new { jobNumber = item.JobNumber, ordNumber = item.OrderNumber }, new { @class = "modalEdit" })%>

       <% Html.RenderPartial("AddComments", Model.InnerModel.RoadReportModelProp); %>

I need to send a POST request to the controller when I click on the SAVE button in the dialog, but I am not able to send a POST.
Please  help.

A: You should be able to use $.post to save your data. For example
$.post(url, data, function(response) {
    // Do something with response
});

You will need to collect the data from the dialog.
Regards,
Huske

A: You can use the following to Post, further, can you provide the code for the form you want to post, & also the controller you have created:

A:

        <% using (Html.BeginForm("Post-FormActionName", "Controllername"))
           {
        %>

              Name: *
                <%=Html.TextBoxFor("Name")%>

              <input id="submit" type="submit" value="Save"/>

        <%}%>


text:
Q: Disabling contextual menu when long clicking text in EditText I want to disable the default Contextual ActionBar (containing the Copy-Paste-Select All items) when long clicking a word in an EditText. This bar:

I tried to use the following code, but the problem with this code is that the selection handles don't appear anymore:
editText.setCustomSelectionActionModeCallback(new Callback() {
      @Override
      public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
        return false;
      }

      @Override
      public void onDestroyActionMode(ActionMode mode) {
      }

      @Override
      public boolean onCreateActionMode(ActionMode mode, Menu menu) {
        // I also tried menu.clear() but has the same behavior.
        return false;
      }

      @Override
      public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
        return true;
      }
    });

Does any one know how to disable the contextual actionbar and keep the selection handles?

A: After long hours of research, unfortunately the only way to do this is by forking TextView & EditText code and changing its code directly.


text:
Q: Typecasting to 'int' in Python generating wrong result I tried performing following typecast operation in Python 3.3

int( 10**23 / 10 )
Output: 10000000000000000000000

And after increasing power by one or further

int( 10**24 / 10 )
Output: 99999999999999991611392
int( 10**25 / 10 )
Output: 999999999999999983222784

Why is this happening? Although a simple typecasting like

int( 10**24 )
Output: 1000000000000000000000000

is not affecting the values.

A: You are doing floating-point division with the / operator. 10**24/10 happens to have an inexact integer representation.
If you need an integer result, divide with //.
>>> type(10**24/10)
<class 'float'>
>>> type(10**24//10)
<class 'int'>

A: In Python 3.x, / always does true(floating point) division. Using floor division // instead could give you the expected result.
>>> int(10**25 // 10)
1000000000000000000000000

The reason of this behavior is that float can't store big integers precisely.
Assuming IEEE-754 double precision is used, it can store integers at most 253 precisely, which is approximitely 1016. Another example:
>>> int(10**17 / 10 + 1)
10000000000000000


text:
Q: what type of "assert" should I use in rspec to validate pre-conditions are ok? I'm using rspec with ruby on rails for testing.
Question - In a spec if I was to do a cross check a pre-condition is established properly before starting the test, what approach is recommended?
For example, using an rspec ".should" type assertion doesn't seem like this would be the right thing as I'm only checking a precondition...

A: I would have two different tests: one asserting that things like your precondition can be set correctly, the other assuming it works and then testing whatever depends on it.

A: A should is perfectly valid in this situation as it is a condition that should be valid at the start of the test.  As a very trivial example:
it "should increment by one" do
  value = 10
  value.should eql(10)
  value += 1
  value.should eql(11)
end

A: I don't think current RSpec has that kind of feature, it would be nice to have some other method for these pre-condition assertions such as
it "should increment by one" do
  value = 10
  value.must eql(10) # This is a necessary pre-condition, not the actual test
  value += 1
  value.should eql(11)
end

But I guess there is no such method to distinguish things, but the rspec-given gem might be of interest.


text:
Q: What is the lifetime of assignments to fields marked as transient within a spring/jpa application? I'm not sure this is the right question or set of frameworks.
The list of frameworks I'm aware of being involved to some degree here are:

*

*Spring

*Hibernate

*QueryDSL

I've been trying to get to grips with a web application using this stuff on the server side and had basically come to the conclusion that the server was a collection of static methods, which had state eg objects etc for only the duration of individual method calls, with basically a huge pile of reflective code generation thrown in to make things confusing easy.
I've just come across the transient annotation and this has thrown my idea of what is going on out the window.
Im not really sure what's relevant so I'll describe the situation I'm looking at:
At login time we are querying a table in the database which has user information in it.
Update
This is from a class that implements UserDetailsService (a spring class) in the method that defines (loadUserByUsername(String username).
This gets called in a class extends AbstractUserDetailsAuthenticationProvider which is set as the authentication provider.  In practice this means it gets called as users login to our webapp.  There can be more than one user logged in at any given time.

This is done using a jpa repository and some querydsl predicate.
UserDetails userDetails = userRepository.findOneLoaded(UserPredicates.hasUserNameEqualsIgnoreCase(username));

Then comes the bit that is confusing:
    Division division = divisionRepository.findDefaultDivision((User) userDetails);
    ((User) userDetails).setCurrentDivision(division);

And that's it.  The setter just sets a field which is marked as @Transient and then none of the code in this stack uses this value.
It does have usages scattered throughout the project however, which would presumably fail (there aren't any tests so that could actually be the case!) if it was null.
What is happening here?  How long do these assignments last?  And I suppose on a related note, how long are the other 'objects' lasting for?  Is my mental model of this stuff as just being static method calls to read and write to the database wrong?  It might explain why the application guzzles so much memory!  I'm assuming a cached version of each row of the database isn't hanging around - is it something more like an in memory dictionary of key value pairs for each row that gets assigned to it when they get loaded from the database?
We're trying to refactor away from some of nastier parts of this stuff and this has made me a bit worried that there's more magic I don't know about yet!


text:
Q: Assign name to a substring in a loop importing raster files I'm importing some raster files from a PostgreSQL connection into R in a loop. I want to assign my newly gained rasters automatically to a variable whose name is derived from the input variable like this: substring(crop, 12)
crop <- "efsa_capri_barley"
ras <- readGDAL(sprintf("PG:dbname='' host='' port='' user='' schema='' table='%s' mode=2", crop))
paste0(substring(crop, 12)) <- raster(ras, 1)

What function do I have to use that R recognizes the result of substring() as a character string and not as the function itself? I was thinking about paste() but it doesn't work.
Probably this question has already been asked but I couldn't find a proper answer.

A: Based on your description, assign is technically correct, but recommending it is bad advice.
If you are pulling in multiple rasters in a loop, best practice in R is to initialize a list to hold all the resulting rasters and name each list element accordingly. You can do this one at a time:
# n is number of rasters
raster_list <- vector("list",n)

for (i in seq_len(n)){
  ...
  #crop[i] is the ith crop name
  raster_list[[substring(crop[i],12)]] <- raster(...)
}

You can also set the names of each element of the list all at once via setNames. But you should try to avoid using assign pretty much at all costs.

A: If I understand your question correctly, you are looking for something like assign. For example you can try this:
assign(substring(crop, 12), raster(ras, 1))

To understand how assign works, you can check this code:
x <- 2
# x is now 2

var_to_assign <- "x"
assign(var_to_assign, 3)
# x is now set to 3
x
# 3

Does that give you what you want?


text:
Q: How can i clear empty array in multiple file upload array I have encountered such a problem. and This is the solution.
$file_count=count($_FILES["sozlesme_pdf"]["tmp_name"]);
        for ($i=0; $i<$file_count; $i++) {
            if($_FILES["sozlesme_pdf"]["error"][$i]==0){
                $sozlesme_array["name"][]=$_FILES["sozlesme_pdf"]["name"][$i];
                $sozlesme_array["type"][]=$_FILES["sozlesme_pdf"]["type"][$i];
                $sozlesme_array["tmp_name"][]=$_FILES["sozlesme_pdf"]["tmp_name"][$i];
                $sozlesme_array["error"][]=$_FILES["sozlesme_pdf"]["error"][$i];
                $sozlesme_array["size"][]=$_FILES["sozlesme_pdf"]["size"][$i];
            }
} print_r($sozlesme_array);

...
When uploading multiple files, if one of the files is empty it returns such an error in the array.
Array
(
    [name] => Array
        (
            [0] =>
            [1] => file.pdf
        )

    [type] => Array
        (
            [0] =>
            [1] => application/pdf
        )

    [tmp_name] => Array
        (
            [0] =>
            [1] => C:\wamp64\tmp\php2FE0.tmp
        )

    [error] => Array
        (
            [0] => 4
            [1] => 0
        )

    [size] => Array
        (
            [0] => 0
            [1] => 150728
        )

)

I want to delete empty elements in the array.
https://indir360.com/
son dakika
phpstorm indir

A: Use unset to clear an array:
unset($sozlesme_array);

A: You should check the file name like following :
$file_count=count($_FILES["sozlesme_pdf"]["tmp_name"]);
        for ($i=0; $i<$file_count; $i++) {
            if(isset($_FILES["sozlesme_pdf"]["name"][$i]) && !empty($_FILES["sozlesme_pdf"]["name"][$i])){
                $sozlesme_array["name"][]=$_FILES["sozlesme_pdf"]["name"][$i];
                $sozlesme_array["type"][]=$_FILES["sozlesme_pdf"]["type"][$i];
                $sozlesme_array["tmp_name"][]=$_FILES["sozlesme_pdf"]["tmp_name"][$i];
                $sozlesme_array["error"][]=$_FILES["sozlesme_pdf"]["error"][$i];
                $sozlesme_array["size"][]=$_FILES["sozlesme_pdf"]["size"][$i];
            }
} print_r($sozlesme_array);


text:
Q: Can't mutate despite object as data.frame I have a subset of some data (as shown below). Now for some reason I can't mutate the data.frame in any way.
I get the error message:

Error: data_frames can only contain 1d atomic vectors and lists

Which should stem from me not returning an object class that is either a list or data.frame itself, however I can't even make mutations that clearly returns a numeric value.
Data
> FValuation.head
           conm  firm.value         isin fyear         Industry Total.PMG Exchange Industry.Classification                List Short.Name Feb.Price Current.Price
1      2E GROUP  15.2460627 SE0000680902 2015f    Other service      0.62      STO       Consumer Services First North Premier         2E     12.75         12.95
2      A-COM AB          NA SE0000592677 2015f    Other service      0.62     <NA>                    <NA>                <NA>       <NA>        NA            NA
3        AAK AB 423.2503370 SE0001493776 2015f Other production      0.31      STO          Consumer Goods               LARGE        AAK    430.00        425.00
4      AB SAGAX          NA SE0001629288 2015f      Real estate      0.56      STO              Financials                 MID  SAGA PREF        NA            NA
5     ABELCO AB   0.3730399 SE0003617075 2015f Other production      0.31      STO                    <NA>         AktieTorget        ABE      1.69          2.00
6 ACADEMEDIA AB          NA SE0007897079 2015f    Other service      0.62     <NA>                    <NA>                <NA>       <NA>        NA            NA

> str(FValuation.head)
'data.frame':   6 obs. of  12 variables:
 $ conm                   : chr  "2E GROUP" "A-COM AB" "AAK AB" "AB SAGAX" ...
 $ firm.value             : num  15.246 NA 423.25 NA 0.373 ...
 $ isin                   : chr  "SE0000680902" "SE0000592677" "SE0001493776" "SE0001629288" ...
 $ fyear                  : chr  "2015f" "2015f" "2015f" "2015f" ...
 $ Industry               : Factor w/ 16 levels "Building and construction",..: 11 11 10 14 10 11
 $ Total.PMG              : num  0.62 0.62 0.31 0.56 0.31 0.62
 $ Exchange               : Factor w/ 5 levels "","CPH","HEL",..: 5 NA 5 5 5 NA
 $ Industry.Classification: Factor w/ 11 levels "","Basic Materials",..: 4 NA 3 5 NA NA
 $ List                   : Factor w/ 7 levels ""," ","AktieTorget",..: 4 NA 5 6 3 NA
 $ Short.Name             : Factor w/ 1058 levels "","203","2E",..: 3 NA 6 805 9 NA
 $ Feb.Price              : num [1:6, 1] 12.75 NA 430 NA 1.69 ...
 $ Current.Price          : num [1:6, 1] 12.9 NA 425 NA 2 ...

> FValuation.summary <- FValuation.head %>% mutate(Buy.Sell.Signal = derivedFactor(
+                                            "NA"   = (is.na(firm.value) == TRUE | is.na(Feb.Price) == TRUE),
+                                            "sell" = (firm.value < Feb.Price),
+                                            "buy"  = (firm.value > Feb.Price),
+                                            .method = 'first'))
Error: data_frames can only contain 1d atomic vectors and lists

> FValuation.head  %>% mutate(test = firm.value * 2)
Error: data_frames can only contain 1d atomic vectors and lists

What could be wrong? And how can this be resolved?
> dput(droplevels(FValuation.head))
structure(list(conm = c("2E GROUP", "A-COM AB", "AAK AB", "AB SAGAX",
"ABELCO AB", "ACADEMEDIA AB"), firm.value = c(15.2460627037116,
NA, 423.25033702408, NA, 0.373039901083465, NA), isin = c("SE0000680902",
"SE0000592677", "SE0001493776", "SE0001629288", "SE0003617075",
"SE0007897079"), fyear = c("2015f", "2015f", "2015f", "2015f",
"2015f", "2015f"), Industry = structure(c(2L, 2L, 1L, 3L, 1L,
2L), .Label = c("Other production", "Other service", "Real estate"
), class = "factor"), Total.PMG = c(0.62, 0.62, 0.31, 0.56, 0.31,
0.62), Exchange = structure(c(1L, NA, 1L, 1L, 1L, NA), .Label = "STO", class = "factor"),
    Industry.Classification = structure(c(2L, NA, 1L, 3L, NA,
    NA), .Label = c("Consumer Goods", "Consumer Services", "Financials"
    ), class = "factor"), List = structure(c(2L, NA, 3L, 4L,
    1L, NA), .Label = c("AktieTorget", "First North Premier",
    "LARGE", "MID"), class = "factor"), Short.Name = structure(c(1L,
    NA, 2L, 4L, 3L, NA), .Label = c("2E", "AAK", "ABE", "SAGA PREF"
    ), class = "factor"), Feb.Price = structure(c(12.75, NA,
    430, NA, 1.69, NA), .Dim = c(6L, 1L)), Current.Price = structure(c(12.95,
    NA, 425, NA, 2, NA), .Dim = c(6L, 1L))), .Names = c("conm",
"firm.value", "isin", "fyear", "Industry", "Total.PMG", "Exchange",
"Industry.Classification", "List", "Short.Name", "Feb.Price",
"Current.Price"), row.names = c(NA, 6L), class = "data.frame")

A: Because last 2 columns of your dataframe contain matrix, i.e. it has 2 dimensions, see:
class(FValuation.head$Feb.Price)

If you drop (or convert to numeric) last 2 columns, it should work:
FValuation.head[, 1:10] %>%
            mutate(test = firm.value * 2)

str(FValuation.head$Feb.Price) will show that it has 6 rows and 1 column.
$ Feb.Price : num [1:6, 1]


text:
Q: Check if any text in multiple spans is negative I have a group of span tags with the same class. I am trying to use a filter function that gets a count of all the spans with a text value less than zero. I have used something similar

$('#go').on('click', function(){
 var $nonneg = $('.test').filter(function(){
 return parseInt(this.text) < 0;
 });
 if ($nonneg.length !=0){
  alert('fail');
 }else{
  alert('pass');
 }
})

0
0
0
-5

<button id="go">go</button>

using input values, but I am trying to figure out how to do it using the .text of an element.

A: There is no text property in plain JavaScript. Use textContent instead.

$('#go').on('click', function(){
 var $nonneg = $('.test').filter(function(){
 return parseInt(this.textContent) < 0;
 });
 if ($nonneg.length !=0){
  alert('fail');
 }else{
  alert('pass');
 }
})

0
0
0
-5

<button id="go">go</button>

A: Here's your code in a fiddle
 $('#go').on('click', function(){
    var $nonneg = $('.test').filter(function(){
        return parseInt($(this).text()) < 0;
    });
    if ($nonneg.length !=0){
        alert('fail');
    }else{
        alert('pass');
    }
})

A: Possible solution without using filter.

$('#go').on('click', function() {
  var lessThanZeroCount = 0;
  $('.test').each(function() {
    if (parseInt($(this).text()) < 0) {
      lessThanZeroCount++;
    }
  }).promise().done(function() {
    alert('spans with numbers less than zero = ' + lessThanZeroCount);
  });
})

0
-5
0
-5
0

<button id="go">go</button>

Fiddle
https://jsfiddle.net/Hastig/vngm5xzf/


text:
Q: Combinatorial problem Consider the set 1,2,3,4,5,6,7,8 and the equation
$a+2b+3c+4d+5e+6f+7g+8h=S$
where $a,b,c,d,e,f,g,h$ are still the set $1,2,3,4,5,6,7,8$.
The $8!$ permutations of a,b,..h  determine  the variation of S
in the range [120,204].
Now, how many times S is equal, for instance, to 156  or,
better, how many permutations determine S to take the
value 156?
In short words, can we solve the equation above
(and also determine the S distribution), without
of course merely sum executing or computer using?

A: Interesting question.
I think you can at least restrict your search space a bit if you're looking to compute the frequency for a single value of $S$.
Take $h=8$.  There are indeed some cases for which $h=8$ and $S = 156$.  The minimum value for $S$ with $h=8$ is
$$1(7) + 2(6) + 3(5) + 4(4) + 5(3) + 6(2) + 7(1) + 8(8) = 148.$$
The value os $S$ is most sensitive to the value of $h$, and second-most-sensitive to the value of $g$.  What if we set $h=8, g=2$?  Then the minimum value of $S$ is
$$1(7) + 2(6) + 3(5) + 4(4) + 5(3) + 6(1) + 7(2) + 8(8) = 149.$$
Taking it further, $g = 3$ has a minimum of $151$, and $g=4$ has a minimum of $154$.  But $g=5$ gives a minimum of $158$ which is greater than $156$.  So you don't have to worry about searching any values for $h=8, g=5,6,7$.  That's over two thousand cases (out of about forty thousand) you don't have to worry about.
Then, for each of $h=8, g=1,2,3,4$, increase the value of $f$ until your minimum exceeds $156$, and throw those cases out.
For $h=7, g=6$ the minimum is $156$.  That's the only case there.  You can throw away all cases for $h=7, g=8$.
For $h=6$ down, you have to check all values of $g$ based on this criterion.
Then start from the other end: $h=1$.  The maximum value for $S$ is $176$.  Decrease $g$ to see if you can get the maximum sum below $156$.  And you can: $h=1, g=2$.  Throw those out.
As you go along, you can also take advantage of the fact that $156$ is even.  You can throw away cases for which exactly one, or exactly three, of $a,c,e,g$ are odd, because the sum will be odd.
By being smart about what you calculate, you can get rid of a bunch of your cases and not cycle through all of them.
I don't see a way to get a full distribution without calculating all of them, though.


text:
Q: Installing Hadoop on windows 7 with 32 bit processor? I have a 32 bit machine with windows 7,
I need to install hadoop and try it out, I checked Cloudera distribution and it is for linux, VMWare images with 64 bit processor.
How do I install Hadoop on windows 7 with 32 bit processor?

A: You can install Hadoop on windows if you install cygwin see http://ebiquity.umbc.edu/Tutorials/Hadoop/00%20-%20Intro.html
Also Microsoft is working with Hortonworks to bring Hadoop to windows properly but for now it is only available on Azure. I understands there are plans to make it available on windows in general in the future.

A: Well, the closest thing is that you can install VMWare Player, a linux distro as a virtual machine on the top of VMWare and then the Hadoop packages on your virtual linux box. But that's slow and I wouldn't recommend it.
There's no Hadoop for windows.

A:
Hadoop version 2.2 onwards includes native support for Windows.
Do not attempt to run the installation from within Cygwin. Cygwin is
  neither required nor supported.

Figure out more information at http://wiki.apache.org/hadoop/Hadoop2OnWindows

A: Try Hortonworks' Sandbox, it's good for learning the (very) basics.


text:
Q: CakePHP extend currency formatting I need to extend the number helper to include other currencies. Using the "addFormat" function in the number helper, I have created a new "CurrenciesHelper" to add these currencies.
<?php

class CurrenciesHelper extends NumberHelper {

I know I need to make it possible for this helper to run this function immediately. What am I missing to contain this so it runs and adds this format?
     $this->Number->addFormat('CAD', array(
        'before'=>'$',
        'after' => false,
        'zero' => 0,
        'places' => 2,
        'thousands' => '.',
        'decimals' => ',',
        'negative' => '()',

}

A: Starting CakePHP 2.1, you don't need to extend the helper to get this done. NumberHelper has been re-factored into CakeNumber class. If you go through the code, you can see that the formats are now stored as a static array.
That helps us configure currency formats within app/Config/core.php, like the following:
App::uses( 'CakeNumber', 'Utility' );

CakeNumber::addFormat(
    'CAD',
    array(
       'before' => '$ ', 'after' => false,
       'zero' => 0, 'places' => 2, 'thousands' => '.',
       'decimals' => ',', 'negative' => '()', 'escape' => true
    )
);

// ... and any more definitions to follow.

Once your currency definitions are part of the core configuration, you can use them in any view using NumberHelper like $this->Number->currency( $c, 'CAD' ).

A: PREVIOUS ANSWER CHANGED: Due to position of functions, after the fact. Had to change to:
function __beforeRender(){
}

Was causing overwriting of other custom currencies.

By encapsulating it in a construct
  function, it run on helper
  construction. I was sure to include
  the parent constructor just in case.
function __construct() {
    parent::__construct();
    // code goes here
}


text:
Q: content layout is spole when we put html in ckediotor when  i  put HTML code  in ck editor text area then the style is changed i have give HTML content so  when  i save that ck-editor data then the layout of HTML is totally different and also ck editor add extra space in that  HTML tag so any suggestive for that .
i have application  in that i am creating PDF .so to edit pdf data i first show in ck editor  so when this data is saved then ck-editor add extra space between HTML tag like extra ''
tag and also extra nbsp; tag or html enity so is there any way we can ignore this one and save as original so
Thanks

A: umm, if I understand you right, then It could be if you have not defined a
<DOCTYPE ....>

which means that different browsers and editors will render it differently.  Hope this helps :)


text:
Q: Flink streaming file sink cannot recover from savepoint We have a flink streaming job which read data from kinesis and sink it to S3 in parquet format.
Sink:
    val parquetEventsWriterSink: StreamingFileSink[GenericRecord] = StreamingFileSink
      .forBulkFormat(new Path(s"s3a://some-bucket-name/"), ParquetAvroWriters.forGenericRecord(AvroSchema[ParquetEvent]))
      .withBucketCheckInterval(1000)
      .withBucketAssigner(new DateTimeBucketAssigner("yyyyMMdd"))
      .build()

when i want do flink app update, i do following (stop flink app with savepoint and rerun from savepoint)
/usr/bin/flink stop ${FLINK_APP_ID} -p s3a://bucket-to-save/savepoint -d -yid ${YARN_APP_ID}
/usr/bin/flink run -m yarn-cluster -s s3a://bucket-to-save/savepoint/savepoint-588ff0-7a7febf4f80a --allowNonRestoredState /path/to/flink.jar

Shutdown flink app log:
...
2020-07-02 09:30:37,448 INFO  org.apache.flink.runtime.checkpoint.CheckpointCoordinator     - Triggering checkpoint 32 @ 1593682237275 for job af23c08acc92229281cd28a12f8c42da.
2020-07-02 09:30:41,129 INFO  org.apache.flink.runtime.checkpoint.CheckpointCoordinator     - Completed checkpoint 32 for job af23c08acc92229281cd28a12f8c42da (145557 bytes in 2408 ms).
2020-07-02 09:30:41,294 INFO  org.apache.flink.runtime.executiongraph.ExecutionGraph        - Source: Custom Source -> Map -> Timestamps/Watermarks -> (....) (1/1) (67dc5d50d1713166b4e06d59c044806d) switched from RUNNING to FINISHED.
2020-07-02 09:30:41,303 INFO  org.apache.flink.runtime.executiongraph.ExecutionGraph        - Window(TumblingEventTimeWindows(30000), EventTimeTrigger, ScalaProcessWindowFunctionWrapper) (1/1) (7820bd149b8a2bf2c18a7dbef24dea2a) switched from RUNNING to FINISHED.
2020-07-02 09:30:41,303 INFO  org.apache.flink.runtime.executiongraph.ExecutionGraph        - KeyedProcess (1/1) (7edae003a3d86bd0b0b6ccd6978d7225) switched from RUNNING to FINISHED.
2020-07-02 09:30:42,331 INFO  org.apache.flink.runtime.executiongraph.ExecutionGraph        - KeyedProcess -> (Map -> Sink: Unnamed, Map -> Map -> Sink: Unnamed) (1/1) (e5ab39b6b0841aa5f90dfddf7035a014) switched from RUNNING to FINISHED.
2020-07-02 09:30:42,331 INFO  org.apache.flink.runtime.executiongraph.ExecutionGraph        - Window(TumblingEventTimeWindows(30000), EventTimeTrigger, ScalaProcessWindowFunctionWrapper) -> (Map -> Sink: Unnamed, Map -> Map -> Sink: Unnamed) (1/1) (54c9e5818615472a94bd4164748af8ab) switched from RUNNING to FINISHED.
2020-07-02 09:30:42,420 INFO  org.apache.flink.runtime.executiongraph.ExecutionGraph        - Window(TumblingEventTimeWindows(120000), EventTimeTrigger, ScalaProcessWindowFunctionWrapper) -> (Map -> Sink: Unnamed, Map -> Map -> Sink: Unnamed) (1/1) (45b06521f0dc628909f36e526281120e) switched from RUNNING to FINISHED.
2020-07-02 09:30:42,430 INFO  org.apache.flink.runtime.executiongraph.ExecutionGraph        - Window(TumblingEventTimeWindows(4000), EventTimeTrigger, ScalaProcessWindowFunctionWrapper) -> (Map -> Sink: Unnamed, Map -> Map -> Sink: Unnamed) (1/1) (4290ac65e1cfa537c6fc2eda6f82030f) switched from RUNNING to FINISHED.
2020-07-02 09:30:42,431 INFO  org.apache.flink.runtime.executiongraph.ExecutionGraph        - Window(TumblingEventTimeWindows(30000), EventTimeTrigger, ScalaProcessWindowFunctionWrapper) -> (Map -> Sink: Unnamed, Map -> Map -> Sink: Unnamed) (1/1) (2031b6da4375863db5b5496d359e4afe) switched from RUNNING to FINISHED.
2020-07-02 09:30:42,466 INFO  org.apache.flink.runtime.executiongraph.ExecutionGraph        - Window(SlidingEventTimeWindows(120000, 2000), EventTimeTrigger, ScalaProcessWindowFunctionWrapper) -> (Map -> Sink: Unnamed, Map -> Map -> Sink: Unnamed) (1/1) (fb335e9cc26f3973e335fb5e52abc62c) switched from RUNNING to FINISHED.
2020-07-02 09:30:42,468 INFO  org.apache.flink.runtime.executiongraph.ExecutionGraph        - Job JOB_NAME (af23c08acc92229281cd28a12f8c42da) switched from state RUNNING to FINISHED.
2020-07-02 09:30:42,468 INFO  org.apache.flink.runtime.checkpoint.CheckpointCoordinator     - Stopping checkpoint coordinator for job af23c08acc92229281cd28a12f8c42da.
2020-07-02 09:30:42,468 INFO  org.apache.flink.runtime.checkpoint.StandaloneCompletedCheckpointStore  - Shutting down
2020-07-02 09:30:42,468 INFO  org.apache.flink.runtime.checkpoint.CompletedCheckpoint       - Checkpoint with ID 32 at 's3a://bucket-savepoint/savepoint-af23c0-91247f37c4e0' not discarded.
2020-07-02 09:30:42,479 INFO  org.apache.flink.runtime.dispatcher.StandaloneDispatcher      - Job af23c08acc92229281cd28a12f8c42da reached globally terminal state FINISHED.
2020-07-02 09:30:42,496 INFO  org.apache.flink.runtime.jobmaster.JobMaster                  - Stopping the JobMaster for job JOB_NAME(af23c08acc92229281cd28a12f8c42da).
2020-07-02 09:30:42,499 INFO  org.apache.flink.runtime.jobmaster.slotpool.SlotPoolImpl      - Suspending SlotPool.
2020-07-02 09:30:42,500 INFO  org.apache.flink.runtime.jobmaster.JobMaster                  - Close ResourceManager connection b1b71407ad4d004faf36b9ca5ff59897: JobManager is shutting down..
2020-07-02 09:30:42,500 INFO  org.apache.flink.runtime.jobmaster.slotpool.SlotPoolImpl      - Stopping SlotPool.
2020-07-02 09:30:42,500 INFO  org.apache.flink.yarn.YarnResourceManager                     - Disconnect job manager 00000000000000000000000000000000@akka.tcp://flink@ip-10-60-37-55.ec2.internal:39455/user/jobmanager_0 for job af23c08acc92229281cd28a12f8c42da from the resource manager.
2020-07-02 09:30:42,502 INFO  org.apache.flink.runtime.jobmaster.JobManagerRunner           - JobManagerRunner already shutdown.

Resume job from savepoint:
...
2020-07-02 09:32:59,878 INFO  org.apache.flink.runtime.checkpoint.CheckpointCoordinator     - Starting job c9b11c5904dd3182c68a967b1af8623c from savepoint s3a://bucket-savepoint/sp-s/savepoint-af23c0-91247f37c4e0 (allowing non restored state)
2020-07-02 09:33:00,225 INFO  org.apache.flink.runtime.checkpoint.CheckpointCoordinator     - Reset the checkpoint ID of job c9b11c5904dd3182c68a967b1af8623c to 33.
2020-07-02 09:33:00,225 INFO  org.apache.flink.runtime.checkpoint.CheckpointCoordinator     - Restoring job c9b11c5904dd3182c68a967b1af8623c from latest valid checkpoint: Checkpoint 32 @ 0 for c9b11c5904dd3182c68a967b1af8623c.
2020-07-02 09:33:00,232 INFO  org.apache.flink.runtime.checkpoint.CheckpointCoordinator     - No master state to restore
2020-07-02 09:33:00,234 INFO  org.apache.flink.runtime.jobmaster.JobManagerRunner           - JobManager runner for job JOB_NAME (c9b11c5904dd3182c68a967b1af8623c) was granted leadership with session id 00000000-0000-0000-0000-000000000000 at akka.tcp://flink@ip-10-60-37-55.ec2.internal:45829/user/jobmanager_0.
2020-07-02 09:33:00,236 INFO  org.apache.flink.runtime.jobmaster.JobMaster                  - Starting execution of job JOB_NAME (c9b11c5904dd3182c68a967b1af8623c) under job master id 00000000000000000000000000000000.
2020-07-02 09:33:00,237 INFO  org.apache.flink.runtime.executiongraph.ExecutionGraph        - Job JOB_NAME (c9b11c5904dd3182c68a967b1af8623c) switched from state CREATED to RUNNING.
2020-07-02 09:33:00,245 INFO  org.apache.flink.runtime.executiongraph.ExecutionGraph        - Source: Custom Source -> Map -> Timestamps/Watermarks -> (Map -> files to s3 -> Sink: Unnamed, Filter, Filter, Filter, Filter, Filter) (1/1) (d9b4be9984c2ab3f468d7f286f8106cf) switched from CREATED to SCHEDULED.
...
2020-07-02 09:33:15,286 INFO  org.apache.flink.runtime.executiongraph.ExecutionGraph        - Window(TumblingEventTimeWindows(4000), EventTimeTrigger, ScalaProcessWindowFunctionWrapper) -> (Map -> Sink: Unnamed, Map -> Map -> Sink: Unnamed) (1/1) (79f5b69107d200d78bb8a32dfa32e126) switched from RUNNING to FAILED.
java.io.IOException: Inconsistent result for object 20200702/part-0-29: conflicting lengths. Recovered committer for upload 4jAOkQuDaQiMt53wlO3z8bzO6KtwkaDXXZIA6sTUE1f5pmvZs8EDPlRvu6VYI4y34sK5Zwr4p8fa8EglWvVvC_8z5sn_Dk6L6b5YJnWNIdThRHQ4qfMUK3dj1Eoi7cYweq0J42PcRrK7VOJLJmo8hg-- **indicates 12810 bytes, present object is 5825 bytes**
    at org.apache.flink.fs.s3.common.writer.S3Committer.commitAfterRecovery(S3Committer.java:98)
    at org.apache.flink.streaming.api.functions.sink.filesystem.Bucket.commitRecoveredPendingFiles(Bucket.java:156)
    at org.apache.flink.streaming.api.functions.sink.filesystem.Bucket.<init>(Bucket.java:128)
    at org.apache.flink.streaming.api.functions.sink.filesystem.Bucket.restore(Bucket.java:399)
    at org.apache.flink.streaming.api.functions.sink.filesystem.DefaultBucketFactoryImpl.restoreBucket(DefaultBucketFactoryImpl.java:64)
    at org.apache.flink.streaming.api.functions.sink.filesystem.Buckets.handleRestoredBucketState(Buckets.java:177)
    at org.apache.flink.streaming.api.functions.sink.filesystem.Buckets.initializeActiveBuckets(Buckets.java:165)
    at org.apache.flink.streaming.api.functions.sink.filesystem.Buckets.initializeState(Buckets.java:149)
    at org.apache.flink.streaming.api.functions.sink.filesystem.StreamingFileSink.initializeState(StreamingFileSink.java:334)
    at org.apache.flink.streaming.util.functions.StreamingFunctionUtils.tryRestoreFunction(StreamingFunctionUtils.java:178)
    at org.apache.flink.streaming.util.functions.StreamingFunctionUtils.restoreFunctionState(StreamingFunctionUtils.java:160)
    at org.apache.flink.streaming.api.operators.AbstractUdfStreamOperator.initializeState(AbstractUdfStreamOperator.java:96)
    at org.apache.flink.streaming.api.operators.AbstractStreamOperator.initializeState(AbstractStreamOperator.java:281)
    at org.apache.flink.streaming.runtime.tasks.StreamTask.initializeState(StreamTask.java:881)
    at org.apache.flink.streaming.runtime.tasks.StreamTask.invoke(StreamTask.java:395)
    at org.apache.flink.runtime.taskmanager.Task.doRun(Task.java:705)
    at org.apache.flink.runtime.taskmanager.Task.run(Task.java:530)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.io.FileNotFoundException: Completing multipart commit on 20200702/part-0-29: org.apache.flink.fs.s3base.shaded.com.amazonaws.services.s3.model.AmazonS3Exception: The specified upload does not exist. The upload ID may be invalid, or the upload may have been aborted or completed. (Service: Amazon S3; Status Code: 404; Error Code: NoSuchUpload; Request ID: _hidden_; S3 Extended Request ID: nBiv1K/zDVx/FuA+/UJVY/1xODua8n8=), S3 Extended Request ID: nBiv1K/zDVx/FuA+/UJVY/1xODua8n8=:NoSuchUpload
    at org.apache.flink.fs.shaded.hadoop3.org.apache.hadoop.fs.s3a.S3AUtils.translateException(S3AUtils.java:225)
    at org.apache.flink.fs.shaded.hadoop3.org.apache.hadoop.fs.s3a.Invoker.once(Invoker.java:111)
    at org.apache.flink.fs.shaded.hadoop3.org.apache.hadoop.fs.s3a.Invoker.lambda$retry$3(Invoker.java:260)
    at org.apache.flink.fs.shaded.hadoop3.org.apache.hadoop.fs.s3a.Invoker.retryUntranslated(Invoker.java:317)
    at org.apache.flink.fs.shaded.hadoop3.org.apache.hadoop.fs.s3a.Invoker.retry(Invoker.java:256)
    at org.apache.flink.fs.shaded.hadoop3.org.apache.hadoop.fs.s3a.WriteOperationHelper.finalizeMultipartUpload(WriteOperationHelper.java:222)
    at org.apache.flink.fs.shaded.hadoop3.org.apache.hadoop.fs.s3a.WriteOperationHelper.completeMPUwithRetries(WriteOperationHelper.java:267)
    at org.apache.flink.fs.s3hadoop.HadoopS3AccessHelper.commitMultiPartUpload(HadoopS3AccessHelper.java:84)
    at org.apache.flink.fs.s3.common.writer.S3Committer.commitAfterRecovery(S3Committer.java:85)
    ... 17 more
Caused by: org.apache.flink.fs.s3base.shaded.com.amazonaws.services.s3.model.AmazonS3Exception: The specified upload does not exist. The upload ID may be invalid, or the upload may have been aborted or completed. (Service: Amazon S3; Status Code: 404; Error Code: NoSuchUpload; Request ID:; S3 Extended Request ID: nBiv1K/zDVx/FuA+/UJVY/1xODua8n8=), S3 Extended Request ID: nBiv1K/zDVx/FuA+bEPoiI1idEj3UQQzSYOz3V6uesSrV3fXtcLkkYGuexCL/UJVY/1xODua8n8=
    at org.apache.flink.fs.s3base.shaded.com.amazonaws.http.AmazonHttpClient$RequestExecutor.handleErrorResponse(AmazonHttpClient.java:1639)
    at org.apache.flink.fs.s3base.shaded.com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeOneRequest(AmazonHttpClient.java:1304)
    at org.apache.flink.fs.s3base.shaded.com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeHelper(AmazonHttpClient.java:1056)
    at org.apache.flink.fs.s3base.shaded.com.amazonaws.http.AmazonHttpClient$RequestExecutor.doExecute(AmazonHttpClient.java:743)
    at org.apache.flink.fs.s3base.shaded.com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeWithTimer(AmazonHttpClient.java:717)
    at org.apache.flink.fs.s3base.shaded.com.amazonaws.http.AmazonHttpClient$RequestExecutor.execute(AmazonHttpClient.java:699)
    at org.apache.flink.fs.s3base.shaded.com.amazonaws.http.AmazonHttpClient$RequestExecutor.access$500(AmazonHttpClient.java:667)
    at org.apache.flink.fs.s3base.shaded.com.amazonaws.http.AmazonHttpClient$RequestExecutionBuilderImpl.execute(AmazonHttpClient.java:649)
    at org.apache.flink.fs.s3base.shaded.com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:513)
    at org.apache.flink.fs.s3base.shaded.com.amazonaws.services.s3.AmazonS3Client.invoke(AmazonS3Client.java:4325)
    at org.apache.flink.fs.s3base.shaded.com.amazonaws.services.s3.AmazonS3Client.invoke(AmazonS3Client.java:4272)
    at org.apache.flink.fs.s3base.shaded.com.amazonaws.services.s3.AmazonS3Client.completeMultipartUpload(AmazonS3Client.java:3065)
    at org.apache.flink.fs.shaded.hadoop3.org.apache.hadoop.fs.s3a.WriteOperationHelper.lambda$finalizeMultipartUpload$1(WriteOperationHelper.java:229)
    at org.apache.flink.fs.shaded.hadoop3.org.apache.hadoop.fs.s3a.Invoker.once(Invoker.java:109)
    ... 24 more
2020-07-02 09:33:15,287 INFO  org.apache.flink.runtime.executiongraph.ExecutionGraph        - Job JOB_NAME (c9b11c5904dd3182c68a967b1af8623c) switched from state RUNNING to FAILING.
java.io.IOException: Inconsistent result for object 20200702/part-0-29: conflicting lengths. Recovered committer for upload 4jAOkQuDaQiMt53wlO3z8bzO6KtwkaDXXZIA6sTUE1f5pmvZs8EDPlRvu6VYI4y34sK5Zwr4p8fa8EglWvVvC_8z5sn_Dk6L6b5YJnWNIdThRHQ4qfMUK3dj1Eoi7cYweq0J42PcRrK7VOJLJmo8hg-- indicates 12810 bytes, present object is 5825 bytes
    at org.apache.flink.fs.s3.common.writer.S3Committer.commitAfterRecovery(S3Committer.java:98)
    at org.apache.flink.streaming.api.functions.sink.filesystem.Bucket.commitRecoveredPendingFiles(Bucket.java:156)
    at org.apache.flink.streaming.api.functions.sink.filesystem.Bucket.<init>(Bucket.java:128)
    at org.apache.flink.streaming.api.functions.sink.filesystem.Bucket.restore(Bucket.java:399)
    at org.apache.flink.streaming.api.functions.sink.filesystem.DefaultBucketFactoryImpl.restoreBucket(DefaultBucketFactoryImpl.java:64)
    at org.apache.flink.streaming.api.functions.sink.filesystem.Buckets.handleRestoredBucketState(Buckets.java:177)
    at org.apache.flink.streaming.api.functions.sink.filesystem.Buckets.initializeActiveBuckets(Buckets.java:165)
    at org.apache.flink.streaming.api.functions.sink.filesystem.Buckets.initializeState(Buckets.java:149)
    at org.apache.flink.streaming.api.functions.sink.filesystem.StreamingFileSink.initializeState(StreamingFileSink.java:334)
    at org.apache.flink.streaming.util.functions.StreamingFunctionUtils.tryRestoreFunction(StreamingFunctionUtils.java:178)
    at org.apache.flink.streaming.util.functions.StreamingFunctionUtils.restoreFunctionState(StreamingFunctionUtils.java:160)
    at org.apache.flink.streaming.api.operators.AbstractUdfStreamOperator.initializeState(AbstractUdfStreamOperator.java:96)
    at org.apache.flink.streaming.api.operators.AbstractStreamOperator.initializeState(AbstractStreamOperator.java:281)
    at org.apache.flink.streaming.runtime.tasks.StreamTask.initializeState(StreamTask.java:881)
    at org.apache.flink.streaming.runtime.tasks.StreamTask.invoke(StreamTask.java:395)
    at org.apache.flink.runtime.taskmanager.Task.doRun(Task.java:705)
    at org.apache.flink.runtime.taskmanager.Task.run(Task.java:530)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.io.FileNotFoundException: Completing multipart commit on 20200702/part-0-29: org.apache.flink.fs.s3base.shaded.com.amazonaws.services.s3.model.AmazonS3Exception: The specified upload does not exist. The upload ID may be invalid, or the upload may have been aborted or completed. (Service: Amazon S3; Status Code: 404; Error Code: NoSuchUpload; Request ID: 26483B8A3458BB00; S3 Extended Request ID: nBiv1K/zDVx/FuA+/UJVY/1xODua8n8=), S3 Extended Request ID: nBiv1K/zDVx/FuA+/UJVY/1xODua8n8=:NoSuchUpload
    at org.apache.flink.fs.shaded.hadoop3.org.apache.hadoop.fs.s3a.S3AUtils.translateException(S3AUtils.java:225)
    at org.apache.flink.fs.shaded.hadoop3.org.apache.hadoop.fs.s3a.Invoker.once(Invoker.java:111)
    at org.apache.flink.fs.shaded.hadoop3.org.apache.hadoop.fs.s3a.Invoker.lambda$retry$3(Invoker.java:260)
    at org.apache.flink.fs.shaded.hadoop3.org.apache.hadoop.fs.s3a.Invoker.retryUntranslated(Invoker.java:317)
    at org.apache.flink.fs.shaded.hadoop3.org.apache.hadoop.fs.s3a.Invoker.retry(Invoker.java:256)
    at org.apache.flink.fs.shaded.hadoop3.org.apache.hadoop.fs.s3a.WriteOperationHelper.finalizeMultipartUpload(WriteOperationHelper.java:222)
    at org.apache.flink.fs.shaded.hadoop3.org.apache.hadoop.fs.s3a.WriteOperationHelper.completeMPUwithRetries(WriteOperationHelper.java:267)
    at org.apache.flink.fs.s3hadoop.HadoopS3AccessHelper.commitMultiPartUpload(HadoopS3AccessHelper.java:84)
    at org.apache.flink.fs.s3.common.writer.S3Committer.commitAfterRecovery(S3Committer.java:85)
    ... 17 more
Caused by: org.apache.flink.fs.s3base.shaded.com.amazonaws.services.s3.model.AmazonS3Exception: The specified upload does not exist. The upload ID may be invalid, or the upload may have been aborted or completed. (Service: Amazon S3; Status Code: 404; Error Code: NoSuchUpload; Request ID: 26483B8A3458BB00; S3 Extended Request ID: nBiv1K/zDVx/FuA+/UJVY/1xODua8n8=), S3 Extended Request ID: nBiv1K/zDVx/FuA+bEPoiI1idEj3UQQzSYOz3V6uesSrV3fXtcLkkYGuexCL/UJVY/1xODua8n8=
    at org.apache.flink.fs.s3base.shaded.com.amazonaws.http.AmazonHttpClient$RequestExecutor.handleErrorResponse(AmazonHttpClient.java:1639)
    at
    at org.apache.flink.fs.shaded.hadoop3.org.apache.hadoop.fs.s3a.Invoker.once(Invoker.java:109)
    ... 24 more
2020-07-02 09:33:15,316 INFO  org.apache.flink.runtime.executiongraph.ExecutionGraph        - Source: Custom Source -> Map -> Timestamps/Watermarks -> (Map -> packets to s3 -> Sink: Unnamed, Filter, Filter, Filter, Filter, Filter) (1/1) (d9b4be9984c2ab3f468d7f286f8106cf) switched from RUNNING to CANCELING.

Flink 1.9.1 (EMR emr-5.29.0)
Use
"org.apache.flink" %% "flink-parquet" % "1.10.0",
"org.apache.parquet" % "parquet-avro" % "1.10.0",

A: If you restart with the same Flink version and the same job (unmodified) it works or it throws the same exception? Also, can it be that you have configured any pruning policy for your pending Multi-part Uploads that cancels them before they are committed?


text:
Q: How to preserve the state of an application upon shutdown or power outage? Let's say I have an application with a lot of activities. Some activities play media (audio or video). On the other hand, assume that the device, which in this case is an Android TV Box, is used in a business environment like a train. The devices have no built-in battery. The boxes stream video from a local server. Passengers are watching a movie or listening to a music track and there is suddenly a (short) power outage. The question is how can I preserve the state of the application so that when the device is rebooted, the latest activity the user was on is started and the media resumes playback from the point it was last playing.
Currently, I think I can get current progress say every 5 seconds and save the playback progress in a SharedPreference like this:
    SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPref.edit();

    Timer timer = new Timer();
    timer.schedule(new TimerTask() {
     @Override
     void run() {
     editor.putInt(getString(R.string.saved_player_progress), exoPlayer.getCurrentPosition());
 editor.putString(getString(R.string.saved_video_uri), videoUri.toString());
     editor.commit();
     }
    }, 5000, 5000);

This way I can store video position and URI and then each time I start a player I check the preferences and if there was a stored position with matching uri, I'll resume the playback from that point on.
But, how what to resume my application altogether not just a component (an activity or a player) so that the user starts the app and goes back to the activity he was before?


text:
Q: Why two same statements are returning different results with just parentheses wrapping one and not the other one? Why two same statements are returning different results with just parentheses wrapping one and not the other one?
function foo(bar){
    return !bar;
}(false) ? false : true; // returns true

(function foo(bar){
    return !bar;
}(false) ? false : true); // returns false! why?!

A: function foo(bar){
    return !bar;
}
(false) ? false : true

is like saying:
if(false){
   //false
} else {
   //true
}

your function is not called, and your condition is false, meaning it returns the second statement (which has //true).

the second is VERY different
(function foo(bar){
    return !bar;
}
(false) ? false : true)

is like this:
function foo(bar){
    return !bar;
}

var temp = foo(false)

if(temp){
    //false
} else {
    //true
}

you are technically creating a self-executing function immediately invoked function expressions (IFFE) with false as a parameter. whatever it returns is subject to the condition. so:

*

*you passed false as parameter

*the function returns an inversion, which is true

*the return is evaluated, and since the return is true, it executes the first statement of your condition (which has //false)

self-executing functions immediately invoked function expressions (IFFE) commonly have these forms, and are commonly used to form closures (which is out of the scope of this question)
var result = (function(innerParam){
    //function body
}(passedParam));

and

//this form commonly seen in jQuery plugins
var result = (function(innerParam){
    //function body
})(passedParam);

A: Try this:
function foo(bar)
{
    alert('fun 1 executed');
    return !bar;
}
(false) ? false : true; // returns true

And this:
(function foo(bar)
{
    alert('fun 2 executed');
    return !bar;
}
(false) ? false : true);

Notice that in case 1 the function is never called.

A: It doesn't for me.
http://jsfiddle.net/JPv3j/1/
But anyway it's a weird construct that you shouldn't probably use in the first place if it has the possibility to be misinterpreted.


text:
Q: I see an answer with absolutely no user information - should I flag it? Over on Stack Overflow there's an answer to a question - Best Practices for Comments on Code Commit - with absolutely no user information.
In the past I've seen answers by users who have no profile (name but no link or photo), but this is the first time I've ever seen an answer with no name.
Should I flag this in any way for clean-up, or simply ignore it?
(Realistically, the user is asking a follow-up question to an answer, but assuming his rep was lower than the threshold, couldn't post a comment to an answer.)

A: Nope, you don't have to. That account is deleted for some reasons.

A: That's flaggable for being a follow-up question posted as an answer, but the lack of user information isn't an issue.

A: It's frequent to see answer without profile.

*

*Can be anonymous

*Can be from a user on a different StackExchange site and question got migrated to one site where the user do not have the account.

So no you do not have to flag this.
On the other hand, if the answer is not an answer but a follow-up to other answer with new question inside it, the problem is not the same. And then it should be flaged as "Not a real answer"

This was posted as an answer, but it does not answer the question. It should possibly be an edit, a comment, another question, or deleted altogether.


text:
Q: Вкладки на C++ как в Firefox Как сделать вкладки на C++ как в Firefox? Пробовал изучить исходник Firefox, но ничего не понял =(
A: *

*Вот описание православного tabcontrol WinAPI.

*Есть еще 100500 разных СПО вариантов.

*Его можно нарисовать самому вручную. Это долго и так никто обычно не делает, если требуется быстро нарисовать GUI. Внутри firefox скорее всего собственная реализация т.к. это реально важная часть браузера.


text:
Q: multiselect drop down with select all checkboxes I have jquery script
script src="~/Scripts/jquery-3.4.1.min.js">script

Then i have added the multiselect jquery plugins
link href="https://cdn.rawgit.com/davidstutz/bootstrap-multiselect/master/dist/css/bootstrap-multiselect.css"
      rel="stylesheet" type="text/css" /
script src="https://cdn.rawgit.com/davidstutz/bootstrap-multiselect/master/dist/js/bootstrap-multiselect.js"
        type="text/javascript"></script

But i get the error

$(...).multiselect is not a function

how to add the jquery plugins?

A: Did you include a function? Bootstrap and jquery goes in the head of your code.

type="text/javascript"
$(document).ready(function(){
    $('#select_all').on('click',function(){
        if(this.checked){
            $('.checkbox').each(function(){
                this.checked = true;
            });
        }else{
             $('.checkbox').each(function(){
                this.checked = false;
            });
        }
    });

    $('.checkbox').on('click',function(){
        if($('.checkbox:checked').length == $('.checkbox').length){
            $('#select_all').prop('checked',true);
        }else{
            $('#select_all').prop('checked',false);
        }
    });
});
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">

<input type="checkbox" id="select_all" /> Select all

<input type="checkbox" class="checkbox" value="1"/>Item 1

<input type="checkbox" class="checkbox" value="2"/>Item 2

<input type="checkbox" class="checkbox" value="3"/>Item 3

<input type="checkbox" class="checkbox" value="4"/>Item 4

<input type="checkbox" class="checkbox" value="5"/>Item 5