text:
Q: How to add a client using JDBC for ClientDetailsServiceConfigurer in Spring? I have the in memory thing working as follows:
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {

        clients.inMemory()
               .withClient("clientapp")
               .authorizedGrantTypes("password", "refresh_token")
               .authorities("USER")
               .scopes("read", "write")
               .resourceIds(RESOURCE_ID)
               .secret("123456");
}

I would like to use the JDBC implementation. For this, I have created the following tables (using MySQL):
-- Tables for OAuth token store

CREATE TABLE oauth_client_details (
  client_id               VARCHAR(255) PRIMARY KEY,
  resource_ids            VARCHAR(255),
  client_secret           VARCHAR(255),
  scope                   VARCHAR(255),
  authorized_grant_types  VARCHAR(255),
  web_server_redirect_uri VARCHAR(255),
  authorities             VARCHAR(255),
  access_token_validity   INTEGER,
  refresh_token_validity  INTEGER,
  additional_information  VARCHAR(4096),
  autoapprove             TINYINT
);

CREATE TABLE oauth_client_token (
  token_id          VARCHAR(255),
  token             BLOB,
  authentication_id VARCHAR(255),
  user_name         VARCHAR(255),
  client_id         VARCHAR(255)
);

CREATE TABLE oauth_access_token (
  token_id          VARCHAR(255),
  token             BLOB,
  authentication_id VARCHAR(255),
  user_name         VARCHAR(255),
  client_id         VARCHAR(255),
  authentication    BLOB,
  refresh_token     VARCHAR(255)
);

CREATE TABLE oauth_refresh_token (
  token_id       VARCHAR(255),
  token          BLOB,
  authentication BLOB
);

CREATE TABLE oauth_code (
  code           VARCHAR(255),
  authentication BLOB
);

Do I need to manually add a client in the MySQL tables?
I tried this:
clients.jdbc(dataSource).withClient("clientapp")
               .authorizedGrantTypes("password", "refresh_token")
               .authorities("USER")
               .scopes("read", "write")
               .resourceIds(RESOURCE_ID)
               .secret("123456");

Hoping that Spring would insert the correct things in the good tables, but it does not seem to do that. Why is it that you can further chain after jdbc() ?

A: @AndroidLover 's answer is good, but it could be simplified. You don't need to create tables like oauth_access_token, oauth_refresh_token, etc. unless you need a jdbc token store.
Since you only need a jdbc client detail service, all you need to do is:
1. create a client detail table oauth_client_details, for example:
drop table if exists oauth_client_details;
    create table oauth_client_details (
    client_id VARCHAR(255) PRIMARY KEY,
    resource_ids VARCHAR(255),
    client_secret VARCHAR(255),
    scope VARCHAR(255),
    authorized_grant_types VARCHAR(255),
    web_server_redirect_uri VARCHAR(255),
    authorities VARCHAR(255),
    access_token_validity INTEGER,
    refresh_token_validity INTEGER,
    additional_information VARCHAR(4096),
    autoapprove VARCHAR(255)
    );

2. create a user model that implements the UserDetail interface, for example(I'm using spring jpa in this case, you could use mybatis, jdbc, whatever):
@Entity
@Table(name = "users")
public class User implements UserDetails {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "user_id", nullable = false, updatable = false)
private String id;

@Column(name = "username", nullable = false, unique = true)
private String username;

@Column(name = "password", nullable = false)
private String password;

@Column(name = "enabled", nullable = false)
@Type(type = "org.hibernate.type.NumericBooleanType")
private boolean enabled;

public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

public void setUsername(String username) {
    this.username = username;
}

public void setPassword(String password) {
    this.password = password;
}

public void setEnabled(boolean enabled) {
    this.enabled = enabled;
}

@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
    List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
    authorities.add((GrantedAuthority) () -> "ROLE_USER");
    return authorities;
}

@Override
public String getPassword() {
    return this.password;
}

@Override
public String getUsername() {
    return this.username;
}

@Override
public boolean isAccountNonExpired() {
    return true;
}

@Override
public boolean isAccountNonLocked() {
    return true;
}

@Override
public boolean isCredentialsNonExpired() {
    return true;
}

@Override
    public boolean isEnabled() {
        return this.enabled;
    }
}

3. create a custom user detail service. notice that in your implementation, you should inject your dao service(in my case, I injected a jpaRepository.) and your dao service MUST have a method to find user by username.:
@Service("userDetailsService")
public class UserService implements UserDetailsService {

@Autowired
UserRepository userRepository;

@Override
public UserDetails loadUserByUsername(String userName) throws
UsernameNotFoundException {
    return userRepository.findByUsername(userName);
}
}

4. finally, config you authentication server:
@Configuration
@EnableAuthorizationServer
public class AuthServerConfig extends AuthorizationServerConfigurerAdapter {

@Autowired
@Qualifier("dataSource")
DataSource dataSource;

@Autowired
@Qualifier("userDetailsService")
private UserDetailsService userDetailsService;

@Autowired
private AuthenticationManager authenticationManager;

@Override
public void configure(AuthorizationServerEndpointsConfigurer configurer) {
    configurer
            .authenticationManager(authenticationManager)
            .approvalStoreDisabled()
            .userDetailsService(userDetailsService);
}

@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception
{
    clients
            .jdbc(dataSource)
            .inMemory().withClient("my-trusted-
client").secret("secret").accessTokenValiditySeconds(3600)
            .scopes("read", "write").authorizedGrantTypes("password",
"refresh_token").resourceIds("resource");
}
}

A: Please fallow this steps:

*

*
        put this schema.sql inside your resource folder to be detected by SpringBoot once you start your server. If you don't use spring boot no worries just import this script from any Mysql App Client (phpmyadmin,HeidiSQL,Navicat..)
drop table if exists oauth_client_details;
        create table oauth_client_details (
        client_id VARCHAR(255) PRIMARY KEY,
        resource_ids VARCHAR(255),
        client_secret VARCHAR(255),
        scope VARCHAR(255),
        authorized_grant_types VARCHAR(255),
        web_server_redirect_uri VARCHAR(255),
        authorities VARCHAR(255),
        access_token_validity INTEGER,
        refresh_token_validity INTEGER,
        additional_information VARCHAR(4096),
        autoapprove VARCHAR(255)
        );
        drop table if exists oauth_client_token;
        create table oauth_client_token (
        token_id VARCHAR(255),
        token LONG VARBINARY,
        authentication_id VARCHAR(255) PRIMARY KEY,
        user_name VARCHAR(255),
        client_id VARCHAR(255)
        );
        drop table if exists oauth_access_token;
        create table oauth_access_token (
        token_id VARCHAR(255),
        token LONG VARBINARY,
        authentication_id VARCHAR(255) PRIMARY KEY,
        user_name VARCHAR(255),
        client_id VARCHAR(255),
        authentication LONG VARBINARY,
        refresh_token VARCHAR(255)
        );
        drop table if exists oauth_refresh_token;
        create table oauth_refresh_token (
        token_id VARCHAR(255),
        token LONG VARBINARY,
        authentication LONG VARBINARY
        );
        drop table if exists oauth_code;
        create table oauth_code (
        code VARCHAR(255), authentication LONG VARBINARY
        );
        drop table if exists oauth_approvals;
        create table oauth_approvals (
        userId VARCHAR(255),
        clientId VARCHAR(255),
        scope VARCHAR(255),
        status VARCHAR(10),
        expiresAt TIMESTAMP,
        lastModifiedAt TIMESTAMP
        );
        drop table if exists ClientDetails;
        create table ClientDetails (
        appId VARCHAR(255) PRIMARY KEY,
        resourceIds VARCHAR(255),
        appSecret VARCHAR(255),
        scope VARCHAR(255),
        grantTypes VARCHAR(255),
        redirectUrl VARCHAR(255),
        authorities VARCHAR(255),
        access_token_validity INTEGER,
        refresh_token_validity INTEGER,
        additionalInformation VARCHAR(4096),
        autoApproveScopes VARCHAR(255)
        );

*
        Inject your DataSource, authenticationManager,UserDetailsService inside your OthorizationServer

