text:
Q: Axios interceptor doesn't work on App.js but yes in another file hope you doing well.
I've got my private routes on the app.js, but when adding the interceptor to catch errors (401), it doesn't work. Im always getting "err.response not defined".
But when i move the private routes along the interceptor to another file, is working , but the routes won't render and i get a blank page.
Im not sure where is the problem, but im think is related to the app.js file and his defaults settings. Im using laravel as a backend.
Here is my app.js where the interceptor wont work.
import React, { useEffect, useState } from 'react';
import { BrowserRouter as Router, Switch, Route, Redirect, useHistory } from 'react-router-dom';
import './App.css';
import axios from "./axios-instance";
import Homepage from './pages/home/homepage';
import Login from './pages/admin/login';
import Admin from './pages/admin/admin';
import Adminhouses from './pages/admin/adminhouses';

function App() {
  const [adminAuthenticated, setAdminAuthenticated] = useState(false);
  const [loading, setLoading] = useState(true);
  const history = useHistory();

  useEffect(() => {
    axios.get(`api/checkAuthenticated`).then((res) => {
      if (res.status === 200) {
        console.log(res);
        setAdminAuthenticated(true);
      }
      setLoading(false);
    });

    return () => {
      setAdminAuthenticated(false);
    };
  }, []);

  axios.interceptors.response.use(undefined, function axiosRetryInterceptor(err) {
    if (err.response.status === 401) {
      history.push('/');
    }
    return Promise.reject(err);
  });

  axios.interceptors.response.use(function (response) {
    console.log(response);
    return response;
  }, function (error) {
    console.log(error);
    if (error.response.status === 403)// acces denied
    {
      history.push('/login')
    }
    else if (error.response.status === 404)// page not found
    {
      history.push('404')
    }
    return Promise.reject(error);
  }
  );

  let routes = (
    <>

      <Route exact path="/">
        <Homepage />
      </Route>
      <Route exact path="/admin">
        <Admin />
      </Route>

    </>
  );

  if (adminAuthenticated) {

    if (loading) {
      return
Loading...
;
    }
    routes = (
      <>

        <Route exact path="/admin">
          <Admin />
        </Route>

        <Route path="/admin/houses">
          <Adminhouses />
        </Route>

      </>
    );
  }

  return (
    <Router>

      <Switch>

        <Route exact path="/">
          <Homepage />
        </Route>

        <Route exact path="/login">
          <Login />
        </Route>
        {routes}

      </Switch>
    </Router>
  );
}

export default App;

This is my axios-instance
import axios from "axios";

axios.defaults.baseURL = "http://localhost:8000/";
axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
axios.defaults.headers.post['Content-Type'] = 'application/json';
axios.defaults.headers.post['Accept'] = 'application/json';
axios.defaults.headers['Access-Control-Allow-Origin'] = '*';

axios.defaults.withCredentials = true;

axios.interceptors.request.use(function (config) {
  const token = localStorage.getItem('auth_token');
  config.headers.Authorization = token ? `Bearer ${token}` : '';
  return config;
});

export default axios;

This is my other file ADMINPRIVATE
import axios from "../axios-instance";
import React, { useEffect, useState } from "react";
import { BrowserRouter as Router, Switch, Route, Redirect, useHistory } from 'react-router-dom';
import Admin from "../pages/admin/admin";
import Adminhouses from "../pages/admin/adminhouses";
import Homepage from "../pages/home/homepage";
import Login from "../pages/admin/login";

function Adminprivate() {

    const [adminAuthenticated, setAdminAuthenticated] = useState(false);
    const [loading, setLoading] = useState(true);
    const history = useHistory();

    useEffect(() => {
        axios.get(`api/checkAuthenticated`).then((res) => {
            if (res.status === 200) {
                console.log(res);
                setAdminAuthenticated(true);
            }
            setLoading(false);
        });

        return () => {
            setAdminAuthenticated(false);
        };
    }, []);

    axios.interceptors.response.use(undefined, function axiosRetryInterceptor(err) {
        if (err.response.status === 401) {
            history.push('/');
        }
        return Promise.reject(err);
    });

    axios.interceptors.response.use(function (response) {
        console.log(response);
        return response;
    }, function (error) {
        console.log(error);
        if (error.response.status === 403)// acces denied
        {
            history.push('/login')
        }
        else if (error.response.status === 404)// page not found
        {
            history.push('404')
        }
        return Promise.reject(error);
    }
    );
    let routes = (
        <>
            <Route exact path="/admin">
                <Admin />
            </Route>
        </>
    );

    if (adminAuthenticated) {

        routes = (
            <>
                <Router>
                    <Switch>
                        <Route exact path="/admin">
                            <Admin />
                        </Route>

                        <Route path="/admin/houses">
                            <Adminhouses />
                        </Route>
                    </Switch>
                </Router>
            </>
        );
    }

}
export let routes = (

    <>

        <Route exact path="/">
            <Homepage />
        </Route>

        <Route exact path="/login">
            <Login />
        </Route>

        <Route exact path="/admin">
            <Admin />
        </Route>

        <Route path="/admin/houses">
            <Adminhouses />
        </Route>

    </>

);
export default Adminprivate;

So there is the thing. Private routes on app.js = interceptor doesn't work.
Private routes on different file + interceptor = Routes won't show up, but interceptors works.
Im not sure why is that, any information will be helpful. Thanks


text:
Q: How to Run SSJS in Application Layout Item Buttons / Nodes? I've just started using the xe:applicationLayout for an application. I have added a "Basic Node" to the "Place Bar". I want to run some server side JavaScript code onClick of the node/button. I have tried computing the onClick property of the Basic Node, but this doesn't do anything and it seems like the onClick only runs client side JavaScript.
Is there a property or node that can run SSJS? Thanks for any help.

A: Set the submittedValue property of the node. ( the procedure is the same for all places in the application layout; here is an example snippet for the banner.ApplicationLinks )
    <xe:this.bannerApplicationLinks>
                <xe:basicContainerNode styleClass="firstApplication" label="${langString_CRM['CREATE']}">
                    <xe:this.children>
                        <xe:basicLeafNode submitValue="company_new"

