text:
Q: Issue when trying to send emails through Python OS: MacCatalinva V10.15.3
Python: 3.7.7
PiP: 20.0.2
Hey,
I'm new to coding so I'm not sure what this really means.
I'm trying to send emails via Python through Gmail, I've set my account to accept "Less secure app access" and followed the steps in this guide, but all I get is the following:
`[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1076)
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/smtplib.py", line 354, in send
self.sock.sendall(s)
OSError: [Errno 9] Bad file descriptor
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/mymac/Desktop/Test2.py", line 34, in
server.quit()
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/smtplib.py", line 984, in quit
res = self.docmd("quit")
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/smtplib.py", line 420, in docmd
self.putcmd(cmd, args)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/smtplib.py", line 367, in putcmd
self.send(str)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/smtplib.py", line 357, in send
raise SMTPServerDisconnected('Server not connected')
smtplib.SMTPServerDisconnected: Server not connected`
And this is my Code:
import smtplib
import ssl

sender_email = "myemailadress@gmail.com"
receiver_email = "myadress@hotmail.com"
message = """\
Subject: Hi there

This message is sent from Python."""

# Send email here

smtp_server = "smtp.gmail.com"
port = 587  # For starttls
sender_email = "myemailadress@gmail.com"
password = input("Type your password and press enter: ")

# Create a secure SSL context
context = ssl.create_default_context()

# Try to log in to server and send email
try:
    server = smtplib.SMTP(smtp_server, port)
    server.ehlo()  # Can be omitted
    server.starttls(context=context)  # Secure the connection
    server.ehlo()  # Can be omitted
    server.login(sender_email, password)
    # TODO: Send email here
except Exception as e:
    # Print any error messages to stdout
    print(e)
finally:
    server.quit()

A: 1)After this line:
server.login(sender_email, password)

make sure to send the message you have it.
For that:
server.sendmail(sender_email,receiver_email,message)

that's it, I hope.


text:
Q: tcpdump: always show numerical port numbers The option -n in tcpdump is useful. Sometimes I prefer to see IP addresses, and sometimes I prefer to have the IP addresses resolved into hostnames.
But never do I want to have port numbers translated into "names".
How can I always show port numbers as numbers, ie 53 and not domain.
If this is not possible, how could I patch tcpdump so that port numbers are always show numerically?
I am using tcpdump 4.9.3-1~deb10u2 on Debian 10.

A: There may be a -nn flag in the tcpdump that ships with Linux (the flags are not portable†; Centos Linux Stream has 4.9.3 which hopefully is the same as Debian) to prevent e.g. .22 from being shown as .ssh, but that also disables hostname lookups. So you're probably looking at a source code patch.
The -n flag is used for all sorts of things if you look at the source (addrtoname.c) so the simplest thing would probably be to invent a new flag, get support for that into tcpdump.c where the getopt processing happens and elsewhere (there's a struct, but you could probably just kluge in a global int Flag_Myflag; if you want), and then over in addrtoname.c modify the port conversion to not happen when your custom flag is present (there's a bunch of different ways you could combine it with -n or -nn or whatever, depending on what you want).
            if (Flag_Myflag) {
                    (void)snprintf(buf, sizeof(buf), "%d", port);
                    table->name = strdup(buf);
            } else
                    table->name = strdup(sv->s_name);

Downsides: you now get to manually update and patch your custom tcpdump for security vulnerabilities and whatnot, or not, which has risks.
† A coworker once tried to have me to enter Linux tcpdump flags; they did not know my desktop system was OpenBSD. It did not go well.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to dispatch an action and show the data in the app.js using react/redux I don't know how to load the data of the fetchLatestAnime action in the react app.js file.
My mission is to show the endpoint data that I am doing fetch.
I have already implemented the part of the reducers and action, which you can see in the part below. The only thing I need is to learn how to display the data.
App.js
import React from 'react';
import './App.css';

function App() {
  return (

  );
}

export default App;

actions/types.js
export const FETCHING_ANIME_REQUEST = 'FETCHING_ANIME_REQUEST';
export const FETCHING_ANIME_SUCCESS = 'FETCHING_ANIME_SUCCESS';
export const FETCHING_ANIME_FAILURE = 'FETCHING_ANIME_FAILURE';

actions/animesActions.js
import{
  FETCHING_ANIME_FAILURE,
  FETCHING_ANIME_REQUEST,
  FETCHING_ANIME_SUCCESS
} from './types';

import axios from 'axios';

export const fetchingAnimeRequest = () => ({
  type: FETCHING_ANIME_REQUEST
});

export const fetchingAnimeSuccess = (json) => ({
  type: FETCHING_ANIME_SUCCESS,
  payload: json
});

export const fetchingAnimeFailure = (error) => ({
  type: FETCHING_ANIME_FAILURE,
  payload: error
});

export const fetchLatestAnime = () =>{
  return async dispatch =>{
    dispatch(fetchingAnimeRequest());
    try{
      let res = await axios.get('https://animeflv.chrismichael.now.sh/api/v1/latestAnimeAdded');
      let json = await res.data;
      dispatch(fetchingAnimeSuccess(json));
    }catch(error){
      dispatch(fetchingAnimeFailure(error));
    }
  };
};

reducers/latestAnimeReducers.js
import {
  FETCHING_ANIME_FAILURE,
  FETCHING_ANIME_REQUEST,
  FETCHING_ANIME_SUCCESS
} from '../actions/types';

const initialState = {
  isFetching: false,
  errorMessage: '',
  latestAnime: []
};

const latestAnimeReducer = (state = initialState , action) =>{
  switch (action.type){
    case FETCHING_ANIME_REQUEST:
      return{
        ...state,
        isFetching: true,
      }
    case FETCHING_ANIME_FAILURE:
      return{
        ...state,
        isFetching: false,
        errorMessage: action.payload
      }
    case FETCHING_ANIME_SUCCESS:
      return{
        ...state,
        isFetching: false,
        latestAnime: action.payload
      }
    default:
      return state;
  }
};

export default latestAnimeReducer;

reducers/index.js
import latestAnimeReducers from './latestAnimeReducers'
import {combineReducers} from 'redux';

const reducers = combineReducers({
  latestAnimeReducers
});

export default reducers;

index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import resolvers from './redux/reducers/index';
import {createStore , applyMiddleware} from 'redux';
import {Provider} from 'react-redux';
import thunk from 'redux-thunk';

const REDUX_DEV_TOOLS = window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
const createStoreWithMiddleware = applyMiddleware(thunk)(createStore);
const store = createStoreWithMiddleware(resolvers , REDUX_DEV_TOOLS)

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
);

serviceWorker.unregister();

A: Ideally, this is how your app.js should look like. I created a working codesandbox for you here. Your initial latestAnime state was an empty array but the action payload you set to it is an object, so remember to pass payload.anime like i have done in the sandbox.
import React, { useEffect } from "react";
import { connect } from "react-redux";
import { fetchLatestAnime } from "./redux/actions/animesActions";
const App = props => {
  const { fetchLatestAnime, isFetching, latestAnime, errorMessage } = props;
  useEffect(() => {
    fetchLatestAnime();
  }, [fetchLatestAnime]);

  console.log(props);
  if (isFetching) {
    return
Loading
;
  }

  if (!isFetching && latestAnime.length === 0) {
    return
No animes to show
;
  }

  if (!isFetching && errorMessage.length > 0) {
    return
{errorMessage}
;
  }

  return (

      {latestAnime.map((anime, index) => {
        return
{anime.title}
;
      })}

  );
};

const mapState = state => {
  return {
    isFetching: state.latestAnimeReducers.isFetching,
    latestAnime: state.latestAnimeReducers.latestAnime,
    errorMessage: state.latestAnimeReducers.errorMessage
  };
};

const mapDispatch = dispatch => {
  return {
    fetchLatestAnime: () => dispatch(fetchLatestAnime())
  };
};

export default connect(
  mapState,
  mapDispatch
)(App);


text:
Q: How to update data directly in row? I have a problem with my code. I have a php script where i, in a while, i write a table in html with html name and html value attr with the data of database, like the printscreen above
My table was assembled with input inside the TDs, to be able to "edit" directly in the table, without MODAL or redirection

        <?php
        $i = 1;
        while ($row = mysqli_fetch_array($result)) :;
        ?>

                <form name="presencaForm" id="presencaForm" method="POST">
                    <input type="hidden" id="idcrmmedico" name="idcrmmedico" value="<?php echo $row['id']; ?>"></input>

See that the opening of the form tag is inside the while, that is, for each row of the table, for each TR, I have a form (all with the same name)
The end of the form tag still inside php while. The Button, who receives the ID referring to the record in the DB, has the same name of the form
<button id="d" name="presencaForm" value="<?php echo $row['id'] ?>" class="btn btn-sm btn-info">Atualizar

                        <button type="submit" id="" name="deletamedico" class="btn btn-sm btn-danger">Excluir</button>

                </form>

    <?php
        endwhile;
    }
    ?>

This is my ajax script, which updates the data in the database without refreshing the page and returning me a success message.