        @Autowired
        private MyUserDetailsService userDetailsService;
        @Inject
        private AuthenticationManager authenticationManager;
        @Autowired
        private DataSource dataSource;

*
        You will need to create this two beans
@Bean
        public JdbcTokenStore tokenStore() {
        return new JdbcTokenStore(dataSource);
        }
        @Bean
        protected AuthorizationCodeServices authorizationCodeServices() {
        return new JdbcAuthorizationCodeServices(dataSource);
        }
 and please don't forget about the @Configuration on top of your AuthorizationServer class

*
        Configure your clients apps to be created in your mysql database: clients.jdbc(dataSource).withClient("clientapp")
        .authorizedGrantTypes("password", "refresh_token")
        .authorities("USER")
        .scopes("read", "write")
        .resourceIds(RESOURCE_ID)
        .secret("123456");
you've already done this.

*
        the most important thing ( and I think that you forgot about it ..) is: to configure your endpoints with the AuthorizationServerEndpointsConfigurer:
endpoints.userDetailsService(userDetailsService) .authorizationCodeServices(authorizationCodeServices()).authenticationManager(this.authenticationManager).tokenStore(tokenStore()).approvalStoreDisabled();

and that's it man , now it should work ;)
And feel free to ask for more... I'll be happy to help
I have sent you a message from tweeter !

A: This question is fairly old but none of the replies gave an answer to the questioner's original problem. I've stumbled over the same issue while getting myself familar with spring's oauth2 implementation and wondered why the ClientDetailsServiceConfigurer is not persisting the clients that were programmatically added via the JdbcClientDetailsServiceBuilder (which is instantiated by calling the jdbc(datasource) method on the configurer), despite that all tutorials on the net showed a similar example such as that posted by Wim. After digging deeper into the code i've noticed the reason. Well, it's simply because the code to update the oauth_clients_details table is never called. What's missing is the following call after configuring all clients: .and().build(). So, Wim's code must actually look as follows:
clients.jdbc(dataSource).withClient("clientapp")
           .authorizedGrantTypes("password", "refresh_token")
           .authorities("USER")
           .scopes("read", "write")
           .resourceIds(RESOURCE_ID)
           .secret("123456").and().build();

Et voila, the client clientapp is now persisted into the database.

A: @Override
public void configure(ClientDetailsServiceConfigurer configurer) throws Exception {

    JdbcClientDetailsService jdbcClientDetailsService = new JdbcClientDetailsService(dataSource);

    if(!jdbcClientDetailsService.listClientDetails().isEmpty() ) {
    jdbcClientDetailsService.removeClientDetails(CLIEN_ID);
    }

    if(jdbcClientDetailsService.listClientDetails().isEmpty() ) {
        configurer.jdbc(dataSource).withClient(CLIEN_ID).secret(encoder.encode(CLIENT_SECRET))
        .authorizedGrantTypes(GRANT_TYPE_PASSWORD, AUTHORIZATION_CODE, REFRESH_TOKEN, IMPLICIT)
        .scopes(SCOPE_READ, SCOPE_WRITE, TRUST).accessTokenValiditySeconds(ACCESS_TOKEN_VALIDITY_SECONDS)
        .refreshTokenValiditySeconds(FREFRESH_TOKEN_VALIDITY_SECONDS).and().build();
    }
    configurer.jdbc(dataSource).build().loadClientByClientId(CLIEN_ID);
}

Here i am checking there is any client exist in the database table oauth_client_details. If there is any client exist I am removing that entry because the first time it will work without any error but when you restart your application then it gives primary key errors while adding entry in database. Thats why I added this code:
 if(!jdbcClientDetailsService.listClientDetails().isEmpty() ) {

    jdbcClientDetailsService.removeClientDetails(CLIEN_ID);

    }

After removing the client entry you need to add client here is the code for adding client :
if(jdbcClientDetailsService.listClientDetails().isEmpty() ) {
        configurer.jdbc(dataSource).withClient(CLIEN_ID).secret(encoder.encode(CLIENT_SECRET))
        .authorizedGrantTypes(GRANT_TYPE_PASSWORD, AUTHORIZATION_CODE, REFRESH_TOKEN, IMPLICIT)
        .scopes(SCOPE_READ, SCOPE_WRITE, TRUST).accessTokenValiditySeconds(ACCESS_TOKEN_VALIDITY_SECONDS)
        .refreshTokenValiditySeconds(FREFRESH_TOKEN_VALIDITY_SECONDS).and().build();

    }

In this code you can change configuration as you want because we are removing client entry each time after restarting your application.
here we are loading all client details :
configurer.jdbc(dataSource).build().loadClientByClientId(CLIEN_ID);

It will works fine for you without any errors. Thanks

A: Use the following table schema for Postgres when following @AndroidLover answer.
create table IF NOT EXISTS   oauth_client_details
(
    client_id               VARCHAR(256) PRIMARY KEY,
    resource_ids            VARCHAR(256),
    client_secret           VARCHAR(256),
    scope                   VARCHAR(256),
    authorized_grant_types  VARCHAR(256),
    web_server_redirect_uri VARCHAR(256),
    authorities             VARCHAR(256),
    access_token_validity   INTEGER,
    refresh_token_validity  INTEGER,
    additional_information  VARCHAR(4096),
    autoapprove             VARCHAR(256)
);

create table IF NOT EXISTS  oauth_client_token
(
    token_id          VARCHAR(256),
    token             bytea,
    authentication_id VARCHAR(256) PRIMARY KEY,
    user_name         VARCHAR(256),
    client_id         VARCHAR(256)
);

create table IF NOT EXISTS  oauth_access_token
(
    token_id          VARCHAR(256),
    token             bytea,
    authentication_id VARCHAR(256) PRIMARY KEY,
    user_name         VARCHAR(256),
    client_id         VARCHAR(256),
    authentication    bytea,
    refresh_token     VARCHAR(256)
);

create table IF NOT EXISTS  oauth_refresh_token
(
    token_id       VARCHAR(256),
    token          bytea,
    authentication bytea
);

create table IF NOT EXISTS  oauth_code
(
    code           VARCHAR(256),
    authentication bytea
);

create table IF NOT EXISTS  oauth_approvals
(
    userId         VARCHAR(256),
    clientId       VARCHAR(256),
    scope          VARCHAR(256),
    status         VARCHAR(10),
    expiresAt      TIMESTAMP,
    lastModifiedAt TIMESTAMP
);

-- customized oauth_client_details table
create table IF NOT EXISTS  ClientDetails
(
    appId                  VARCHAR(256) PRIMARY KEY,
    resourceIds            VARCHAR(256),
    appSecret              VARCHAR(256),
    scope                  VARCHAR(256),
    grantTypes             VARCHAR(256),
    redirectUrl            VARCHAR(256),
    authorities            VARCHAR(256),
    access_token_validity  INTEGER,
    refresh_token_validity INTEGER,
    additionalInformation  VARCHAR(4096),
    autoApproveScopes      VARCHAR(256)
);

The following is my OAuth2 configuration loading and validating tokens from the database
@Configuration
@EnableAuthorizationServer
class OAuth2Config extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Autowired
    @Qualifier("dataSource")
    DataSource dataSource;

    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public TokenStore tokenStore() {
        return new JdbcTokenStore(dataSource);
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security
                .tokenKeyAccess("permitAll()")
                .checkTokenAccess("isAuthenticated()")
                .allowFormAuthenticationForClients();
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.jdbc(dataSource);
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer authorizationServerEndpointsConfigurer) throws Exception {
        authorizationServerEndpointsConfigurer.tokenStore(tokenStore());
    }
}

A: Adding my two cents.
If you are initializing db structures on startup (with dropping previous), for example like this:
@Bean
public DataSourceInitializer dataSourceInitializer(DataSource dataSource) {
    //...setting dataSource and databasePopulator
}
private DatabasePopulator databasePopulator() {
    //...adding your schema script
}
@Bean
public DataSource dataSource() {
    //...setting driverclassname, url, etc
}

@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
    //...
    clients.jdbc(this.dataSource()).withClient("example").(...).build()
}

beware.
Beans does not have to be created in some specific order, so you may catch situation when you insert lines in your old tables, and then replacing it with new, from your schema. So, you may wonder for a while, why is it still not inserting lines. I hope, this would help someone.


text:
Q: Misunderstanding of an exercise on topology? Let $\mathbb{R}$ be the set of reals with a topology $\mathcal{T}$ such, that each $x\in\mathbb{R}$ has a base of open regions
$$\mathcal{B}_x=\{\{x\}\cup\{y\in\mathbb{Q}:|x-y|<1/n\}\}_{n\in\mathbb{N}}$$

*

*Show the space is seperable and $T_2$

*Show that for each $x\in\mathbb{R}$ and $U$ open subset of $(\mathbb{R}, \mathcal{T})$ which contains $x$, there is an open set $V$ such that $x\in V\subseteq\overline{V}\subseteq U$. Then conclude that the space is $T_3$.

*Show that the singleton $\{q\}$, where $q\in\mathbb{Q}$, and the set of irrationals $\mathbf{Irr}$ are closed and not separable by two disjoint open sets. Conclude that the space is not $T_4$.

My question is

How can this space be $T_3$ when, according to (3), for $q\in\mathbb{Q}$ and $\mathbf{Irr}$ (which is closed and does not contain $q$) there is no open set separating them? Isn't this exercise contradictory?

A: You are right, the exercise is contradictory. And the space is not $T_3$. For rational $x$, the closed neighbourhoods don't form a neighbourhood base.
If $x\in\mathbb{Q}$, take $U = (x-1,x+1) \cap \mathbb{Q}$. This is an open set, and every open set $x \in V \subset U$ contains $W_\varepsilon := (x-\varepsilon,x+\varepsilon)\cap\mathbb{Q}$ for some $\varepsilon > 0$. But $(x-\varepsilon,x+\varepsilon) \subset \overline{W}_\varepsilon$, whence $\overline{W}_\varepsilon \not\subset U$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Use `index.html` rather than `index.ejs` I have a mean-stack application. By going to https://localhost:3000/#/home, it reads views/index.ejs. Here is the setting in app.js:
var app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(express.static(path.join(__dirname, 'public')));
app.all('/*', function(req, res, next) {
    res.sendFile('index.ejs', { root: __dirname });
});

Actually, I don't use the feature of ejs in index.ejs. So now I want to use just a index.html rather than index.ejs.
I put the content of index.ejs in public/htmls/index.html and views/index.html. And here is the current setting in app.js:
var app = express();
// app.set('views', path.join(__dirname, 'views'));
// app.set('view engine', 'ejs');
app.use(express.static(path.join(__dirname, 'public')));
app.all('/*', function(req, res, next) {
    res.sendFile('index.html', { root: __dirname });
    // res.sendFile('index.html'); // does not work either
});

However, running https://localhost:3000/#/home returns
Error: No default engine was specified and no extension was provided.

Does anyone know how to fix it?
Edit 1: by following the answer of user818510, I tried res.sendFile('index.html', { root: path.join(__dirname, 'views') }); in app.js, it still can NOT find index.html.
Whereas, in routes/index.js, the following can find index.html, but it gives a warning express deprecated res.sendfile: Use res.sendFile instead routes/index.js:460:9.
var express = require('express');
var router = express.Router();
var path = require('path');
... ...
router.get('*', function(req, res) {
    res.sendfile('./views/index.html'); // works, but a deprecation warning
    // res.sendFile('index.html', { root: path.join(__dirname, 'views') }); does not work
});

It is really confusing...

A: If it's a single page mean application, then you only need to start express with static and put index.html in static/ dir :
Project layout
static/
  index.html
server.js

server.js
'use strict';

var express = require('express');

var app = express();
app.use(express.static('public'));

var server = app.listen(8888, function () {
  console.log("Server started. Listening on port %s", server.address().port);
});

Now you can call http://localhost:8888/#home

A: It looks like a problem with the path. Your index.html is located at public/htmls/index.html and views/index.html. Your root option in res.sendFile should be __dirname+/public/htmls/ or __dirname+/views
In your code, you are using the path:
res.sendFile('index.html', { root: __dirname });

Your app.js would be in the project root where you have public directory alongside at the same level. Based on your rootoption in res.sendFile, you would have to place index.html at the same level as your app.js.
You should change the root path in res.sendFile. Use:
res.sendFile('index.html', { root: path.join(__dirname, 'public', 'htmls') });

OR
res.sendFile('index.html', { root: path.join(__dirname, 'views') });

The above root is based on the path that you've mentioned in your question.
Here's the link to the docs:
http://expressjs.com/en/api.html#res.sendFile
Your no default engine error is probably because you have commented the line where you set the view engine to ejs but still have existing ejs views. Uncommenting that line with the root path change should solve your issue.

A: Do not serve static content from an application server.
Use a web server for that, and in production, a content delivery network like Akamai.
A content delivery network will charge you per bandwidth (e.g: 10 cents per Terabyte). Serving the equivalent of 10 cents in Akamai can cost you thousands of dollars using cloud instances.
In addition to that, your servers will have unnecessary load.
If you absolutely have to serve static content from your application servers, then put a reverse proxy cache like nginx, varnish or squid in front of your server. But that will still be very cost inefficient. This is documented in the express website.
This is common practice in every Internet company.


text:
Q: Angularfire2 how to combine two list I am using Angularfire2 v5. In my database I have two lists one is cartand other one is product. In cart list there is a field which contains product id and now I want a Observable that contains data for both the cart and it's product. Currently I am trying with this way
cart: Observable<any>;
constructor(public db: AngularFireDatabase) {}