Then add an event handler to your page and run your SSJS depending on the submitted value
        <xp:eventHandler event="onItemClick" submit="true"
        refreshMode="partial" disableValidators="true" refreshId="cois_application_layout"
        execMode="partial">
        <xp:this.action><![CDATA[#{javascript:
        var submittedValue=context.getSubmittedValue();
// evaluate the submitted value here ...

A: Not the nicest version but it works.
Add buttons to the XPage and hide then using css.
In your application layout add a client side script that gets a handle to the buttons using
dojo.byId and do a click() on them. Then it's easy to have different panels update when you click on different buttons.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I reactively update a value in a component from a store value? I have two components and a basic store as per the docs here: https://v2.vuejs.org/v2/guide/state-management.html#Simple-State-Management-from-Scratch.
I want to make it so that when I type into an input the value in a different component is updated by using the store.
Basic example here.
App.vue
<template>

Store Demo

    <BaseInputText /> Value From Store: {{ test }}

</template>

BaseInput.vue
<template>
  <input type="text" class="input" v-model="test" />
</template>

store.js
export const store = {
  debug: true,
  state: {
    test: "hi"
  },
  setTest(newValue) {
    if (this.debug) console.log("Set the test field with:", newValue);
    this.state.test = newValue;
  }
};

I want to make it so that when I type a string into the input the test variable in App.vue is updated. I'm trying to understand how the store pattern works. I'm aware of how to use props.
I also have a working copy here: https://codesandbox.io/s/loz79jnoq?fontsize=14

A: Updated
2.6.0+
To make store reactive use Vue.observable (added in in 2.6.0+)
store.js
import Vue from 'vue'

export const store = Vue.observable({
  debug: true,
  state: {
    test: 'hi'
  }
})

BaseInputText.vue
<input type="text" class="input" v-model="state.test">
...
data() {
    return {
      state: store.state
    };
  },

before 2.6.0
store.js
import Vue from 'vue'

export const store = new Vue({
  data: {
    debug: true,
    state: {
      test: 'hi'
    }
  }
})

BaseInputText.vue
<input type="text" class="input" v-model="state.test">
...
data() {
  return {
    state: store.state
  };
}

Old answer
From documentation However, the difference is that computed properties are cached based on their reactive dependencies.
The store is not reactive
Change to
App.vue
  data() {
    return {
      state: store.state
    };
  },
  computed: {
    test: function() {
      return this.state.test;
    }
  },

It looks bad but I don't see another way to make it work


text:
Q: how to lower reactance of an electromagnet? I have an electromagnet that I want to switch on or off quickly. After making the prototype I found that the magnetic force remains for about 1 sec after I turn the current off . This is a problem as I want the magnetic force as quickly on or off as possible.
Right now the electromagnet is made of a 2000 turn solenoid, and current in the solenoid stabilizes at 0.6 amps (after the annoying slow ramp up).
If I were to bundle 4 strands of magnet wire and coil the bundle 500 turns (500 x4 =2000 turns) and then connect each wire in parallel, then adjust the voltage so that the current in each wire is still 0.6, would that improve the response time of the magnet (by lowering the impedance and therefore reactance of each individual coil) ??

simulate this circuit – Schematic created using CircuitLab

A: If you are driving the coil with (say) a transistor you will have a diode across the coil to prevent back-emfs destroying the transistor however, this makes the turn off time quite long so you might consider, as a simple option, using a zener diode in series with the protection diode. This burns the stored energy much more quickly.

If I were to bundle 4 strands of magnet wire and coil the bundle 500
  turns (500 x4 =2000 turns) and then connect each wire in parallel,
  then adjust the voltage so that the current in each wire is still 0.6,
  would that improve the response time of the magnet (by lowering the
  impedance and therefore reactance of each individual coil) ??

You have to keep ampere turns the same for producing the same mechanical force so, 500 turns x 2.4 amps = 2000 turns at 0.6 amps. In other words, it's a bit simpler than what you propose but you can do it your way to re-use the wire.
Force = \$(N\cdot I)^2\cdot 4\pi 10^{-7}\cdot \dfrac{A}{2g^2}\$

*

*F = Force

*I = Current

*N = Number of turns

*g = Length of the gap between the solenoid and the magnetizable metal

*A = Area of solenoid/electromagnet

Reducing turns by a factor of 4 (irrespective of number of parallel windings) reduces the inductance by 16 (ratio of turns squared) so your response speed improves by a factor of 16. This assumes the same core and geometry of windings on that core (which I'm sure in this example will be true). So if you only wished to quarter the inductance (1/4 the response time) then halving the turns to 1000 would work and only requires 1.2 amps.

A: Take a couple of steps back to energy, this will allow you to clear your head of the details of turns, volts, inductance etc.
When the magnet is on, and operating at its design flux, there will be a certain amount of energy stored in the magnetic field.
If you are happy to change the field slowly, so change the amount of stored energy slowly, then you only need a small amount of power. To change it quickly, you need a large amount of power. Power is rate of change of energy.
Power is volts times current. Now unfortunately, the copper wire has resistance, and this confuses the situation a bit, because we also need power to push the current through the resistance of the copper wire. However, let's simplify for a moment and imagine that we have a superconducting solenoid, like an MRI magnet. Just like a spherical cow in a vacuum beloved of physicists, this allows us to concentrate on the important bits.
To change the field quickly requires a lot of power, so more volts at any given current. If you alter the windings so you need more current to produce the field (reduce the inductance), then you will need fewer volts to slew the field at the same speed, and vice versa.
For any given electromagnet, you slew it as fast as possible by using the maximum drive voltage you can achieve. This might be limited by the breakdown voltage of your windings, or switching devices, or power supply. To slew the field up, you need to supply energy. To slew the field down, you are withdrawing energy, so you can generate the voltage by passing the current through a resistor, you do not need a power supply.
If the voltage range you can handle is limited, and you are not yet at your current limit, then you can improve the slew speed if you rewind your magnet to use more current, obviously limited by the maximum current you can tolerate. This will reduce the voltage needed to get the same slew power.
Finally, what about that pesky copper resistance? It means you have to supply power to keep the magnet on, and that your slew up takes longer, and your slew down is quicker. It does not alter the general conclusions that more slew power means faster field changes.


text:
Q: "Primary script unknown" while reading response header from upstream - NGINX Olá,
estou tentando executar meu site do Wordpress na Host que possui está configuração:

*

*Ubuntu LTS 16.04, Nginx, Apache, MySQL, PHP, Webmin

Ao tentar entrar na página inicial, o erro que é exibido no arquivo de error log, é este abaixo:

2018/05/03 02:35:22 [error] 3372#3372: *1 FastCGI sent in stderr: "Primary script unknown" while reading response header from upstream, client: 187.103.234.71, server: meusite.com, request: "GET / HTTP/1.1", upstream: "fastcgi://unix:/run/php/php7.0-fpm.sock:", host: "meusite.com"

Alguma ideia do que possa ser?
Comecei a me aventurar agora na criação do meu próprio servidor, então os erros começaram a aparecer e preciso de ajuda para entender a raiz e tentar resolver.
Obrigada!

A: O seu problema é esta na configuração fastcgi.
No Webmin >>> Vá para VirtualMin >>> Selecione o Dominio >>>
Services >> Server configuration >> Website Options
Lá deve ter mais de uma opção, alem do selecionado CGI.
Selecione outra opção e Salve.
O SITE NAO IRA FUNCIONAR (MAS VERIFIQUE, TALVEZ SEJA O CASO DE TROCAR SUA CONFIGURAÇÃO)
CASO SEU SITE NÃO VOLTE...
Faça o mesmo caminho acima e volte para CGI como estava.
Assim o seu site vai reconfigurar o SOCKET do CGI.

NGINX & APACHE é Servidor Web e Proxy Reverso
Isto é os dois só pode ser utilizado se você configurar em portas diferentes.
Por exemplo:
APACHE= PORTA:8080
NGINX= PORTA:80
Caso use cache como Varsish, verifique as configurações de portas
Contudo utilizando os dois é possivel.
Configurar o Nginx como um Servidor Web e Proxy Reverso Apache.


text:
Q: How to display the sum of a column? How can I find the sum of this column from a file named cars?
73
60
45
102
15
50
115
30
10
180
85
25

How can I add these numbers up (using the command line)?
I showed this list typing
awk '{ print $4 }' cars

A: Given:
$ cat file
73
60
45
102
15
50
115
30
10
180
85
25

You can do:
$ paste -sd+ file | bc
790

Or, given a multi column file:
$ cat file
0   73  1
2   60  3
4   45  5
6   102 7
8   15  8
9   50  10
11  115 12
13  30  14
15  10  16
17  180 18
19  85  20
21  25  22

You can use cut to get the column of interest:
$ cut -f 2 file | paste -sd+ - | bc
790

A: 1st Solution in awk: Could you please try following once.(I am taking sum of column 4 since your attempt shows it, had written a dynamic command where you need to change only variable's value and it will take that column's SUM then)
awk -v column_number=4 '{sum+=$column_number} END{print "SUM of column " column_number " is: " sum}'  Input_file

By running above code you could give any column number in variable column_number and could take some of it. In case you have any other requirement then kindly do show us sample input and expected sample output in code tags in your post.
Explanation of above code:
awk -v column_number=4 '    ##Starting awk program here and setting variable column_number value to 4 you could change it as per your column number too, for which you want to take SUM for all lines of Input_file.
{                           ##Starting a BLOCK here.
  sum+=$column_number       ##Creating a variable named SUM whose value is value of current lines $column_number value and it keep adding SUMs value to its own to get cumulative sum of all columns in all lines.
}                           ##Closing BLOCK here.
END{                        ##Mentioning awk program END block here, it will be executed when an Input_file is being done with reading.
  print "SUM of column " column_number " of all lines in Input_file is: " sum     ##Printing SUM variable value here.
}'  Input_file              ##Mentioning Input_file name here.

2nd Solution in bash: Considering that your lines in Input_file have only 1 entry.
while read line; do    sum=$(($sum+$line)) ; done < "Input_file"; echo "$sum"

A: Here is a way to do it on command line, but not awk.
vim /tmp/text
let sum=0
for X in `cat /tmp/text`; do let sum=$sum+$X; done
echo $sum


text:
Q: AWS Lambda - Access resources (EC2) in another AWS account I have an AWS Lambda which is querying EC2 instances in my account, I'll call it account A and its working fine, I can see its finding my servers. I also want the lambda to query EC2 instances in another AWS account at the same time, I'll call that account B - is that possible?
I've got the following policy to allow the lambda to assume the role in account B but it only queried the same servers - all in account A - I'm just wondering if I am missing something?
Here is my policy which I've attached to the lambda role:
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "Assume Role",
      "Effect": "Allow",
      "Action": "sts:AssumeRole",
      "Resource": "arn:aws:iam::AccountB:role/MyRoleNameInAccountB"
    },
    {
      "Effect": "Allow",
      "Action": "ec2:DescribeInstances",
      "Resource": "*"
    }
  ]
}

Thanks

A: For the Lambda to be able to assume a role in a AccountB, the role in AccountB has to have a trust policy which needs to allow the Lambda to assume the role.
Also, the role in AccountB has to have the policy which allows the Lambda to describe EC2 instances. AccountB should be the entity which allows actions inside itself, not the other way around, for obvious security reasons.
Recommend checking out this AWS support page.


text:
Q: Is there a GUI framework available in anaconda (python )? I have been studying python and looking for ways to install and use some GUI framework I can use. I have read of native tkinter, and QtPy, Kivy, wxPython etc, but getting problems installing them.
Recently I read about Anaconda, and want to give it a try. But is it going to solve my issue for GUI framework ? I am seeing some frameworks in the list, however not sure, which one of them is GUI framework. Or is their no GUI framework included ( other than tkinter of course )

A: Yes, there are some GUI frameworks in Anaconda. The list of included packages is here. Because you mentioned it specifically, pyqt is included.

A: Try libraries traitsUI and Enaml.  These are both supported in anaconda and both open-source projects from the company Enthought (many anaconda employees/founders are closely tied to Enthought).  These libraries make use of underlying backends (wx, qt, tk) and facilitate much faster GUI dev than does working with those core frameworks directly.


text:
Q: Creating product view block with custom template in controller action fails I want to create a Magento\Catalog\Block\Product\View block in a custom controller action (which will be used for an AJAX call later on). However I am getting the following error when creating the block (and setting the template):
Exception #0 (Magento\Framework\Exception\ValidatorException): Invalid template file: 'Vendor_Module::product.phtml' in module: 'Magento_Catalog' block's name: 'product\view_0'

app/code/Vendor/Module/Controller/Product/View.php
<?php

namespace Vendor\Module\Controller\Product;

class View extends \Magento\Catalog\Controller\Product
{
    protected $layoutFactory;
    protected $resultFactory;

    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\View\LayoutFactory $layoutFactory,
        \Magento\Framework\Controller\Result\RawFactory $resultFactory
    ) {
        $this->layoutFactory = $layoutFactory;
        $this->resultFactory = $resultFactory;
        parent::__construct($context);
    }

    public function execute()
    {
        $block = $this->layoutFactory->create()
                    ->createBlock('Magento\Catalog\Block\Product\View')
                    ->setTemplate('Vendor_Module::product.phtml')
                    ->toHtml();

        $result = $this->resultFactory->create();
        $result->setContents($block);

        return $result;
    }
}

app/code/Vendor/Module/view/frontend/product.phtml

Hello World!

app/code/Vendor/Module/etc/frontend/routes.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
    <router id="standard">
        <route id="foo" frontName="foo">
            <module name="Vendor_Module" />
        </route>
    </router>
</config>

I can't find the mistake. The definition of the template (Vendor_Module::product.html) plus the template's location should be correct. I also tried putting the template directly in app/code/Vendor/Module/view - but that did not change anything.
What could be the problem here?

A: Simple solution: I forgot the templates subfolder in my template's path. So instead of
app/code/Vendor/Module/view/frontend/product.phtml
it should of course be
app/code/Vendor/Module/view/frontend/templates/product.phtml

A: Try to add the template in this tree directory app/code/Vendor/Module/view/frontend/templates/product/view/product.phtml


text:
Q: SSRS Reports, Group filtering I have groups with specific filters. Within these groups I have few "Count" expression with conditions. All works great. But when group doesn't have any elements then it disappears. But I need to show in "Count" cells "0" for this group. How can I do this?

A: Here are two suggestions.
In your query use an ISNULL function.
 Select
 ISNULL(YourExpression, 0)
 From Table

In SSRS Use an expression for the fields you want to eliminate nulls.
 iif(fields!Field.Value is nothing , 0 , Fields!Field.Value)

Hope this helps :)

A: use the below expression:
=iif(isnothing(Field!Name.value),0,count(Field!Name.value))