The problem is that if i try to refresh the second line, the page just refreshes.
I used the code below to check, and I saw that all buttons return only the first record in the LOG.
Is there any way to update the data as I want, right in the table?
$(document).ready(function() {
            $("button[name='presencaForm']").on("click", function(event) {
                event.preventDefault();
                for (var i = 1; i < document.getElementById("dataTable").rows.length; i++) {
                    console.log($('#idcrmmedico').val());
                }
                var val = document.getElementById('d').value;
                var x = document.getElementById("dataTable").rows.length;

            });

A: id is unique,if you want to control a group of form,you can use class.
For example:
<form class="presencaForm" method="POST">

Then in your javascript:
$('.presencaForm').on('submit', function(event) {


text:
Q: How to prop the attribute of checked to the checkbox in each checkbox if the value two loop is match value (Using Jquery) I currently have problem, I want to prop the checked attribute to the checkbox if the value of two loops is match. so right now I can determine if the value match or not. I will show you guys sample code and illustration where I got already the result if same or not.
Problem: Is there way i can prop the attribute checked to checkbox if the condition is match.

Jquery:
var push_value_of_checker = [];

            $(res.children_checker_details).each(function (key_checker, value_checker) {

                push_value_of_checker.push(value_checker.details_id);
            });

            // console.log(push_value_of_checker);

            $('.csdtc_chkbox').each(function (key, value_chekbox) {

                var value = $(this).val();

                $(push_value_of_checker).each(function (key, value_chekboxx) {

                    console.log(value_chekbox);

                    if(value == value_chekboxx) {
                        console.log('match');
                    }
                    else {
                        console.log('not match');
                    }
                });

            });

A: I've created a demo for you, I've explained it in the code itself. See if it works for you.

const push_value_of_checker = ['1', '2', '3'];  // get the data in an array-- Your logic

$(document).ready(function() {

  //loop through all the checkboxes
  $('.csdtc_chkbox').each(function(key, value_chekbox) {

      let $this = $(this);  // current element

      // check if the array exists and is not empty
      if (typeof push_value_of_checker !== 'undefined' && push_value_of_checker.length > 0) {

        let value = $(this).val();  // get value of the current checkbox
        //console.log(value);
        let include = push_value_of_checker.includes(value); // check if the value exists in the array

        if(include === true){ // if yes, check the checkbox
          $this.prop('checked', 'checked');
        }
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!--
1. All checkboxes should have a name, if you're going to save it.
2. Name is an array so that it can store multiple values.
3. Same name inputs should have different values(here just for demo purpose{value2})
3. Id of all the elements should be unique.
-->
<input type="checkbox" value="1" name="xyz[]" class="csdtc_chkbox" id="any-id-1">Value 1
<input type="checkbox" value="2" name="xyz[]" class="csdtc_chkbox" id="any-id-2">Value 2
<input type="checkbox" value="2" name="xyz[]" class="csdtc_chkbox" id="any-id-3">Value 2
<input type="checkbox" value="3" name="xyz[]" class="csdtc_chkbox" id="any-id-4">Value 3
<input type="checkbox" value="4" name="xyz[]" class="csdtc_chkbox" id="any-id-5">Value 4


text:
Q: Base units in CGS and technic systems What are the base units in the CGS and the technical system of units? Is there not seven? How could it be that what is fundamental in any system is not in other?
By the way, how many minimal "base units" do we need in any system of units?
It seems there is no clear list of basic units in the above systems (unlike the SI) in the bibliography (Wikipedia, physics books talking about the CGS system,...). I mean, I found out that there is no "list" of basic gaussian/cgs/technical system of units (are there 6,7, 17,...basic units?).


text:
Q: How to run a docker container from within java I want to run the following command from within a Java Eclipse Project:
docker container run -p 4000:5000 virtuprint:vp

where virtuprint:vp is an image.
I installed the docker-java api from here https://github.com/docker-java/docker-java using all its dependencies via maven.
I am using MacOS, I guess that's causing my trouble.
I already read the docs and wikis, and just did some test code to see if it's running (and of course it's not.)
DockerClient dockerClient = DockerClientBuilder.getInstance().build();

        List<Container> containers = dockerClient.listContainersCmd().exec();

        for(Container c: containers) {
            System.out.println(c.getId());
        }

So I just want to print the container-ID in short term. Long term I want to run multiple docker containers on demand from within my java application.
But if I run the code I get:

java.lang.NoClassDefFoundError: Could not initialize class org.newsclub.net.unix.NativeUnixSocket

I guess it's because he is trying to find unix sockets on places they aren't, but I neither know where they are nor how to tell him where to find them.

A: Played with the dependencies, downgraded to version 3.0.14 and sticked closely to this guide:
https://www.baeldung.com/docker-java-api
don't know why but now it works.

A: I also faced the same issue, but the issue got resolved when I switched to JAVA 8.
There is an issue with JAVA11 and higher versions.
JAVA 11 and Docker-java issue


text:
Q: Efficiency of electric heaters I was reading this question. A person was asking what is the efficiency of an electric heater, and to sum up, people were answering "All resistive heating, can be considered to have 100% efficiency" and that this is true also for things that are not built to heat, but that produce heat, such has computers, TV etc.
Now my question then is, why different ovens have different levels of "energy efficiency"? If all the ovens are just made by a resistance, shouldn't them all have a 100% efficiency?

A:
If all the ovens are just made by a resistance, shouldn't them all have a 100% efficiency?

An oven is not the same thing as a space heater. The purpose of the space heater is to deliver heat to the space that surrounds it. The purpose of the oven is to maintain a certain, elevated temperature inside a closed chamber.
I'm not sure how one would define "efficiency" for an electric oven. Efficiencies usually are expressed as some ratio—most often, as a ratio of some actual value to some "ideal" value.
An ideal oven would have perfect insulation. It would not allow any heat to escape. Once it achieved the desired temperature, it would not require any energy at all to maintain that temperature. Compared to that, every practical oven would have to be called 0% efficient, regardless of how well it actually was insulated.

A:
Now my question then is, why different ovens have different levels of
"energy efficiency"? If all the ovens are just made by a resistance,
shouldn't them all have a 100% efficiency?

I didn't see ovens listed in the examples in the "energy efficiency" link, so I don't know what criteria are used to determine their "efficiency". But in general terms I would think "efficiency" would be the ratio of the energy that produces the desired output or outcome divided by the energy required to produce that outcome (energy input).
In that context, the desired output of the oven is to cook food. Similarly the desired output of the clothes dryer is to dry clothes. Only heat that elevates the temperature of the contents of the oven (or dryer) can produce the desired outcome. Heat lost to the environment of the oven (the kitchen) is not available to produce the desired output. An example would be a poorly thermally insulated oven. In the winter that may be a plus since it might save on heating bills if the home is heated by electricity. But in the summer it increases your air conditioning bill. A refrigerator cools its contents but in the process transfers heat to its surroundings (the air in the kitchen). Again, in the winter that may be desirable, but in the summer it wouldn't.
I have put "efficiency" in quotes because different terms are used to describe the ratio discussed above. For example, the "efficiency" of a refrigerator or heat pump is called its Coefficient of Performance (COP), which is the ratio of the desired heat transfer to the work required to make the transfer.
It has been said that the energy input of all electrical products eventually winds up as "heat". While that may be true, it alone provides no information on the efficiency of the product as described above, with the possible exception of electric room fan type air or radiant heaters.
Hope this helps.


text:
Q: Asymptotic local limit theorem and applications in analytic number theory I'm wondering if one could get similar results to the classical local limit theorem if one assumes that conditions, such as independence and identicallity of distribution of the random variables involved, only hold at the asymptotic level. In a sense this is similar to what Erdos and Kac did here, in connection to the central limit theorem, where the dependence of the Bernoulli variables $I_{n_p}$, for $p$ prime, tend to $0$ as $n \to \infty$.
Here's a problem I'm interested in (or rather in its applications). I wonder if you could point me in the right direction.
For $n \geq 1$ and each $i$ with $1 \leq i \leq n$, let $X_{n,i} : \Omega_n \to \{0, 1\}$ be Bernoulli random variables on a finite sample space $\Omega_n$ (whose size grows with $n$). Assume that $\mathbb{E}[X_{n,i}] = p + O(\epsilon(n))$, for some fixed $p$ with $0 < p < 1$, and some function $\epsilon(n) \to 0$ as $n \to \infty$. Further assume that $\mathbb{E}[X_{n,i} X_{n,j}] = \mathbb{E}[X_{n,i}] \mathbb{E}[X_{n,j}] + O(\epsilon(n))$ for $i \neq j$, i.e., the variables are "asymptotically independent". Let $S_n = \sum_{i=1}^n X_{n,i}$. I'm interested in an asymptotic Gaussian/normal/local limit theorem type approximation for $\mathbb{P}(S_n \geq n-k)$ (at the right tail) with $k > 0$ fixed and $n$ large. Given that $n \to \infty$ anyways, I feel the lack of independence of the variables at small scales should be irrelevant...


text:
Q: Ambigious types in class definition haskell I am learning Haskell and in my pet project I defined several newtypes. When simplified, they are something like this
newtype A = A [Double]

I do not want type A to be created by just any list of doubles, but by list that satisfies some conditions. Moreover, I would like to be able to take the list, transform it by some function Double->Double and then create from it type A again. Since I want to do this for several different types, I was thinking about defining class
class Functor f => Transform a f b err where
  create :: f b -> Either err a
  get :: a -> f b
  transform :: (b -> b) -> a -> Either err a
  transform f a= create  (f <$> (get a)

And creating instance
instance Transformator A [] Double String where
   create [] = Left "err"
   create xs = Right $ A xs
   get (A xs) = xs

but this does not seem to be allowed in Haskell. The problem seems to be that return type of get is not the same as input type of create, the ambiguous type f in transform function cannot seem to be paired together between get and create.
In the end I gave up and solved the issue with two typeclasses:
class Transform a b err where
  transform :: (b -> b) -> a -> Either err a

class Create a b err where
  create :: b -> Either err a

newtype A = A [Double]

instance Create A [Double] String where
  create [] = Left "err"
  create xs = Right $ A xs

instance Transformator A Double String where
  transform f (A ps)= create  $ f <$> ps

This works quite nicely, but the transform function has always the same implementation - get data from inside the type, fmap function over them and apply create on the result.  Is there some way to make the default implementation work? Also, if you have some completely different suggestion how to approach the problem, I would be glad for any tips.


text:
Q: Spring boot reactive and GraalVM java.lang.NoClassDefFoundError: Could not initialize class reactor.netty.http.client.HttpClientSecure When I'm creating a native image using Spring reactive and WebClient everything ends correctly but when I'm making a request using the WebClient, I get this error given below :
2021-01-10 04:10:22.904 ERROR 1 --- [ctor-http-nio-2] reactor.netty.http.server.HttpServer     : [id: 0x3dd90c0b, L:/172.17.0.2:8080 - R:/172.17.0.1:48222]

java.lang.NoClassDefFoundError: Could not initialize class reactor.netty.http.client.HttpClientSecure
        at com.oracle.svm.core.classinitialization.ClassInitializationInfo.initialize(ClassInitializationInfo.java:215) ~[na:na]
        at reactor.netty.http.client.HttpClientConnect$MonoHttpConnect.lambda$subscribe$0(HttpClientConnect.java:211) ~[na:na]
        at reactor.core.publisher.MonoCreate.subscribe(MonoCreate.java:57) ~[na:na]
        at reactor.core.publisher.FluxRetryWhen.subscribe(FluxRetryWhen.java:76) ~[na:na]
        at reactor.core.publisher.MonoRetryWhen.subscribeOrReturn(MonoRetryWhen.java:46) ~[na:na]
        at reactor.core.publisher.InternalMonoOperator.subscribe(InternalMonoOperator.java:57) ~[na:na]
        at reactor.netty.http.client.HttpClientConnect$MonoHttpConnect.subscribe(HttpClientConnect.java:263) ~[na:na]
        at reactor.core.publisher.InternalMonoOperator.subscribe(InternalMonoOperator.java:64) ~[na:na]
        at reactor.core.publisher.MonoDefer.subscribe(MonoDefer.java:52) ~[na:na]
        at reactor.core.publisher.FluxFromMonoOperator.subscribe(FluxFromMonoOperator.java:83) ~[na:na]

This is my code
public Flux<User> getAllUser() {
        return webClient
                .get()
                .uri("/v1/07defb0d")
                .retrieve()
                .bodyToFlux(User.class);
    }

This is my full example code
Any suggestion for me?


text:
Q: How to run the java code from command prompt which is dependent on many other projects I am new to maven. I have maven code repository synced in eclipse. I have a one main file say Main.java which is dependent on several other projects which I have added using maven. I am able to run Main.java from eclipse.
How can I run the same file from command prompt?

A: Assuming that the class you are trying to run has a main method, try the command mvn compile exec:java -Dexec.mainClass=yourpackage.yourClassName


text:
Q: Analyse the US presidential election from the perspective of Arrow's theory I want to consider the voting system against the 4 Arrow's axioms.
So first the voting system simplifies to first-past-the post system where the highest polling candidate wins the election.
How does this fit in with the 4 axioms?

Unrestricted domain

A full ordering is provided given by the number of votes for each candidate

No dictator

There is no individual whose votes decide the final result - everyone's vote matters.

Pareto

If everybody prefers candidate $y$ to $x$ then so will the group, because $y$ will receive more votes

Independence of irrelevant alternatives

What is the effect of removing candidate $X$ on the preference between $Y$ and $Z$? This will have no effect because if $Y$ has more votes than $Z$ then this will remain the case even if $X$ is removed.

By my working, all $4$ axioms are fulfilled but this contradicts Arrow's Impossibility Theorem: there is no social welfare function meeting all $4$ above conditions.
Where have I gone wrong?
Perhaps Pareto needs to be reconsidered. This is "If each individual has $x>_iy$ then the group has $x>_gy$"
But I suppose the group preference is there is just one candidate who is better than them all. So say if candidate $A$ wins, $B$ has the second most votes and $C$ has the third most votes. Every individual has $B$ is preferred to $C$ but this is not reflected by the group.
Would really appreciate some input on this.
Edit: My interpretation of the 4th condition was incorrect, please see the below answer

A: Independence of irrelevant alternatives fails. Your conclusion that removing $X$ will have no effect on the preference between $Y$ and $Z$ is wrong. If one person has preference $Z\gt Y\gt X$ and everyone else has preference $X\gt Y\gt Z$, then $Z$ is socially preferred to $Y$ if $X$ is in the race, whereas otherwise $Y$ is socially preferred to $Z$. (I'm assuming that by "votes" you meant "first preferences".)


text:
Q: Obtener datos de una fila seleccionada Estoy trabajando con GridControl de DevExpress para Windows Forms, lo que deseo es obtener datos de ciertas row, no se como hacerlo.
En DataGridView de Windows Forms lo hago de la siguiente manera
if (dgvCategoria.Rows.Count > 0)
            Helper.IdRow = Convert.ToInt32(dgvCategoria.CurrentRow.Cells[0].Value);

A: Utiliza el método GetFocusedRowCellValue, así:
Helper.IdRow = Convert.ToInt32(GridControl1.GetFocusedRowCellValue("miColumna"));


text:
Q: Iam trying to run my nextjs application , but getting an error TypeError: Only absolute URLs are supported Iam trying to run my nextjs application , but getting an error TypeError: Only absolute URLs are supported

API_BASE_URL='http://localhost:3000'

export function getStrapiURL(path = "") {
  return `${process.env.API_BASE_URL}${path}`;
}

export async function fetchAPI(path) {
  const requestUrl = getStrapiURL(path);
  const response = await fetch(requestUrl);
  const data = await response.json();
  return data;
}

A: As the error states, you will have to use an absolute URL for the fetch you're making. I'm assuming it has something to do with the different environments (client & server) on which your code can be executed. Relative URLs are just not explicit & reliable enough in this case.
One way to solve this would be to just hardcode the server address into your fetch request, another to set up a config module that reacts to your environment:
config/index.js
const dev = process.env.NODE_ENV !== 'production';

export const API_BASE_URL = dev ? 'http://localhost:3000' : 'https://your_deployment.server.com';


text:
Q: How to send local file from Flask to Reactjs I have React JS as frontend and Flask as backend for my application. The idea is that the user upload image to react, then transfer to process in Flask and then Flask return the processed image back to React for display.
To send file from Flask to React, I saved the image in a local folder. So the order looks like this:
--node_modules,public,src // React files
--api  //Flask files
  -upload_image
  -app.py
  -...

So in Flask, I will send the url of the image from my local server to React like this:
@app.route('/get-cut-image',methods=["GET"])
def get_cut_img():
    if path_is_valid:
        return "http://127.0.0.1:5000/api/upload_image/img.png"
    else:
        return "No valid path"

and in React, I use axios to call the server:
export default class Body extends Component {
  constructor(props) {
    super(props);
    this.state = {
      images: "",
      result: false,
      upload: true,
    };
    this.getDatas = this.getDatas.bind(this);
  }
  getDatas() {
    try {
      const dataImage = axios.get(
        "http://127.0.0.1:5000/get-cut-image"
      );
      this.setState({
        images: dataImage.data,
      });
    } catch (error) {
      console.log(error);
    }
    this.setState({result: true, upload: false});

  }
  render() {
    return (

    );
  }

However, the server send the right url to image folder, however, I cannot get the url in client. Any help?
EDIT:
So I figure out that localhost:3000/ is the public folder of react. So my directories looks like this:
--node_modules,public,src // React files
--api  //Flask files
  -app.py

I have another function that process the image, and save the image to the public folder
@app.route('/upload', methods=['GET', 'POST'])
def upload_file():
   img_BGRA = <some_processing> #return PIL image
   img_BGRA.save(<home/user/.../public/filename.png>)

When I try to do so, in my react page crashes and restart again.


text:
Q: Reorder lines in each 3-line record I have a file which contains lots of records in following manner.
Name
Address
Phone

This is the sequence for each record in that file. Now, I want to copy this file to other file with changed order as below.
Address
Phone
Name

How to write shell script to do this?

A: Try:
sed -n 'h;n;p;n;G;p' < file.in > file.out

For example:
$ seq 9 | sed -n 'h;n;p;n;G;p'
2
3
1
5
6
4
8
9
7

A: If I'm reading your question right, you want to take sequences of 3 lines from the file, and swap the order of the first and last in each? With GNU sed, you could do something like this I think:
sed -e :a -e '$!N' -e 's/\(.*\)\n\(.*\)\n\(.*\)$/\2\n\3\n\1/;Ta' file

which continually slurps up lines until it is able to make the swap, and then starts over.

A: With awk:
awk '{l=$0;getline;print;getline;print $0"\n"l;}' < file_in > file_out

Explanation:

*

*Save current record in variable l

*Get next record using getline

*Print that record (print, invoked without arguments will always
print the current record)

*Get the next record again using getline

*Print that record, a newline and the first record stored in l

*For the next record(s) start over at 1.
References

*

*awk String Functions


text:
Q: I am unable to access condition set up in component-1 by Subject of rxjs in component-2 Service:
import { Injectable } from "@angular/core";
import { Subject } from "rxjs";

@Injectable({
  providedIn: "root"
})
export class AdminRoleLocalService {
    public newRoleAdded = new Subject<boolean>();
    constructor() {}
       newRoleAddedEvent() {
       this.newRoleAdded.next(true);
    }
}

component-1:
submitAddRoleForm(addRoleForm: AddRoleData) {
    this.isFetching = true;
    this.roleService.addRoleData(addRoleForm).subscribe(
    httpResponse => {
       console.log(httpResponse);
       this.isFetching = false;
       this.roleLocalService.newRoleAddedEvent();
       this.router.navigate(["/role-management"]);
    },
    errorMessage => {
     console.log(errorMessage);
     this.errorMessageContent(errorMessage);
    }
   );
}

component-2:
ngOnInit() {
   this.roleLocalService.newRoleAdded.subscribe(flag => {
      this.newRoleAddedFlag = flag;
   });
}

i am seeing newRoleAddedFlag as undefined where as i am expecting value as True. I am unable to find out where i am seeing. Request you to help me out.

A: try with
public newRoleAdded = new BehaviorSubject<boolean>(true);

BehaviorSubjectis a Subject-like observable. But you initiate your observable with a value and when you subscribe to it, you get the last value.

A: You can try using
public newRoleAdded = new ReplaySubject<boolean>(1);

In this case you not need to set initial value and second component will wait for next method call. Or you can use
public newRoleAdded = new BehaviorSubject<boolean>(null);

And access via method:
getNewRoleAddedObservable(): Observable<boolean> {
  return this.newRoleAdded.pipe(filter(value => value !=null)).asObservable();
}

Never expose subjects public this is bad practice.


text:
Q: Query related to Bluemix Secure Gateway Client on DataPower Our customer is planning for APIC on Bluemix cloud to On-premise connectivity for IIB APIs.
For secure connection we are planning to use Secure gateway service on Bluemix and creating secure gateway client on customer existing DataPower .
At present there is an internet connectivity via eth0 of DataPower at customer datacenter where a service is running on 443.
We want to seggregate traffic comming from Bluemix and the existing non-bluemix traffic.
So We are planning to create a new eth1 dedicated for Bluemix calls, that will also talk to internet on port 443 and 9000 (as required by secure gateway service) .
How do we make sure Bluemix traffic cames to Gateway via Eth1

A: The Secure Gateway Client initiates the connection to the SG Servers in Bluemix with the combination of requests across 443 and 9000.  Once that connection has been initiated, it will remain open and all traffic from Secure Gateway will travel across it.


text:
Q: Stop first
* being draggable This is my demo: http://jsfiddle.net/michelejs/PeS2D/560/
How can I stop the first
 being draggable?
$(document).ready(function(e) {
$('li').removeClass('ui-corner-bottom');
$('ul')
    .addClass('ui-corner-top')
    .removeClass('ui-corner-all')
    .sortable({
        'containment': 'parent',
        'opacity': 0.6,
        update: function(event, ui) {
            alert("dropped");
        }
    });
});

Thanks a lot.

A: You can use the items property:
$(document).ready(function(e) {
    $('li').removeClass('ui-corner-bottom');
    $('ul')
        .addClass('ui-corner-top')
        .removeClass('ui-corner-all')
        .sortable({
            items: 'li:not(:first)',
            'containment': 'parent',
            'opacity': 0.6,
            update: function(event, ui) {
                console.log(ui)

            }
        });
});

http://jsfiddle.net/ppRJL/

A: You can use the option items in the .sortable() widget method.
Combined with the jQuery selector gt(), you could easily get what you are looking for.
This works for me (jsFiddle example) :
$(document).ready(function(e) {
    $('li').removeClass('ui-corner-bottom');
    $('ul')
        .addClass('ui-corner-top')
        .removeClass('ui-corner-all')
        .sortable({
            'items': '>li:gt(1)',
            'containment': 'parent',
            'opacity': 0.6,
            update: function(event, ui) {
                alert("dropped");
            }
        });
});

A: try this.
http://jsfiddle.net/PeS2D/561/
I added an extra class called header to the first li and then there is a function called cancel
to save people a click:
[Cancel] Prevents sorting if you start on elements matching the selector.
Code examples:
Initialize the sortable with the cancel option specified:
$( ".selector" ).sortable({ cancel: "a,button" });

Get or set the cancel option, after initialization:
// getter
var cancel = $( ".selector" ).sortable( "option", "cancel" );

// setter
$( ".selector" ).sortable( "option", "cancel", "a,button" );

A: Just read the documentation : http://api.jqueryui.com/sortable/#option-items
The items option allow you to specify a selector for sortables elements.

A: Fiddle: http://jsfiddle.net/PeS2D/562/
You can set it to be like this
$(document).ready(function(e) {
  $('li').removeClass('ui-corner-bottom');
  $('ul')
    .addClass('ui-corner-top')
    .removeClass('ui-corner-all')
    .sortable({
        'containment': 'parent',
        'opacity': 0.6,
        update: function(event, ui) {
            alert("dropped");
        },
    items: 'li[id!=heading]'
    });
});

then add an id to your first li

Re-order


text:
Q: PHPMyAdmin - How to fix #1006 - Can't create database 'database_name' (errno: 13 "permission denied") in Ubuntu 20.04? In my Ubuntu 20.04 (Desktop/Laptop not server) OS based machine I recently install XAMPP (Version: 7.4.7).
Now when I try to create a database it shows #1006 - Can't create database 'database_name' (errno: 13 "permission denied").
I am not quite familiar with Ubuntu in recent times (last use Ubuntu 18.04), so I can't figure out in which file I need to do the configuration or in which directory I need to allow the permission so that the problem is fixed. Can anyone help me to fix the issue?

A: TO be able to create database you have to login to phpmyadmin as root or with the account that have required permission. first make sue you have started mysql by typeing
$service mysql start

To get started you can create a new user for your mysql. you can do that by
mysql>CREATE USER 'newuser'@'localhost' IDENTIFIED BY 'password';

where newuser is the username. You can set that to the username of your accountwhuch make it easier to work with.and yes localhost is the server you are using and password is the password you want to set for mysql login.
Now you have creates a new user and it's time to make that user capable of doing stuffs. You can do so by
mysql>GRANT ALL PRIVILEGES ON *.* TO 'newuser'@'localhost';

here *.*means that we are granting the permission for every table of every database which also meanwe can create if we need. So now you should be able to create database by username newuser Just in case if you need to log into mysql from terminal then do
mysql -u newuser -p

During this proces I am assuming that you will run all these command as root.


text:
Q: Gcloud app deploy. Stopping Master I am trying to deploy my app to the app engine but for some reason, I can't do so. My logs says

Shutting down master
Reason: worker failed to boot

I think it has something to do with gunicorn. How do I go about this?
My app.yaml is
runtime: Python
 env: flex
entrypoint: gunicorn -b :$PORT .wsgi
beta_settings:
      cloud_sql_instance: /*mysqlinstance*/
 runtime_config:
       python_version: 3

A: So my solution:
I started afresh!
I created a new project in my cloud because a lot of complications had gotten into the one I was using. Then I included django==1.10 and gunicorn==19.7.1 in the requirements.txt file and ran
pip install -r requirements.txt

in the virtual environment and then deployed to the new project
Everything worked fine.


text:
Q: grails/hibernate - use lock with getAll() method As documented we could use obtain pessimistic lock like this:
def airport = Airport.get(10, [lock:true)
airport.lock() // lock for update
airport.name = "Heathrow"
airport.save()

I tried to de the same think with getAll but it doesn't work
def airport = Airport.getAll(idsList, [lock:true])

Error:
getAll() is applicable for argument types: (java.util.ArrayList, java.util.LinkedHashMap)...

Is there another way to obtain a pessimistic lock for a list?
Thanks


text:
Q: converting date in to second in excel In attached link there is an image of excel file. I would like to convert date and time in to seconds. I am using below mentioned formula for that.
for sec:
 =(STUNDE(A243) * 3600 + MINUTE(A243) * 60 + SEKUNDE(A243))
     -(STUNDE($A$11) * 3600 + MINUTE($A$11) * 60 + SEKUNDE($A$11))

for hr:
 =B243/3600

but If you see in sheet, my values become minus when the date is changed from 13 to 14. How I can make it in positive?

A: You are converting the time value to seconds but also subtracting the time value in A11 - I can't see A11 in your screenshot but from the values shown you can calculate that A11 has the time value 16:54:57 (and presumably a date?), so whenever the time value in a cell is lower than that the result is negative.
What are you trying to achieve? What result do you expect in row 251?
If you just want elapsed seconds since the date/time in A11 then use this formula for B243 copied down to always get a positive result
=(A243-A$11)*86400
Format B243 as general or number with no decimals
That takes the difference between A243 and A11 and multiplies by the number of seconds in a day to give the result in seconds
Your elapsed hours formula can stay the same

A: The formula to make something positive in Excel is called =ABS().
ABS MSDN.
It takes a value and it makes sure the output is positive. Give it a try.


text:
Q: EF6 Repository pattern in Windows Service I have implemented a Windows service which is to get a list of emails from the database and send them using .net mail every 60 seconds.
I have designed it using repository pattern, please see the screenshot of the solution folders and projects.Click to see the picture
Questions:

*

*In terms of the pattern am I on the right track? structure of the separated projects, creating an interface for each repository and a service per repository.

*If some of the business logics have nothing to do with the database, do I still need to create a repository for them or a service is enough?

*I have a SMTP service class which is implementing .net mail and sending emails, while I'm sending each email I need to update the database, I would like to know if putting the update logic in the SMTP Service class is a good practice? It's something like below
    public class SMTPService : ISMTPService
    {

        SmtpClient client;
        MailMessage newMessage;
        EmailService emailService;
        IEventLoggerService MailCheckerLog;

        public async Task SendEmail(tb_Email email)
        {...}

        void SendCompletedCallback(object sender, System.ComponentModel.AsyncCompletedEventArgs e, tb_Email email)
        {

            if (e.Cancelled)
            {

            }
            if (e.Error != null)
            {

            }
            else
            {
                email.DateSent = DateTime.Now;
                emailService.Update(email);
            }

            client.Dispose();
            newMessage.Dispose();

        }

}

A: I'm not sure what you'd like to achieve exactly and what business requirements you have.
The structure is OK for now, but consider this: you have a user entity and a photo entity. Each user must have a photo associated with them. How would you handle that scenario?
You have to create a UserRepository and a PhotoRepository. Of couse you first have to insert the user record in order for the photo record to reference it later.
So you call the Insert() method of the UserRepository. When the user is inserted, you call the Insert() method of the PhotoRepository. But what if that Insert() fails? Now you have a user in the db who doesn't have a photo.
You have to insert the user and the photo together, in one transaction. That's where the unit of work pattern comes in. You have to use that if you have business logic that concerns more than one entity type. If all you do is handle emails, then this is fine. If not, you have to add that pattern to your application. See an example here.
A service, again, is something that handles business transactions, and a business transaction can touch multiple types of entites. Again, the unit-of-work pattern can help you with this. But usually repositories are created based on your entites, and services based on your business logic. In the example, you could have a UserService that uses both the UserRepository and the PhotoRepository (usually through the unit of work).
In case of sending the e-mails, I would again design the services based on my business logic. And probably the business logic is to 'send e-mails', not to 'send e-mails via SMTP'. What happens if you decide to use a service like SendGrid? Then it is not SMTPService anymore.
I would probably create an EmailService (which you also have), and this would have a SendEmails() method. This would use the EmailRepository to fetch the emails, send it using SMTP, then update it and save it through the unit-of-work.
Or, if you want to be really abstract, you can create an IEmailSenderService interface with one method, SendEmail(Email email). Then you can create an SmtpEmailSenderService, which implements this interface and wraps the SmtpClient class and sends the email using SMTP. If you decide to move to SendGrid, you can create a SendGridEmailSenderService, that uses HttpClient to issue requests to SendGrid. The update is still done in the EmailService using the repository and the unit of work, but now the EmailService itself does not use SmtpClient but simply the IEmailSenderService interface.


text:
Q: Service Area polygon appears to fill in between the roads for areas it should not reach In ArcMap 10.5.1, I have created a service area polygon of 1000m along a road network, with a trim of 50m. In the image you will see where the road is linked around, the inside is filled in (red circles). However there should be a hole in this area as it is outside of the trim and not reachable within the parameters.
I am using ArcGIS Network Analyst. After adding the Network Dataset I used the Network Analyst toolbar to create a new service area. I added Facilities, which was one single central point. Within Service Area layer properties I set the Impedance to 1000m, in the direction away from the facility. I chose to Generate Polygons - Detailed with a 50m trim. I also chose to generate a line.
What am I doing wrong here?

A: See this bug description:
Bug NIM066645

Network Analyst does not trim a Service Area polygon properly if the area is enclosed by a Network Analyst Route in versions 9.3.1 SP2 and
  10.0 SP1. If trim option is only meant to trim the exterior of the service area, then please update the documentation to reflect this
  behavior.

So this seems to be the expected behaviour, but the documentation is not crystal clear (is 'periphery' only the outer border of the service area or does it also include 'islands').


text:
Q: Load fixture in django migrations using loaddata My django application needs data to work properly, so in certain migration I loaded data using the recommended method by almost all stack overflow answers:
    from django.core.management import call_command

    def load_fixture(apps, schema_editor):
        call_command('loaddata', 'fixture_name', app_label='my_app')

    class Migration(migrations.Migration):

        ...

        operations = [
            migrations.RunPython(load_fixture),
        ]

In the following migration, I deleted a field and added another field. So far so good.
Now I want to test my application, but when the test database is being created, the 'call_command' above fails because the fixtures don't specify  values for the field created in the next migration. I suspect this is because call_command isn't loading the objects on the test database but on settings.DATABASES['default'].
How should I load fixtures in a migration so that I can build test databases?

A: For tests, I know you can load in fixtures within Djangos TestCase, see django docs
For production, The approach you are taking using loaddata seems viable, but you would need to make sure your fixtures are kept up to date (as youve highlighted), as fixture inserting is quite forceful, an alternative is to create your models using the ORM inside of a RunPython operation, this can help to give them more flexibility..
There is a feature request in Django for something more official, though I'm not sure if its being considered or not, but it would only add convenience for fixture loading, not a way to make fixtures dynamic..
this other stack overflow post contains some other interesting approaches
Hope that's in some way helpful


text:
Q: knitr install from github I'm looking forward to getting my hands on an update of Yihui Xie's knitr package that includes a new chunk option (collapse). I'm trying to install the development version from github but am getting an error. I'm using:
install_github("knitr", 'yihui')
And get the error:
Error: processing vignette 'datatables.Rmd' failed with diagnostics:
unused argument (encoding = encoding)
Execution halted
Error: Command failed (1)

I see a discussion of this issue at: https://github.com/yihui/knitr/issues/398 where the suggestion is to update the evaluate package. I've updated the evaluate package successfully and I also updated the devtools package successfully. Below is my sessionInfo().
Anyone have a suggestion?
ZR
R version 3.0.2 (2013-09-25)
Platform: x86_64-w64-mingw32/x64 (64-bit)

locale:
[1] LC_COLLATE=English_United States.1252  LC_CTYPE=English_United States.1252
[3] LC_MONETARY=English_United States.1252 LC_NUMERIC=C
[5] LC_TIME=English_United States.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] devtools_1.5    evaluate_0.5.2  RPostgreSQL_0.4 DBI_0.2-7

loaded via a namespace (and not attached):
 [1] assertthat_0.1 digest_0.6.4   dplyr_0.1.2    formatR_0.10   httr_0.2
 [6] knitr_1.5      memoise_0.1    parallel_3.0.2 Rcpp_0.11.0    RCurl_1.95-4.1
[11] stringr_0.6.2  tools_3.0.2    whisker_0.3-2

A: If you install the development version of knitr, just follow the instructions for installation in the README file on Github.
For this particular problem, it was caused by an insufficient version of the markdown package at that time, but now the new version of markdown is on CRAN, so just run update.packages(ask = FALSE) and you should be able to install knitr from Github. You do not really need to know these details if you install from RForge as mentioned in the instructions.


text:
Q: Changing drop Down Text in JAVAFX after the page is loaded How do I change the text size in the drop down in java FX? Currently it's not coming out correctly as per the css. Looks fine when I run the url through a browser. However the drop down text sizes are coming out very small when the url is loaded and viewed in JAVA FX.
Here is my code:
public void start(Stage stage) throws InterruptedException {
    stage.setTitle("test");
    Pane stackPane = new Pane();
    Browser browser = new Browser();
    stackPane.getChildren().add(browser);
    Rectangle2D primaryScreenBounds = Screen.getPrimary().getVisualBounds();
    webScene = new Scene(stackPane, primaryScreenBounds.getWidth(), (primaryScreenBounds.getHeight()-50), Color.web("red"));
    webScene.getStylesheets().add(this.getClass().getResource("main.css").toExternalForm());
    stage.setScene(webScene);
    stage.show();
}

public Browser() {
    //apply the styles
    getStyleClass().add("browser");
    String url = "http://localhost:8000/myapp";
    webEngine.load(url);
    getChildren().add(browser);
}


text:
Q: Using array.clone() and changing values, affects the original array too I have written a program for an exercise that generates numOfValidBoardsToCreate Sudoku boards with emptyCellsPerBoard cells with 0s (fills the rest with random numbers) and then solves them. If a generated board isn't valid or solvable it tries to create another one until it gets it. Now let's say we request just one board with 75 empty cells and its solution for the sake of simplicity.
The solve() method checks if a board is solvable and if so it solves it and returns true. Now, since when i check for each board's validity in the if statement of the for loop using isSolvableBoard() which in turn calls solve(), i don't want to solve the original board since i'm going to need to display the original unsolved one and then the solution. So i decided to use sudokuBoard.clone() to make a copy of the original one and use that for the check and disregard it since it's going to be solved after the condition is evaluated. I'd expect that the original sudokuBoard inside the if() statement wouldn't be solved when i print it the first time but the output is the solved version. What am i missing here?
public static void main(String[] args) {
        BacktrackingAlgorithm solver = new BacktrackingAlgorithm();

        // Get the required input from the user
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter the number of empty cells that the board should have:");
        int emptyCellsPerBoard = scanner.nextInt();
        System.out.println("Enter how many boards the app should create and solve:");
        int numOfValidBoardsToCreate = scanner.nextInt();

        // extra data to keep track of for printing purposes
        int numOfInvalidBoards = 0;
        int numOfUnsolvableBoards = 0;

        // finding the time before the operation is executed
        long start = System.currentTimeMillis();

        int[][] sudokuBoard;
        int[][] copyOfBoard;

        for (int i = 1; i <= numOfValidBoardsToCreate; i++) {
            sudokuBoard = solver.generateSudokuBoard(emptyCellsPerBoard);

            // Create a copy of the board to pass to isSolvableBoard to test the condition without altering the board
            copyOfBoard = sudokuBoard.clone();

            if (solver.isSolvableBoard(copyOfBoard)) {
                System.out.println("Board #"+i);
                solver.printBoard(sudokuBoard);
                System.out.println("Solution of board #"+i);
                solver.solve(sudokuBoard);
                solver.printBoard(sudokuBoard);
            } else {
                numOfUnsolvableBoards++;
                numOfInvalidBoards++;
                i--; // run the loop again if we haven't reached the end
            }
        }

        // finding the time after the operation is executed
        long end = System.currentTimeMillis();
        //finding the time difference and converting it into seconds
        float sec = (end - start) / 1000F;

        // Print final message
        System.out.println("Empty Cells per board: " + emptyCellsPerBoard + "\nValid boards created: " + numOfValidBoardsToCreate + "\nInvalid boards created: "
                + numOfInvalidBoards + "\nUnsolvable boards created: " + numOfUnsolvableBoards + "\nElapsed time: " + sec + " seconds");
    }
}

boolean solve(int[][] board) {
    for (int row = BOARD_START_INDEX; row < BOARD_SIZE; row++) {
        for (int column = BOARD_START_INDEX; column < BOARD_SIZE; column++) {
            if (board[row][column] == NO_VALUE) {
                for (int k = MIN_VALUE; k <= MAX_VALUE; k++) {
                    board[row][column] = k;
                    if (isValid(board, row, column) && solve(board)) {
                        return true;
                    }
                    board[row][column] = NO_VALUE;
                }
                return false;
            }
        }
    }
    return true;
}

/**
 * Checks if a Sudoku board is valid and solvable.
 *
 * @param board The given board
 * @return True if it is or false otherwise.
 */
boolean isSolvableBoard(int[][] board) {
    return isValidBoard(board) && solve(board);
}

/**
 * Checks if the given sudoku board is valid.
 *
 * @param brd The 9x9 board
 * @return True if it's valid or false otherwise.
 */
private boolean isValidBoard(int[][] brd) {
    for (int i = BOARD_START_INDEX; i < BOARD_SIZE; i++) {
        for (int j = BOARD_START_INDEX; j < BOARD_SIZE; j++) {
            try {
                if (!isValid(brd, i, j)) return false;
            } catch (ArrayIndexOutOfBoundsException e) { // if a given cell has a value > 9, an exception is thrown, so handle it
                return false;
            }
        }
    }
    return true;
}

A: Turns out a good solution is the following:
for(int j=0; j <9; j++) {
  copyOfBoard[j] = Arrays.copyOf(sudokuBoard[j], sudokuBoard.length); // deep copy of the subarray
}

Which basically performs a deep copy of each subarray of the 2D array.


text:
Q: VBA code to compare two worksheets and add the missing lines I have below code which is working but taking time (around 10 min) and sometimes it is going in to not responding mode as my data has around 60k lines.
What i am trying to do is to compare values in column A of both worksheets paste the entire line(A-X) in to sh1 if the value is present in sh2 but not in sh1.
Can someone help to if there is better, faster and efficient way than this.
Sub t()
Dim sh1 As Worksheet, sh2 As Worksheet, c As Range
Set sh1 = Workbooks(WK1).Sheets(sheet1)
Set sh2 = Workbooks(WK2).Sheets(sheet1)
    For Each c In sh2.Range("A2", sh2.Cells(Rows.Count, 1).End(xlUp))
        If Application.CountIf(sh1.Range("A:A"), c.Value) = 0 Then
            c.Resize(, 24).Copy sh1.Cells(Rows.Count, 1).End(xlUp)(2)
        End If
    Next
End Sub

A: try add
Application.ScreenUpdate=False Application.EnableEvents = False
on start and
Application.ScreenUpdate=True  Application.EnableEvents = True
on end of code. it should speed up a whole code. like below. You can add userform with progress bar to show actual status.
Sub t()
Dim sh1 As Worksheet, sh2 As Worksheet, c As Range
Application.ScreenUpdate=False
Application.EnableEvents = False
Set sh1 = Workbooks(WK1).Sheets(sheet1)
Set sh2 = Workbooks(WK2).Sheets(sheet1)
For Each c In sh2.Range("A2", sh2.Cells(Rows.Count, 1).End(xlUp))
    If Application.CountIf(sh1.Range("A:A"), c.Value) = 0 Then
        c.Resize(, 24).Copy sh1.Cells(Rows.Count, 1).End(xlUp)(2)
    End If
Next
Application.ScreenUpdate=True
Application.EnableEvents = True
End Sub

\\ edited \\
Try code below. there is no necesary to check all range by worksheetfunction every lane. find method is faster
Sub t()
Dim sh1 As Worksheet, sh2 As Worksheet, c As Range
Dim str_LookUp As String, rng_FindRange As Range
Application.ScreenUpdating = False
Application.EnableEvents = False
Set sh1 = Workbooks(WK1).Sheets(sheet1)
Set sh2 = Workbooks(WK2).Sheets(sheet1)
For Each c In sh2.Range("A2", sh2.Cells(Rows.Count, 1).End(xlUp))
str_LookUp = c.Text
Set rng_FindRange = sh1.Range("A:A").Find(str_LookUp, , , xlWhole)
If rng_FindRange Is Nothing Then
    c.Resize(, 24).Copy sh1.Cells(Rows.Count, 1).End(xlUp)(2)
End If
Next
Application.ScreenUpdating = True
Application.EnableEvents = True
End Sub


text:
Q: Bootstrap 4 creating non modal dialog box I'm want to create a non modal dialog box using bootstrap 4.

  <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal">
    Open modal
  </button>

          Modal body..

I tried by overriding model  class as below
.modal{
  top:10%;
  left:50%;
  bottom:auto;
  right:auto;
  margin-left: 30%;
}

Can someone please help me out

A: Add a class to your modal, named modalless. Like this -

Then in CSS, do the following. Now it should work.
.modalless{
    top:10%;
    left:50%;
    bottom:auto;
    right:auto;
    margin-left:-300px;
}

Check this link for an example.


text:
Q: Spring not able to autowire repository in Controller I am new to Spring and was trying to get a simple webapp up and running using Spring Data and Spring MVC.
Here is my Controller:
package org.springbyexample.web.servlet.mvc;

@Controller
@EnableJpaRepositories
public class PersonController {

    @Autowired
    private UserRepository userRepository;

    public UserRepository getRepository() {
        return userRepository;
    }

    public void setUserRepository(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    // code removed
 }

Here is my repository:
package org.springbyexample.web.orm.repository;

@Repository
public interface UserRepository extends JpaRepository<Users, String> {

    Users findByUsername(String username);

}

Here is my webmvc-context.xml
 <?xml version="1.0" encoding="UTF-8"?>
 <beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:p="http://www.springframework.org/schema/p"
   xmlns:context="http://www.springframework.org/schema/context"
   xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:jpa="http://www.springframework.org/schema/data/jpa"
   xsi:schemaLocation="http://www.springframework.org/schema/beans
                       http://www.springframework.org/schema/beans/spring-beans.xsd
                       http://www.springframework.org/schema/context
                       http://www.springframework.org/schema/context/spring-context.xsd
                       http://www.springframework.org/schema/mvc
                       http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">

<context:component-scan base-package="org.springbyexample.web.servlet.mvc" />
<context:component-scan base-package="org.springbyexample.web.security" />

<jpa:repositories base-package="org.springbyexample.web.orm org.springbyexample.web.beans" entity-manager-factory-ref="emf"/>

<mvc:annotation-driven />

<mvc:view-controller path="/index.html" />

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <property name="url" value="jdbc:mysql://localhost/demodb" />
    <property name="username" value="root" />
    <property name="password" value="" />
</bean>

<bean id="emf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="packagesToScan" value="org.springbyexample.web.orm" />
    <property name="dataSource" ref="dataSource" />
    <property name="jpaProperties">
        <props>
            <prop key="hibernate.show_sql">true</prop>
            <prop key="hibernate.hbm2ddl.auto">create</prop>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
        </props>
    </property>
    <property name="persistenceProvider">
        <bean class="org.hibernate.jpa.HibernatePersistenceProvider"></bean>
    </property>
</bean>

On running this using maven-jetty-plugin, I get the following error:
2015-04-02 16:08:39.272:WARN::Nested in    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'personController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.springbyexample.web.orm.repository.UserRepository org.springbyexample.web.servlet.mvc.PersonController.userRepository; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springbyexample.web.orm.repository.UserRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springbyexample.web.orm.repository.UserRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1308)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1054)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:949)

This is my User entity:
package org.springbyexample.web.beans;

@Entity
public class Users {

   private Timestamp activationDate;
   private Timestamp registrationDate;
   private int isActive;
   private String role;
   private String email;
   private int userId;
   @Id
   private String username;
   private String password;
   private String fullname;
   private String tranauth;
   private String clientPIN;

   // Getters and Setters for all of them

}
Appreciate any help.

A: In your xml
<jpa:repositories base-package="org.springbyexample.web.orm org.springbyexample.web.beans" entity-manager-factory-ref="emf"/>

is not correct.
If your repository in only under package org.springbyexample.web.orm
Then just remove org.springbyexample.web.beans so it will look like as
As well in your controller remove getter and setter as its not required autowire enoguh to do the magic.
<jpa:repositories base-package="org.springbyexample.web.orm" entity-manager-factory-ref="emf"/>

A: The @Enable annotations must be specified on @Configuration classes. Putting it on your controller will have no effect. You may also need to specify a base package if the repository interfaces are in a different package tree from the annotated configuration class.
(Additionally, you shouldn't annotate repository interfaces; just use the annotation for actual DAO classes when you want Spring Data to modify the handling.)

A: Can you try adding the below annotation in the class which has a public static void main(String... args) if you have one. or just try adding it to the controller.
  @Configuration
@ComponentScan
@EnableJpaRepositories
@EnableAutoConfiguration

A: In my case, the issue is resolved by changing(moving) the
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        /WEB-INF/root-context.xml
    </param-value>
</context-param>

to
<servlet>
    <servlet-name>mvc-dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/root-context.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>{code}


text:
Q: Highlight if-else-endif structures in Vim Is there a way to highlight if-else-endif structures in Vim on demand based on their 'level' in the overall program hierarchy?
I.e. I want something like
if <<< highlight in red
   foo
else <<<< red
   if <<< blue
      baz
      bar
   endif <<< blue
endif <<< red

I'm mostly editing FORTRAN code, but I guess this feature would be pretty generic, as long as the syntax highlighting works for the given language...

A: I wrote my own Vim plugin that does this (at least for FORTRAN, which is my use-case): https://github.com/fpnick/flowhighlight
Feel free to give it a try and/or extend it to your needs.
flowhighlight.vim
" File: flowhighlight.vim
" Author: Fabian P. Nick <fp.nick@gmail.com>
" Version: 0.1
" Description:
"   Highlights if-else-endif structures in different colors based on
"   their 'level' in the program flow.
"   As of October 2015 only works with Fortran.
"   VERY EARLY DEVELOPMENT VERSION!
" Uasge:
"   Use the 'FlowHighlight' command to highlight control structures.
"   Use 'FlowHighlightClear' to disable highlights.
" Configuration:
"   To define custom colors set the following variables
"     g:lcolor_bg - Background color for line highlighting
"     g:lcolor_fg - Foreground color for line highlighting
"     g:pcolor_bg - Background color for pattern highlighting
"     g:pcolor_fg - Foreground color for pattern highlighting
" Limitation:
"   Only works with a very limited FORTRAN syntax
" Acknowledgement:
"   Thanks to Amit Sethi, Dan Sharp, Michael Geddes and Benji Fisher
"   for their wonderful pieces of code.
"   Also thanks to Jarrod Taylor for his Vim Plugin framework.

python import sys
python import vim
python sys.path.append(vim.eval('expand("<sfile>:h")'))

" Main function to highlight control structures.
function! FlowHighlight()

" Python script adding 'tags' to control stuctures that are used to
" highlight the structures later.
" Also writes maximal 'depth' of control structures to the last line
" of the file.
python << endOfPython
from flowhighlight import find_flow
old_buffer = vim.current.buffer
vim.current.buffer[:] = find_flow(vim.current.buffer[:])
endOfPython

:normal mT

" Get maximum 'depth' of structures in this file
:normal G
let g:fhl_max_level = eval(getline("."))
:normal dd

" For each level, highlight the control structures
let i = 0
while i <= g:fhl_max_level
   :normal gg
   let curr_line = line(".")
   let last_line = -1
   while curr_line > last_line
      let last_line = curr_line
      let match_pat = 'flowhighlightlevel'.string(i)
      execute 'normal /' . match_pat . '
'
      let curr_line = line(".")
      let match_pat = '.*\%'.line(".").'l.*'
      exec 'syn match '. s:lcolor_grp . i  . ' "' . match_pat . '" containedin=ALL'
   endw
   let match_pat = '!flowhighlightlevel'.string(i)
   execute 'normal :%s/' . match_pat . '//g
'
   let i = i+1
endw

:normal 'T
endfunction

" Clear highlights.
function! FlowHighlight_clear()
   let i = 0
   while i <= g:fhl_max_level
      exec 'syn clear ' . s:lcolor_grp . i
      let i = i+1
   endw
endfunction

" --------------------------------
"  Expose our commands to the user
" --------------------------------
command! FlowHighlight call FlowHighlight()
command! FlowHighlightClear call FlowHighlight_clear()

" #############################################################################
" The code after this line is from highlight.vim
" (http://www.vim.org/scripts/script.php?script_id=1599) by Amit Sethi.

" Define colors for Line highlight
if !exists('g:lcolor_bg')
   let g:lcolor_bg = "purple,seagreen,violet,lightred,lightgreen,lightblue,darkmagenta,slateblue"
endif
if !exists('g:lcolor_fg')
   let g:lcolor_fg = "white,white,black,black,black,black,white,white"
endif
if !exists('g:lcolor_bg_cterm')
   let g:lcolor_bg_cterm = "Blue,Green,Cyan,Red,Yellow,Magenta,Brown,LightGray"
endif
if !exists('g:lcolor_fg_cterm')
   let g:lcolor_fg_cterm = "White,White,White,White,White,White,Black,Black"
endif
" HighlightInitFH: Initialize the highlight groups for line highlight
" Based on 'MultipleSearchInit' function developed by Dan Sharp in
" MultipleSearch2.vim at http://www.vim.org/scripts/script.php?script_id=1183
function! s:HighlightInitFH()
   let s:lcolor_grp = "FlowHiColor"
   let s:lcolor_n = 0

   let s:lcolor_max = s:Min(s:ItemCount(g:lcolor_bg . ','), s:ItemCount(g:lcolor_fg . ','))

   let ci = 0
   while ci < s:lcolor_max
      let bgColor = s:Strntok(g:lcolor_bg, ',', ci + 1)
      let fgColor = s:Strntok(g:lcolor_fg, ',', ci + 1)
      let bgColor_cterm = s:Strntok(g:lcolor_bg_cterm, ',', ci + 1)
      let fgColor_cterm = s:Strntok(g:lcolor_fg_cterm, ',', ci + 1)

      exec 'hi ' . s:lcolor_grp . ci .
         \ ' guifg =' . fgColor . ' guibg=' . bgColor
         \ ' ctermfg =' . fgColor_cterm . ' ctermbg=' . bgColor_cterm

      let ci = ci + 1
   endw
endfunction
" Min: Returns the minimum of the given parameters.
" Developed by Dan Sharp in MultipleSearch2.vim at
" http://www.vim.org/scripts/script.php?script_id=1183
function! s:Min(...)
    let min = a:1
    let index = 2
    while index <= a:0
        execute "if min > a:" . index . " | let min = a:" . index . " | endif"
        let index = index + 1
    endwhile
    return min
endfunction
" Strntok: Utility function to implement C-like strntok() by Michael Geddes
" and Benji Fisher at http://groups.yahoo.com/group/vimdev/message/26788
function! s:Strntok( s, tok, n)
    return matchstr( a:s.a:tok[0], '\v(\zs([^'.a:tok.']*)\ze['.a:tok.']){'.a:n.'}')
endfunction
" ItemCount: Returns the number of items in the given string.
" Developed by Dan Sharp in MultipleSearch2.vim at
" http://www.vim.org/scripts/script.php?script_id=1183
function! s:ItemCount(string)
    let itemCount = 0
    let newstring = a:string
    let pos = stridx(newstring, ',')
    while pos > -1
        let itemCount = itemCount + 1
        let newstring = strpart(newstring, pos + 1)
        let pos = stridx(newstring, ',')
    endwhile
    return itemCount
endfunction
" #############################################################################

call s:HighlightInitFH()

flowhighlight.py
import re
def find_flow(buffer_contents):
    """ Uses regex to find ifs and corresponding elses and endifs
    Marks them with a tag that can be used by vi later.
    """
    level = 0
    max_level = 0
    for i in range(len(buffer_contents)):

        string = buffer_contents[i]
        if ( re.match('[ ]*if.*then.*',string,re.IGNORECASE) ):
            buffer_contents[i] = string + '!flowhighlightlevel' + str(level)
            level = level+1
            if max_level < level:
                max_level = level

        if ( re.match('[ ]*else',string,re.IGNORECASE) ):
            buffer_contents[i] = string + '!flowhighlightlevel' + str(level-1)

        if ( re.match('[ ]*else if .* then',string,re.IGNORECASE) ):
            buffer_contents[i] = string + '!flowhighlightlevel' + str(level-1)

        if ( re.match('[ ]*endif',string,re.IGNORECASE) ):
            level = level-1
            buffer_contents[i] = string + '!flowhighlightlevel' + str(level)

    buffer_contents.append(str(max_level-1))
    return buffer_contents


text:
Q: How to display progress for complex Observable? I wonder how to display progress for complex Observable when I use flatMap like this:
Observable<Int>.from([1,2,3,4])
    .flatMap { queryApi($0) }
    .flatMap { queryApi2($0) }
    .flatMap { queryApi3($0) }

I was thinking to use do operator:
func longOperation() -> Observable<Progress> {

    return Observable.create { observer in
        observer.onNext(.step1)

        let operation = Observable<Int>.from([1,2,3,4])
            .flatMap { queryApi($0) }
            .do(onNext: { _ in observer.onNext(.step2) })
            .flatMap { queryApi2($0) }
            .do(onNext: { _ in observer.onNext(.step3) })
            .flatMap { queryApi3($0) }
            .do(onNext: { _ in observer.onNext(.finished) })
            .subscribe()

        return Disposables.create { operation.dispose() }
    }
}

However, I'm not sure if this is the best way to track progress. Is there any better way to handle this?

A: I like the way that Krunoslav Zaher implement ActivityIndicator in RxExample project in RxSwift repository.
https://github.com/ReactiveX/RxSwift/blob/2e64568/RxExample/RxExample/Services/ActivityIndicator.swift
Usage:
let activityIndicator = ActivityIndicator()

let state = githubSearchRepositories(
            searchText: searchBar.rx.text.orEmpty.changed.asSignal().throttle(0.3),
            loadNextPageTrigger: loadNextPageTrigger,
            performSearch: { URL in
                GitHubSearchRepositoriesAPI.sharedAPI.loadSearchURL(URL)
                    .trackActivity(activityIndicator)
})

So in your case, you can implement another observable similar to ActivityIndicator
let operationProgress = OperationProgress<Progress>()

Observable<Int>.from([1,2,3,4])
    .flatMap { queryApi($0).updateProgress(operationProgress, to: .step1) }
    .flatMap { queryApi2($0).updateProgress(operationProgress, to: .step2) }
    .flatMap { queryApi3($0).updateProgress(operationProgress, to: .step3) }

I don't know if that suits your situation, but at least it decouples your progress logic from the operation observable.


text:
Q: ng-repeat uses parent scope which is separated by two preceding isolated parent scopes - why I have this simple HTML:
  <div ng-controller="MainController">
    <tabset>
      <tab ng-repeat="tab in tabs" heading="{{tab.title}}" active="tab.active" disabled="tab.disabled">

MainController creates its own scope, tabset directive creates its own isolated scope, tab directive also creates its own isolated scope, and ng-repeat creates its own child scope as well. So we have like 4 scopes here. I'm told that ng-repeat will use MainController's scope to find tabs property. My question is why if there are two scopes created by tabset and tab in between? Is it because those scopes are isolated?
EDIT:
I'm adding the picture of my understanding based on the answers in comments

Is my understanding correct?


text:
Q: Align text in a drop-down form Bootstrap I have an inline form in a row that contains an email form and a drop down form. After resizing, the text on the drop down has lost its original positioning (text on the left, arrow on the right.) I tried using:
text-align: left;

However, my arrow is not aligned to the right, and I have no idea how to do so.

HTML file:

<title>Demo</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="style.css">

    <form class="form-inline">

        <input type="email" class="form-control" placeholder="Email Address" id="email-form">

        <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdown" data-toggle="dropdown"> Interested In... </button>

    </form>

CSS file:
body
{
  background: #000639;
}

#email-form
{
    line-height: 250%;
    margin-right: 115px;
    width: 158%;
}

#dropdown
{
    line-height: 250%;
    width: 238%;
    text-align: left;
}

.row
{
    margin-top: 10%;
}

Full screen:

A: You can target the arrow by using the ::after selector.
.dropdown-toggle::after {
    position: absolute;
    top: 26px;
    right: -155px;
}

body {
  background: #000639;
}

#email-form {
  line-height: 250%;
  margin-right: 115px;
  width: 158%;
}

#dropdown {
  line-height: 250%;
  width: 238%;
  text-align: left;
}

.row {
  margin-top: 10%;
}

.dropdown-toggle::after {
    position: absolute;
    top: 26px;
    right: -155px;
}

  <title>Demo</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css">
  <link rel="stylesheet" type="text/css" href="style.css">

      <form class="form-inline">

            <input type="email" class="form-control" placeholder="Email Address" id="email-form">

            <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdown" data-toggle="dropdown"> Interested In... </button>

      </form>

A: Adjust the left-margin to the ::after selector.
jsfiddle
.dropdown-toggle::after{

margin-left: 3.3em;
}

A: This effect can easily be obtained by using Flexbox. Add display:flex; to your #dropdown definition and set align-items: center; so that the elements will be centered vertically within its container.
To make sure your first element sticks to the left, and the right dropdown arrow sticks to the right. You can set justify-content: space-between, this will try and fill up all the space between the two items.
#dropdown {
  line-height: 250%;
  width: 238%;
  text-align: left;
  display:flex;
  align-items: center;
  justify-content: space-between;
}

Long live flexbox!


text:
Q: Backbone View not properly passing data to underscore template I am having a horrible time trying to get my template to properly display data from my View/Model.  I can get the object overall but I cannot access any data contained in the object.  I just get a response saying the object is undefined.
App.js
$(document).ready(function() {

    var Doctor = Doctor || {};

    var startup = function() {
        Doctor.groupProfile = new Group();

        Doctor.groupProfile.fetch().done(
            $.when().then(initializeUI)
        );
    };

    var initializeUI = function() {
        Doctor.groupView = new GroupsView({
            group: Doctor.groupProfile,
            el: '#template'
        });

        Doctor.groupView.render();
    };

    startup();
});

Model.js
var Group = Backbone.Model.extend({

    url: getMeetupData('groups'),

    parse: function(resp) {
        this.name = resp.results[0].name;
        this.link = resp.results[0].link;
        this.organizer = resp.results[0].organizer;
        this.description = resp.results[0].description;
        this.photo = resp.results[0].group_photo;
        this.city = resp.results[0].city;
        this.topics = new TopicCollection(resp.results[0].topics);
        return resp;
    }

});

View.js
var GroupsView = Backbone.View.extend({

    el: $('template'),

    initialize: function(options) {
      this.group = options.group;
    },

    // Use an external template
    template: _.template($('#groupsTemplate').html()),

    render: function() {
        // Fill the html with the template and the collection
        //$(this.el).html(this.template({ tweets: this.collection.toJSON() }));
        $(this.el).html(this.template({ group: this.group}));
      return this;
    }
});

Page.jade
extends ./layout/layout
    block content
        section(class="row"): div(class="column"): div(class="row")
                div(class="large-12 columns")
                    h1 Mile Hi Who
        section(class="row space"): div(class="column")
            nav(class="backboneNav"): ul
                li(class="large-3 columns about"): a(href="#about") About the Group
                li(class="large-3 columns events"): a(href='#events') Upcoming Events
                li(class="large-3 pull-3 columns"): a(href='#') Members
    section(id="template")
    script(type="text/template", id="groupsTemplate")
        section(id="swiping", class="row"): div(class="column"): div(class="row")
            div(class="large-3 large-centered columns")
                |<img id="groupPhoto" src='<%= this.group.get('groupPhoto') %>' />
                <% console.log(group); %>
            .large-12.columns.main-content.group
                h3 <%= group.name %>
                p.text <%= group.description %>
    section(class="row ajaxSpacing"): div(class="column"): div(class="row")
        div(class="large-12 columns main-content", id="templateEvent")
            script(type="text/template", id="eventsTemplate")
                <% _.each(events, function(event){ %>
                |

                |
<%= event.name %>

                |       <%= new Date(event.time).toDateString()  %>
                |       <%= new Date(event.time).toLocaleTimeString() %>
                |        <%= event.venue.name %>

                |       <button data-event-id='<%= event.id %>'>See More</button>
                |
<%= event.description %>

                |

                <% }); %>

I get the overall object but I cannot ever get any other data.
Any ideas?

A: I figured it out on my own after taking a small break and having breakfast (well second breakfast).
What was happening is I had my chaining event on the Doctor.groupProfile.fetch function wrong.  In the case above it was calling and instantiating the UI before the event was finished so while I could see console data the model did not have all the data at the time thus being undefined.
it should be:
Doctor.groupProfile.fetch().done(function() {
    $.when().then(initializeUI);
});

This way the view will be instantiated after the Model has data.
Thanks!


text:
Q: Changing the color of a point on an object I am pretty new to the shaders in WEBGL,I have an object(.Json) in my webgl scene. When I click on the object with my mouse, I want the clicked point to change its color to blue. I can get the click locations on the object in x,y,z format( called mouseclicks), and I am aware I need to use the shaders, this is what I have so far in the  shaders.
varying vec3 mouseclick;
attribute mouse;

//vertex shader
void main()
 {
  vec4 mouse =(mouseclick,1.0);

 }

  //fragmant shader

 void main()
 {

  colorout = vec3(0.0f,0.0f,1.0f);

  gl_FragColor =vec4(0.0,0.0,1.0,1.0);
  }

A: The provided shader will not work - the usage of varyings and uniforms is incorrect. Also, it is quite difficult to do it in the shader itself. You can follow below steps:

*

*Use a mechanism to find out object that is clicked (this is tricky, you need to be familiar with model to world space, transformations)

*For this object, set the color to change as required (in the application code). Send this as an attribute for this object

*Shader can be a generic shader, that sets the color as a varying, and the frag shader can use this to interpolate the colors


text:
Q: Rename multiple variables within a pipeline The pipeline metaphor enabled by packages like dplyr and magrittr is incredibly useful and does great things for making your code readable in R (a daunting task!)
How can one make a pipeline that ended with renaming all the variables in a data frame to a pre-determined list?
Here is what I tried. First, simple sample data to test on:
> library(dplyr)
> iris %>% head(n=3) %>% select(-Species) %>% t %>% as.data.frame -> test.data
> test.data

               1   2   3
Sepal.Length 5.1 4.9 4.7
Sepal.Width  3.5 3.0 3.2
Petal.Length 1.4 1.4 1.3
Petal.Width  0.2 0.2 0.2

This doesn't work:
> test.data %>% rename(a=1,b=2,c=3)
Error: Arguments to rename must be unquoted variable names. Arguments a, b, c are not.

I wasn't able to figure out the precise meaning of this error from reading the documentation on rename. My other attempt avoids an error by using curly braces to define a code block, but the renaming doesn't actually happen:
> test.data %>% { names(.) <- c('a','b','c')}

A: '1','2','3'You were correct except use setNames {stats} instead of rename (zx8754 answered in your comment before me)

setNames: This is a convenience function that sets the names on an
  object and returns the object. It is most useful at the end of a
  function definition where one is creating the object to be returned
  and would prefer not to store it under a name just so the names can be
  assigned.

Your example (Close just change rename with setNames)
iris %>%
   head(n=3) %>%
   select(-Species) %>%
   t %>%
   as.data.frame %>%
   rename(a=1,b=2,c=3)

Answer
iris %>%
   head(n=3) %>%
   select(-Species) %>%
   t %>%
   as.data.frame %>%
   setNames(c('1','2','3'))

Another Example
name_list <- c('1','2','3')

iris %>%
   head(n=3) %>%
   select(-Species) %>%
   t %>%
   as.data.frame %>%
   setNames(name_list)

A: The way I got this to work, I needed the tee operator from the magrittr package:
> library(magrittr)
> test.data %T>% { names(.) <- c('a','b','c')} -> renamed.test.data
> renamed.test.data
               a   b   c
Sepal.Length 5.1 4.9 4.7
Sepal.Width  3.5 3.0 3.2
Petal.Length 1.4 1.4 1.3
Petal.Width  0.2 0.2 0.2

Note that for a data frame with normal (i.e. not numbers) variable names, you can do this:
> # Rename it with rename in a normal pipe
> renamed.test.data %>% rename(x=a,y=b,z=c) -> renamed.again.test.data
> renamed.again.test.data
               x   y   z
Sepal.Length 5.1 4.9 4.7
Sepal.Width  3.5 3.0 3.2
Petal.Length 1.4 1.4 1.3
Petal.Width  0.2 0.2 0.2

The above trick (edit: or, even better, using setNames) is still useful, though, because sometimes you already have the list of names in a character vector and you just want to set them all at once without worrying about writing out each replacement pair.

A: We can rename the numerical variable names with dplyr::rename by enclosing in Backquote(`).
library(dplyr)

iris %>%
  head(n=3) %>% select(-Species) %>% t %>% as.data.frame %>%
  dplyr::rename(a=`1`, b=`2`, c=`3`)
# a   b   c
# Sepal.Length 5.1 4.9 4.7
# Sepal.Width  3.5 3.0 3.2
# Petal.Length 1.4 1.4 1.3
# Petal.Width  0.2 0.2 0.2

As another way, we can set column name by using stats::setNames,  magrittr::set_names and purrr::set_names.
library(dplyr)
library(magrittr)
library(purrr)

iris %>%
  head(n=3) %>% select(-Species) %>% t %>% as.data.frame %>%
  stats::setNames(c("a", "b", "c"))

iris %>%
  head(n=3) %>% select(-Species) %>% t %>% as.data.frame %>%
  magrittr::set_names(c("a", "b", "c"))

iris %>%
  head(n=3) %>% select(-Species) %>% t %>% as.data.frame %>%
  purrr::set_names(c("a", "b", "c"))
# The results of above all codes is as follows:
# a   b   c
# Sepal.Length 5.1 4.9 4.7
# Sepal.Width  3.5 3.0 3.2
# Petal.Length 1.4 1.4 1.3
# Petal.Width  0.2 0.2 0.2


text:
Q: Neo4j - social network - relationship properties - two way or one way with properties Say I have two people who are friends, in an effort to keep the number of relationships used low, should I use an outbound relationship from one to the other with a property of "friend_type: mutual" in order to indicate a two way friendship?  (one way friendship would have  "friend_type: following")
Will this affect performance since properties are not first class objects?  Or should I make inbound and outbound friendship relationships so that performance won't suffer.
For example, to find a friend of mine that has friended me, using an outgoing relationship such as:
Ruben [f:Friend]->You
where f.friend_type="mutual"
or instead, rely on incoming and outgoing relationships (not properties)
Ruben <-[:Friend]-> You
Which option offers the best performance?
32 billion relationship limit might seem like enough, but hey, I have big plans and if it works out I'll need all relationships I can get....

A: Your graph will be faster if you just have to traverse relationships without having to look at the properties on those relationships.  The 32 Billion Relationship constraint will soon be removed, I wouldn't worry about it.


text:
Q: String array count and merge to one I have searched around the web, but dont know the right keywords to find the solution.
Example code:
$arr = array(1, 2, 3, 4);

$json_components = array();
$count = 0;

foreach ($arr as &$value) { $count++;
  $array_string = array("type" => "list", 'name' => 'example '.$count.'');
}

$json_components = array_merge($json_components, $array_string);

print_r($json_components);
die();

In the foreach there's a $array_string this can have the same names/keys/values each time (with small differences).
What I want to succeed is to merge it to one array.
I have tried: $array_string.count = array("type" => "list", 'name' => 'example '.$count.''); but this is not working.
Final result what I'm looking for:
$json_components = array(
 array("type" => "list", 'name' => 'example 1'),
 array("type" => "list", 'name' => 'example 2'),
 array("type" => "list", 'name' => 'example 3'),
 array("type" => "list", 'name' => 'example 4')
);

print_r($json_components);
die();

A: Simply add to the array like this and then you dont need to merge the arrays
$arr = array(1, 2, 3, 4);

$json_components = array();

foreach ($arr as $value) {
    $json_components[] = [ "type" => "list",
                           'name' => "example $value"
                      ];
}

print_r($json_components);

RESULT
Array
(
    [0] => Array
        (
            [type] => list
            [name] => example 1
        )
    [1] => Array
        (
            [type] => list
            [name] => example 2
        )
    [2] => Array
        (
            [type] => list
            [name] => example 3
        )
    [3] => Array
        (
            [type] => list
            [name] => example 4
        )
)

A: You don't need to use loop with array_merge(), you can just use array_map()  function:
<?php
$arr = array(1, 2, 3, 4);

$json_components = array();

$new_array = array_map(function($val) {
    return array("type" => "list", 'name' => 'example '. $val);
}, $arr);

print_r($new_array);
die();

Here is a working snippet: https://3v4l.org/BvaVF


text:
Q: Bind static data as dictionary key How to bind dictionary static data as dictionary key?

My XAML code:
<TextBlock
    x:Name="AxisXTextBlock"
    Width="37"
    Height="18"
    Margin="106,19,0,0"
    HorizontalAlignment="Left"
    VerticalAlignment="Top"
    FontFamily="Source Code Pro"
    Text="{Binding DataStructure.DictionaryOfValuesReadOnly[AXIS_X].IntValue, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"
    TextWrapping="Wrap" />

Class of static data for keys of dictionaries:
public static class DataNames
{
    public static string SomeDataName { get; } = "some_data_name";
    ...
}

How can I bind DataNames.SomeDataName as a key of my dictionary in XAML code?
UPDATE
I use dictionary converter and then bind it as StaticResource
xmlns:converters="clr-namespace:AppName.Converters"
...
<converters:SomeConverter x:Key="SomeConverter " />
...
Text="{Binding Path=DataStructure, Converter={StaticResource SomeConverter}, ConverterParameter={x:Static data:DataNames.SomeDataName}}"

Thanks mm8 for helping in solution. His answer contains code for dictionary converter.

A: I am afraid XAML doesn't support this kind of "dynamic" binding paths.
You could use a converter though, e.g.:
public class DictConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        IDictionary<string, string> dict = value as IDictionary<string, string>;
        string key = parameter as string;

        string s;
        if (dict != null && !string.IsNullOrEmpty(key) && dict.TryGetValue(key, out s))
            return s;

        return null;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}

<TextBlock Text="{Binding Path=Dict, Converter={StaticResource conv}, ConverterParameter={x:Static local:DataNames.AxisX}}" />

A: You can use static markup extension:
<TextBlock
    x:Name="AxisXTextBlock"
    Background="Yellow"
    Width="100"
    Height="30"
    Margin="106,19,0,0"
    HorizontalAlignment="Left"
    VerticalAlignment="Top"
    FontFamily="Source Code Pro"
    Text="{Binding DataStructure.DictionaryOfValuesReadOnly[{x:Static local:DataNames.AxisX}].IntValue, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"
    TextWrapping="Wrap" />