ionViewDidLoad() {

this.cart = this.db.list(`/cart`)
  .snapshotChanges()
  .map(changes => {
    return changes.map(c => {
      let productObservables:Observable<any> = this.db
        .list(`product/${c.key}`).snapshotChanges()
        .map(m=>{
            m.map(p=>({
              key:c.payload.key, ...p.payload.val()
            }));
            return m;
        });
        return productObservables;
    })
  });

now in html using this
<ion-item *ngFor="let item of cart|async">
  <ion-label>
    {{item.key}}
    {{item.name}}
  </ion-label>

but it shows me null. How can I display both data the cart and product list in one ngFor async

A: Say you had a structure like this:
cart:
  yyy:
    productId: aaa
    qty: 2
  zzz:
    productId: bbb
    qty: 1
products:
  aaa:
    name: AAA
  bbb:
    name: BBB

Then you could map it against the other part of the db, since you already have the key I'm just using valueChanges() here.
this.cart = this.db.list(`/cart`)
  .snapshotChanges()
  .map(changes =>
    changes.map(c => ({
      key: c.payload.key,
      product: this.db.object(`products/${c.payload.val().productId}`).valueChanges(),
      ...p.payload.val()
    }))
  );

The product will then be async, so you'd need to pipe that in your view too:
<ion-item *ngFor="let item of cart | async">
  <ion-label *ngIf="item.product | async; let product; else loading">
    {{product.name}} x {{item.qty}} {{item.key}}
  </ion-label>
<ion-item>
<ng-template #loading><ion-spinner></ion-spinner></ng-template>


text:
Q: Searching in an array for numbers with each element +1 or -1 of preceding element An array of integers contains elements such that each element is 1 more or less than its preceding element. Now we are given a number, we need to determine the index of that number's first occurrence in the array.
Need to optimize linear search. Its not homework.

A: My algorithm would be like this:

*

*p=0

*if (A[p] == x) then idx=p and the algorithm is finished else goto next step

*set p += |x-A[p]|

*goto 2.

say A[p] > x. Then, since A items increase or decrease by 1, idx is for sure at least (A[p] - x) index away from p. Same principle goes for A[p] < x.
int p=0, idx=-1;
while (p<len && p>=0)
   if (A[p]==x)
       idx = p;
   else
       p+= abs(x-A[p]);

Time complexity: The worst case would be O(n). I expect the average case to be better than O(n) ( I think it's O(log n) but not sure about it).
Running time: Definitely better than linear search for all cases.

A: You can't be faster than linear. The following code should be as fast as you can go:
int findFirstIndex(int num, int[] array) {
     int i = 0;
     while (i< array.length)
          if (array[i] == num) return i;
          else i += abs(array[i] - num)
     return -1
}

But it's still O(array.length) in the worst case. Think for example if you are looking for 1 in an array containing only 0. Then, you can't skip any position.

A: Start from first position; now consider the difference between the searched number N and first number. if array[0] == N then we finished; otherwise we have to jump of abs(array[0] -N ) positions; now just repeat this until the end of the array.


text:
Q: Forcing function If the forcing function on the right-hand side of a linear $n^{th}$ order differential equation is nonconstant and periodic, can the solution of the equation be a nonperiodic function?

A: Yes.  Consider the equation
$\ddot y + \omega^2 y = A \cos \omega t, \; \omega \ne 0; \tag{1}$
with initial conditions
$y(0) = 0, \tag{2}$
$\dot y(0) = 0; \tag{3}$
then the unique solution is
$y(t) = \dfrac{A}{2\omega}t\sin \omega t; \tag{4}$
we see that  with $y(t)$ as in (4) we have
$\dot y(t) = \dfrac{A}{2\omega}\sin \omega t + \dfrac{A}{2} t \cos \omega t, \tag{5}$
$\ddot y(t) = \dfrac{A}{2} \cos \omega t +  \dfrac{A}{2} \cos \omega t - \dfrac{A\omega}{2} t \sin \omega t = A \cos \omega t - \dfrac{A\omega}{2} t \sin \omega t, \tag{6}$
and furthermore (4) and (5) satisfy (2) and (3); since
$\omega^2 y(t) = \dfrac{A \omega}{2}t \sin \omega t, \tag{7}$
we see that (4) satisfies (1).  But the solution (4) is not periodic; in fact, it is unbounded as $t \to \pm \infty$.  This gives an affirmative example in the case $n = 2$,
We generalize the above to construct examples for all $n > 2$ as follows:
A.)  differentiate (1) $n - 2$ times to obtain the equation:
$\dfrac{d^n y}{dt^n} + \omega^2 \dfrac{d^{n - 2} y}{dt^{n - 2}} = \dfrac{d^{n - 2}}{dt^{n - 2}}(A \cos \omega t); \tag{7}$
note the right-hand side of (7) is periodic.
B.)  Evaluate $\dfrac{d^j}{dt^j}(\dfrac{A}{2\omega} t \sin \omega t)$, $2 \le j \le n - 1$, at $t = 0$ to obtain a complete set of initial conditions $\dfrac{d^j y}{dt^j}(0)$ for (7), using $y(0)$ and $\dot y(0)$ as in (2), (3);
C.)  Observe that then $y(t)$ as in (4) is the unique solution to (7) satisfying the initial conditions obtained under item (B.) above.
I leave the case $n = 1$ to the interested members of my readership; it is not difficult, but if I am not mistaken the sought-for solution must be of the form $y(t) = t(C\sin \omega t + D\cos \omega t)$ if (1) is replaced by $\dot y + \omega y = A\cos \omega t$.  And, of course the value of $y(0)$ must be specified.  Quite likely we must have $y(0) = 0$. ;-)
Hope this helps.  Cheerio,
and as always,
Fiat Lux!!!


text: Q: Cannot generate Opensearch Reports I've updated to 2.3 on all my OpenSearch clusters in my AWS accounts. I try to generate reports in the Reporting Plugin. Both pdfs and pngs, based off of Dashboards. Only 1 time ever have I been successful to generate and download a pdf report. Most of the time the progress wheel just keeps spinning, and never finishes. I do see the browser console a few errors, and a 500, but I'm just curios if this feature even works? As across different clusters, with different versions, and different report settings it seems to not work.


text:
Q: Searching for an example of classes and objects using Processing I am a beginner and I have little to no prior programming experience, I was hoping I could learn something. I think a ellipse would be the best object.

A: Let's assume I want to build cars in Processing. I could have several variables to describe information about the car, say, the bodyColor, yearMade or model. However, having global variables to define these is redundant. We use Objects in Java (which is what Processing is made in) to define a collection of variables and methods.
A class is a blueprint for an object. You can't have an object without a class to define it from. For instance, if we want to make a Car object, we need to define a Car type. This is done using classes.
class Car //defines the class Car
{
  color bodyColor; //the body color of the car
  int yearMade; //the year the car was made
  String model; //the model of the car

  void drive() {
    //add code for making the car move here
  }

  void paint(color newColor) {
    bodyColor = newColor; //paints the car to a new color
  }
}

Every class can have variables, like model, and methods, like drive().
Now remember, this is a blueprint, not an object. To make a Car object, the class needs something called a constructor function. A constructor function is something that builds the object using the information from the class.
Inside of Car:
public Car(color colorChosen, int thisYear, String modelName) {
  bodyColor = colorChosen;
  yearMade = thisYear;
  model = modelName;
}

We can imagine that when we call this function anywhere in our code, we are creating a new car object:
Car myFirstCar = new Car(color(0, 255, 0) /*green*/, 2020, "Toyota");

In that example, myFirstCar is a car that is green, made in 2020, and is a Toyota.
You can also get and set properties of objects:
print(myFirstCar.yearMade); //2020
myFirstCar.model = "Honda";
print(myFirstCar.model); //Honda
myFirstCar.paint(color(255, 0, 0)); //paints the car red. Now myFirstCar.bodyColor = color(255, 0, 0).

There are lots of great things you can do with objects. They are so important to Java, because it is the foundation of object-oriented programming. With time and practice, creating classes and objects will be a piece of cake.
Best of luck.

A: The answer already given by Ben Myers is a great explanation of objects and classes in general.
This answer gives a small example in Processing that could be helpful to show how you can use objects and classes in a Processing sketch:
// Create two moving ellipse objects that follow the mouse pointer.
// The MovingEllipse class can be found below.
MovingEllipse movingEllipse1 = new MovingEllipse(20, 2.0);
MovingEllipse movingEllipse2 = new MovingEllipse(50, 3.2);

void setup() {
  size(600, 600);
  frameRate(60);
}

void draw() {
  // Clear the previous frame and set the background color to anthracite.
  background(56, 62, 66);

  movingEllipse1.move();
  movingEllipse1.draw();

  movingEllipse2.move();
  movingEllipse2.draw();
}

class MovingEllipse {
  float x;
  float y;
  float speed;
  float fillColor;
  float ellipseWidth;
  float ellipseHeight;

  MovingEllipse(float position, float speed) {
    this.x = position;
    this.y = position;
    this.speed = speed;
    this.fillColor = 7 * speed * speed * speed;
    this.ellipseWidth = 6.0 + speed * speed;
    this.ellipseHeight = 2.0 * speed;
  }

  void move() {
    PVector direction = new PVector(mouseX - x, mouseY - y).setMag(speed);
    x += direction.x;
    y += direction.y;
  }

  void draw() {
    fill(fillColor);
    ellipse(x, y, ellipseWidth, ellipseHeight);
  }
}


text:
Q: "Loader.o: File not recognized: File format not recognized" Error I have a problem with the G++ ld command.
I'm trying to use this: ld -T linker.ld -o Kernel.bin Loader.o Video.o Kernel.o, but it's giving me the error: Loader.o: File not recognized: File format not recognized.
What's causing this error, and how can I fix it.


text:
Q: Doctrine (symfony) YAML schema/fixture constraint trouble Morning,
I'm having some trouble creating tables/loading fixtures.
(symfony 1.4.6 with the bundled Doctrine 1.2.3(?))

Tables (simplified):
Horseman:
    tableName: Horseman
    actAs: { Timestampable: ~ }
    columns:
        id:     { type: integer(4), primary: true, autoincrement: true, unsigned: true }
        name:   { type: string(100), notnull: true }

Stable:
    tableName: Stable
    actAs: { Timestampable: ~ }
    columns:
        id:         { type: integer(4), primary: true, autoincrement: true, unsigned: true }
        info:       { type: clob }
        id_owner:   { type: integer(4), unsigned: true }
    relations:
        Horseman:   { local: id_owner, foreign: id }

Horses:
    tableName: Horses
    actAs: { Timestampable: ~ }
    columns:
        id:         { type: integer(4), primary: true, autoincrement: true, unsigned: true }
        name:       { type: string(100), notnull: true }
        id_owner:   { type: integer(4), unsigned: true }
        id_stable:  { type: integer(4), unsigned: true }
    relations:
        Horseman:   { local: id_owner, foreign: id }
        Stable:     { local: id_stable, foreign: id }

"Horseman" doesn't have any dependencies
"Stable" has one "Horseman"
"Horses" has one "Horseman" and one "Stable"
fixtures:
Horseman:
    Hector:
        name: Hector

Stable:
    StableA:
        info: Lorem Ipsum Dolor Sit Amet
        id_owner: Hector

Horses:
    Ed:
        name: Ed
        id_owner: Hector
        id_stable: StableA

When Inserting the fixtures:
$ php symfony doctrine:build --all --and-load

i get a constraint violation:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`issuetracker/Stable`, CONSTRAINT `Stable_id_owner_Horseman_id` FOREIGN KEY (`id_owner`) REFERENCES `Horseman` (`id`))

The "Horseman" entry gets inserted without a problem.
Inserting the other two entries by hand is not a problem either:
INSERT INTO Stable (id,info,id_owner,created_at,updated_at) VALUES (null,"foo",1,NOW(),NOW())
INSERT INTO Horses (id,name,id_owner,id_stable,created_at,updated_at) VALUES (null,"foo",1,1,NOW(),NOW())

(Does symfony save the created insert statements somewhere?)

If i get it right, Doctrine should take care of inserting orders by itself(?) Since I'm giving the correct order anyways that shouldn't be the problem..

In the hope that i just didn't see or didn't get a small thing, would one of you nice guys tell me why i get that constraint violation and/or how to fix it, pretty please..

Thanks.

A: Try it like this:
Horseman:
    Hector:
        name: Hector

Stable:
    StableA:
        info: Lorem Ipsum Dolor Sit Amet
        Horseman: Hector

Horses:
    Ed:
        name: Ed
        Horseman: Hector
        Stable: StableA

You don't want to use an id of related object but THE related object. That's why you should use relation names rather than field names.


text:
Q: Exclude executable property from JSON serialization I'm using Newtonsoft.Json to serialize values for caching and I'm wondering if there is a way to exclude executable properties in the same way that methods are excluded from serialization? Preferably a way to set it globally so I don't need to mark hundreds of properties with an attribute (that I would first have to find among many thousands of properties).
The code:
[Serializable]
public class Item
{
    public long Id { get; set; }