text:
Q: How can I manage a different setup for my Ruby on Rails application dependent on production or development? I am trying to deploy my first rails app and struggling a bit. My plan is to initially host it on a heroku free account to get a feel for live deployments and do some production testing. Eventually I might move it to a VPS.
I use git and do not use Capistrano at the moment.
Heroku primarily uses git, which is fine, but git manages the entire project state not files. So I have issues managing configuration files that are different from production to development, for example captcha keys in the environment.rb or goolge js api keys.
So what I did was to..
1 - Take the environment specific configuration out of the enviornment.rb and put it in the development.rb and production.rb. Created a branch called dev where I do my development and then merge it with master and push master to the production heroku remote.
This all works ok, but wondering if there is a better way to do it.
The other massive problem is I might have to use different gems in dev and in herouku. For example, I use ThinkingSphinix for search in dev, but Heroku I have to use acts_as_solr, which means my "Article.search call in the controller, will have to be Article.find_by_solr in production. This can become messy very fast.
What's the best way to deal with this kind of situation?
Thanks

A: For non-sensitive keys such as Google's JS API key etc., I found this RailsCasts episode very helpful.
Just created a config file under config/ and store your development settings in there.
# /config/google.yml
development:
  google:
    js:
      key: 123456

test:
  google:
    js:
      key: 345678

production:
  google:
    js:
      key: 567890

Then create an initializer inside config/initializers/ that will parse the yaml and create an object which can be used without worrying about the current environment.
# /config/initializers/google.rb
GOOGLE_CONFIG = YAML.load_file("#{RAILS_ROOT}/config/google.yml")[RAILS_ENV]

The environment variable RAILS_ENV refers to the current environment, so on application startup it picks up the current type, and you can refer to the settings in your code through GOOGLE_CONFIG:
<script type="text/javascript" src="http://www.google.com/jsapi?key=<%= GOOGLE_CONFIG['js']['key'] %>"></script>

For the latter issue, where code itself differs from environment to environment, I believe Capistrano would be a better solution.

A: For values that you want to keep different between environments, Heroku offers config vars.
As for using one indexing program in production and another in development, that's a bad idea, and will make things way messier than they need to be. Either start using Solr locally, or set up a Thinking Sphinx instance in EC2 yourself, and have your dynos connect to it.

A: I would suggest that it is very unwise to have different code in development and production.
Your development, test and production environments should be as similar as possible.
In fact, I would go so far as to say the entire point of the different environments is to simply provide an easy system for allowing minor configuration changes between setups. Different databases, different API parameters, different aching options, but the core system MUST be the same.
The the issue you will face is doubling your development effort. You still have to write the code. So in the search example you provide above, you will have to develop and test twice - once for the Solr production system and once for you local Sphinx, then you need to be able to switch and test between the two approaches in all of your environments to ensure test coverage and functionality.


text:
Q: Image smoothing using opencv data structures I would like to implement Gaussian blur on the AVI Files i read, i know about the in-built functions of opencv however i would need help from SO users to assist me so that i can get started by implementing it myself.
I know how to access the Image Pixels of an IplImage * , CvARR * , etc....
However i am just not sure how to begin. I know this is a very elementary question, but i would please please please request for patience and assistance from users out here and give me a way through this.

A: 6 month back I was also new to the opencv. The way I learn it is:
http://opencv.itseez.com/doc/tutorials/tutorials.html
http://www.packtpub.com/opencv-2-computer-vision-application-programming-cookbook/book


text:
Q: (iOS + Firebase) Unable to pass the Image to the next ViewController from a UITableViewCell I have a UITableView where the data is coming from a Firebase RealtimeDatabase. Once the user selects the row, the data from the row i.e: Title, Description and an Image will be taken to the next ViewController.
I'm able to pass the Title and Description but I'm unable to pass the Image.
Here is my code for the UITableView:
import UIKit
import Firebase

class PostTable: UIViewController, UITableViewDelegate, UITableViewDataSource {

    var tableView:UITableView!

    var posts = [Post]()

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView = UITableView(frame: view.bounds, style: .plain)
        view.addSubview(tableView)

        let cellNib = UINib(nibName: "PostTableViewCell", bundle: nil)
        tableView.register(cellNib, forCellReuseIdentifier: "postCell")
        var layoutGuide:UILayoutGuide!

        layoutGuide = view.safeAreaLayoutGuide

        tableView.leadingAnchor.constraint(equalTo: layoutGuide.leadingAnchor).isActive = true
        tableView.topAnchor.constraint(equalTo: layoutGuide.topAnchor).isActive = true
        tableView.trailingAnchor.constraint(equalTo: layoutGuide.trailingAnchor).isActive = true
        tableView.bottomAnchor.constraint(equalTo: layoutGuide.bottomAnchor).isActive = true

        tableView.delegate = self
        tableView.dataSource = self
        tableView.tableFooterView = UIView()
        tableView.reloadData()

        observePosts()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func observePosts() {
        let postsRef = Database.database().reference().child("Data")
        print(postsRef)
        postsRef.observe(.value, with: { snapshot in
            var tempPosts = [Post]()

            for child in snapshot.children{

                if let childSnapshot = child as? DataSnapshot,
                    let dict = childSnapshot.value as? [String:Any],
                    let title = dict["title"] as? String,
                    let logoImage = dict["image"] as? String,
                    let url = URL(string:logoImage),
                    let description = dict["description"] as? String{

                    let userProfile = UserProfile(title: title, photoURL: url)
                    let post = Post(id: childSnapshot.key, title: userProfile, description: description, image: userProfile)
                    print(post)
                    tempPosts.append(post)
                }
            }

            self.posts = tempPosts
            self.tableView.reloadData()
        })
    }

    func getImage(url: String, completion: @escaping (UIImage?) -> ()) {
        URLSession.shared.dataTask(with: URL(string: url)!) { data, response, error in
            if error == nil {
                completion(UIImage(data: data!))
            } else {
                completion(nil)
            }
            }.resume()
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        print(posts.count)
        return posts.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
        let cell = tableView.dequeueReusableCell(withIdentifier: "postCell", for: indexPath) as! PostTableViewCell
        cell.set(post: posts[indexPath.row])
        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let postsInfo = posts[indexPath.row]
        print(postsInfo)

        let Storyboard = UIStoryboard(name: "Main", bundle: nil)
        let DvC = Storyboard.instantiateViewController(withIdentifier: "PostTableDetailed") as! PostTableDetailed
        DvC.getName = postsInfo.title.title
        DvC.getDesc = postsInfo.description
//        DvC.getImg = postsInfo.title.photoURL
        self.navigationController?.pushViewController(DvC, animated: true)
    }
}

Here is the second ViewControler which has the post details:
import UIKit

class PostTableDetailed: UIViewController {

    var getName = String()
    var getDesc = String()

    @IBOutlet weak var Name: UILabel!
    @IBOutlet weak var Description: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        Name.text! = getName
        Description.text! = getDesc
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

I also have a few Models (Post, UserProfile) and Services (UserService and ImageService), please let me know if that is required to break down this problem.

A: if you have the imageUrl, all you need is to pass it from PostTable to PostTableDetailed and download the image.
   // PostTable
       func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
            let postsInfo = posts[indexPath.row]
            print(postsInfo)

            let Storyboard = UIStoryboard(name: "Main", bundle: nil)
            let DvC = Storyboard.instantiateViewController(withIdentifier: "PostTableDetailed") as! PostTableDetailed
            DvC.getName = postsInfo.title.title
            DvC.getDesc = postsInfo.description
            DvC.getImg = postsInfo.photoURL
            self.navigationController?.pushViewController(DvC, animated: true)
        }

// PostTableDetailed
class PostTableDetailed: UIViewController {

    var getName = String()
    var getDesc = String()
    var imageUrl = ""

    @IBOutlet weak var Name: UILabel!
    @IBOutlet weak var Description: UILabel!
    @IBOutlet weak var imageView: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()

        Name.text! = getName
        Description.text! = getDesc
        updayeImage()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

 private func updateImage() {
        URLSession.shared.dataTask(with: URL(string: self.imageUrl)!) { data, response, error in
            if error == nil, let data = data {
                imageView.image = UIImage(data: data)
            }
            }.resume()
    }

}

The image will be shown when the task will complete.
so I suggest for you to add a spinner to the imageView.

A: In PostDetail ViewController do like this
import UIKit

class PostTableDetailed: UIViewController {

    var getName = String()
    var getDesc = String()
    var getImg = String()

    @IBOutlet weak var Name: UILabel!
    @IBOutlet weak var Description: UILabel!
    @IBOutlet weak var ImageContainer: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()

        Name.text! = getName
        Description.text! = getDesc
        if let image = getImage(url: getImg) { (image)
            ImageContainer.image = image
        }

    }

    override func didReceiveMemoryWarning() {
         super.didReceiveMemoryWarning()
         // Dispose of any resources that can be recreated.
    }

    func getImage(url: String, completion: @escaping (UIImage?) -> ()) {
        URLSession.shared.dataTask(with: URL(string: url)!) { data, response, error in
            if error == nil {
                completion(UIImage(data: data!))
            } else {
                completion(nil)
            }
        }.resume()
    }

}

A: First of all, you can use this code to download the image:
let imageCache = NSCache<AnyObject, AnyObject>()

extension UIImageView {

func downloadImageWithUrlString(urlString: String) -> Void {

    if urlString.count == 0 {
        print("Image Url is not found")
        return
    }

    self.image = nil
    if let cachedImage = imageCache.object(forKey: urlString as AnyObject) as? UIImage {
        self.image = cachedImage
        return
    }

    let request = URLRequest(url: URL(string: urlString)!)
    let dataTask = URLSession.shared.dataTask(with: request) {data, response, error in
        if error != nil { return }
        DispatchQueue.main.async {
            let downloadedImage = UIImage(data: data!)
            if let image = downloadedImage {
                imageCache.setObject(image, forKey: urlString as AnyObject)
                self.image = UIImage(data: data!)
            }
        }
    }
    dataTask.resume()
}
}

Now, if you are using the model that contains Title, Description, and ImageUrlString, then simply pass the selected model object to the next viewController.
In next ViewController, just simply call the same method to download the image which you are using on first ViewController. You don't need to pass the image from VC1 to VC2 because it might be the possible image is not downloaded yet and you select a row to move on next VC.
So here simple thing that pass the model object and calls the image downloading method.


text:
Q: How do I loop through the rows in a column and count them using Python? I am trying to loop through column in an access table using Python. The column I have is sorted ascending.
I am trying to loop though the rows and when the value in the column changes, I want to get count of of all those values. In the example column below, the first group of values I want to count are the M1's. When the next row changes to M21, I want to count the M21's until it changes to M23b and so on.
I don't want to use an if/else statement, because there are a few hundred different possible values. I played around with the groupby function in the itertools module, but I haven't been able to solve the syntax to work in my example. I also tried a silly loop doing something like if row != row.next(): do_something but that blew up in my face. If anyone can suggest a work-around or show me a sample script that will do this for me, I'd appreciate it.
Example Column:

M1
M1
M1
M21
M21
M23b
M23b
S2
S23b
S23B
O1
O2
O2
O2

A: Your intuition to use itertools.groupby was correct:
for key, group in groupby(column):
    count = sum(1 for item in group) # Thanks JBernardo
    # the key is what is in the column, count is the number of items

Alternatively, if all you need is the counts, it's as simple as:
from collections import Counter # Python 2.7+

group_counts = Counter(column)

You can implement Counter as:
from collections import defaultdict:

group_counts = defaultdict(int)

for item in column:
    group_counts[item] += 1

on older versions of Python.

A: If you want to add printing in a loop doing other work, the following may be helpful:
from collections import Counter  # or defaultdict

col_counts = Counter()           # or defaultdict(int)

last_value = object()            # won't show up in table
for row in access_table:
    col_counts[row[field]] += 1
    if row[field] != last_value:
        print(col_counts[last_value])
        last_value = row[field]
    ...
    other_processing()
    ...


text:
Q: When i hover css menu horizontal scrollbar appears Like the title says.
I made a css hover menu in the , and i always want it in the top right corner of the browser.
But when i hover the menu the horizontal scrollbar appears down in  the browser.
Someone know why ?? and how to solve it ?
Here a link with a example: http://jsfiddle.net/pdbYz/24/

A: Your overflowing your dirty sub menu...
try that :
div#sub_menu div.sub_menu_top {
    width:150px;
}

http://jsfiddle.net/pdbYz/25/

A: it's because of submenu's box-shadow, you have to clip it somehow
EDIT: it is because of

, you have to set it's position to right:0

A: div#sub_menu div.sub_menu_top {
    width:250px;
    height:13px;
    background-image:url(../images/arrow_up.png);
    background-repeat:no-repeat;
    background-position:109px bottom;
    position:absolute;
    top:-13px;
}

Remove position:absolute; and the scrollbar disappears.

A: In the HMTL code on http://jsfiddle.net/pdbYz/24/, if you change the line

to

the scrollbar will not show when you hover over Menu.
You still need to figure out where to put the added CSS in your CSS file, but I guess you can do that pretty easily. If not, let me know and I will try and add more info.


text:
Q: Firefox can't establish a connection to the server at ws://sockets.ny.stackexchange.com/
Update
This issue was fixed in later versions of Firefox and no longer applies
It is kept here for reference for those having to use legacy browsers for specific reasons. Otherwise please upgrade to the latest version.

Fx 12 on XP
Timestamp: 08-06-2012 11:02:18
Error: Firefox can't establish a connection to the server at ws://sockets.ny.stackexchange.com/.
Source File: http://cdn.sstatic.net/js/full.js?v=3ea93510c9eb
Line: 11

Getting this repeatedly - do you want me to report such things or are they possibly too localised to whatever is happening with my connection right now?
Webtest - and I am not on a wireless

Some other screenshot showing the issue:

A: It works fine from here ;p
I strongly suspect that this is primarily the effect of down-level intermediary proxy servers mangling the web-socket request. In most cases... "squid". Basically, a web-socket request is meant to have something like (as http-headers):
Connection: Upgrade
Upgrade: websocket

plus some other headers, such as Sec-WebSocket-Version and Sec-WebSocket-Key for up-to-date implementations (RFC6455 and most of the Hybi versions), or Sec-WebSocket-Key1 and Sec-WebSocket-Key2 (for the early implementations, Hixie-76).
We even accept multi-value headers that we see in-the-field, such as:
Connection: Upgrade, Keep-Alive
Upgrade: websocket

even though that isn't really all that meaningful (it doesn't make sense to ask whether a web-socket connection has "keep alive" enabled). However, we get a constant stream of requests of the form:
Connection: Keep-Alive

(with no upgrade header), or
Connection: Keep-Alive
Upgrade: websocket

which are... not web-socket requests. I know that no web-socket aware browser issued that request, so it basically screams "dodgy proxy server". If you have a dodgy proxy server that doesn't know how to change protocol to web-sockets, then the chances are good that it would get very ill if we did change protocol, so if we see something obviously bad we kill the connection dead, to protect all parties.

Perhaps the best thing to do is to look at http://websocketstest.com - if that reports errors, then we can't help - your network infrastructure is actively preventing successful use of web-sockets. Also note the caveats from that page:

Antiviruses, firewalls and HTTP proxies may interfere WebSocket connections, sometimes rendering them useless.

The good news, however, is that we only use web-sockets for nice to have functionality. Web-sockets being down does not stop your usage of Stack Exchange - it just prevents instant updates. We also use web-sockets on the chat system, but we fallback to polling if we can't establish a web-sockets connection.

A: OUTDATED - 2013-05-28
There was more than 5 major upgrades in Firefox, from the time this question was asked.
Now this work fine with the version 21 and 22 of Firefox.
This seem not to be an SO issue, in fine.
Original post - 2012-11-04
I know Me too answer are not welcome on SO,  but...
I'm using Firefox 17.0 (french version), behind a proxy and a firewall.
The dialog with websocketstest seem pretty good:
Environment
WebSockets supported    Yes✔
HTTP Proxy  YES
1.1 netmaster:3128 (squid/2.7.STABLE9)
WebSocket protocol version  rfc-6455
WebSockets (Port 80)
Connected   No✘ Disconnected at 22:0:36
WebSockets (Port 443)
Connected   Yes✔
Data Receive    Yes✔
Data Send   Yes✔
Echo Test   Yes✔
Server time 2012/11/4 21:07:28
WebSockets (Port 8080)
Connected   No✘ Disconnected at 22:0:37
WebSockets (Port 443, SSL)
Connected   Yes✔
Data Receive    Yes✔
Data Send   Yes✔
Echo Test   Yes✔
Server time 2012/11/4 21:07:28
Comet (Port 80)
Connected   Yes✔
Server time 2012/11/4 21:07:28

But, as I'm writting this (with some SO windows opened on background), the error console display:
Horodatage : 04. 11. 12 22:05:12
Erreur : Firefox ne peut établir de connexion avec le serveur à l'adresse ws://sockets-se.or.stackexchange.com/.
Fichier Source : http://cdn.sstatic.net/js/full.js?v=60ed68b57396
Ligne : 12

Horodatage : 04. 11. 12 22:06:12
Erreur : Firefox ne peut établir de connexion avec le serveur à l'adresse ws://69.59.197.29/.
Fichier Source : http://meta.stackoverflow.com/content/js/full.js?v=60ed68b57396
Ligne : 12


text:
Q: Tikz trees - line feature In my MWE :

*

*why line width=0pt doesn't work ?

*why the dashed argument on a level leeks on the next ?

\documentclass[tikz]{standalone}
\usetikzlibrary{trees}

\begin{document}

\begin{tikzpicture}[level distance=5mm,
    level 1/.style={sibling distance=32mm,line width=0pt},
    level 2/.style={sibling distance=16mm,dashed},
    level 3/.style={sibling distance=8mm,level distance=12mm},
    %level 4/.style={sibling distance=7mm},
    %every fit/.style={rectangle,draw,inner sep=3.5pt},
    grow=right]

\scriptsize
\node {$\bullet$}
child {node {P}
        child {node{PP}
            child {node{PPP}}
            child {node{PPF}}
        }
        child {node{PF}
            child {node{PFP}}
            child {node{PFF}}
        }
    }
child {node {F}
        child {node{FP}
            child {node{FPP}}
            child {node{FPF}}
        }
        child {node{FF}
            child {node{FFP}}
            child {node{FFF}}
        }
    } ;
\end{tikzpicture}

\end{document}

A: You have to change the edge from parent style
\documentclass[tikz,margin=5mm]{standalone}
\usetikzlibrary{trees}

\begin{document}

\begin{tikzpicture}[level distance=5mm,
    level 1/.style={sibling distance=32mm,
      edge from parent/.style={draw=none}},
    level 2/.style={sibling distance=16mm,
      edge from parent/.append style={draw,dashed}},
    level 3/.style={sibling distance=8mm,level distance=12mm,
      edge from parent/.append style={solid}},
    %level 4/.style={sibling distance=7mm},
    %every fit/.style={rectangle,draw,inner sep=3.5pt},
    grow=right]

\scriptsize
\node {$\bullet$}
child {node {P}
        child {node{PP}
            child {node{PPP}}
            child {node{PPF}}
        }
        child {node{PF}
            child {node{PFP}}
            child {node{PFF}}
        }
    }
child {node {F}
        child {node{FP}
            child {node{FPP}}
            child {node{FPF}}
        }
        child {node{FF}
            child {node{FFP}}
            child {node{FFF}}
        }
    } ;
\end{tikzpicture}

\end{document}