    public string Name { get; set; }

    public List<Image> Images { get; set; }

    public Image PrimaryImage { get { return Images[0]; } }
}

[Serializable]
public class Image
{
    public long Id { get; set; }

    public string FileName { get; set; }
}

The error:
Error getting value from 'PrimaryImage' on 'Item'.
at Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue(Object target)
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.CalculatePropertyValues(JsonWriter writer, Object value, JsonContainerContract contract, JsonProperty member, JsonProperty property, JsonContract& memberContract, Object& memberValue)
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter, Object value, Type objectType)
at Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter, Object value, Type objectType)
at Newtonsoft.Json.JsonConvert.SerializeObjectInternal(Object value, Type type, JsonSerializer jsonSerializer)

I'll also mention that the logic in PrimaryImage has been simplified so the solution is not to skip using the property. This seems like a pretty common use of properties so I find it strange that it does not handle it already.

A: Try this code (serialize only get-set properties):
public static class NewtonsoftDefaultSettings
{
    public static JsonSerializerSettings CreateRelease()
    {
        return Create(Formatting.None);
    }

    public static JsonSerializerSettings CreateDebug()
    {
        return Create(Formatting.Indented);
    }

    private static JsonSerializerSettings Create(Formatting formatting)
    {
        return new JsonSerializerSettings
        {
            Formatting = formatting,
            ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
            ContractResolver = new MyContractResolver()
        };
    }
}

internal class MyContractResolver : DefaultContractResolver
{
    protected override List<MemberInfo> GetSerializableMembers(Type objectType)
    {
        var members = base.GetSerializableMembers(objectType).Cast<PropertyInfo>().ToList();
        members.RemoveAll(x => !x.CanRead || !x.CanWrite);
        return members.Cast<MemberInfo>().ToList();
    }
}

And finally:
var str = JsonConvert.SerializeObject(value, NewtonsoftDefaultSettings.CreateDebug());


text:
Q: Xpath: How to get text located outside of any html tag I have the following HTML:

       This is text I don't want to extract.

This is the text I'd like Xpath to extract

Using xpath, how can I extract "This is the text I'd like Xpath to extract"

A: In case the provided HTML is just a fragment and there is a single root element, the text can be selected by the following XPath expression:
//br/following-sibling::text()[1]


text:
Q: How to trim the enclosures (''some text") reading CSV file in PHP I am trying to use a web API to get some data. The problem is that I need to convert CSV data to JSON format.
<?php
    // allows us to skip the first row while looping through the file
     $i = 0;
    //web api
    $stocks = "https://www.google.com/finance/historical?output=csv&q=aapl";

    //read csv file
    $handle = fopen($stocks, 'r');
    //loop through CSV file
    while (($data = fgetcsv($handle, 2000, ",")) !== FALSE) {
        if ($i > 0) {
            trim($data[0]);
            trim($data[1]);
            trim($data[2]);
            trim($data[3]);
            trim($data[4]);
            trim($data[5]);

            // an array
            $chartArray[] = $data;
        }
        $i++;
    }

   fclose($handle);

   //Convert PHP Array to JSON String
   print (json_encode($chartArray));

?>

As you can see from the image, I am getting JSON with enclosure. ["19-May-17","153.38","153.98","152.63","153.06","26960788"].
Please let me know if there is a solution. Thank you in advance!

A: You will never ever put non-string values into a json. Never.
Otherwise. You can simply convert the number parts to number, and the date parts to php date.
Something like this:
while (($data = fgetcsv($handle, 2000, ",")) !== FALSE) {
    if ($i > 0) {

        $data[0] = date('Y-m-d', strtotime($data[0]));
        $data[1] = intval($data[1]);
        $data[2] = intval($data[2]);
        $data[3] = intval($data[3]);
        $data[4] = intval($data[4]);
        $data[5] = intval($data[5]);

        $chartArray[] = $data;
    }
    $i++;
}

But as soon as you convert it to a json, it will auto-place the " chars. So you will need to convert the strings at reciever (client?) side.

A: You misunderstand what JSON is. This is what your data looks like when it is in JSON format: It must be a series of values that are legal in the JSON subset of javascript syntax (string, int, array, etc.). There is no problem to solve. The function that consumes JSON will know what to do.


text:
Q: how to add cms static block to newsletter subscriber templates I would like to know how I can add static block to newsletter subscriber templates

A: You can add static block in any template using this code
echo $this->getLayout()->createBlock('cms/block')->setBlockId('my-new-block')->toHtml();

You first have to create static block
add your block id instead of my-new-block.

A: You can edit your newsletter subscribe template file and call static block with following code :
<?php echo $this->getLayout()->createBlock('cms/block')->setBlockId('block_identifier')->toHtml(); ?>

Newsletter file will be in following path :
{magento root path}/app/design/frontend/{your package}/{your theme}/template/newsletter


text:
Q: Performance gain for functional style in Dart Should I expect performance gains for using a purely functional style (without side effects) in Dart? Naively I'd expect the opposite, but I'm imagining there might be more opportunity for optimization.
To give an example, imagine a vector class that could be implemented like so:
class Vec {
  final num x, y, z;
  Vec(this.x, this.y, this.z);
  Vec add(Vec v) => new Vec(x + v.x, y + v.y, z + v.z);
}
final x = new Vec(1,2,3).add(new Vec(4,5,6));

vs an implementation like this:
class Vec {
  num x, y, z;
  Vec(this.x, this.y, this.z);
  Vec add(Vec v) { x += v.x; y += v.y; z += v.z; return this; }
}
var x = new Vec(1,2,3).add(new Vec(4,5,6));

which creates one less Vec object. (Obviously there could be an add(x,y,z) method to create still one fewer Vec but I'm imagining the added vectors as not being constant values in real life.)
In the Javascript VM, as I understand it, the extra object creation is relatively expensive and you'd rather not create new objects when you don't have to. If this were C++, I'd expect a lot of Vec objects would be on the stack and I'd expect any difference between these two to get optimized away.
I suppose the major optimizability gain of a pure functional style is parallelism, which probably doesn't apply to the Dart VM.

A: In Dart using an operator is just like calling a method. There is no performance overhead due to implicit operand conversion.
I believe the VM is pretty good an unboxing simple objects and keeping them on the stack, especially where all of the members are final. So for hot code there shouldn't be extra pressure on the garbage collector due to the extra object created.
But like Marcin says - best way to know for sure is to profile this.
Perhaps have a look at the Tracer benchmark source code (It's a simple raytracer). I'm pretty sure this uses operator overloading for it's 3D points and vectors. This will give you an idea about javascript vs Dart performance. You could even remove the + operator calls and replace them with an add() method to see if there is much difference. (This is probably more useful than trying to create a micro-benchmark).
Also - perhaps you should change the title of this question - this is not about pure functional programming. Although Dart has a bunch of functional style methods such as map() and fold() it doesn't support pure functional programming as it does not support proper tail calls, which means pure functional programs would cause stack overflows.

A: Alright, I went ahead and ran a quick test. Basically I just called added a billion vectors according to each implementation. The functional one took around three times as long. So it seems like, currently, at least, the object creation isn't optimized away.
void main() {
  const N = 1000000000;
  int i = 0;
  var v = new Vec(0,0,0);
  while (i < N * 3) {
    v = v.add(new Vec(i++, i++, i++));
  }
  print('$v');
}

I also tried an implementation with semantics like add(num,num,num), rather than add(new Vec(num,num,num)), eliminating another temporary object. That's even faster, but only marginally so; leading me to believe that the compiler does manage to partially optimize away that particular temporary object creation.


text:
Q: Strange java enum bug I have a really strange enum bug in Java.
for(Answer ans : assessmentResult.getAnswersAsList()) { //originally stored in a table
    //AnswerStatus stat = ans.getStatus();
    if (ans.getStatus() == AnswerStatus.NOT_ASSESSED) {
        assessed = false;
    }
}

An answer is an answer to a question on a test. An assessment result is the result a student gets on a test (this includes a collection of answers).
I've debugged the above code, and ans.getStatus() returns AnswerStatus.ASSESSED.
Still, the if line returns true, and assessed is set to false.
But, the thing I think is most strange; When I declare the AnswerStatus stat variable, it works, even if I don't use the stat variable in the if test. Could someone tell me what is going on?.
I've read something about enum bugs in serialization/RMI-IIOP but I don't use that here.
The enum AnswerStatus can be ASSESSED or NOT_ASSESSED.
The getStatus method in class Answer just returns the status, nothing else.

A:
I've debugged the above code, and
  ans.getStatus() returns
  AnswerStatus.ASSESSED. Still, the if
  line returns true, and assessed is set
  to false.
But, the thing I think is most
  strange; When I declare the
  AnswerStatus stat variable, it works,
  even if I don't use the stat variable
  in the if test. Could someone tell me
  what is going on?.

This sounds like the getStatus() method does not always return the same result - how is it implemented?
BTW, what's the point in having an enum with the values ASSESSED, and NOT_ASSESSED? Why not use a boolean isAssessed()?

A: Solved.
It was the NetBeans debugger that tricked me. It does not pass the if test (although NetBeans says that).
Sorry for the inconvenience :-)

A: What happens if you use .equals instead of ==?

A: No answer to your question but a suggestion:
It's always better to place the fix enum value in the first place in the compare statement and the variable part in the second place. Because, if in any circumstance the variable part delivers NULL you won't get a NullPointerException.
In your example it will look like this
...
if (AnswerStatus.NOT_ASSESSED == ans.getStatus())
...

MISTAKE:
Of course I make a mistake and mixed two things with each other. If you use the equals method to compare a fixed enum value with a variable containing this enum it's good to compare the constant enum value with the variable and not vic versa. For example:
write
if (AnswerStatus.NOT_ASSESSED.equals(ans.getStatus()))

instead of
if (ans.getStatus().equals(AnswerStatus.NOT_ASSESSED))

because, this could harm a NullPointerException if ans.getStatus() == null.


text:
Q: Will str(float(s)) == s Will str(float(s)) == s if s contains a valid floating point string? (Ignoring whitespace and other complications)
Background:
I have a text box where the user enters a floating point number. I store the number as a float, maybe writing it to a file and retrieving it later. If I write the value back to the text box, without changing it, I want it to be exactly as before.
I don't want floating point "precision" errors such as the classic 0.3 - 0.1 = 0.1999999.....  Does that only occur after doing a floating point operation, or can it happen to a float which was entered as a decimal string?
Edit:
I don't care about loss of precision e.g. str(float("1.99999999999999999999999999999999999999999")), or losing exponents eg str(float("1e3")), or formatting stuff like str(float("1"))=="1.0". I just want to check whether sensible values like str(float("0.1")) could ever come back as weird values which would confuse a user.

A: No.
Consider, for example, 1.2e10.
>>> str(float("1.2e10"))
'12000000000.0'

Or,
>>> str(float("1.20000000000000000000000"))
'1.2'

This is due to differences in the way python parses and prints floats. When parsing a float, it must understand a wide variety of values, such as scientific notation. However, the code for turning this float into a string has zero knowledge of how it was originally written to the python program; and will write out the number in it's own 'ideal' way.

I don't want floating point "precision" errors such as the classic 0.3 - 0.1 = 0.1999999..... Does that only occur after doing a floating point operation, or can it happen to a float which was entered as a decimal string?

Unless you're working on highly sensitive software, you won't need to worry about this. Floating-point (and especially 64-bit floating point) are very precise, and an inputted value (such as 1.2345678910111213) will always be 'close enough' unless you're working with more than fourteen digits (a lot).
TL;DR: Unless you can guarantee s came from str, you cannot guarantee that str(float(s)) will equal s. Nonetheless, you probably won't be needing to check such a thing anyways, as floating point numbers are almost always 'good enough'.


text:
Q: Android java.lang.OutOfMemoryError only on Samsung devices I have an app on Google Play that updated yesterday and I have started getting numerous reports from Crashlytics where my app crashes only on Samsung devices with Android 4.x (4.1.2 - 4.4.4).
The trace of the exception is as follows:
Fatal Exception: java.lang.RuntimeException: An error occured while executing doInBackground()
       at android.os.AsyncTask$3.done(AsyncTask.java:300)
       at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
       at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
       at java.util.concurrent.FutureTask.run(FutureTask.java:242)
       at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
       at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
       at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
       at java.lang.Thread.run(Thread.java:841)
Caused by java.lang.OutOfMemoryError
       at java.util.Arrays.copyOfRange(Arrays.java:2684)
       at com.android.org.conscrypt.OpenSSLCipher.engineDoFinal(OpenSSLCipher.java:467)
       at javax.crypto.Cipher.doFinal(Cipher.java:1204)
       at com.ijsoft.cpul.Util.DbMainFunctions.com.ijsoft.cpul.Util.AES256Cipher.decrypt(DbMainFunctions.java:2059)
       at com.ijsoft.cpul.Util.DbMainFunctions.initializeDb(DbMainFunctions.java:94)
       at com.ijsoft.cpul.SplashActivity$InitializeDb.doInBackground$9ecd34e(SplashActivity.java:2095)
       at android.os.AsyncTask$2.call(AsyncTask.java:288)
       at java.util.concurrent.FutureTask.run(FutureTask.java:237)
       at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
       at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
       at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
       at java.lang.Thread.run(Thread.java:841)

In other cases I received the following trace:
Fatal Exception: java.lang.RuntimeException: An error occured while executing doInBackground()
       at android.os.AsyncTask$3.done(AsyncTask.java:299)
       at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
       at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
       at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
       at java.util.concurrent.FutureTask.run(FutureTask.java:137)
       at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
       at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
       at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
       at java.lang.Thread.run(Thread.java:856)
Caused by java.lang.OutOfMemoryError
       at java.io.ByteArrayOutputStream.expand(ByteArrayOutputStream.java:91)
       at java.io.ByteArrayOutputStream.write(ByteArrayOutputStream.java:201)
       at com.ijsoft.cpul.Util.DbMainFunctions.initializeDb(DbMainFunctions.java:90)
       at com.ijsoft.cpul.SplashActivity$InitializeDb.doInBackground$9ecd34e(SplashActivity.java:2095)
       at android.os.AsyncTask$2.call(AsyncTask.java:287)
       at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
       at java.util.concurrent.FutureTask.run(FutureTask.java:137)
       at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
       at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
       at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
       at java.lang.Thread.run(Thread.java:856)

I leave part of the code where the error occurs:
AES256Cipher.java
public class AES256Cipher {
    public byte[] decrypt(byte[] textBytes, Context context)
            throws java.io.UnsupportedEncodingException,
            NoSuchAlgorithmException,
            NoSuchPaddingException,
            InvalidKeyException,
            InvalidAlgorithmParameterException,
            IllegalBlockSizeException,
            BadPaddingException {

        byte[] keyBytes = CommonFunctions.md5Package(context).getBytes();
        byte[] ivBytes = new byte[16];
        for (int j = 0; j < keyBytes.length; j+=2) {
            ivBytes[j/2]=keyBytes[31-j];
        }

        AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes);
        SecretKeySpec newKey = new SecretKeySpec(keyBytes, "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, newKey, ivSpec);
        return cipher.doFinal(textBytes);
    }
}

DbMainFunctions.java
public synchronized static int initializeDb(int release, Context context) {
        int resultCode = 0;
        try {
            // Get the encrypted json file (database) from Assets
            AssetManager am = context.getAssets();
            InputStream is = am.open("assets");
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buff = new byte[4096];
            int i;
            while ((i = is.read(buff, 0, buff.length)) > 0) {
                baos.write(buff, 0, i);
            }
            is.close();
            baos.close();
            resultCode = updateDb(baos.toByteArray(), release, context);
            //baos.close();
        } catch (Exception e) {
            Log.e("DbMainFunctions", e.getMessage());
            //e.printStackTrace();
            resultCode = -1;
        }
        return resultCode;
    }

public synchronized static int updateDb(byte[] cipherJson, int release, Context context) {
        int resultCode = 0;
        AES256Cipher aes256;
        try {
            aes256 = new AES256Cipher();
            cipherJson = aes256.decrypt(cipherJson, context);
        } catch (UnsupportedEncodingException | NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException |
                InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException e) {
            Log.e("DbMainFuctions", e.getMessage());
            return -2;
        }

     ...
}

My application does at that point is to get an encrypted file (filename: assets) with AES256 from the Assets directory included in the APK. The file is then decrypted and saved in a Byte Array. The file is approximately 4.4 MB in size. The initializeDb() method is called from an AsyncTask during doInBackground(), that is, all the previous code is executed in an AsyncTask

A: This is highly likely to give you an OutOfMemoryError, particularly prior to Android 5.0, as you do not necessarily have a 4.4MB contiguous block of free memory.
I would get rid of the encryption, since it offers no security (anyone can decrypt your file) and it wastes CPU, battery, and memory.
At minimum, stop trying to read the entire contents into memory, and decrypt the data in a streaming fashion (e.g., 16KB at a time), streaming the decrypted data to an output file (since you do not have enough memory to hold that either, most likely).


text:
Q: Laravel login not working in edge and internet explorer Login with Laravel 5 is not working with Edge and Internet Explorer, while working perfectly fine in other browsers.
We suspect it has something to do with the sessions not being properly stored but to be honest we have no idea what causes this problem.
When we login in with proper details, the login logic is fired and completed properly, but after that its just redirected back to the login page, so is likely that the middleware thinks that the user is not logged in and returns them to the login page, that is why we think is has something to do with the sessions.
This is our login script:
    $rules = array('email' => 'required|email|min:3|max:60',
                   'password' => 'required|min:6|max:20');

    $attributeNames = array(
       'email' => strtolower(Lang::get('auth.email')),
       'password' => strtolower(Lang::get('auth.password')),
    );

    $validator = Validator::make(Input::all(), $rules);
    $validator->setAttributeNames($attributeNames);

    if ($validator->fails()){ return Redirect::back()->withErrors($validator); die(); }

    //Make an login attempt
    $auth = Auth::attempt(array(
        'email' => Input::get('email'),
        'password' => Input::get('password'),
        'role' => 'admin'
    ), false);

    if(!$auth){

        $auth2 = Auth::attempt(array(
            'email' => Input::get('email'),
            'password' => Input::get('password'),
            'role' => 'user'
        ), false);

        if(!$auth2){

            return Redirect::back()->withErrors(Lang::get('auth.errorText'))->withInput(Input::all());
            die();
        }

    }

    //If user is not activated
    if(Auth::User()->activated != 'OK'){

        Auth::logout();
        return Redirect::back()->withErrors(Lang::get('auth.notActivated'));
        die();
    }

    if(Auth::User()->sms_verificatie == '1') {

        $user = Auth::User();
        $user->sms_ok = 0;
        $user->save();

        $sms_codes_verwijderen = UsersSMSLogin::where('id_cms_users','=',Auth::User()->id)->delete();

        return Redirect::route('sms-verificatie');
        die();

    }

    Session::forget('dashboard_werkgever');

    return Redirect::route('dashboard');

A: Changing the cookie name to remove the _ (underscore) worked for me.
In app/config/session.php changed
'cookie' => 'laravel_session'
to
'cookie' => 'laravelsession'

A: The problem seems to be related to Google Analytics, we removed the Analytics script in Edge and internet exploder, and now everything seems to work fine...

A: Just in case it helps anyone, I've recently had a very similar issue. It turns out I had two web applications on the same domain sharing the same session cookie name and while some browsers were sending the right cookie (by sheer luck I suppose), IE wasn't.
Lesson from this? Always change the default laravel_session cookie name :)
This post proved useful...
How to handle multiple cookies with the same name?


text:
Q: Issue with updating a JFrame dynamically I am using NetNeans
I have a JPanel that is supposed to show some already input data along with a progress bar while the remainder of the program carries out some lengthy processing (about 1 minute long). Once the processing is done, this same JPanel is supposed to be updated with a few JTextFields containing the processed data.
The issue:
The JPanel shows up completely blank throughout the time period the processing is going on. Once the processing is done, then all the data shows up. Its baffling me. Here is how i've programmed it:
    /*The parent class which calls the output JPanel
     *Lister is the output JPanel. The constructor calls initComponents(), and fills
     *text fields that contain the data that has already been input.
     *fillresult then triggers the processing function that takes a while. Once the
     *processing function is done, fillresult fills the processed data into the
     *respective Text Fields
     */
    ListWords = new Lister();
    System.out.println("l");
    ListWords.setVisible(true);
    ListWords.fillResult();

   //Lister constructor:
   Lister(){
         initComponents();
       MatchWords = new Matcher();//Matcher() only contains the initialization of a List

         jTextField1.setText(Scrabbulous.scrab.EntryWind.getCombo().substring(0, 1));
         jTextField2.setText(Scrabbulous.scrab.EntryWind.getCombo().substring(1, 2));
         jTextField3.setText(Scrabbulous.scrab.EntryWind.getCombo().substring(2, 3));
         jTextField4.setText(Scrabbulous.scrab.EntryWind.getCombo().substring(3, 4));
         jTextField5.setText(Scrabbulous.scrab.EntryWind.getCombo().substring(4, 5));
         jTextField6.setText(Scrabbulous.scrab.EntryWind.getCombo().substring(5, 6));
         jTextField7.setText(Scrabbulous.scrab.EntryWind.getCombo().substring(6));
   }

   //fillresult():
 public void fillResult(){
    int rIndex = 0;
    MatchWords.makeWords(rIndex);
    while(MatchWords.realWords.Head == null && rIndex < 2){
        rIndex++;
        updateStatusBar();
        MatchWords.makeWords(rIndex);
    }
    Wordpoints = new String[MatchWords.realWords.getSize()];
    for(int i=0; i<Wordpoints.length; i++){
        Wordpoints[i] = "";
    }

    for(int i=0; i<MatchWords.realWords.getSize(); i++){
        int total = 0;
        for(int j=0; j<MatchWords.realWords.getNode(i).getWord().length(); j++){
            for(int k=0; k<Scrabbulous.scrab.scralphabet.length; k++){
                if(MatchWords.realWords.getNode(i).getWord().charAt(j) == Scrabbulous.scrab.scralphabet[k].getLetter()){
                    total += Scrabbulous.scrab.scralphabet[k].getValue();
                    Wordpoints[i] = ""+total;
                }
            }
        }
    }

    try{
        jTextField8.setText(MatchWords.realWords.Head.getWord());
        jTextField13.setText(Wordpoints[0]);
    }catch(NullPointerException e){
        jTextField8.setText("No Match Found");
        jTextField13.setText("-");
    }
    try{
        jTextField9.setText(MatchWords.realWords.getNode(1).getWord());
        jTextField14.setText(Wordpoints[1]);
    }catch(NullPointerException e){
        jTextField9.setText("No Match Found");
        jTextField14.setText("-");
    }
    try{
        jTextField10.setText(MatchWords.realWords.getNode(2).getWord());
        jTextField15.setText(Wordpoints[2]);
    }catch(NullPointerException e){
        jTextField10.setText("No Match Found");
        jTextField15.setText("-");
    }
    try{
        jTextField11.setText(MatchWords.realWords.getNode(3).getWord());
        jTextField16.setText(Wordpoints[3]);
    }catch(NullPointerException e){
        jTextField11.setText("No Match Found");
        jTextField16.setText("-");
    }
    try{
        jTextField12.setText(MatchWords.realWords.getNode(4).getWord());
        jTextField17.setText(Wordpoints[4]);
    }catch(NullPointerException e){
        jTextField12.setText("No Match Found");
        jTextField17.setText("-");
    }

Could someone please be of assistance? Oh yes, and I read about adding a .refactor() and/or repaint(), but atleast the jForms initialized in the constructor should show up? :/
Also, it might be worth mentioning that all the code that is currently in the fillresult() function was initially in the constructor, and the output was displaying. However, since I want the progressbar here, I've shifted it to a new function. help please?

A:
"The issue: The JPanel shows up completely blank throughout the time period the processing is going on. Once the processing is done, then all the data shows up."

What's happening is that everything is occurring on one thread, the Event Dispatch Thread (EDT). In order for an event to occur, like your JPanel updating, the process before it needs to complete.
As stated about the EDT:

" Tasks on the event dispatch thread must finish quickly; if they don't, unhandled events back up and the user interface becomes unresponsive."

To work around this, you'll want to run your long process in a background thread. You should have look at Concurrency in Swing - the section on Worker Threads and SwingWorker in particular.


text:
Q: WCF Requests Hanging Infinitely in IIS until Recycled We have been dealing with a troublesome issue with WCF for quite some time, and it has gotten to a point that we are desperate to find a fix.
I have a WCF Service that is hit frequently, approximately 50 requests /second sometimes. Average execution times are 10-20 seconds, but may go up to 45 seconds.
The problem we are having is randomly (we have not been able to recreate for 2 months since it started), when viewing the IIS requests in the worker process, they will just continue to add up and will not complete, and will infinitely increase in time until we have to recycle the app pool.
We have done performance metrics on the DB, and on the code using CPU and memory analyzers and have confirmed that there are no bottle necks in our code that stand out.
I have service throttlign config values set to the following:
<serviceThrottling maxConcurrentInstances="800"
                         maxConcurrentCalls="800"
                         maxConcurrentSessions="800"/>

I am enabling WCF Tracing right now to see if anything turns up, but its hard because we are unable to recreate.


text:
Q: Is integrability metric-dependent? Does integrability of real functions depend on the metric chosen? Although the Riemann integrability depends on limits, the Darboux integrability depends on the order defined (a function is Darboux integrable if the infimum of all the upper sums is equal to the supremum of all lower sums), since it uses the notion of supremum and infimum. So my question is - if I change the metric defined on the reals, will all standard integrable function will remain integrable with the same values?
EDIT:
Suppose that we change the metric of both the domain and the range. Also, I am asking generally if Riemann integrable can become non-integrable and vice versa. I am talking about finite-interval integrability. Also, a general metric change with no special care about the topology.

A: First of all, let me spell out what I mean by Riemann integral with respect to the metrics $d$ on the range and $\rho$ on the domain of a function, restricting to bounded functions $f$ defined on closed intervals.
Let $P=(x_0<...<x_n)$ denote a partition of $[a,b]$ of mesh $m_\rho(P)$ (defined via the metric $\rho$). For this partition and a choice of sample points $t_i\in [x_{i-1}, x_{i}], t=(t_1,...,t_n)$, define the partial sum
$$
S(f, P, t):= \sum_{i} d(f(t_i), 0) sign(f(t_i)) \rho(x_i, x_{i+1}).
$$
Here $sign(y)= y/|y|$ if $y\ne 0$ and $sign(y)=0$ if $y=0$. Thus, this sum is the sum of "signed areas" of rectangles where the area is defined via the product metric on ${\mathbb R}^2$ defined via the metrics $\rho$ and $d$. Unlike what Alex M. is proposing, this definition is consistent with the more general notions of integration on metric / measure spaces. Riemann himself did not intend to define his integral beyond the realm of Euclidean spaces.
Then the Riemann integral
$$
\int_{d,\rho, [a,b]} f(x)dx
$$
is defined as the limit (if it exists)
$$
\lim_{m_\rho(P)\to 0} S(f, P, t).
$$
Now, consider some examples: Take the constant function $f(x)=1$ on $[0,1]$. Then $\int_0^1 f(x)dx=1$. But if you change the metric on $[0,1]$ by multiplying it by $a>0$ then the integral of the same function becomes $a$. Hence, even in the simplest case, you cannot  hope to retain the values of integrals. Next, let me restrict to bounded functions on closed intervals. Then a function $f$ on $[a,b]$ is Riemann-integrable if and only if it is continuous almost everywhere in $[a,b]$ in the Lebesgue sense. Now, if $h: [a,b]\to [a,b]$ is a homeomorphism (a continuous monotonic function) which carries a Cantor set $C$ of zero Lebesgue measure to a Cantor set of positive Lebesgue measure then $\chi_C$ is Riemann-integrable but not $\chi_C \circ h^{-1}$. Hence, by changing the metric  on $[a,b]$ via the function $h$:
$$
\rho(x,y):= |h^{-1}(x)- h^{-1}(y)|,
$$
does not preserve Riemann-integrability.
If you change the metric on the range while preserving the topology on the range then the notion of continuity does not change, hence, Riemann-integrability is preserved. But changing the metric on the target to, say, the discrete metric, makes every nonconstant continuous function on $[0,1]$ a discontinuous function. Therefore, say, the function $f(x)=x$ becomes discontinuous everywhere and hence, non-integrable.
The bottom line is that you want to retain the topology on the range and make an absolutely continuous change of topology on the domain. Then Riemann integrability is retained (for bounded functions).


text:
Q: How to filter object within an array that matches search object in Javascript I am trying to filter and remove objects that are inside of my array however more objects are getting removed than I am hoping to target
const people = [
  {name: 'Adam', age: 30, country: 'USA'},
  {name: 'Carl', age: 30, country: 'UK'},
  {name: 'Bob', age: 40, country: 'China'},
 ];

const results = people.filter(element => {
  //  using AND (&&) operator
  return element.age !== 30 && element.name !== 'Carl';
});

console.log(results);

outputs:
[ { name: 'Bob', age: 40, country: 'China' } ]

I am hoping to only remove the object where Carl is found
My desired output would be
[ { name: 'Adam', age: 30, country: 'USA' }, { name: 'Bob', age: 40, country: 'China' } ]

A: You need to update the filter condition if you need to remove only 30yo Carls
return !(element.age === 30 && element.name === 'Carl');

which is equal to
return element.age !== 30 || element.name !== 'Carl';


text:
Q: matrix&eigenvalues Let $A \in M_n(C)$ and $A^{-1}=A^*$. Prove that the eigenvalues of A have the modul equal with one.
P.S. I know that this is a property well-known, but I couldn't find a demonstration for it.

A: If $v$ is an eigenvector of $A$, then
$$
\|Av\|^2 = (Av)^*(Av) = (\lambda v)^*(\lambda v) = |\lambda|^2 \|v\|^2
$$
However, in this case we can also write
$$
\|Av\|^2 = v^*A^*Av = v^*v = \|v\|^2
$$

A: Let $\lambda$ be an eigenvalue of $A$. Then $\lambda\neq0$ because $A$ is invertible. Let $v$ be an eigenvector with eigenvalue $\lambda$. Then $A.v=\lambda v$. Therefore$$A^{-1}.v=A^{-1}.\left(\frac1\lambda.\lambda.v\right)=\frac1\lambda.(A^{-1}.(\lambda v))=\frac1\lambda v.$$But $A^{-1}=A^*$ and $A^*.v=\overline\lambda.v$. Therefore…

A: The eigenvalues of $A^{-1}$ and $A^*$ are $1\over\lambda$ and $\lambda^*$ respectively. So we can write: ${1\over\lambda}=\lambda^*$ or $\lambda=e^{i\theta}$


text:
Q: Proving Fermat's Little Theorem by Induction A common form of Fermat's Little Theorem is: $a^{p}=a$ (mod $p$), for any prime $p$ and integer $a$. Prove this by induction on $a$.
I tried to prove that $(a+b)^p= a^p+b^p$ (modulo $p$) since it's a more general statement, but couldn't get further.

A: $(a+1)^P=a^p+ \binom{p}{1} a^{p-1} +\binom{p}{2}a^{p-2}+.....+ \binom{p}{p-1}a+1.$
Note that $p$ divides into any binomial coefficient of the form $\binom{p}{k}$
 for $1 \le k\le p-1$
This follows by the definition of the binomial coefficient as $\binom{p}{k}= \left(\frac{p!}{k!(p-k)!}\right)$; since $p$ is prime, then $p$ divides the numerator but not denominator.
Taken mod $p$, all of the middle terms disappear, and we end up with
$(a+1)^p\equiv a^p +1$ (mod $p$). Since we also know that $a^p\equiv a$ (mod $p$)
$(a+1)^p\equiv a +1$ (mod $p$). As we needed


text:
Q: Is it useful to apply mathematical transformations in a NIR spectra before applying LS-SVM? I am trying to make predictions for vegetable quality indices with Near Infrared Spectroscopy. I noticed that many machine learning tools are commonly used this purpose. Conventionally, certain transformations like MSC (Multiplicative Scatter Correction), SNV (Standard Normal Variate), and derivatives are used to separate out the more valuable diffuse reflection from the spectra which helps to improve the models. Those methods seemed intuitive for multiple linear regression but I don't understand whether they still hold useful for LS-SVM. In my study they seem to improve the model but I am not sure if it is a good idea to apply preprocessing methods. Besides, I read here that log and square transformation in the spectra is accounted in the algorithm.

A: Yes, it is useful to apply these transformation. All these transformation that you mentioned are actually mathematical treatments for noise removal. The SNV removes baseline effect and the first-derivative removes scattering effect. In my experience, first derivative gives better results in most of the cases. You are better off applying these transformations.
Let me know if you are looking for some other specific information.


text:
Q: 2D List Plot in a 3D box: What am I doing wrong? Let me just show the result first, and you'll see the error easily:

Now, this is just a 2D image sent into a 3D box, so you'd think they looked alike. But the 2D image behaves well:

The code was picked from an answer to a different question, here. I simplified it, and modified it to put in a list plot, so the final code looks like this:
p1 := Plot[{CDF[BinomialDistribution[5, 0.3], t], 0}, {t, 1, 4}, Filling -> {2 -> {{1}, {RGBColor[0.3, 1, 0.3, 0.6]}}}]
p2 := ListPlot[ Table[PDF[BinomialDistribution[5, 0.3], t], {t, 0, 10}], Filling -> Bottom, FillingStyle -> Directive[Thickness[0.01], Blue], PlotStyle -> Directive[PointSize[0.02], Blue]]

p2

Graphics3D[
 {
  p1[[1]] /. {x_?NumericQ, y_?NumericQ} :> {1, x, y},
  p2[[1]] /. {x_?NumericQ, y_?NumericQ} :> {2, x, y}
  }
 , Axes -> {True, False, True}, Boxed -> {Right, Bottom, Back}, BoxRatios -> {1, 1, 0.5}, FaceGrids -> {{0, 0, -1}, {0, 1, 0}, {1, 0, 0}}, FaceGridsStyle -> Directive[GrayLevel[0.3, 1], AbsoluteDashing[{1, 2}]], ViewPoint -> {-2, -2.5, 1}, AxesLabel -> {"Nothing, really", "", Rotate[Row[{Spacer[50], "Distribution"}], 90 Degree]}, LabelStyle -> Directive[Black, Bold, 14], ImageSize -> 500]

Can anyone see what causes the error? Is it my code, or does Mathematica have a funny bug here?

A: I sometimes find it easier to reconstruct the plots from Graphics primitives, rather than messing with the internal structure of the Plot output.
Here is an idea:
discretes = Table[{t, 0, PDF[BinomialDistribution[5, 0.3], t]}, {t, 0, 10}];

Graphics3D[
 {
  (* PDF stems and points *)
  Blue, Thickness[0.01], PointSize[0.02], Point[discretes],
  Line[{{#1, #2, #3}, {#1, #2, 0}}] & @@@ discretes,

  (* CDF *)
  Cases[
   DiscretePlot[
    CDF[BinomialDistribution[5, 0.3], t], {t, 0, 10},
    ExtentSize -> Full, FillingStyle -> RGBColor[0.3, 1, 0.3, 0.6],
    PlotRange -> {0, Automatic}
   ],
   {directives__, Rectangle[{x0_, y0_}, {x1_, y1_}]} ->
    {Opacity[0.5, RGBColor[0.3, 1, 0.3, 0.6]],
     EdgeForm[RGBColor[0.3, 1, 0.3, 0.6]], directives,
     Cuboid[{x0, 1, y0}, {x1, 1, y1}]},
   Infinity
  ]
 },
 PlotRange -> {Automatic, {-3, 4}, Automatic},

 (* the directives below are from your original plot *)
 Axes -> {True, False, True}, Boxed -> {Right, Bottom, Back},
 BoxRatios -> {1, 1, 0.5},
 FaceGrids -> {{0, 0, -1}, {0, 1, 0}, {1, 0, 0}},
 FaceGridsStyle ->
  Directive[GrayLevel[0.3, 1], AbsoluteDashing[{1, 2}]],
 ViewPoint -> {-2, -2.5, 1},
 AxesLabel -> {"", "", Rotate[Row[{Spacer[50], "Distribution"}], 90 Degree]},
 LabelStyle -> Directive[Black, Bold, 14], ImageSize -> 500
]

A: p2[[1]] contains a GraphicsComplex expression, and your replacement is affecting the integer coordinate indices as well as the coordinates themselves. So something like Line[{14, 3}] becomes Line[{2, 14, 3}] which is why you see the spurious extra line segments all sprouting from point number 2.
A solution is simply to wrap p2[[1]] in Normal:
Graphics3D[{
  Normal[p2[[1]]] /. {x_?NumericQ, y_?NumericQ} :> {2, x, y}},
 BoxRatios -> {.1, 1, 1}]


text:
Q: Which way do electrons transfer? When an object is rubbed against another object, it transfers electrons, that much I know.
But what determines the way it's going?
Against the object that's being rubbed against, or the object that's rubbing?
I tried searching on the internet for a while, but nothing popped up.


text:
Q: How do you choose the last string in a String value? There are two tables:
Student(sid integer, sname varchar(20), programme varchar(4), level integer, age integer)
Tutor(tid integer, tname varchar(20))

The task is to find the names of all IT students who are enrolled in a class taught by a tutor whose surname is Hoffman.
This is what I have so far:
SELECT s.sname
FROM student s, tutor t
WHERE s.programme = 'IT' AND t.tname = '%Hoffman';

However, the '%Hoffman' part will only search for a string which contains 'Hoffman', so technically if if there would be anyone with Hoffman as the first name, the query will return his data too.
The tname column is of type String and consist of a first name, a space, and a last name, and possible middle names in between.
How do you choose the last string (or index?) of a value in t.tname in this case?

A: You could use something like this:
WHERE s.programme = 'IT' and RIGHT(t.tname, 7)
since 'Hoffman' has 7 characters


text:
Q: How to download a file from a protected web folder in Android App? I'm looking for some help on how to download an image file from a password protected folder to my Android App.  The code I have is using URLConnection along with getInputStream/BufferedInputStream but I don't see how to get the username/password authentication in there.  I see that HttpClient has UsernamePasswordCredentials  -- but I don't know how to download a file using HttpClient so that isn't helping me much.
Here's the code I found so far, how would I download a file using this?
public class ClientAuthentication {

    public static void main(String[] args) throws Exception {
        DefaultHttpClient httpclient = new DefaultHttpClient();
        try {
            httpclient.getCredentialsProvider().setCredentials(
                    new AuthScope("localhost", 443),
                    new UsernamePasswordCredentials("username", "password"));

            HttpGet httpget = new HttpGet("https://localhost/protected");

            System.out.println("executing request" + httpget.getRequestLine());
            HttpResponse response = httpclient.execute(httpget);
            HttpEntity entity = response.getEntity();

            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            if (entity != null) {
                System.out.println("Response content length: " + entity.getContentLength());
            }
            EntityUtils.consume(entity);
        } finally {
            // When HttpClient instance is no longer needed,
            // shut down the connection manager to ensure
            // immediate deallocation of all system resources
            httpclient.getConnectionManager().shutdown();
        }
    }
}

Or, I have this code for downloading file -- how would I add credentials to this:
http://www.helloandroid.com/tutorials/how-download-fileimage-url-your-device
Thanks!
EDIT: well, not getting much help here.  I found this answer which I'm going to try and rework for my purposes: Download a file with DefaultHTTPClient and preemptive authentication

A: Well, this is the code I've come up with, seems to work.  I'm posting it since I had so much trouble finding code like this anywhere on the web.  I welcome suggestions on how to improve it :)
public void downloadHTTPC(Activity act, String imageURL, String fileName) {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {
        String pathDir = act.getExternalFilesDir(null).toString() + "/" + fileName;
        File file = new File(pathDir);
        long startTime = System.currentTimeMillis();
        httpclient.getCredentialsProvider().setCredentials(
                new AuthScope(null, -1),
                new UsernamePasswordCredentials("user", "password"));

        HttpGet httpget = new HttpGet(IMGURL + imageURL);

        System.out.println("executing request" + httpget.getRequestLine());
        HttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();

        System.out.println("----------------------------------------");
        System.out.println(response.getStatusLine());

        if (entity != null) {
            System.out.println("Response content length: " + entity.getContentLength());
            InputStream is = entity.getContent();

            BufferedInputStream bis = new BufferedInputStream(is);

            /*
             * Read bytes to the Buffer until there is nothing more to read(-1).
             */
            ByteArrayBuffer baf = new ByteArrayBuffer(50);
            int current = 0;
            while ((current = bis.read()) != -1) {
                baf.append((byte) current);
            }

            /* Convert the Bytes read to a Stream. */
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(baf.toByteArray());
            fos.close();
            Log.d("ImageManager", "download ready in"
                    + ((System.currentTimeMillis() - startTime) / 1000)
                    + " sec");
        }

        //EntityUtils.consume(entity);
    } catch (IOException e) {
        Log.d("ImageManager", "Error: " + e);

    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }
}


text:
Q: setting orientation and aspect ratio in android multiple screen support I found that there are 4 aspects to change the android application for multiple screen support.
1.screen size
2. screen density
3.orientation(portrait/landscape)
4.aspect ratio(long/not long)
I have clear idea about screen size,density and orientation. But I don't know how to identify aspect ratio. Is it necessary to explicitly create folder for orientation and aspect ratio?. Please guide me.
Thanks in advance.

A: Refer to this question
Multiple screen resolutions/aspect ratios (games)
And also from doc read this thing

The orientation of the screen from the user's point of view. This is
  either landscape or portrait, meaning that the screen's aspect ratio
  is either wide or tall, respectively.
Be aware that not only do
  different devices operate in different orientations by default, but
  the orientation can change at runtime when the user rotates the
  device.

Resources for screens in the landscape orientation (wide aspect ratio).
Resources for screens in the portrait orientation (tall aspect ratio).


text:
Q: IE7 and dojo onchange of radio buttons fires too late? I have a page which has a form and say 3 input radio-buttons and I want to run some code when any of them are changed, so my code looks like this
dojo.query("#ze_form > input:radio").onchange(function () {
    alert("onchange fired!");
}

this works fine in normal web browsers, but in IE7 the alert is displayed only after clicking on a radio button, then clicking outside somewhere! It fires when it looses focus it appears!
Notice: in the console and previously doing alerts and stuff, I can see that my query selector does in fact select the correct radio buttons.
What is this strange phenomenon?

A: IE7 doesn't fire the onChange event until the radio button loses focus.  Your alternative is to connect to the onClick event.


text:
Q: Error in quantile.default(x$residuals) :missing values and NaN's not allowed if 'na.rm' is FALSE -R I am receiving this error when running a zero-inflated negative binomial:
Error in quantile.default(x$residuals) : missing values and NaN's not allowed if 'na.rm' is FALSE
I read other posts where this occurred; some suggested it might be because of NAs in the data, others suggested that the variable in question was not a numeric variable.
I confirmed that the variable avgcontractvalue has no NA's and is numeric. This is what a sample of it looks like:
avgcontractvalue=c(0, 0.01, 0.015, 0.02, 0.025, 0.03, 0.0333333333333333, 0.035, 0.036, 0.0366666666666667, 0.038, 0.04)
I wanted to create sample data to replicate the error, but haven't been able to replicate the error with sample data.
Here is the command I am using:
fit.zinb<-zeroinfl(y~log10(1+bc)*iscovid+avgcontractvalue|1,dist="negbin",link="logit",offset=log(offset),
                          data=df)

Could the issue be perfect separation? No other variables give this error when included in the model. But I'm not sure how to test that the issue might be perfect separation. Any ideas are much appreciated. Apologies for not being able to provide sample data.
str(df) yields:

grouped_df[,6] [2,097,277 x 6] (S3: grouped_df/tbl_df/tbl/data.frame)
 $ tendereren      : chr [1:2097277] "<U+041C><U+041E><U+0417> <U+0423><U+043A><U+0440><U+0430><U+0457><U+043D><U+0438> | 00012925" "<U+041C><U+041E><U+0417> <U+0423><U+043A><U+0440><U+0430><U+0457><U+043D><U+0438> | 00012925" "<U+041A><U+041E><U+041D><U+0421><U+0422><U+0418><U+0422><U+0423><U+0426><U+0406><U+0419><U+041D><U+0418><U+0419"| __truncated__ "<U+0420><U+0410><U+0425><U+0423><U+041D><U+041A><U+041E><U+0412><U+0410> <U+041F><U+0410><U+041B><U+0410><U+042"| __truncated__ ...
 $ bc              : num [1:2097277] 1508804 1508804 1464341 1011615 3110461 ...
 $ iscovid_month   : num [1:2097277] 1 1 1 1 0 1 1 1 1 1 ...
 $ avgcontractvalue: num [1:2097277] 334.22 324.38 0.03 4710.63 256.11 ...
 $ y     : num [1:2097277] 0 0 0 0 0 0 0 0 0 0 ...
 $ offset   : int [1:2097277] 1 2 1 1 1 1 1 1 1 1 ...
 - attr(*, "groups")= tibble[,2] [354,112 x 2] (S3: tbl_df/tbl/data.frame)
  ..$ tendereren: chr [1:354112] "' Elena Mikhailovna | 2349816526" "'kyi municipal enterprise \"BERAPROST\" | 31273334" "'menets'kyi REM | 130760" "'Phase-N' | 40161563" ...
  ..$ .rows     : list<int> [1:354112]
  .. ..$ : int 492652
  .. ..$ : int [1:7] 541217 639048 651626 938829 1185960 1628479 1679886
  .. ..$ : int [1:3] 256340 658815 679255
  .. ..$ : int [1:9] 265208 289648 339159 417554 649852 1180562 1611103 1878222 1980464
  .. ..$ : int 462567
  .. ..$ : int [1:3] 463915 467303 541675
  .. ..$ : int [1:29] 233664 297616 336391 370997 466842 499574 530920 641250 741655 785447 ...
  .. ..$ : int [1:4] 625705 1814029 1873246 2089453
  .. ..$ : int 972790
  .. ..$ : int [1:2] 1686500 1844516
  .. ..$ : int [1:7] 292888 635219 761081 945664 1011539 1701894 1744966
  .. ..$ : int [1:2] 524536 577889
  .. ..$ : int [1:9] 742395 788185 888699 1135612 1265377 1383289 1804695 1881300 2050082
  .. ..$ : int [1:2] 891246 987278
  .. ..$ : int [1:7] 386067 759192 825774 988015 1362075 1389220 1895858
  .. ..$ : int 937678
  .. ..$ : int 544483
  .. ..$ : int [1:2] 932144 1375352
  .. ..$ : int 926588
  .. ..$ : int [1:28] 224624 333342 382296 501539 536447 556983 799902 832753 853716 892521 ...
  .. ..$ : int 775963
  .. ..$ : int [1:2] 1126090 1157531
  .. ..$ : int 997924
  .. ..$ : int 934959
  .. ..$ : int [1:4] 912765 970666 1861143 1977875
  .. ..$ : int [1:7] 300433 412062 745511 1620143 1895861 1954472 2080261
  .. ..$ : int 744439
  .. ..$ : int [1:24] 288457 344392 405003 482949 740512 787971 822717 831155 976478 1210026 ...
  .. ..$ : int [1:16] 210023 358825 389807 538839 771104 828757 993872 1218611 1222058 1304384 ...
  .. ..$ : int [1:3] 279805 331496 1701169
  .. ..$ : int [1:12] 218928 277545 408455 770974 800538 974122 1388265 1398658 1823772 1883440 ...
  .. ..$ : int 958735
  .. ..$ : int [1:6] 740403 836297 918292 1262856 1263329 1385681
  .. ..$ : int 1001355
  .. ..$ : int [1:3] 752477 778214 1094179
  .. ..$ : int [1:3] 988025 1507189 2017487
  .. ..$ : int [1:2] 1282416 1961778
  .. ..$ : int 1346301
  .. ..$ : int [1:4] 1226928 1753208 2018328 2089892
  .. ..$ : int 1525208
  .. ..$ : int [1:11] 826653 1180482 1192868 1201883 1211342 1217351 1217661 1221824 1475010 1499849 ...
  .. ..$ : int [1:12] 244847 281370 405932 748532 1619008 1690741 1734935 1769544 1857874 1915638 ...
  .. ..$ : int 901251
  .. ..$ : int [1:8] 507746 776781 828212 1267231 1275363 1280279 1297113 1910354
  .. ..$ : int [1:6] 579416 590198 609925 616994 644882 661202
  .. ..$ : int 1939687
  .. ..$ : int 1842098
  .. ..$ : int 1917404
  .. ..$ : int 1837756
  .. ..$ : int 1889649
  .. ..$ : int 298180
  .. ..$ : int 1317058
  .. ..$ : int 302138
  .. ..$ : int 1495113
  .. ..$ : int 2089454
  .. ..$ : int 389229
  .. ..$ : int 1869762
  .. ..$ : int 312236
  .. ..$ : int 2094540
  .. ..$ : int 1856886
  .. ..$ : int [1:2] 299692 390017
  .. ..$ : int 1779820
  .. ..$ : int 1610124
  .. ..$ : int 1943638
  .. ..$ : int 1797556
  .. ..$ : int 298178
  .. ..$ : int 301403
  .. ..$ : int 1975049
  .. ..$ : int 1919491
  .. ..$ : int [1:2] 256104 2088455
  .. ..$ : int 230740
  .. ..$ : int 255871
  .. ..$ : int [1:2] 250898 300869
  .. ..$ : int 419992
  .. ..$ : int 427909
  .. ..$ : int 428759
  .. ..$ : int 410116
  .. ..$ : int 1656987
  .. ..$ : int 301266
  .. ..$ : int 1665254
  .. ..$ : int 864668
  .. ..$ : int 527916
  .. ..$ : int [1:21] 32498 32499 194559 497299 507773 581148 610145 688240 707126 774309 ...
  .. ..$ : int 546047
  .. ..$ : int [1:12] 32500 1025155 1037153 1060193 1064161 1068560 1229433 1438222 1453252 1454780 ...
  .. ..$ : int [1:2] 1109930 1200560
  .. ..$ : int [1:11] 32501 32502 32503 32504 432717 435909 690565 694298 723476 772270 ...
  .. ..$ : int 1386396
  .. ..$ : int [1:6] 32505 32506 699138 704411 711937 758688
  .. ..$ : int [1:7] 358277 391510 1111715 1135284 1331873 1520200 1588250
  .. ..$ : int [1:10] 192583 207459 237364 437979 444860 504226 759684 974135 1175305 1417777
  .. ..$ : int [1:7] 260859 333979 391394 1238986 1597551 1854801 1884383
  .. ..$ : int [1:2] 1084803 1639862
  .. ..$ : int 1156839
  .. ..$ : int [1:2] 1161397 1259682
  .. ..$ : int 1382213
  .. ..$ : int [1:5] 32507 196818 1090314 1100185 1119835
  .. ..$ : int [1:7] 32508 1022205 1025244 1167778 1242423 1417892 1946858
  .. ..$ : int 1858251
  .. .. [list output truncated]
  .. ..@ ptype: int(0)
  ..- attr(*, ".drop")= logi TRUE

(tendereren is the id variable)


text:
Q: How to export MySQL workbench database for Java application runs in other computers? I developed a Java application connecting to MySQL database through a localhost connection.
Class.forName("com.mysql.jdbc.Driver");
        Connection conexao = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/bd_sensores", "root", "rootadmin");

I want to run the application on other computers. To do that I need to export the database, and the information already recorded. I think I need to create an installer and install it on other computers, but I need to change local and type of database.

A: You could have a properties file that has the following properties:

*

*driver class name

*Database Host

*Database Port

as well as username.
Read the db configurations from this properties file and then load the driver and prepare your jdbc url.
Also, you can export your database through mysql workbench to a .sql file that will create a db script to run on another database. Use 'Manage Export / Import' functionality of workbench under 'Server Administration'


text:
Q: How to loop within div to maintain correct order of values, and scroll page to get entire data I want to get data within div loop, so that the values can be ordered in correct rows. Also, I want data from entire page, not only from the visible part of the page.

*

*How can I get Firm_name, Remediation_status, ... from div[@class='sc-kbGplQ bCRLdc']?

*The code below gives less than 20 rows, while total firms are 1800+. How can I scroll page and get data from entire page?
Thanks in advance.

ruby = driver.find_elements(By.XPATH, "//div[@class='sc-kbGplQ bCRLdc']")
for i in ruby:
    try:
        Firm_name = [Firm_name.text for Firm_name in i.find_elements(By.XPATH, "//div[1]/h2[@class='sc-idjmjb jDJltL']")]
        Remediation_status = [Remediation_status.text for Remediation_status in i.find_elements(By.XPATH, "//div[1]/span[2][@class='sc-iKpIOp iKvkEG']")]
        Safety_training = [Safety_training.text for Safety_training in i.find_elements(By.XPATH, "//div[2]/span[2][@class = 'sc-iKpIOp iKvkEG']" )]
        Worker_number = [Worker_number.text for Worker_number in i.find_elements(By.XPATH, "//div[1]/h2[@class='sc-bsVVwV gnfeLF']")]
        Progress_rate = [Progress_rate.text for Progress_rate in i.find_elements(By.XPATH, "//div[2]/h2[@class= 'sc-bsVVwV gnfeLF']")]
    except:
        print("na")

df1 = pd.DataFrame(data=list(zip(Firm_name, Remediation_status, Safety_training, Progress_rate, Worker_number)), columns=['Firm_name', 'Remediation_status', 'Safety_training', 'Progress_rate', 'Worker_number'])


text:
Q: How to get MAX and MIN in GROUP BY query? In this query:
SELECT col1, col2, col3
FROM table1
GROUP BY col1

each row includes the first value of col2 and col3 for each unique value of col1.
How to select MAX and MIN for each value of col1.
Something like:
SELECT col1, minimum of col2, maximum of col2, minimum of col3, maximum of col3

A: Would you believe...
SELECT col1, MIN(col2), MAX(col2), MIN(col3), MAX(col3)
  FROM table1
 GROUP BY col1;

...?

each row includes the first value of col2 and col3 for each unique value of col.

That assertion is not exactly true.  That may be what you're seeing, but do not assume this to be meaningful and do not write code based on this observation.  Your original query would not be valid at all were not for a MySQL extension that departs from standard SQL handling of GROUP BY.

MySQL extends the use of GROUP BY so that the select list can refer to nonaggregated columns not named in the GROUP BY clause.

...which is what you did in your initial query, col2 and col3 are not nonaggregated columns (columns without an aggregate function applied, and not in the group-by).  When you do this...

The server is free to choose any value from each group, so unless they are the same, the values chosen are indeterminate

http://dev.mysql.com/doc/refman/5.5/en/group-by-extensions.html


text:
Q: GitHub Deployment to Azure I've tried to upload my Angular2 project from GitHub to Azure but I get the following error when I open the Azure page:
You do not have permission to view this directory or page.
The GitHub deploy to Azure worked fine, no problem. Does anybody know the reason why I still get this error message?
Here's my GitHub project
Here's my Azure website

A: You are using Azure Web App and Azure uses IIS to host your application. So, basically, you no longer need to handle your Angular2 project with the Node.js script.
Please try to delete your server.js file from /wwwroot folder, and also remove the following content in web.config file.
<handlers>
    <!-- indicates that the app.js file is a node.js application to be handled by the iisnode module -->
    <add name="iisnode" path="server.js" verb="*" modules="iisnode" />
</handlers>


text:
Q: How to find the order of a distribution? Let $S_n = \sum_{i=1}^n i^{\alpha} (\delta_{1/i}-\delta_{-1/i})$. These are distributions of order zero for all $n \in \mathbb{N}$ and for all $\alpha \in \mathbb{R}$. I know that, if $\alpha < 0$ then $S_n$ sequence converges in $D'(\mathbb{R})$ to a distribution $S \in D'(\mathbb{R})$. Moreover, if $\alpha < -1$ then $S$ has exactly order zero (because $\sum_{i=1}^{\infty} i^{\alpha}$ converges).
Now, if $-1 \leq\alpha < 0$  I claim that the order is exactly $1$.
My idea is to find $\phi_{\epsilon} \in C_c^{\infty} (\mathbb{R})$ such that $1 = | \langle S,\phi_{\epsilon} \rangle| \leq C \Vert \phi_{\epsilon}\Vert_{C^0} \leq C(\text{something that goes to zero as $\epsilon$ goes to zero})$.  My problem is  I can't find such functions; my only idea is using functions such that $\phi_{\epsilon}(x) = x$ for every $\epsilon$ and thus $| \langle S,\phi_{\epsilon} \rangle|$ is constant, but this seems not to work as well as i thought. Of course, I think I should take $\phi_{\epsilon}$ to be odd. Some hint?
There is also the probelem of $\alpha = -1$. For this has value may the distribution  has order zero?