text:
Q: VBA - run a formula which adapts to a range that isn't always the same
If you look at the picture above. The thing I want is to run an formula when the text like 1ST or CUCA or 2ND occurs in column E. I want the formula +countif to run, but in this formula I define the range which is in the example F2:F25, but this depends on how many agents I have. If there is one agent less it needs to adapt the range.
Then I have the next day in this sheet and I need it to do the same thing but again with another range.
Can someone help me?
For the moment I use this but I defined the range but the range can change and I don't want to modify the code constantly
Sub Runcode()

    Dim strFormulas(1 To 6) As Variant

    Range("F26").Select
    ActiveCell.Formula2R1C1 = "=+countbycolor(R2C1,R[-24]C:R[-1]C)"

    Range("F27").Select
    ActiveCell.Formula2R1C1 = "=+countbycolor(R5C1,R[-24]C:R[-1]C)"

    Range("F28").Select
    ActiveCell.Formula2R1C1 = "=+countbycolor(R3C1,R[-24]C:R[-1]C)"

    Range("F29").Select
    ActiveCell.Formula2R1C1 = "=+countbycolor(R4C1,R[-24]C:R[-1]C)"

    Range("F30").Select
    ActiveCell.Formula2R1C1 = "=+countbycolor(R7C1,R[-24]C:R[-1]C)"

    Range("F31").Select
    ActiveCell.Formula2R1C1 = "=+countbycolor(R6C1,R[-24]C:R[-1]C)"

    Range("F57").Select
    ActiveCell.Formula2R1C1 = "=+countbycolor(R2C1,R[-24]C:R[-1]C)"

    Range("F58").Select
    ActiveCell.Formula2R1C1 = "=+countbycolor(R5C1,R[-24]C:R[-1]C)"

    Range("F59").Select
    ActiveCell.Formula2R1C1 = "=+countbycolor(R3C1,R[-24]C:R[-1]C)"

    Range("F60").Select
    ActiveCell.Formula2R1C1 = "=+countbycolor(R4C1,R[-24]C:R[-1]C)"

    Range("F61").Select
    ActiveCell.Formula2R1C1 = "=+countbycolor(R7C1,R[-24]C:R[-1]C)"

    Range("F62").Select
    ActiveCell.Formula2R1C1 = "=+countbycolor(R6C1,R[-24]C:R[-1]C)"

    Range("F88").Select
    ActiveCell.Formula2R1C1 = "=+countbycolor(R2C1,R[-24]C:R[-1]C)"

    Range("F89").Select
    ActiveCell.Formula2R1C1 = "=+countbycolor(R5C1,R[-24]C:R[-1]C)"

    Range("F90").Select
    ActiveCell.Formula2R1C1 = "=+countbycolor(R3C1,R[-24]C:R[-1]C)"

    Range("F91").Select
    ActiveCell.Formula2R1C1 = "=+countbycolor(R4C1,R[-24]C:R[-1]C)"

    Range("F92").Select
    ActiveCell.Formula2R1C1 = "=+countbycolor(R7C1,R[-24]C:R[-1]C)"

    Range("F93").Select
    ActiveCell.Formula2R1C1 = "=+countbycolor(R6C1,R[-24]C:R[-1]C)"

    Range("F119").Select
    ActiveCell.Formula2R1C1 = "=+countbycolor(R2C1,R[-24]C:R[-1]C)"

    Range("F120").Select
    ActiveCell.Formula2R1C1 = "=+countbycolor(R5C1,R[-24]C:R[-1]C)"

    Range("F121").Select
    ActiveCell.Formula2R1C1 = "=+countbycolor(R3C1,R[-24]C:R[-1]C)"

    Range("F122").Select
    ActiveCell.Formula2R1C1 = "=+countbycolor(R4C1,R[-24]C:R[-1]C)"

    Range("F123").Select
    ActiveCell.Formula2R1C1 = "=+countbycolor(R7C1,R[-24]C:R[-1]C)"

    Range("F124").Select
    ActiveCell.Formula2R1C1 = "=+countbycolor(R6C1,R[-24]C:R[-1]C)"

    Range("F150").Select
    ActiveCell.Formula2R1C1 = "=+countbycolor(R2C1,R[-24]C:R[-1]C)"

    Range("F151").Select
    ActiveCell.Formula2R1C1 = "=+countbycolor(R5C1,R[-24]C:R[-1]C)"

    Range("F152").Select
    ActiveCell.Formula2R1C1 = "=+countbycolor(R3C1,R[-24]C:R[-1]C)"

    Range("F153").Select
    ActiveCell.Formula2R1C1 = "=+countbycolor(R4C1,R[-24]C:R[-1]C)"

    Range("F154").Select
    ActiveCell.Formula2R1C1 = "=+countbycolor(R7C1,R[-24]C:R[-1]C)"

    Range("F155").Select
    ActiveCell.Formula2R1C1 = "=+countbycolor(R6C1,R[-24]C:R[-1]C)"

    Range("F181").Select
    ActiveCell.Formula2R1C1 = "=+countbycolor(R2C1,R[-24]C:R[-1]C)"

    Range("F182").Select
    ActiveCell.Formula2R1C1 = "=+countbycolor(R5C1,R[-24]C:R[-1]C)"

    Range("F183").Select
    ActiveCell.Formula2R1C1 = "=+countbycolor(R3C1,R[-24]C:R[-1]C)"

    Range("F184").Select
    ActiveCell.Formula2R1C1 = "=+countbycolor(R4C1,R[-24]C:R[-1]C)"

    Range("F185").Select
    ActiveCell.Formula2R1C1 = "=+countbycolor(R7C1,R[-24]C:R[-1]C)"

    Range("F186").Select
    ActiveCell.Formula2R1C1 = "=+countbycolor(R6C1,R[-24]C:R[-1]C)"

    Range("F212").Select
    ActiveCell.Formula2R1C1 = "=+countbycolor(R2C1,R[-24]C:R[-1]C)"

    Range("F213").Select
    ActiveCell.Formula2R1C1 = "=+countbycolor(R5C1,R[-24]C:R[-1]C)"

    Range("F214").Select
    ActiveCell.Formula2R1C1 = "=+countbycolor(R3C1,R[-24]C:R[-1]C)"

    Range("F215").Select
    ActiveCell.Formula2R1C1 = "=+countbycolor(R4C1,R[-24]C:R[-1]C)"

    Range("F216").Select
    ActiveCell.Formula2R1C1 = "=+countbycolor(R7C1,R[-24]C:R[-1]C)"

    Range("F217").Select
    ActiveCell.Formula2R1C1 = "=+countbycolor(R6C1,R[-24]C:R[-1]C)"

        strFormulas(1) = "+countbycolor(R2C1,R[-24]C:R[-1]C)"
        strFormulas(2) = "+countbycolor(R5C1,R[-24]C:R[-1]C)"
        strFormulas(3) = "+countbycolor(R3C1,R[-24]C:R[-1]C)"
        strFormulas(4) = "+countbycolor(R4C1,R[-24]C:R[-1]C)"
        strFormulas(5) = "+countbycolor(R7C1,R[-24]C:R[-1]C)"
        strFormulas(6) = "+countbycolor(R6C1,R[-24]C:R[-1]C)"

        Range("F26:AG31").FillRight
        Range("F57:AG62").FillRight
        Range("F88:AG93").FillRight
        Range("F119:AG124").FillRight
        Range("F150:AG155").FillRight
        Range("F181:AG186").FillRight
        Range("F212:AG217").FillRight

    Range("A2").Select
    ActiveCell.FormulaR1C1 = "1ST"
    Range("A3").Select

A: One approach is below
Sub SetFormulas()
    With ActiveSheet
        For Each cl In Application.Intersect(.Columns("E"), .UsedRange)
            ' found upper row of the data in table
            If cl.Text = "Agent" Then Set Start = cl.Offset(1)
            ' found the place for formulas under table
            If UCase(cl.Text) = "1ST" Then
                If Not Start Is Nothing Then
                    ' rows between header "Agent" and "1ST" formula
                    Delta = Start.Row - cl.Row
                    ' loop for each color (category) cell
                    For i = 2 To 7
                        ' next statement construct the formula for whole row
                        cl.Offset(i - 2, 1).Resize(1, 31).FormulaR1C1 = _
                            "=countbycolor(R" & i & "C1,R[" & (Delta - i + 2) & "]C:R[" & (1 - i) & "]C)"
                    Next i
                    ' reset Start cell before next table
                    Set Start = Nothing
                End If
            End If
        Next cl
    End With
End Sub


text:
Q: Android Facebook SDK and authenticating on my server I am trying to setup login on my app using facebook. Currently I have the SDK working fine, it authenticates and I can accession user information and then I start an Intent to my activity. (not sure if this is what I should be doing)
Now I am wondering what the workflow is for this is to authenticate with my RestAPI.
I can post the facebook_id to my server and add to my users database but I then read that I should be using the AccessToken, but how do I know if this is the correct AccessToken for that user?
What should be the flow here? Where should I be posting to the server and what should I be posting for every request in every Activity?
Here is my code I currently have.
private Session.StatusCallback statusCallback = new Session.StatusCallback() {
    @Override
    public void call(final Session session, SessionState sessionState, Exception e) {
        if (sessionState.isOpened()) {
            Request.newMeRequest(session, new Request.GraphUserCallback() {
                @Override
                public void onCompleted(GraphUser graphUser, Response response) {
                    if (graphUser != null) {
                        Log.w(TAG, graphUser.getFirstName() + ' ' + graphUser.getId());
                        Log.w(TAG, session.getAccessToken() + ' ' + session.getExpirationDate());
                        Intent intent = new Intent(LoginActivityFragment.this, MainActivity.class);
                        startActivity(intent);
                    }
                }
            }).executeAsync();
        } else if (sessionState.isClosed()) {

        }
    }
};

A: You should use the user ID as the unique identifier. The access token can change under many situations (updated permissions, user log in/out, etc), and should not be used to identify someone. The user ID will remain stable within your app.
You can send the access token along with the ID to your server, perhaps to make some FB requests from the server side, but that's a separate issue.


text:
Q: do you need wifi or 3G for CLLocationManager getting current location? - iphone Can CLLocationManager getCurrentLocation work without wifi or a cellular network? with the inbuilt GPS?
Thanks.

A: For iPod Touch, yes.
For iPhone, no.
iPod Touch doesn't have a built-in GPS receiver and it uses WiFi hot spot signatures for approximation.
The iPhone does have a built-in GPS receiver, so it works fine without 3G or WiFi.
Proof? Drive down the thruway and you'll go outside of 3G/Edge network, but Google Maps still tracks your current location.

A:
I cannot find any documentation that confirms either yes or no, but from my experience I'd say yes. Core Location uses cell towers, wifi, and gps together to find your location so if one or two of the services are unavailable I would assume the system would use whatever resource it can. If it doesn't seem to work, it could be (I'm just guessing here) that you have to set the desired accuracy to something high (try kCLLocationAccuracyBest) in order for GPS to kick in.
If you haven't already, check out the video "What's new in Core Location" https://developer.apple.com/videos/wwdc/2011/index.php

A: if you want to get the gps go to maps, after turning the 3g and wifi off, and click the location icon on the bottom. then you will see loading and then it will give you the current location


text:
Q: Unir 2 columnas en una sola DataTable y aplicar un if en columna status Estoy empezando con el uso de DataTable y poseo 2 consultas:
Consulta 1
Estoy migrando un proyecto que esta escrito 100% en PHP pero por la cantidad de datos en la Base de Datos (BD) ya es necesario tratar los datos con ajax y estoy muy novato en ese lenguaje.
Mi problema es el siguiente.
Tengo una tabla:

        ID Pedido
        Fecha de su Pedido
        Monto
        Banco Emisor / Nro. de Transferencia
        Status

Y mi código js que genera los datos:
$(document).ready(function() {
     listar();
 });

var listar = function(){
    var table = $('#dt_pedidos').DataTable({

        "language": idioma_espanol,
        "ajax": {
            "method":"POST",
            "url":"funciones/listar_t.php"
        },
        "columns":[
            {"data":"id"},
            {"data":"fecha_pedido"},
            {"data":"monto"},
            //{"data":"banco_emisor"},
            //{"data":"nro_transf"},
            {"data":"banco_emisor", "data": 'nro_transf'},
            {"data":"status_pedido"}
        ]

});
//console.log(table);

}
No he logrado unir ambos datos para que se muestren en una sola columna, de momento como solución temporal he optado por crear 2 columnas diferentes una para "data":"banco_emisor" y otra para "data": 'nro_transf' pero quisiera mostrar estos datos en una sola columna.
He intentado lo sugerido en: Como juntar 2 columnas en un datatables sin éxito al igual que he tratado de hacer un render pero me da como resultado que el dato es undefined imagino que he tratado de aplicar una solución de una forma incorrecta.
Consulta 2
Por último la columna status lógicamente me trae los resultados esperados que son los que están en mi BD en dicha columna trae como resultado letras que son: E, C, E y R.
Las letras corresponden a:
E = Esperando
C = Conformado
E = Entrega
R = Rechazado

ESPERANDO = '

      EN ESPERA

'

CONFORMADO = '

       CONFORMADO

'

RECHAZADO = '
             RECHAZADO

';

ENTREGA = '<form autocomplete="off" class="was-validated" method="get" action= "ver_pedido.php?id_pedido='.{"data":"id"}.'">
            <input type="hidden" name="id_pedido" value="'.{"data":"id"}.'">
            <button data-html="true" data-toggle="popover" title="SECCION DE DESCARGAS" data-content="Aca podra acceder a su pedido." type="submit" class="btn btn-success" >DESCARGAR  </button> </form>'

Como hago para mostrar en DataTable la salida esperada según el resultado de: {"data":"status_pedido"}.

A: Suponiendo que recibes un json correcto desde listar_t.php donde haces un query y obtienes los campos que quieres imprimir en la tabla: id, fecha_pedido, monto, banco_emisor, nro_transf, status_pedido. Lo que sugiero hacer es manipular el json a travez de un array y un bucle $.each, para formatear la tabla de la manera que deseas:
$.ajax({
    url: "funciones/listar_t.php",
    type: "POST",
    dataType: "json",
    success: function (data, textStatus, jqXHR) {
        var datos = [];
        $.each(data, function (i, col) {
            var status="";
            //validamos el campo de la consulta 2
            switch(col.status_pedido){
                 case 'E':{
                    status = '

                                  EN ESPERA

';
                    break;
                 }
                 case 'C':{
                    status = '

                               CONFORMADO

';
                    break;
                 }
                 case 'E':{
                    status= '<form autocomplete="off" class="was-validated" method="get" action= "ver_pedido.php?id_pedido='.{"data":"id"}.'">
                    <input type="hidden" name="id_pedido" value="'.{"data":"id"}.'">
                    <button data-html="true" data-toggle="popover" title="SECCION DE DESCARGAS" data-content="Aca podra acceder a su pedido." type="submit" class="btn btn-success" >DESCARGAR  </button> </form>';
                    break;
                 }
                 case 'R':{
                    status = '
                                 RECHAZADO

';
                 }
            }
            datos.push([col.id, col.fecha_pedido, col.monto, col.banco_emisor + ' ' + col.nro_transf, status ]); //Aqui hacemos un push al arreglo vacio, para añadir los cambios
        });

        $('#dt_pedidos').DataTable({
            destroy: true,
            data: datos,  //pasamos el arreglo
            columns: [
                {title: "ID Pedido"},  //generamos las columnas
                {title: "Fecha de su Pedido"},
                {title: "Monto"},
                {title: "Banco Emisor / Nro. de Transferencia"},
                {title: "Status"}
            ]
        });
    },
    error: function (jqXHR, textStatus, errorThrown) {
        //codigo en caso de error ajax
    }
});

Y el html de tu tabla quedaría mas sencillo, ya que el constructor de DataTable, te formara la tabla:

A: En la $consulta haces la union de las columnas que necesitas y en el recorrido del arreglo de la consulta compuebas si ROW['status'] es = C,R, etc dependiendo de como estén almacenados en la BD, despues en una variable $tabla obtienes los campos que deseas llamar en el script de dataTables (Sólo hice el if del status C)
<?php

        include('comexion_db.php');
        $consulta = "SELECT tabla1.status,tabla2.otro_campo
                     FROM tabla1
                     LEFT JOIN tabla2 ON tabla1.id_tabla = tabla2.id_tabla;";
        $registro = mysqli_query($con, $consulta);

        $i=1;
        $tabla = "";
        while ($row = mysqli_fetch_array($registro)) {

            if ($row['status'] == 'C') {

                $status = '

          EN ESPERA

';
            }

        $tabla.='{"otro_campo":"'.$row['otro_campo'].'","status":"'.$status.'"},';
        $i++;

        }

        $tabla = substr($tabla,0, strlen($tabla) - 1);

        echo '{"data":['.$tabla.']}';
    ?>

A: Para mi primera consulta he solucionado con el siguiente código:
{
            "data": "banco_emisor",
            "render": function ( data, type, row ) {
                if(type === 'display'){
                    return row.banco_emisor + " " + row.nro_transf;
                }else{
                    return data;
                }
            }
        },

Lo he logrado cambiando la linea return data.banco_emisor + " " + data.nro_transf; por return row.banco_emisor + " " + row.nro_transf;
Para mi segunda consulta lo he solucionado desde el While de mi query, he efectuado una serie de if que imprimen la linea de código según sea el caso.


text:
Q: Removing dynamic controls from panel not working After this "foreach" done, there is still buttons into panelGroups.Controls
foreach (Button button in panelGroups.Controls)
{
    panelGroups.Controls.Remove(button);
}

Debug mode in Visual Studio:

A: The code you show is very error prone:

*

*If there is a Control in your panelGroups.Controls that is no Button and not inherited from Button, your code will throw an InvalidCastException. That is because you try to cast every Control in that panel into a Button, which will fail for example for a Label

*You try to change an enumeration (by calling Remove) while you are iterating through it. This causes an InvalidOperationException.
You better try it that way:
foreach(Button button in panelGroups.Controls.OfType<Button>().ToList())
    panelGroups.Controls.Remove(button);

By using OfType<Button>() you select only the controls from the panel that really are Button.
By calling ToList() you complete that iteration to select the buttons from Controls before starting the iteration over the resulting Button set.
This way you would avoid the exceptions and your code should work.
Note however that this only works for Buttons that are directly contained in your panelGroups. If you have other containers (like panels or groupboxes) inside that panel that contain more buttons, these buttons are not enumerated this way. You would have to recurse down through the containers and remove these buttons from the containers' Controls collection.


text:
Q: Support for multiple environments in JavaFX + Spring Boot + Hibernate application I am building a JavaFX application in Spring Boot with hibernate. It connects to the database to display some data, currently it takes the connection details from properties file and loads sessionFactory, datasource and transaction manager beans using pure Java config. However, I have multiple databases sitting on multiple remote machines, each has a different IP and user details. Ideally I would like to display a login form which prompts for db username and password on the application startup. I do not want to read those details from the file. It possible? I would really appreciate some help with this issue.
Edit:
Managed to achieve this, in my login controller I simply implement ApplicationContextAware and then load register beans manually using data from textfields.

A: You can use a Spring Boot Active Profile features
Depending on your current profile PROD, DEV, PRE-PROD you can active a certain configration with a given application.properties file. You can find here a complete How to
EDIT 2 :
If you want to change the whole configuration base on user input (for example it's credentials) you have to change dynamically properties and it appears that @RefreshScope does the work.
Bad news is that this annotation aappears to only exists in Spring Cloud

A: That is my solution, the only drawback is that I am not able to log in after unsuccessful login attempt. It works fine but if I first use incorrect login credentials and then correct ones it throws an exception saying that EntityManagerFactory is closed. (I do remove bean definitions in my  catch block, just wanted to make code shorter)
@Component
public class LoginController implements Initializable, ApplicationContextAware{

    @FXML
    private AnchorPane login;
    @FXML
    private JFXTextField dbUsernameTextField;
    @FXML
    private JFXPasswordField dbPasswordTextField;
    @FXML
    private JFXTextField boxUsernameTextField;
    @FXML
    private JFXPasswordField boxPasswordTextField;
    @FXML
    private JFXComboBox<ComboItem> environmentComboBox;
    @FXML
    private JFXButton loginButton;
    @Autowired
    private Environment environment;

    @Autowired
    private OrderService orderService;

    private AnnotationConfigApplicationContext context;
    @Override
    public void initialize(URL location, ResourceBundle resources) {
        loginButton.setDisable(true);
        List<ComboItem> envs=new ArrayList<ComboItem>();
        String[]environments=environment.getProperty("environments").split(",");
        for(String s:environments) {
            environmentComboBox.getItems().add(new ComboItem(s.toUpperCase(),s));
        }
        environmentComboBox.setConverter(new StringConverter<ComboItem>() {
            @Override
            public String toString(ComboItem object) {
                return object.getKey();
            }
            @Override
            public ComboItem fromString(String string) {
                return null;
            }
        });
    }

    @FXML
    public void selectEnvironment() {
        if(!environmentComboBox.getSelectionModel().isEmpty())
            loginButton.setDisable(false);
    }

    @FXML
    public void authenticate(ActionEvent actionEvent) {

        String boxUsername=boxUsernameTextField.getText();
        String boxPassword=boxPasswordTextField.getText();
        try {
            context.registerBean("dataSource",DataSource.class,()->dataSource());
            context.registerBean("sessionFactory", LocalSessionFactoryBean.class,()->sessionFactory());
            context.registerBean("transactionManager",HibernateTransactionManager.class,()->getTransactionManager());

            Order order=orderService.findById("");

            FXMLLoader fxmlLoader=new FXMLLoader(getClass().getResource("/fxml/Main.fxml"));
            fxmlLoader.setControllerFactory(context::getBean);
            Parent rootNode=fxmlLoader.load();
            Stage stage=(Stage) login.getScene().getWindow();
            Scene scene=new Scene(rootNode,400,300);
            stage.setScene(scene);
            stage.setTitle("Login");
            stage.setMaximized(true);
            stage.show();
            stage.setOnCloseRequest(event->JSchConnection.close());
        }catch(Exception e) {
        context.removeBeanDefinition("dataSource");
        context.removeBeanDefinition("sessionFactory");
        context.removeBeanDefinition("transactionManager");

            e.printStackTrace();
        }

    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context=(AnnotationConfigApplicationContext) applicationContext;
    }

    private  Properties hibernateProperties() {
        Properties properties = new Properties();
        properties.put("hibernate.dialect", "org.hibernate.dialect.Oracle10gDialect");
        properties.put("hibernate.show_sql", "false");
        properties.put("hibernate.format_sql", "true");
        properties.put("hibernate.hbm2ddl.auto", "none");
        return properties;
    }

    public  DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("oracle.jdbc.OracleDriver");
        dataSource.setUrl("myurl");
        dataSource.setUsername(dbUsernameTextField.getText());
        dataSource.setPassword(dbPasswordTextField.getText());
        return dataSource;
    }

    public  LocalSessionFactoryBean sessionFactory() {
        LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
        sessionFactory.setDataSource(dataSource());
        sessionFactory.setPackagesToScan(new String[] { "com.mypackage" });
        sessionFactory.setHibernateProperties(hibernateProperties());
        return sessionFactory;
    }

    public HibernateTransactionManager getTransactionManager() {
        HibernateTransactionManager transactionManager = new HibernateTransactionManager();
        transactionManager.setSessionFactory(context.getBean(SessionFactory.class,"sessionFactory"));
        return transactionManager;
    }

}


text:
Q: Controlling motor EMI - more ferrite turns or shorter cables? In wiring up a small robot, powered by two BLDC motors (of the "hoverboard" variety), I was going to shorten the leads a bit, and wrap them one turn around a soft-core ferrite for EMI supression.
Then I thought: wouldn't it be better to leave the wire longer and just wrap it more times through the ferrite?
What is the appropriate trade-off?


text:
Q: Ruby gem to "lock" an accepted agreement I am looking for a Ruby gem to lock an agreement digitally. In other words, when a user clicks "I have read and accept the agreement", I would like to be able to save a copy of the agreement right at the time the user accepted and be able to later on prove that that was indeed a copy of the agreement at that time (in other words make it tamper proof).

A: I think this is not possible. If you are able to create this prove yourself then you are also able to recreate that proof with a different content or any timestamp.
But there are services that add digital signatures to your document. If both sides (or a court) also trusts this service provider then this might be a way: https://en.wikipedia.org/wiki/Digital_signature
The basic idea is: After the user agreed, you send all interesting pieces or information (content of agreement, ip address, timestamp, user address, etc.) to the service. The services returns you a signed version of that document. This works as a proof, since you are unable to change that document later on.


text:
Q: How to run/start VsCode on Centos 7 I'm a beginner studying centos.
I installed centos and vscode, but there's no response when I click the vscode icon.
And when i enter the [code] at the terminal, only an error message comes out and it can't be executed (the screen below).
And if you look at the top left of my screen, it says [Activities]. Is this normal?
I saw [Applications] other centos image
enter image description here
enter image description here

A: Both problems stem from logging in as the root user. This is not a good idea for many reasons (e.g., security, desktop shortcuts do not work correctly, etc.), and, once deployed, your program may not work correctly for non-privileged users.
If you need to run as root, the command from the Terminal is:
code "/home/<your default username>/<optional projects directory>" --user-data-dir="." --no-sandbox
Output:

However, if you have no reason to use root over sudo, I strongly recommend you log out as root, and run VS Code as a regular user. Also, VS Code will continue to warn you about being root.
As far as the Gnome desktop, Applications on CentOS 7 and Activities on CentOS 8+.


text:
Q: Applescript - Recursively step through directories I have found similar solutions like this:
property theOpenFile : missing value

tell application "Finder" to set theSel to selection
if theSel is not {} then
    set pathToYourTextFile to (path to desktop folder as string) & "SampleTextFile2.txt"
    set theOpenFile to open for access file (pathToYourTextFile as string) with write permission
    repeat with aItem in theSel
        tell application "Finder" to class of aItem is folder
        if the result then my getFilesIn(aItem) -- aItem is a folder
    end repeat
    close access theOpenFile
end if

on getFilesIn(thisFolder)
    tell application "Finder" to set theseFiles to files of thisFolder as alias list
    repeat with thisFile in theseFiles
        set f to thisFile as string
        set pathLength to length of f
        if pathLength > 255 then my writeToFile(f)
    end repeat
    tell application "Finder" to set theseSubFolders to folders of thisFolder
    repeat with tSubF in theseSubFolders
        my getFilesIn(tSubF) -- call this handler (recursively through this folder)
    end repeat
end getFilesIn

on writeToFile(t)
    write (t & return) to theOpenFile starting at eof
end writeToFile

They all work in with a file reference in alias format. As I understand I cannot change the filename of the original in this case, or delete it, etc. and thats what I want to do.
Am I right ? If yes what else can I do ?

A: You can rename and delete files, the Finder can handle alias specifiers
repeat with thisFile in (get theseFiles) -- you need get to capture the reference list
    set f to thisFile as string
    set pathLength to length of f
    if pathLength > 255 then my writeToFile(f)
    tell application "Finder" to set name of thisFile to "foo.txt"
    -- or
    tell application "Finder" to delete thisFile
end repeat

or rather than an alias you can use Finder file specifiers
repeat with thisFile in (get theseFiles)
    set f to thisFile as string
    set pathLength to length of f
    if pathLength > 255 then my writeToFile(f)
    tell application "Finder" to set name of file f to "foo.txt"
    -- or
    tell application "Finder" to delete file f
end repeat


text:
Q: Clicking on divs doesn't scroll to elements as it should using jQuery I have the following code with click handlers:

$(document).ready(function() {
  $('.black-btn').click(function() {
    $('.popup-cats-wrapper').animate({
      scrollTop: $(".black-anchor").offset().top - 100
    }, 400)
  });
  $('.red-btn').click(function() {
    $('.popup-cats-wrapper').animate({
      scrollTop: $(".red-anchor").offset().top - 100
    }, 400)
  });
  $('.green-btn').click(function() {
    $('.popup-cats-wrapper').animate({
      scrollTop: $(".green-anchor").offset().top - 100
    }, 400)
  });
  $('.blue-btn').click(function() {
    $('.popup-cats-wrapper').animate({
      scrollTop: $(".blue-anchor").offset().top - 100
    }, 400)
  });

});
body {
  font-size: 12px;
  font-family: "sans";
}

.hero-categories-wrap {
  overflow: hidden;
  height: 200px;
}

.popup-cats-wrapper {
  height: 200px;
  width: 300px;
  background: #aaa;
  display: inline-block;
  padding-top: 20px;
  padding-left: 20px;
  padding-right: 20px;
  padding-bottom: 0px;
  overflow-x: auto;
}

.categories-sidebar {
  width: 120px;
  background: #ececef;
  height: 200px;
  padding-top: 20px;
  float: left;
}

.popup-menu-row {
  padding: 5px 8px;
  color: #212121;
  font-weight: 600;
  cursor: pointer;
  border-radius: 25px;
  margin-bottom: 5px;
}

.color-block {
  margin-bottom: 10px;
  margin-top: 25px;
}

.cat-title {
  font-weight: 600;
  font-size: 12px;
  color: #000;
  margin-bottom: 15px;
}

BLACK

RED

GREEN

BLUE

BLACK COLOR

Black is the darkest color, the result of the absence or complete absorption of visible light. It is an achromatic color, a color without hue, like white and gray.

RED COLOR

Red is the color at the end of the visible spectrum of light, next to orange and opposite violet. It has a dominant wavelength of approximately 625–740 nanometres. It is a primary color in the RGB color model and the CMYK color model, and is the
        complementary color of cyan.

GREEN COLOR

Green is the color between blue and yellow on the visible spectrum. It is evoked by light which has a dominant wavelength of roughly 495–570 nm.

BLUE COLOR

Blue is one of the three primary colours of pigments in painting and traditional colour theory, as well as in the RGB colour model. It lies between violet and green on the spectrum of visible light. The eye perceives blue when observing light with
        a dominant wavelength between approximately 450 and 495 nanometres. Most blues contain a slight mixture of other colours; azure contains some green, while ultramarine contains some violet.

Unfortunately when i click on any of the buttons(divs) at the left side, the anchor links at the right side have very strange behavior. On the other hand if you try to click the same btn (eg green-btn) more than once it scrolls the content up and down !
What i 'm doing wrong?

A: Your issue is that .offset().top is giving you the current offset that element is to its parent, which you then use to set the parents scrollTop to. What you need to do is add the elements .offset().top to the current scrollTop of the parent.

$(document).ready(function() {

  var $wrapper = $('.popup-cats-wrapper');

  $('.black-btn').click(function() {
    $wrapper.animate({
      scrollTop: $wrapper.scrollTop() + $(".black-anchor").offset().top - 10
    }, 400)
  });
  $('.red-btn').click(function() {
    $wrapper.animate({
      scrollTop: $wrapper.scrollTop() + $(".red-anchor").offset().top - 10
    }, 400)
  });
  $('.green-btn').click(function() {
    $wrapper.animate({
      scrollTop: $wrapper.scrollTop() + $(".green-anchor").offset().top - 10
    }, 400)
  });
  $('.blue-btn').click(function() {
    $wrapper.animate({
      scrollTop: $wrapper.scrollTop() + $(".blue-anchor").offset().top - 10
    }, 400)
  });

});
body {
  font-size: 12px;
  font-family: "sans";
}

.hero-categories-wrap {
  overflow: hidden;
  height: 200px;
}

.popup-cats-wrapper {
  height: 200px;
  width: 300px;
  background: #aaa;
  display: inline-block;
  padding-top: 20px;
  padding-left: 20px;
  padding-right: 20px;
  padding-bottom: 0px;
  overflow-x: auto;
}

.categories-sidebar {
  width: 120px;
  background: #ececef;
  height: 200px;
  padding-top: 20px;
  float: left;
}

.popup-menu-row {
  padding: 5px 8px;
  color: #212121;
  font-weight: 600;
  cursor: pointer;
  border-radius: 25px;
  margin-bottom: 5px;
}

.color-block {
  margin-bottom: 10px;
  margin-top: 25px;
}

.cat-title {
  font-weight: 600;
  font-size: 12px;
  color: #000;
  margin-bottom: 15px;
}

BLACK

RED

GREEN

BLUE

BLACK COLOR

Black is the darkest color, the result of the absence or complete absorption of visible light. It is an achromatic color, a color without hue, like white and gray.

RED COLOR

Red is the color at the end of the visible spectrum of light, next to orange and opposite violet. It has a dominant wavelength of approximately 625–740 nanometres. It is a primary color in the RGB color model and the CMYK color model, and is the
        complementary color of cyan.

GREEN COLOR

Green is the color between blue and yellow on the visible spectrum. It is evoked by light which has a dominant wavelength of roughly 495–570 nm.

BLUE COLOR

Blue is one of the three primary colours of pigments in painting and traditional colour theory, as well as in the RGB colour model. It lies between violet and green on the spectrum of visible light. The eye perceives blue when observing light with
        a dominant wavelength between approximately 450 and 495 nanometres. Most blues contain a slight mixture of other colours; azure contains some green, while ultramarine contains some violet.


text:
Q: Listbox content not dynamically re-sizing when Listbox size changes I've seen quite a few people asking this question and i feel like my question is slightly different. I have a listbox that holds a series of identical custom made user controls. These controls are added to the listbox at runtime. Now i currently have my listbox items resizing themselves properly upon first creation and insertion into the control.
Here is the strange part. If I resize the listbox the controls that have been visible previously are not resized to the new listbox width. In other words if i add 12 controls and the box only shows 4 (the rest are hidden by a scrollbar) then if i resize the box the first 4 controls will still be the original width and if i scroll then the other 8 will be the correct size. Also if i manipulate the list items in any way they resize themselves to the proper width automatically.   SEE EDIT2
I've tried attaching to the sizeChanged event and issuing the following on both the listbox and the items but it has had no effect. I think i need to find some way of resetting the layout information for the listbox items but i can't find the command.
item.InvalidateArrange();
item.InvalidateMeasure();
Layers.UpdateLayout();
item.UpdateLayout();

I think this has something to do with the items i'm adding because even if i detach the items from the lisbox and then attach them they remain the wrong width.
Here is my listbox code:
<ListBox x:Name="Layers" VerticalContentAlignment="Top" Margin="0,17,0,0" BorderThickness="0,1,0,0" HorizontalContentAlignment="Stretch" SizeChanged="Layers_SizeChanged">
                        <ListBox.ItemContainerStyle>
                            <Style TargetType="ListBoxItem">
                                <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
                            </Style>
                        </ListBox.ItemContainerStyle>
                    </ListBox>

Here is the code for my items
<UserControl x:Class="ListOverlayItem"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:data="clr-namespace:Data"
HorizontalContentAlignment="Stretch">

<UserControl.Resources>
    <data:Translator x:Key="translatorString" />
</UserControl.Resources>

<Border BorderBrush="Silver" BorderThickness="0,0,0,0" Name="border1" HorizontalAlignment="Stretch">
    <Grid x:Name="layout" HorizontalAlignment="Stretch">
        <Grid.RowDefinitions>
            <RowDefinition Height="19"/>
            <RowDefinition Height="25" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="20" />
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="60" />
        </Grid.ColumnDefinitions>
        <!-- Column 0 -->
        <ScrollBar Name="arrangeIcon" FlowDirection="LeftToRight" Maximum="10" SmallChange="1" Value="5" Grid.Column="0" Grid.Row="0" Grid.RowSpan="2"/>

        <!-- Column 1 -->
        <Slider  Name="OverlayOpacity" Height="25" Grid.Column="1" Margin="6,0,0,0" Grid.Row="1"  Maximum="1" LargeChange="0.1" ValueChanged="OverlayOpacity_ValueChanged"/>
        <TextBlock x:Name="OverlayName" Text="{Binding Path=LocationName}" Foreground="#FFF08D2D" Margin="10,2,0,0" Grid.Column="1" FontSize="12" Height="18" VerticalAlignment="Top" />

        <!-- Column 3 -->
        <Button Name="SettingsButton" Grid.Column="3" Content="{Binding TRK_OV_Settings, Source={StaticResource translatorString}}" VerticalAlignment="Center" Click="SettingsButton_Click" />
        <CheckBox x:Name="OverlayEnabled" FlowDirection="LeftToRight" Grid.Column="2" DataContext="{Binding}" HorizontalAlignment="Right" VerticalAlignment="Center" Grid.RowSpan="2" Checked="OverlayEnabled_Checked" Unchecked="OverlayEnabled_Unchecked" />
        <TextBlock Name="percentage" Text="100%" FontSize="9" TextAlignment="Right" Grid.Column="2" Grid.Row="1" VerticalAlignment="Center" Margin="2,6,26,6" MinWidth="30"/>
    </Grid>
</Border>

Again it seems like my UserControl is correctly able to scale itself its just not getting the command to do so when the parent container is resized.
EDIT: Whoops, removed the WPF tag because it was incorrectly added. I think i've got it down to slider being the culprit. If i set the slider to a fixed size instead of 'stretch' then the item correctly scales just fine. So the question now is how do i force the slider to resize itself.
EDIT2: I know what is causing the issue but i don't know how to solve it. What is happening is the slider that i have in my user control will NOT resize along with the rest of the control unless i change the value of the slider during the resize. The instant i change its value even a fraction it resizes itself automatically. How can i force it to resize?

A: I determined that the slider was causing the issue and i tried many ways to force the slider to re-draw when it needed to but i was unsuccessful. My final solution was to remove the slider entirely. Works fine now.


text:
Q: Напишите функцию, которая принимает строку и возвращает массив слов Напишите функцию, которая принимает строку и возвращает массив слов.
Под словом подразумеваются множество символов отличных от пробела. Между словами может стоять больше одного пробела.
Делаю что-то не так - потому что выводит ошибку: [Ljava.lang.String;@
Может кто-нибудь знает где я ошибаюсь....может совсем решение неверное. хотя по логике. вроде получаю слово..
Вот мой код
public static String[] split(String s){
        String [] array = s.split(" ");
        for (int i = 0; i < array.length; i++) {
            String word = array[i];
        }
        return array;
    }
public static void main(String[] args) {
        String s = "I am learning java";
        System.out.println(split(s));
    }

Подскажите пожалуйста, где именно я не верно пишу код
или пишу его не до конца
Текст ошибки: [Ljava.lang.String;@568db2f2

A: Это вовсе не ошибка, это вывод Вашего результата. Дело в том, что Java не умеет выводить массив в том виде, в котором Вы хотите. Если попытаться вывести объект массива просто через System.out.println();, он выводит некое описание объекта.
Во-первых, нужно из метода split удалить ненужный цикл, который не делает ничего.
Во-вторых, нужно сделать вывод всех полученных слов через цикл.
public class Main
{
    public static String[] split(String s){
        String [] array = s.split(" ");
        return array;
    }

    public static void main(String[] args) {
        System.out.println("Hello World");

        String s = "I am learning java";

        // Сохраняем результат разделения
        String[] words = split(s);
        // Перебираем каждый элемент массива
        for(String word : words) {
            System.out.println(word);
        }
    }
}

UPD:
Чтобы решение удовлетворяло условию того, что может быть несколько пробелов подряд нужно отфильтровать то, что вернёт метод String.split(), так как, при разделении по пробелам строки, содержащей множество пробелов, она вернёт массив, где будут тоже пробелы.
Приведу следующее решение. нужно импортировать пакет import java.util.*;
Далее, то, что возвращает метод s.split(" ") приводим к листу и этот лист фильтруем, посредством вызова метода filter((x -> !x.isEmpty()), что означает, вернуть только не пустые элементы списка (листа). Далее уже приводим результат к массиву строк toArray(String[]::new) и этот результат уже возвращаем.
import java.util.*;

public class Main
{
    public static String[] split(String s){
        List<String> words = Arrays.asList(s.split(" "));
        String[] filtered = words.stream().filter((x -> !x.isEmpty())).toArray(String[]::new);
        return filtered;
    }

    public static void main(String[] args) {
        System.out.println("Hello World");

        String s = "I am learning   java    many     spaces";

        // Сохраняем результат разделения
        String[] words = split(s);
        // Перебираем каждый элемент массива
        for(String word : words) {
            System.out.println(word);
        }
    }
}

Теперь даже на строку с множеством пробелом между словами "I am learning   java    many     spaces" он вернёт массив строк, который содержит только отдельные слова.
Более тривиальное решение, без использования лямбда-функциий, но с использованием коллекций, а конкретнее, ArrayList - динамического массива.
import java.util.ArrayList;

public class Main
{
    public static String[] split(String s){
        // сначала разделяем по пробелу и получаем массив
        String[] splitted = s.split(" ");
        // Далее, создаём пустой лист
        ArrayList<String> words = new ArrayList<String>();

        for (String row : splitted) {
            // проверяем каждое значение, не пустое ли оно и сохраняем только слова
            if (!row.isEmpty()) words.add(row);
        }

        String[] result = new String[words.size()];
        words.toArray(result);

        return result;
    }

    public static void main(String[] args) {
        System.out.println("Hello World");

        String s = "I am learning   java    many     spaces";

        // Сохраняем результат разделения
        String[] words = split(s);
        // Перебираем каждый элемент массива
        for(String word : words) {
            System.out.println(word);
        }
    }
}

Ну и в итоге - самое примитивное решение, без использования сложных методов, коллекций и лямбда-выражений, но с лишними циклами и дейсвтиями по подсчёту слов.
public class Main
{
    public static String[] split(String s){
        String[] splitted = s.split(" ");
        int wordsNumber = 0;

        for (String row : splitted) {
            // Подсчитываем сколько слов, без учёта пробелов
            if (!row.isEmpty()) wordsNumber++;
        }
        String[] words = new String[wordsNumber];
        int i = 0;
        for (String row : splitted) {
            // Теперь их сохраняем в массив слов
            if (!row.isEmpty()) {
                words[i] = row;
                i++;
            }
        }

        return words;
    }

    public static void main(String[] args) {
        System.out.println("Hello World");

        String s = "I am learning   java    many     spaces";

        // Сохраняем результат разделения
        String[] words = split(s);
        // Перебираем каждый элемент массива
        for(String word : words) {
            System.out.println(word);
        }
    }
}


text:
Q: GameObject initialization order I'm trying to develop my unity skills while working on some project. Basically I need a dynamic scroll view that will be populate with prefabs at runtime. Here is my object hierarchy:

27_MoreApps is the "holder" element that has Scroll View as it subelement. 27_MoreApps has a script attached(subclass of MonoBehaviour) that uses Start method to populate Content object with prefabs. For this reason the script that is attached to 27_MoreApps has reference to Content(set via scene editor). So, my question is - is it possible that Start method would be called before Content is initialized and cause NPE ?


text:
Q: Strange behaviour syncing between Outlook and Nokia Suite Until recently I was syncing contacts no problem, now suddenly after syncing, Nokia Suite tells me there was a problem. I must repair or reinstall Outlook. I have just repaired Outlook  with no difference. The message also mentions configuring my user account, but I can find no user account setting relevant to synchronising. The only user account settings I can find at all are in fact those on my GMail account in Outlook. That is my 'mail server.
The Nokia Suite message ends with a mysterious "Error code: 83860077" without telling where the error code originated.
PS: I am using the latest "Nokia Suite" 3.6.36, not Ovi Suite or anything. This problem seems very common with Ovi.