text:
Q: Shell function in a file not running when invoked with ". file args..." I am learning bash stuff, and I think I'm confused about functions.  When I write a function(?) to repeat a character a desired number of times like this:
_repeat()
{
    #@ USAGE: _repeate string number
    _REPEAT=$1
    while [ ${#_REPEAT} -lt $2 ]
    do
        _REPEAT=$_REPEAT$_REPEAT$_REPEAT
    done

    _REPEAT=${_REPEAT:0:$2} ## Trim to desired length

    printf "%s\n" "$_REPEAT"
}

and I call it on the command line with . _repeat "hi" 5 nothing prints to the terminal.  If I take away the function name and brackets, and just have the code, and do chmod +x /pathtofile/_repeat and call repeat "hi" 5 it does print to the command line.
I think I'm misunderstanding something about functions but I'm not sure what.

A: What's Going On
When you run:
. _repeat hi 5

...that's running the contents from the file _repeat in your current shell, with $1 being hi and $2 being 5.
However, the contents given in the question merely define a function; they don't invoke that function, so the function body never takes effect.

Modifying Your Script To Invoke The Function
Simply add the following line to the end:
if (( $# )); then _repeat "$@"; fi

This will invoke the function _repeat if the script is passed a nonzero argument list. (If passed no arguments, sourcing the script will merely define the function without executing it).

Invoking Your Function Without The Script
At any point after the function has been defined, you can execute it by just calling it as a command, without the dot:
_repeat hi 5


text:
Q: Crystal Reports Filtering and Organizing data I am writing a small Crystal Report using 2 tables (TICKET,HISTORY,CUSTOMER) from a database I was given access to.  I do not have access to modify the database tables to correct the issue and I am looking to see if this is possible.
The TICKET table is my main table and has a 1 to Many relation to HISTORY table.
The CUSTOMER table has 1 to Many relation to the TICKET table.
Inside the HISTORY table, there is column called Version.  Every time a HISTORY entry is added on a TICKET, the Version number is written into this field, ie 21.4, 19.7, etc.
Ideally, the version would be better suited attached to the CUSTOMER table once the entry was added into the HISTORY table, but that change has not been made.
What I am trying to do with my report is group and display my results as follows:

*

*Version Number

*

*Customer Name

I can get this far, but the issue I am running into is, I only want to show the customer on their latest version number and suppress all previous records so I can get an accurate count of how many and which customers are on each version.  Is this possible to do?

A: If you are allowed to create a VIEW in the database, create one that joins Ticket to History, groups on Ticket ID, and returns the Ticket ID and the Max of the Version.
In Crystal, you can then simply joint to that View.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Tour de Flex Source I like Tour de Flex very much. I would like to build an application looking similar to Tour de Flex.
How can I get the source code of Tour de Flex (just UI code, no backend stuff)?

A: Perhaps sending an e-mail instead of posting it on a website would be a good start? :P
I guess a better place to ask this would be on the Adobe Flex forums

A: The source code for Tour de Flex is not publicly available. However that application is pretty basic.  Just some skinning of a Flex application and a few Flex containers.

A: The source code for Tour De Flex was donated to Apache and can now be found in the Apache Flex utilities github site.


text:
Q: Reshaping tables from long to wide format in R

set
inst
ind
color_Blue

1
0
0
70

1
0
1
60

1
0
2
50

1
1
0
30

1
1
1
20

1
1
2
66

2
0
0
35

2
0
1
22

2
0
2
28

2
1
0
90

2
1
1
47

2
1
2
23

I have data frame looks like this above and I want to convert this to:

ind
set
inst_0
inst_1
inst_2

0
1
70
60
50

1
1
30
20
66

2
1
35
22
28

0
2
90
47
23

1
2
..
..
..

2
2
..
..
..

How can I do this transform? I would appreciate any suggestion. Thank you so much!
I have tried some things but did not really work.I have to do the change based on two columns information and that was confusing me.

A: You can use pivot_wider() from tidyr for reshaping.
library(tidyr)

df %>%
  pivot_wider(names_from = ind, values_from = color_Blue, names_prefix = 'inst_')

# # A tibble: 4 × 5
#     set  inst inst_0 inst_1 inst_2
#   <int> <int>  <int>  <int>  <int>
# 1     1     0     70     60     50
# 2     1     1     30     20     66
# 3     2     0     35     22     28
# 4     2     1     90     47     23

Data
df <- read.table(text = "
set inst    ind color_Blue
1   0   0   70
1   0   1   60
1   0   2   50
1   1   0   30
1   1   1   20
1   1   2   66
2   0   0   35
2   0   1   22
2   0   2   28
2   1   0   90
2   1   1   47
2   1   2   23", header = TRUE)

A: data.table
df <- read.table(text = "set    inst    ind color_Blue
1   0   0   70
1   0   1   60
1   0   2   50
1   1   0   30
1   1   1   20
1   1   2   66
2   0   0   35
2   0   1   22
2   0   2   28
2   1   0   90
2   1   1   47
2   1   2   23", header = T)

library(data.table)
dcast(
  data = setDT(df),
  formula = inst + set ~ paste0("inst_", ind),
  value.var = "color_Blue"
)
#>    inst set inst_0 inst_1 inst_2
#> 1:    0   1     70     60     50
#> 2:    0   2     35     22     28
#> 3:    1   1     30     20     66
#> 4:    1   2     90     47     23

Created on 2023-01-19 with reprex v2.0.2


text:
Q: How can I draw an overline in a UILabel? I'm trying to draw an overline (as opposed to strikethrough or underline) within a UILabel. So far I have not seen any direct way to implement this using NSAttributedString. Is there any way to do overlines in UILabel?

A: There's a good solution of your problem.
Create a subclass of UILabel, may be, OverlineLabel. Create a view in the class that sticks to the top of the label, and is of equal width of the label itself, and is of height 1 or 0.5 (as you see it comfortable). Add the view as subview when text property is not nil. And don't forget to remove it when text is nil.


text:
Q: failure to initialize SDL audio When i Call SDL_Init passing in SDL_AUDIO_INIT, the function returns a failure.
I called SDL_GetError() but there does not seem to be any message.
I am not having problems getting VIDEO to initialize, only audio. I don't get any errors when compiling. I have linked the SDL mixer library in my makefile.
Here is a minimum reproducible example code:
#include <SDL2/SDL.h>
#include <stdio.h>
#include <string>

int main( int argc, char* args[] )
{

        //Initialize SDL
        if( SDL_Init( SDL_INIT_VIDEO  < 0))
        {
                printf( "SDL VIDEO could not initialize! SDL Error: %s\n", SDL_GetError() );
        }
        else if ( SDL_Init( SDL_INIT_AUDIO) < 0)
        {
                printf( "SDL AUDIO could not initialize! SDL Error: %s\n", SDL_GetError() );
        }
        else
        {
                printf("video and audio initialized");
        }

        return 0;
}

output: SDL AUDIO could not initialize! SDL Error:
(there is no message for the error)
Here is the makefile
#OBJS specifies which files to compile as part of the project
OBJS = 21_sound_effects_and_music.cpp

#CC specifies which compiler we're using
CC = g++

#COMPILER_FLAGS specifies the additional compilation options we're using
# -w suppresses all warnings
COMPILER_FLAGS = -g -Wall

#LINKER_FLAGS specifies the libraries we're linking against
LINKER_FLAGS = -lSDL2 -lSDL2_image -lSDL2_ttf -lSDL2_mixer

#OBJ_NAME specifies the name of our exectuable
OBJ_NAME = sdl_program

#This is the target that compiles our executable
all : $(OBJS)
        $(CC) $(OBJS) $(COMPILER_FLAGS) $(LINKER_FLAGS) -o $(OBJ_NAME)

I am using Ubuntu 20.04

A: install libasound2-dev libpulse-dev
and recompyling SDL2
Audio drivers   : disk dummy oss alsa(dynamic) pulse(dynamic) <--- IS OK


text:
Q: How can I fade out one element and fade in another without the "snapping"? I am attempting to fade out one element using "ng-show" and fade in another at the same time.  This is working all fine and dandy, but unfortunately when the element which is fading out is hidden, there appears to be some "snapping" when display: none is set.
I've attempted setting position: absolute on my ng-hide-add-active & ng-hide-remove-active but this simply screws up the layout.
HTML:

Hello

Stuff Box

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis lacinia urna vitae lectus faucibus porta. Nulla eu consequat nisl. Quisque fringilla sapien id vulputate sollicitudin. Curabitur et facilisis justo. Donec malesuada augue vitae diam maximus luctus. Nulla fermentum consectetur ipsum ut tempor. Curabitur pretium eros eget nisi bibendum fermentum. Cras fermentum egestas nunc ut vulputate. Nulla aliquam tortor ut nulla consequat faucibus. Fusce imperdiet, felis nec semper vestibulum, magna dui ultricies tortor, eget mattis mauris arcu et ipsum. Suspendisse imperdiet nec mauris eget placerat.

Nulla purus augue, congue sed sollicitudin ut, volutpat sed ex. Donec lobortis sem eu risus consequat tincidunt. Nullam egestas lectus et semper gravida. Suspendisse facilisis erat a eros scelerisque euismod. Sed elementum eros ac nibh viverra condimentum eu vel mi. Ut sit amet nulla sit amet velit dignissim cursus quis ut mi. In a ultrices dolor. Proin sollicitudin sit amet lorem in fringilla. Mauris ac egestas est. Donec quis fermentum est, nec interdum nisi. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin id massa pellentesque, fringilla orci id, ultrices nisl. Nam non viverra felis, ac sodales justo.

CSS:
/* Styles */

#content-well {
  margin-bottom: 0px;
}

/* Animations */

.animate.ng-hide-add,
.animate.ng-hide-remove {
  -webkit-transition:all linear 0.5s;
  -moz-transition:all linear 0.5s;
  -o-transition:all linear 0.5s;
  transition:all linear 0.5s;
}

.animate.ng-hide-add.ng-hide-add-active,
.animate.ng-hide-remove {
  opacity:0;
}

.animate.ng-hide-add,
.animate.ng-hide-remove.ng-hide-remove-active {
  opacity:1;
}

/* Folding cube spinner */

.sk-folding-cube {
  margin: 40px auto;
  width: 40px;
  height: 40px;
  position: relative;
  -webkit-transform: rotateZ(45deg);
  transform: rotateZ(45deg);
}

Please see this Plunker:
http://plnkr.co/edit/6vSRIJ8xkmn75S9FyLMJ?p=preview
Is it possible to have the loading spinner & content both remain centered and properly positioned while one fades out and the other fades in?  Any assistance would be greatly appreciated.  Thank you!

A: Put position: absolute on one of the two containers.
For example:
.sk-folding-cube {
  position: absolute;

The drawback is that you will have to add more CSS both to position the element as you want and to make it look like the panel wraps it.
For example:
.panel {
  min-height: 161px;
}

.sk-folding-cube {
  position: absolute;
  left: 50%;
  margin-left: -20px;
  margin-top: 40px;
  margin-bottom: 40px;
  width: 40px;
  height: 40px;
  -webkit-transform: rotateZ(45deg);
  transform: rotateZ(45deg);
}

Demo: http://plnkr.co/edit/5lYJneAkT6TwYkfg3KPJ?p=preview
Another solution is to just skip the fade out animation entirely. Personally, when elements are overlapping, I rarely find it necessary to have one of the elements fade in while the other fade out. Instead, just hide the first and fade in the other. A matter of taste perhaps.
Demo: http://plnkr.co/edit/iudjWchMXzc3wILhQmsY?p=preview


text:
Q: How to deactivate and remove old site templates? I have created new site templates, which are meant to replace old templates.
We want to deactivate and remove the old ones so only the new templates are available in template list.
I can deactivate and remove templates that have not been used yet. but when I try to deactivate old templates that have been used up until now, I get an error message saying

I don't have access.

I have owner access to the site. Do I need to have Site Collection administrator rights to be able to do it?

A: Yes, it's a permission issue, The site Owner can only deactivate and delete the Site Template that already not used.
At the other side, the Site Collection Administrator is responsible for the entire site collection and can deactivate and delete a Site Template that already used or not.
So you should be a Site Collection Administrator to be able to deactivate and delete Site Template that already used.

Note: Once the site is saved as a template it saved in Solution Gallery below Web Designer Galleries in the Site Collection,
  Solution Gallery is not available in sub site Web Designer
  Galleries

Site Owners are responsible for one part of a Site Collection only, and cannot change anything on Site Collection level. They have full control on one or more subsites, and can grant permissions to users, create lists and subsite ... etc
Site Collection Administrator: is responsible for the entire site collection, has to access to Site Collection wide features in several places including Site Settings, Solutions Gallary ... etc.
Read more about The difference between Site Owners and Site Collection Administrator


text:
Q: Need help to fix the GUI The problem is that the text under the bar chart is not aligned with the bars in the bar chart. How do I make them align properly?
What more could I possibly add as details to this question to make your detector shut up? :)
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class SimpleBarChart extends JPanel {

    private double[] value;
    private String[] languages;
    private String title;
    private int gapBetweenBars = 40;//MODIFICATION - NOT A PART OF ORIGINAL CODE

    public SimpleBarChart(double[] val, String[] lang, String t) {
        languages = lang;
        value = val;
        title = t;
    }

    public void paintComponent(Graphics graphics) {
        super.paintComponent(graphics);
        if (value == null || value.length == 0) {
            return;
        }
        double minValue = 0;
        double maxValue = 0;
        for (int i = 0; i < value.length; i++) {
            if (minValue > value[i]) {
                minValue = value[i];
            }
            if (maxValue < value[i]) {
                maxValue = value[i];
            }
        }
        Dimension dim = getSize();
        int clientWidth = dim.width;
        int clientHeight = dim.height;
        int barWidth = clientWidth / value.length;

        barWidth = barWidth / 3;//MODIFICATION - NOT A PART OF ORIGINAL CODE

        Font titleFont = new Font("Book Antiqua", Font.BOLD, 15);
        FontMetrics titleFontMetrics = graphics.getFontMetrics(titleFont);
        Font labelFont = new Font("Book Antiqua", Font.PLAIN, 10);
        FontMetrics labelFontMetrics = graphics.getFontMetrics(labelFont);
        int titleWidth = titleFontMetrics.stringWidth(title);
        int q = titleFontMetrics.getAscent();
        int p = (clientWidth - titleWidth) / 2;
        graphics.setFont(titleFont);
        graphics.drawString(title, p, q);
        int top = titleFontMetrics.getHeight();
        int bottom = labelFontMetrics.getHeight();

        if (maxValue == minValue) {
            return;
        }

        double scale = (clientHeight - top - bottom) / (maxValue - minValue);
        q = clientHeight - labelFontMetrics.getDescent();
        graphics.setFont(labelFont);

        for (int j = 0; j < value.length; j++) {
            int valueP = j * (barWidth + gapBetweenBars) + 1; //MODIFICATION - NOT A PART OF    ORIGINAL CODE
            int valueQ = top;
            int height = (int) (value[j] * scale);
            if (value[j] >= 0) {
                valueQ += (int) ((maxValue - value[j]) * scale);
            } else {
                valueQ += (int) (maxValue * scale);
                height = -height;
            }
            graphics.setColor(Color.blue);
            graphics.fillRect(valueP, valueQ, barWidth - 2, height);
            graphics.setColor(Color.black);
            graphics.drawRect(valueP, valueQ, barWidth - 2, height);
            int labelWidth = labelFontMetrics.stringWidth(languages[j]);
            p = j * barWidth + (barWidth - labelWidth) / 2;
            graphics.drawString(languages[j], p, q);
        }
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setSize(500, 500);
        double[] value = new double[5];
        String[] languages = new String[5];
        value[0] = 1;
        languages[0] = "Visual Basic";

        value[1] = 2;
        languages[1] = "PHP";

        value[2] = 3;
        languages[2] = "C++";

        value[3] = 4;
        languages[3] = "C";

        value[4] = 5;
        languages[4] = "Java";

        frame.getContentPane().add(new SimpleBarChart(value, languages, "Programming    Languages"));

        WindowListener winListener = new WindowAdapter() {
            public void windowClosing(WindowEvent event) {
                System.exit(0);
            }
        };
        frame.addWindowListener(winListener);
        frame.setVisible(true);
    }

    public void setGapBetweenBars(int gapBetweenBars) {

        this.gapBetweenBars = gapBetweenBars;
    }

    public int getGapBetweenBars() {

        return this.gapBetweenBars;
    }
}

A: use this in side for loop
int labelWidth = labelFontMetrics.stringWidth(languages[j]);
p = j * (barWidth+gapBetweenBars) + (barWidth - labelWidth) / 2;

changed calculation of space between Languages strings

A: The value of p in your for loop is incorrect and should rather be:
p = j * (barWidth + gapBetweenBars) + (barWidth - labelWidth) / 2;

You forgot to take the gap into account.


text:
Q: onDoubleClick is not working on react to call a function I'm following this React tutorial here: https://ibaslogic.com/how-to-edit-todos-items-in-react/ to build a simple TO DO app.
I've also reviewed Why onDoubleClick event is not working in React.js? but there's no onclick event to worry about in my example.
My onDoubleClick event should call a function handleEditing but nothing happens when I double click a list item.
I'm unsure of why it does not work (the web browser does not seem to register a double click event.
Below is my example:
import React from "react";
import styles from "./TodoItem.module.css";

class TodoItem extends React.Component {
  state = {
    editing: false,
  };

  handleEditing = () => {
      console.log("doubleClick")
    this.setState({
      editing: true,
    });
  };

  render() {

    const completedStyle = {
      fontStyle: "italic",
      color: "#595959",
      opacity: 0.4,
      textDecoration: "line-through",
    };

    const { completed, id, title } = this.props.todo;

    let viewMode = {}
let editMode = {}

if (this.state.editing) {
  viewMode.display = "none"
} else {
  editMode.display = "none"
}

    return (

          <input
            type="checkbox"
            className={styles.checkbox}
            checked={completed}
            onChange={() => this.props.handleChangeProps(id)}
          />
          <button onClick={() => this.props.deleteTodoProps(id)}>Delete</button>
          {title}

        <input type="text" style={editMode} className={styles.textInput} />

    );
  }
}

export default TodoItem;

I don't think this is relevant, but here is my css:
.item {
    font-size: 1.2rem;
    list-style-type: none;
    padding: 17px 0px;
    border-bottom: 1px solid #eaeaea;
  }

  .checkbox {
    margin-right: 15px;
  }

  .item button {
    font-size: 13px;
    background: #f1f3f4;
    border: none;
    cursor: pointer;
    float: right;
    outline: none;
    border-radius: 100px;
    height: 50px;
    width: 50px;
    margin: -10px 0 0 10px;
  }

  .textInput {
    width: 100%;
    padding: 10px;
    border: 1px solid #dfdfdf;
  }

A: onDoubleClick works when your dev tool is not opened

A: Updated answer:
As found out in the comments, the problem was a combination of OS and Browser. Windows / Chrome in this example.
Old answer:
I haven't read into much detail, but the first difference I can spot is that in your code the handleEditing is not bound. Which should not prevent the output of your console.log. Does it appear?
onDoubleClick={this.handleEditing.bind(this)}

Hope this helps in your case.


text:
Q: Predicate as the subject of another triple Lets says I have a RDF triple store that has
:Person1 :hasLocation :Location1.

Am I allowed to create other triples with :hasLocation as subject/object? (examples below):
:hasLocation rdf:Type :LocationPredicates.
:hasLocation rdfs:label "someLabel".
:hasLocation rdfs:comment "someComment".
:hasLocation :someProperty :otherObject


text:
Q: Can apt-get be used on Red Hat systems? We know that apt-get is used on debian based systems so what is used on Red Hat Enterprise Linux (RHEL) systems? Is it possible to install and use apt-get on Red Hat?

A: No, apt is Debian specific. apt uses dpkg to install .deb files (which are binary files that are specific to Debian).
Red Hat based Linux distributions uses the rpm package management system. You can use yum to retrieve and install rpms on Red Hat distributions:
 yum search som-package-name
 yum install some-package-name

If you want to install an rpm that you've downloaded on your own, you could use rpm -i some-package.rpm to install it (and rpm -qa to retrieve a list of all installed rpms). This is equivalent to dpkg -i some-package.deb (and dpkg --get-selections to retrieve a list of all installed deb packages) on Debian based distributions.

A: There is a project out there that claims to support apt style repositories (as well as the apt-get command) on RPM based distros. It is called apt-rpm and is used as the default package manager on a few distros, though not on RHEL/Fedora.
Problems:

*

*It seems not to be really maintained since ~2008; it may have incremental patches or fixes since then, but nothing major.

*Yum repositories are not compatible with apt-rpm, so even if you were to install it on your computer, you would need an apt-rpm repository to connect to in order to use it.

There is a fork of apt-rpm that has been updated to be mostly compatible with rpm version 5, which is used in all recent RPM distros. So if you insist on using it, a good starting point is to check out the Gitorious branch for apt-rpm for rpm5.
The command syntax of yum is close enough to apt-get that you should be able to learn one if you know the other within a day, or at most, a week. So unless there is some very strong business need for using apt and you're willing to create your own apt-rpm repository (and deal with the cruftiness of software that's basically unmaintained), I would advise against proceeding down this train of thought.


text:
Q: d3.js - extent width not match axis line with svg defs I would like to add some extension to axis with arrow head. below code work basically but the width of extent arrow not match the width of axis!

axis_demo()
function axis_demo() {
  var width = 400
  var height = 100
  var margin = {left:20,top:40,right:80,bottom:20}

  var svg = d3.select('body')
  .append('svg')
  .attr('width',width + margin.left + margin.right)
  .attr('height',height + margin.top + margin.bottom)
  .style('border','2px solid red')

  var lc = 'grey'
  var lw = 4
  add_defs(svg,lw,lc)

  var g = svg.append('g')
  .attr('transform',`translate(${margin.left},${margin.top})`)

  add_scalePoint(g,width,height)
  console.log("done")
  function add_scalePoint(g,width,height) {
    var data = [
      {day : 'Mon', value: 10},
      {day : 'Tue', value: 40},
      {day : 'Wed', value: 30},
      {day : 'Thu', value: 60},
      {day : 'Fri', value: 30}
    ];
    var xname = 'day'
    var yname = 'value'

    var xdomain = data.map(d => d[xname])
    var xScale = d3.scalePoint()
      .domain(xdomain)
      .range([0, width]);

    let xaxis = g.append("g")
    .attr("class", "xaxis")
    .call(d3.axisBottom(xScale)
          .tickSizeOuter(0)
          .tickPadding(0))

    xaxis.select('path')
      .attr('stroke-width',lw)
      .attr('stroke',lc)
      .attr('marker-end', 'url(#arrhead)');

    xaxis.selectAll('.tick line')
      .attr('stroke',lc)

    xaxis.selectAll("text")
    .attr("transform", "rotate(-30)")
    .style("text-anchor", "end");

    g.selectAll('circle')
      .data(data)
      .enter()
      .append('circle')
      .attr('cy',-30)
      .attr('cx', function(d) {
        return xScale(d[xname]);
      })
      .attr('r', 2);
  }

  function add_defs(g,lw,lc) {
      var xoff = 10
      var dx = 4
      var dy = 1.5
      var arrpath = ['M',2*lw,dy+2*lw,'l',xoff,0,
         0,dy,dx,-dy,-dx,-dy,0,dy]
      svg
      .append('defs')
      .append('marker')
      .attr('id', 'arrhead')
      .attr('refX', 2*lw)
      .attr('refY', dy+2*lw)
      .attr('markerWidth',xoff + dx + 4*lw )
      .attr('markerHeight', 2*dy + 4*lw)
      .attr('orient', 'auto-start-reverse')
      .append('path')
      .attr('d', arrpath.join(' '))
      .attr('stroke-miterlimit',5)
      .attr('stroke', lc)
      .attr('stroke-width', lw)
      .attr('fill', lc);
  }

  function add_circle(g,cx,cy,r) {
    g.append('circle')
    .attr('cx',cx)
    .attr('cy',cy)
    .attr('r',r);
  }
}
 <script src="https://d3js.org/d3.v6.min.js"></script>

A: Omit
.attr('stroke-width', lw)
when building the marker,
or replace lw with 1:
.attr('stroke-width', 1)

axis_demo()
function axis_demo() {
  var width = 400
  var height = 100
  var margin = {left:20,top:40,right:80,bottom:20}

  var svg = d3.select('body')
  .append('svg')
  .attr('width',width + margin.left + margin.right)
  .attr('height',height + margin.top + margin.bottom)
  .style('border','2px solid red')

  var lc = 'grey'
  var lw = 4
  add_defs(svg,lw,lc)

  var g = svg.append('g')
  .attr('transform',`translate(${margin.left},${margin.top})`)

  add_scalePoint(g,width,height)
  console.log("done")
  function add_scalePoint(g,width,height) {
    var data = [
      {day : 'Mon', value: 10},
      {day : 'Tue', value: 40},
      {day : 'Wed', value: 30},
      {day : 'Thu', value: 60},
      {day : 'Fri', value: 30}
    ];
    var xname = 'day'
    var yname = 'value'

    var xdomain = data.map(d => d[xname])
    var xScale = d3.scalePoint()
      .domain(xdomain)
      .range([0, width]);

    let xaxis = g.append("g")
    .attr("class", "xaxis")
    .call(d3.axisBottom(xScale)
          .tickSizeOuter(0)
          .tickPadding(0))

    xaxis.select('path')
      .attr('stroke-width',lw)
      .attr('stroke',lc)
      .attr('marker-end', 'url(#arrhead)');

    xaxis.selectAll('.tick line')
      .attr('stroke',lc)

    xaxis.selectAll("text")
    .attr("transform", "rotate(-30)")
    .style("text-anchor", "end");

    g.selectAll('circle')
      .data(data)
      .enter()
      .append('circle')
      .attr('cy',-30)
      .attr('cx', function(d) {
        return xScale(d[xname]);
      })
      .attr('r', 2);
  }

  function add_defs(g,lw,lc) {
      var xoff = 10
      var dx = 4
      var dy = 1.5
      var arrpath = ['M',2*lw,dy+2*lw,'l',xoff,0,
         0,dy,dx,-dy,-dx,-dy,0,dy]
      svg
      .append('defs')
      .append('marker')
      .attr('id', 'arrhead')
      .attr('refX', 2*lw)
      .attr('refY', dy+2*lw)
      .attr('markerWidth',xoff + dx + 4*lw )
      .attr('markerHeight', 2*dy + 4*lw)
      .attr('orient', 'auto-start-reverse')
      .append('path')
      .attr('d', arrpath.join(' '))
      .attr('stroke-miterlimit',5)
      .attr('stroke', lc)
      .attr('stroke-width', 1)
      .attr('fill', lc);
  }

  function add_circle(g,cx,cy,r) {
    g.append('circle')
    .attr('cx',cx)
    .attr('cy',cy)
    .attr('r',r);
  }
}
 <script src="https://d3js.org/d3.v6.min.js"></script>


text:
Q: How does Yelp create the "Review Highlights" section? Take the following link as an example: http://www.yelp.com/biz/chef-yu-new-york.
In the section called 'Review Highlights', there are 3 phrases (spicy diced chicken, happy hour, lunch specials) that are highlighted based on reviews submitted by users. Obviously, these are the phrases that appeared most often, or longest phrases that appeared often, or some other logic.
Their official explanation is this:

In their reviews, Yelpers mentioned the linked phrases below a lot.
  And these aren't any old common phrases, they're also the ones that
  our Yelp Robots have determined are unique and good, quick ways to
  describe this business. Click any of the phrases to see all the
  reviews that mention it.

My question is, what did they use to mine the text input to get these data points? Is it some algorithm based on Lempel Ziv, or some kind of map reduce? I was not a CS major, so probably am missing something foundational here. Would love some help, theories, etc.
Thanks!

A: I don't have any insight on the exact algorithm Yelp is using but this is a common problem in natural language processing. Essentially you want to extract the most relevant collocations (http://en.wikipedia.org/wiki/Collocation).
A simple way to do this is to extract a list of n-grams with the highest PMI (pointwise mutual information). This SO question explains how to do this using Python and the nltk library:
How to extract common / significant phrases from a series of text entries

A: Lempel-Ziv is a data compression algorithm, and map-reduce is a technique for data processing. The former is probably not involved, and the latter is generally useful but not relevant here.
Without knowing the details of Yelp's code, it's impossible to say for sure, but it seems likely that their "review highlights" are simply based on tabulating all phrases that appear in reviews for this business, then displaying ones which are more common in reviews for this business than for other businesses. Some amount of natural language processing is likely to be involved to ensure that it picks noun phrases.


text:
Q: Return first cell in range between target values I want to get the value of the first cell in a range that is between two values.
The best I can do is get the first cell that is either smaller or larger than a value. I want the first cell that is BOTH larger than a value AND smaller than an other value.
This did not work (because it's only 1 criteria):
{=INDEX(A1:A10,MATCH(TRUE,A1:A10<B1,0))}

note: A1:A10 is the rage of values and B1 is the comparison
I tried:
{=INDEX(A1:A10,MATCH(TRUE,and(A1:A10<B1,A1:A10>B2),0))}

but it did not work.
Thank you for your help.

A: Try this:
{=INDEX(A1:A10,MATCH(1,(A1:A10<B1)*(A1:A10>B2),0))}

Please note, that it is an array formula, therefore you don't have to write the {}, but when you enter the formula, do this with Ctrl+Shift+Enter.

A: It will work for you everywhere in sheet.
=INDEX(A1:A10,SMALL(IF(A1:A10>=B1,IF(A1:A10<=B2,ROW(A1:A10)-ROW(A1)+1)),ROWS(A1:A1)))

A: Use the AGGREGATE¹ function instead of MATCH to return the relative row position to INDEX.
=INDEX($A$2:$A$11, AGGREGATE(15, 6, ROW($1:$10)/(($A$2:$A$11<$B$1)*($A$2:$A$11>$B$2)), ROW(1:1)))

This forces non-matching row numbers to a #DIV/0! error. The 6 option tells AGGREGATE to ignore errors.
Since this uses AGGREGATE's SMALL, incresing the k parameter will produce the second, third, etc. matches as you fill ROW(1:1) down.

Note that I've shifted your sample range down a row. This was done to illustrate that ROW(1:10) is the position within A2:A11, not the actual row number on the worksheet.

¹ The AGGREGATE function was introduced with Excel 2010. It is not available in earlier versions.


text:
Q: Data transformation: new min, max and mean I have a dataset of 31 values, of which the $min = -0,8,\  max = 11, 1$ and $mean = 5,0$.
Is there a way to transform these data to a $\text{new} \ minimum (0.3),  \ \text{new} \ maximum (11.4)$ and $\text{new} \  mean (5.3)$?
Thanks!
6,7
4,9
4,5
3,0
4,6
1,9
2,7
4,0
2,3
6,4
7,6
6,2
6,7
6,3
11,1
9,1
8,3
8,3
4,5
5,6
5,6
5,9
4,4
5,9
2,4
0,7
1,0
-0,8

A: One way would be to use a quadratic equation to change every value in your dataset from $x_i$ to $y_i= a \cdot x_i^2+b \cdot x_i+ c$. The equation for the new minimum would then be $$0.3 = a \cdot (-0.8)^2+b \cdot (-0.8) + c\tag{1}$$
The equation for the new maximum would be $$11.4 = a \cdot (11.1)^2+b \cdot (11.1) + c \tag{2}$$
And the equation for the new mean would be $$5.3 = \frac{1}{31}\sum_{i=1}^{31} (a \cdot x_i^2+b \cdot x_i + c)$$
or
$$5.3 = a \cdot \frac{1}{31}\sum_{i=1}^{31} x_i^2+b \cdot (5.0) + c \tag{3}$$
Assuming equations $1$, $2$ and $3$ are linearly independent you could work out the values of $a$, $b$ and $c$.


text:
Q: $f(\frac1{1234}) + f(\frac3{1234}) + f(\frac5{1234}) + ..... + f(\frac{1231}{1234}) + f(\frac{1233}{1234}) = ?$ If $f(x) = \frac{e^{2x-1}}{1+e^{2x-1}}$, then how to evaluate $$f(\frac1{1234}) + f(\frac3{1234}) + f(\frac5{1234}) + ..... + f(\frac{1231}{1234}) + f(\frac{1233}{1234}) ?$$
I know I'm missing some trick here, what is it?

A: Using the trick you've identified,
\begin{align*}
f(x) + f(1 - x) &= \frac{e^{2x - 1}}{1 + e^{2x - 1}} + \frac{e^{2(1 - x) - 1}}{1 + e^{2(1 - x) - 1}} \\
&= \frac{e^{2x - 1}(1 + e^{1 - 2x}) + e^{1 - 2x}(1 + e^{2x - 1})}{(1 + e^{2x - 1})(1 + e^{1 - 2x})} \\
&= \frac{e^{2x - 1} + 1 + e^{1 - 2x} + 1}{1 + e^{2x - 1} + e^{1 - 2x} + 1} \\
&= 1
\end{align*}
Now count how many terms there are.


text:
Q: Как игнорировать пробелы при поиске совпадения в массиве строк Функция должна искать значение в массиве строк и возвращать массив если есть значение и -1 если нет.
Строки могут содержать пробелы, их нужно игнорировать, только non-spaces символы имеют значение.
Не могу понять как дополнить функцию условием чтоб игнорировались пробелы.
let arr= ['a' , 'bc' , 'bcd' , 't est']

const find = (arr, value) => {

     if (arr.indexOf) {
         return arr.indexOf(value);
     }

     for (let i = 0; i < arr.length; i++) {
         if (arr[i] === value)
             return i;
     }
        return -1;
};

find(arr , "test");

A: Заменяйте пробелы на пустую строку.

let arr = ['a', 'bc', 'bcd', 't est']

const find = (arr, value) => {

 /* это проверяет не то, что Вы думаете
 if (arr.indexOf) {
   return arr.indexOf(value);
 }*/

  for (let i = 0; i < arr.length; i++) {
    if (arr[i].replace(/ /g, "") === value)
      return i;
  }
  return -1;
};

console.log(find(arr, "test"));


text:
Q: Search reference in text (Create Loop in function) I have a question I've been working with view for a while now and in a table I have a text formatted this way ... name of the book, name of the author, number of pages or name of the book, name of the edition, year of the edition, name of the author, number of pages. I want to make sure that when I move my mouse over the reference ([name of the book] or [name of the book, name of the edition, year of the edition]) the description is displayed after returning my api.  The way to find the reference with only the name of the book works but I don't know how to search on a single parameter or 3 in my function.
getBiblio(biblio) {
    this.resultbiblio = biblio.split(/\s*,|$\s*/, 1)
    axios
        .get('../api/biblio/' + this.resultbiblio )
        .then(response => (this.biblio = response.data))
    },

biblio = Les Fables, Jean de la Fontaine, 1600
Now let's say that my data is biblio: L'avare, édition de poche, 2002, Molière, 1300 I would like to test if there is a reference to L'avare, if the answer is no then I cut the biblio data to form the sentence L'avare, édition de poche, 2002 and I test to see if there is a reference.


text:
Q: JSP Поле с нижним подчеркиванием JSP ругается на поле с нижним подчеркиванием, но информации о том, что так делать нельзя, я не нашел.
Стек Tomcat:
SEVERE: Servlet.service() for servlet [jsp] threw exception
javax.el.PropertyNotFoundException: Property [the_year_of_publishing] not found on type [com.core.newbie.model.Book]
...
21:50:32.693 [http-nio-8080-exec-5] DEBUG
org.springframework.web.servlet.DispatcherServlet - Could not complete request
org.apache.jasper.JasperException: An exception occurred processing [/WEB-
INF/book/showBook.jsp] at line [84]

81:                 ${book.name}
82:                 ${book.author}
83:
84:                 ${book.the_year_of_publishing}

Book.java, часть кода:
public String getPublishingHouse() {
    return publishing_house;
}

public void setPublishingHouse(final String publishing_house) {
    this.publishing_house = publishing_house == null ? null : publishing_house.trim();
}

public Integer getTheYearOfPublishing() {
    return the_year_of_publishing;
}

public void setTheYearOfPublishing(final Integer the_year_of_publishing) {
    this.the_year_of_publishing = the_year_of_publishing;
}

На эти оба поля ругается в JSP, одно убрал. В чем может быть дело?

A: Jsp обращается к полю через геттер, а не напрямую.
Об этом вам и сообщает exception. Не найдено property с таким именем. Поменяйте имя на theYearOfPublishing именно с маленькой буквы.
В модели может вообще не быть поля, но быть метод getSome(), тогда в jsp можно будет обратиться к полю some
Но в java  принято использовать CamelCase для имен. Хотя возможно вы это знаете

A: Просто замените ${book.the_year_of_publishing} на ${book.theYearOfPublishing}. Expression Language Parser подменит это вызовом book.getTheYearOfPublishing().

A: Следует различать понятия поля и свойства.
Как подсказывает википедия

Свойство — способ доступа к внутреннему состоянию объекта, имитирующий
  переменную некоторого типа. Обращение к свойству объекта выглядит так же, как и обращение к структурному  полю (в структурном программировании), но, в действительности, реализовано через вызов функции. При попытке задать значение данного свойства вызывается один метод, а при попытке получить значение данного свойства — другой.

За свойством даже не обязательно стоит какие-то поле класса.
И это очень даже распространённый случай.
В Java не стали придумывать специальный синтаксис для определения свойств. Вместо этого придумали соглашение JavaBean, которое регламентирует названия методов установки, получения значения свойств и соответственно как будут именоваться свойства.
Если у вас есть метод Integer getTheYearOfPublishing(), значит у вас есть свойство theYearOfPublishing.
Пусть даже этот метод такой
public Integer getTheYearOfPublishing() {
    return the_year_of_publishing;
}

Или такой
public Integer getTheYearOfPublishing() {
    return new Random.nextInt();
}

всё равно будет свойство theYearOfPublishing.
В последнем примере не то что название поля не совпадает с название свойства, а вообще всякая чушь.
Все инструменты, фреймвёрки, поддерживающие JavaBean, работают именно с такими свойствами. И JSP в том числе.
Не смотрите как называются поля, смотрите как называются методы.


text:
Q: Spring+Hibernate: How to handle Multiply (Unlimited) Data Sources and Session Factories dynamically? Our application may have multiply databases. Databases may be different type (Oracle and MS SQL) for the same application instance. Databases structures are slightly different but the same set of Hibernate POJOs are used. List od databases can be determined only when the application actually starts (so it cannot be stored as a fixed XML)
User needs to choose a DB during login process. The chosen DB is stored in HTTP Session.
So I'd like to use Sping auto-wiring to have Session Factory auto-wired to my DAOs in Web controllers depends on the current user. Like:
@Repository
@Transactional
@Controller
public abstract class UserGroupDAO {

    @Autowired
    @Qualifier("sessionFactory")
    private SessionFactory sessionFactory;

    public List<Users> getListOfUsers() {
        Session session = sessionFactory.currentSession();
        return session.createCriteria(Users.class).list();
    }
}

@Controller
public class WebController {

    @Autowired
    @Qualifier("userGroupDAO")
    private UserGroupDAO userGroupDAO;

    @RequestMapping("/greeting.html")
    public ModelAndView greeting(Model model) {
        userGroupDAO.getListOfUsers();
    }

For example: there are 2 DBs - Oracle_DB and MS_SQL_DB and two users A and B. User A logged in Oracle_DB, User B logged in MS_SQL_DB. When User A hits /greeting he should see list of users from Oracle_DB, when User B hits /greeting - from MS_SQL_DB.
I reviewed AbstractRoutingDatasource, but it looks like it works only for a single Session Factory with multiply Data Sources. However I am looking for an need individual Session Factory for each Data Source (and Transaction manager too).
Thank you in advance for help
Problem Summary
Databases are generated dynamicaly thus cannot hard code database settings into config file. Spring application needs to be able to determine which databases are available and then connect to them.

A: The solution was
1) Set UserGroupDAO, SessionFactory, etc. scope to 'session'
@Repository
@Transactional
@Scope(value="session",proxyMode=ScopedProxyMode.TARGET_CLASS)
public class UserGroupDAO extends GeneralDAO {

2) Initialize SessionFactory, Session, etc. manually in a Singleton (DataSourceProvider) and get it from this Singleton in ApplicationContextConfig
@Configuration
@ComponentScan(....)
@EnableTransactionManagement
public class ApplicationContextConfig {
    @Autowired
    @Bean("sessionFactory")
    @Scope(value="session")
    public SessionFactory getSessionFactory(DataSource dataSource) {
    return DataSourceProvider.getInstance().getDatasourceByContext().getSessionFactory();
    }
    @Autowired
    @Bean("dataSource")
    @Scope(value="session")
    public DataSource getDataSource() {
        return DataSourceProvider.getInstance().getDatasourceByContext().getDataSource();
    }

3) Detect the current DB inside DataSourceProvider
public class DataSourceProvider {

private static DataSourceProvider instance = new DataSourceProvider();

public static DataSourceProvider getInstance() {
    return instance;
}

private HashMap<String, MyDataSource> dataSources;

private DataSourceProvider(){
}

public MyDataSource getDatasourceByContext() {
    String connectionName;
    if (RequestContextHolder.getRequestAttributes() instanceof ServletRequestAttributes) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        if (request==null) {
            connectionName = null;
        } else {
            //"currentDatabase" is set during logon
            connectionName = (String)request.getSession().getAttribute("currentDatabase");
        }
    } else {
        connectionName = null;
    }
    if (connectionName!=null) {
        MyDataSource dataSource = dataSources.get(connectionName);
        if (dataSource != null) {
            return dataSource;
        }
    }
    throw new IllegalStateException("No datasource for the context");
}


text:
Q: SQL , how not to count 0 values am trying to find a total vote using this code, I have 12 criteria;
So am adding up the TOTAL for each SHOP_ID and then dividing by 12( the amount of columns used to make total). COUNT(shop_id) finds the number of shops, So for example if I have 2 shop_id inputs one with a total of 0 ( 12 entries of 0) and the other a total of 60 which is divided by the 12 criteria's then divided by shop_id count of 2
(60/12)/2 = 2.5
I would like the result to be 5. Some how not counting the column's with 0 in the division.
$sel = mysql_query("SELECT SUM(comfort + service + ambience + mood + spacious +

    experience + cleanliness+ price + drinks + food + music + toilets)/(12/COUNT(shop_id) as total
    FROM ratings
    WHERE shop_id = $shop_id");

if(mysql_num_rows($sel) > 0){
    while($data = mysql_fetch_assoc($sel)){
        $total = $total + $data['total'];
        $rows++;
    }
    $perc = ($total/$rows);
    return round($perc,2);
} else {
    return '0';
}

Would it be better if i supply an image so visually display what am trying to achieve?
each row is NOT 1 vote, each shop_id is 12 votes.
Each column category name: comfort + service + ambience, is a column id and an entry into that field is 1 vote, it counts the 12 as 1 vote, when if you vote for 1 criteria the other 11 are 0, and returns the wrong results, as division by 2 will half the correct answer
I have uploaded a visual example and shortened the rating columns from 12 to 7 for testing purposes.

A: try to use HAVING clause:
select
...
from
...
where
...
having COUNT(shop_id) > 0

A: SELECT SUM(comfort + service + ambience + mood + spacious +
experience + cleanliness+ price + drinks + food + music + toilets)/(12/COUNT(shop_id) as total
FROM ratings
WHERE shop_id = $shop_id
HAVING total > 0

I'm pretty sure your query is not quite right, but that could be a typo.
Here might be a better query:
SELECT shop_id, SUM(comfort + service + ambience + mood + spacious +
experience + cleanliness+ price + drinks + food + music + toilets)/12 as total_rating
FROM ratings
GROUP BY shop_id
HAVING total > 0

Personally, I think if someone is getting 0's across the board, that's worth noting, but the above should give you the average rating per shop and filter out any that are not at least 1.
If each category is from a scale of 0 - 5 and there are 12 categories, that means that their percent score is the (sum of the individual scores)/(possible total) * 100, or, in this case, the sum of the individual scores/.6 (works out the same way). If you want a "star rating" where the number of stars is equal to the top score of each category, that's just the average. In that case, I'd round off to one decimal. So if you want to go that route, here is the query I would use:
   SELECT shop_id,
          Ceiling(
                 Sum(comfort + service + ambience + mood + spacious +
                      experience + cleanliness + price +
                      drinks + food + music + toilets
           ) /. 6)
          AS  percent_rating,
          ROUND(
            SUM(
              comfort + service + ambience + mood +
              spacious + experience + cleanliness +
              price + drinks + food + music + toilets
            )/12, 1)
          as star_rating
   FROM   ratings
   GROUP  BY shop_id

Now, if you want to have it laid out where each score is out of 100%, then it would be (cat_score/5) * 100  or (cat_score/.05). I'm not sure if there is an easy way to apply to that all of the categories without having to explicitly do the math for each field, but really I don't think you need to go to the trouble to figure out that 4/5 is 80%.
As far as what to do regarding a default 0 versus an intentional 0, you have no way of knowing the difference.  If someone didn't feel moved enough to change it from a 0 (or a blank), it must not have been that terrific. Best bet is to set the default to the middle (3) and most folks will mark it lower if it was actually so bad it was a 0.  Similarly, if you are giving the option of leaving it blank (which isn't 0, it's NULL), then you can either move it to 3 (which works out the same. If they left it all blank, that's the same as saying "so average I didn't fill it out) or you can make it some number you think is fair (1 or 2, maybe).  Throwing it out is a pain mysql, and in statistics leads to misleading data (think hanging chad combined with language barrier so they left it blank).  In the end, moving blank to the middle will be fine because you should have enough data when it's all said and done to get a standard deviation and other more valuable stats, rather than rely on plain averages (where a handful of bad reviews can throw off the whole curve).

A: Add to the end of your query:
HAVING comfort + service + ambience + mood + spacious + experience + cleanliness+ price + drinks + food + music + toilets != 0

A: Your query is not quite right. It's missing a parenthesis.
Correct one:
$sel = mysql_query("SELECT SUM(comfort + service + ambience + mood + spacious +
experience + cleanliness+ price + drinks + food + music +toilets)/(12/COUNT(shop_id))
as total FROM ratings WHERE shop_id = $shop_id having COUNT(shop_id) > 0");


text:
Q: Is it possible to fire mouse events without mouse moves in safari? I'm trying to put mouse enter/mouse-leave events on moving elements. There is a problem in handling the hover event with CSS, so I'm trying to process it with JS. This works fine in chrome but not working in safari. How to make mouseenter/mouseleave work properly when the mouse is stopped?
CSS
.big-box {
    position: relative;
    width: 500px;
    height: 100px;
    background: #ee9;
}
.hit-box {
    position: absolute;
    top: 0;
    left: 0;
    width: 100px;
    height: 100px;
    background: #e99;
}

HTML

hit-box

JavaScript
const hitbox = document.querySelector('.hit-box');
var position = 5;
hitbox.style.left = 0;

hitbox.addEventListener('mouseenter', function() {
    console.log('enter');
});
hitbox.addEventListener('mouseleave', function() {
    console.log('leave');
});

setInterval(function() {
    if(parseInt(hitbox.style.left) + position > 400) {
        position = -5;
    } else if(parseInt(hitbox.style.left) + position < 0) {
        position= 5;
    }
    hitbox.style.left = parseInt(hitbox.style.left) + position + 'px';
},20)


text:
Q: Place cursor at the end of text on keyup I'm making the same functionality which a command line has. When you enter some commands and then press the key up button, you will be presented with your previous command.
Now I have all that working and it works fine but I've encountered one small problem.
The problem I encounter now is that when pressing the up key, the cursor is placed at the beginning of the command, while when using the down button, the cursor is placed at the end of the comand.
Expected behaviour is that the cursor will be placed at the end for both.

What makes this different from other questions?

*

*The focus is already on the input field.

*It does work with the down button

setTimeout(function() {
var inputs = document.querySelectorAll('input');

inputs[0].onkeydown = function(e){
  //keyup
  if(e.keyCode == 38) {
    inputs[inputs.length-1].value = 'up pressed';
  }

  if(e.keyCode == 40 ) {
      inputs[0].value = 'down pressed';
  }
}
}, 1000);
<!DOCTYPE html>
<html>

  <head>
    <link rel="stylesheet" href="style.css">
    <script src="script.js"></script>
  </head>

  <body>
    <input type="text" placeholder="press the up or down key"/>
  </body>

</html>

A:

setTimeout(function() {
var inputs = document.querySelectorAll('input');

inputs[0].onkeydown = function(e){
  //keyup
  if(e.keyCode == 38) {
    // placed here, it prevents the key's default behaviour to go at the end of the input text
    e.preventDefault();
    inputs[inputs.length-1].value = 'up pressed';
  }

  if(e.keyCode == 40 ) {
      inputs[0].value = 'down pressed';
  }

}
}, 1000);
<!DOCTYPE html>
<html>

  <head>
    <link rel="stylesheet" href="style.css">
    <script src="script.js"></script>
  </head>

  <body>
    <input type="text" placeholder="press the up or down key"/>
  </body>

</html>


text:
Q: Debug Gradle's parallel mode We are trying Gradle for our very large and complex enterprise app. We are using multi project build structure and are very excited with Gradle's parallel execution feature.
Our codebase is structured in domain layers like this:
UI modules (~20) -> shared ui -> domain -> dao -> framework
Dependencies are uni directional and build happens bottom up.
Unfortunately we are not seeing a big boost in our build times. Its pretty much same as what we were getting with ant before.
Looking at the execution sequence of tasks in parallel mode few things doesn't look right.
Our expectation is Gradle will run tasks in sequence initially when it is building core layers. So after it assembles framework, dao, domain and shared ui, it should kick everything else in parallel.
But execution sequence we are seeing is somewhat like this:
framework.assemble -> dao.assemble -> domain.assemble -> shared.ui.assemble -> Other UI modules.assmble (in parallel) -> war -> Other UI.check + shared.ui.check + dao.check (in parallel) -> domain.check -> framework.check
Bottleneck is at the end when it is running checks for domain and framework in sequence and not in parallel. These 2 modules are the biggest modules for us with around 12k unit tests and they take around 4 mins to run.
We spent lot of time looking at the dependencies using gradle tasks --all and test task for these modules are completely independent and there is nothing that should hold off their execution.
We are wondering if this is a known issue or is there a way to enable some extra debugging in Gradle to get more insight as how Gradle determines execution order with parallel mode. Any help is appreciated.

A: As of Gradle 1.4, parallel task execution is (intentionally) constrained in a few ways. In particular, the set of tasks executing at any time won't contain two tasks belonging to the same project. This will be improved over time. I'm not aware of any debugging aids other than what you get from the logs (e.g. with --debug).
Note that parallel test execution is a separate feature. If you have a lot of tests in the same project, test.maxParallelForks = x with x > 1 should show a noticeable speedup. The value for x is best determined experimentally. A good starting point is the number of physical cores on the machine (e.g. Runtime.getRuntime().availableProcessors() / 2).


text:
Q: Read messages from different AWS account using @SqsListener I have an SQS standard queue that is provided by a third party vendor who has given access to our IAM user to read messages from there. So the AWS account ID for the queue is different than the one of my user.
I'm trying to use spring's @SqsListener annotation to consume these messages but I'm having trouble specifying the accountId that should be consumed from.
My bean configuration for the client looks like this:
@Bean
fun amazonSQSAsyncClient(): AmazonSQSAsync = AmazonSQSAsyncClientBuilder.standard()
.withCredentials(AWSStaticCredentialsProvider(BasicAWSCredentials(awsProperties.accessKey, awsProperties.secretKey)))
.withEndpointConfiguration(AwsClientBuilder.EndpointConfiguration(awsProperties.url, awsProperties.region))
.build()

I see no way of specifying the account Id in the credentials, and I also could not find any properties that can be used to define an accountId.
I tried setting the awsProperties.url shown above to something like https://sqs.us-east-1.amazonaws.com/<accountId> but this does not seem to be working. It is still trying to look for the queue in my own account Id and throwing a queue not found error.
Any ideas how to fix this and force the Spring AWS bean to consume from a specific AwsAccount?

A: You have a user that can access the queu in another account. That means you can run code with that user in your account and that can access the queue on another account.
Initializing a sqsclient will always use the account it is running on
You don't have to adjust this.
@Bean
fun amazonSQSAsyncClient(): AmazonSQSAsync = AmazonSQSAsyncClientBuilder.standard()
.withCredentials(AWSStaticCredentialsProvider(BasicAWSCredentials(awsProperties.accessKey, awsProperties.secretKey)))
.build()

You need to make sure the code can access the queue.
In the code you should set your queue URL like this:
https://sqs.<region>.amazonaws.com/<account>/<queuename>
, I quickly tried to access a queue from another account. If the permissions on the queue are correctly set, you have two possibilities. The first one is using the queue URL instead of the name (I checked, it works). The second one is creating you own DestinationResolver and providing it to the SimpleMessageListenerContainer. I created a small app with Spring Boot and it worked well. I pasted you the code below.
In a next feature release I'll figure out a better way to support this use case.
package demo;

import com.amazonaws.services.sqs.AmazonSQS;
import com.amazonaws.services.sqs.model.GetQueueUrlRequest;
import com.amazonaws.services.sqs.model.GetQueueUrlResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.aws.core.env.ResourceIdResolver;
import org.springframework.cloud.aws.messaging.config.SimpleMessageListenerContainerFactory;
import org.springframework.cloud.aws.messaging.support.destination.DynamicQueueUrlDestinationResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.messaging.core.DestinationResolutionException;
import org.springframework.messaging.core.DestinationResolver;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.util.Assert;

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

    @Bean
    public MessageListener messageListener() {
        return new MessageListener();
    }

    @Bean
    public SimpleMessageListenerContainerFactory simpleMessageListenerFactory(AmazonSQS amazonSqs, ResourceIdResolver resourceIdResolver) {
        SimpleMessageListenerContainerFactory factory = new SimpleMessageListenerContainerFactory();
        factory.setDestinationResolver(new DynamicAccountAwareQueueUrlDestinationResolver(amazonSqs, resourceIdResolver));

        return factory;
    }

    public static class DynamicAccountAwareQueueUrlDestinationResolver implements DestinationResolver<String> {

        public static final String ACCOUNT_QUEUE_SEPARATOR = ":";
        private final AmazonSQS amazonSqs;
        private final DynamicQueueUrlDestinationResolver dynamicQueueUrlDestinationResolverDelegate;

        public DynamicAccountAwareQueueUrlDestinationResolver(AmazonSQS amazonSqs, ResourceIdResolver resourceIdResolver) {
            Assert.notNull(amazonSqs, "amazonSqs must not be null");

            this.amazonSqs = amazonSqs;
            this.dynamicQueueUrlDestinationResolverDelegate = new DynamicQueueUrlDestinationResolver(amazonSqs, resourceIdResolver);
        }

        @Override
        public String resolveDestination(String queue) throws DestinationResolutionException {
            if (queue.contains(ACCOUNT_QUEUE_SEPARATOR)) {
                String account = queue.substring(0, queue.indexOf(ACCOUNT_QUEUE_SEPARATOR));
                String queueName = queue.substring(queue.indexOf(ACCOUNT_QUEUE_SEPARATOR) + 1);
                GetQueueUrlResult queueUrlResult = this.amazonSqs.getQueueUrl(new GetQueueUrlRequest()
                        .withQueueName(queueName)
                        .withQueueOwnerAWSAccountId(account));
                return queueUrlResult.getQueueUrl();
            } else {
                return this.dynamicQueueUrlDestinationResolverDelegate.resolveDestination(queue);
            }
        }
    }

    public static class MessageListener {

        private static Logger LOG = LoggerFactory.getLogger(MessageListener.class);

        @MessageMapping("633332177961:queue-name")
        public void listen(String message) {
            LOG.info("Received message: {}", message);
        }

    }

}


text:
Q: can i chain request in vue method? I have a button when user click on it I will send a request and receive answer. If user click 100 times on this button I want to send 100 requests to server and each request send after previous. because  I need previous response in next request.
example:
    <button @click="sendRequest">send</button>

    methods:{

    sendRequest:function(){

        axios.post('https:/url/store-project-item', {
            'id': this.project.id,
            "items": this.lists,
            'labels': this.labels,
            'last_update_key': this.lastUpdateKey,
            'debug': 'hYjis6kwW',
          }).then((r) => {
            if (r.data.status) {
              this.change = false
              this.lastUpdateKey = r.data.lastUpdateKey;
              this.showAlert('success')
            } else {
              if (r.data.state == "refresh") {
                this.showAlert('error')
                this.getProject()
              } else {
                this.showAlert('error')
              }
            }
          }).catch(() => {
            this.showAlert('error')
          })
        }}

A: I keep a higher-order function (i.e. a function that returns a function) withMaxDOP (DOP = degrees-of-parallelism) handy for this kind of thing:
const withMaxDOP = (f, maxDop) => {
  const [push, pop] = createAsyncStack();
  for (let x = 0; x < maxDop; ++x) {
    push({});
  }
  return async(...args) => {
    const token = await pop();
    try {
      return await f(...args);
    } finally {
      push(token);
    }
  };
};

The function makes use of an async stack data structure (implementation is in the attached demo), where the pop function is async and will only resolve when an item is available to be consumed. maxDop tokens are placed in the stack. Before invoking the supplied function, a token is popped from the stack, sometimes waiting if no token is immediately available. When the supplied completes, the token is returned to the stack. This has the effect of limiting concurrent calls to the supplied function to the number of tokens that are placed in the stack.
You can use the function to wrap a promise-returning (i.e. async) function and use it to limit re-entrancy into that function.
In your case, it could be used as follows:
sendRequest: withMaxDOP(async function(){ /*await axios.post...*/ }, 1)

to ensure that no call to this function ever overlaps another.
Demo:

const createAsyncStack = () => {
  const stack = [];
  const waitingConsumers = [];
  const push = (v) => {
    if (waitingConsumers.length > 0) {
      const resolver = waitingConsumers.shift();
      if (resolver) {
        resolver(v);
      }
    } else {
      stack.push(v);
    }
  };
  const pop = () => {
    if (stack.length > 0) {
      const queueItem = stack.pop();
      return typeof queueItem !== 'undefined' ?
        Promise.resolve(queueItem) :
        Promise.reject(Error('unexpected'));
    } else {
      return new Promise((resolve) => waitingConsumers.push(resolve));
    }
  };
  return [push, pop];
};
const withMaxDOP = (f, maxDop) => {
  const [push, pop] = createAsyncStack();
  for (let x = 0; x < maxDop; ++x) {
    push({});
  }
  return async(...args) => {
    const token = await pop();
    try {
      return await f(...args);
    } finally {
      push(token);
    }
  };
};
// example usage
const delay = (duration) => {
  return new Promise((resolve) => setTimeout(() => resolve(), duration));
};
async function doSomething(name) {
  console.log("starting");
  // simulate async IO
  await delay(1000);
  const ret = `hello ${name}`;
  console.log(`returning: ${ret}`);
  return ret;
}
const limitedDoSomething = withMaxDOP(doSomething, 1);
//call limitedDoSomething 5 times
const promises = [...new Array(5)].map((_, i) => limitedDoSomething(`person${i}`));
//collect the resolved values and log
Promise.all(promises).then(v => console.log(v));


text:
Q: How to update null values by the previous record in the same table? I have a table named "BBSEC2013_REPORTS" where some value in column "Q19_MARKETING" is NULL. What I want is to update those null values with the previous values of "Q1_UNIT_SERIAL_NO" in the main table.
SQL :
FIND NULLS
SELECT R.BOOK_ID, R.QUESTIONNARIE_ID, R.Q1_UNIT_SERIAL_NO ,     R.Q19_MARKETING
FROM  BBSEC2013_REPORTS  R
WHERE ( R.Q19_MARKETING = 9 OR R.Q19_MARKETING  is null )
AND F_TO_NUMBER(SUBSTR(R.Q6_IND_CODE_CLASS_CODE,1,2)) BETWEEN 10 AND 33
ORDER BY R.BOOK_ID, R.QUESTIONNARIE_ID, R.Q1_UNIT_SERIAL_NO

SELECTING VALUE OF PREVIOUS UNIT
SELECT R.Q19_MARKETING FROM BBSEC2013_REPORTS R
WHERE R.BOOK_ID = * BOOK_ID OF SQL-1
AND   R.Q1_UNIT_SERIAL_NO = * DECREMENT VALUE OF "Q1_UNIT_SERIAL_NO" OF SQL-1
ORDER R.BY BOOK_ID, R.QUESTIONNARIE_ID,R.Q1_UNIT_SERIAL_NO

UPDATING
UPDATE BBSEC2013_REPORTS
SET Q19_MARKETING= Q19_MARKETING OF SQL-2
WHERE BOOK_ID = * BOOK_ID OF SQL-1
AND Q1_UNIT_SERIAL_NO = * Q1_UNIT_SERIAL_NO OF SQL-1

A: You should be able to combine your supplied DML statements into one e.g.
UPDATE bbsec2013_reports r
SET    r.q19_marketing =
   (SELECT r1.q19_marketing
    FROM   bbsec2013_reports r1
    WHERE  r1.book_id = r.book_id
    AND    r1.q1_unit_serial_no = to_char(to_number(r.q1_unit_serial_no)-1, 'FM000'))
WHERE  (  r.q19_marketing = 9
       OR r.q19_marketing IS NULL)
AND    f_to_number(substr(r.q6_ind_code_class_code, 1, 2)) BETWEEN 10 AND 33

(EDIT) or if the decrement if not necessarily 1:
UPDATE bbsec2013_reports r
SET    r.q19_marketing =
   (SELECT max(r1.q19_marketing) KEEP (DENSE_RANK LAST ORDER BY r1.q1_unit_serial_no)
    FROM   bbsec2013_reports r1
    WHERE  r1.book_id = r.book_id
    AND    r1.q1_unit_serial_no < r.q1_unit_serial_no)
WHERE  (  r.q19_marketing = 9
       OR r.q19_marketing IS NULL)
AND    f_to_number(substr(r.q6_ind_code_class_code, 1, 2)) BETWEEN 10 AND 33

Now you could add additional WHERE clauses into the subquery if required e.g. r1.q19_marketing <> 9 AND r1.q19_marketing IS NOT NULL to find the previous record with a valid q19_marketing value.

A: (Posted on behalf of OP).
I got this solution:
DECLARE
V_MARKETING NUMBER;

BEGIN

FOR X IN (SELECT QUESTIONNARIE_ID FROM BBSEC2013_REPORTS
        WHERE Q6_IND_CODE_CLASS_CODE < 3400
        AND (Q19_MARKETING IS NULL OR Q19_MARKETING=9)
        )

LOOP
    SELECT Q19_MARKETING
    INTO V_MARKETING
    FROM BBSEC2013_REPORTS
    WHERE QUESTIONNARIE_ID=(SELECT MAX(QUESTIONNARIE_ID)
                            FROM BBSEC2013_REPORTS
                            WHERE QUESTIONNARIE_ID < X.QUESTIONNARIE_ID
                            AND Q6_IND_CODE_CLASS_CODE<3400
                            AND (Q19_MARKETING IS NOT NULL OR Q19_MARKETING!=9)
                            );

    IF V_MARKETING > 0 THEN

        UPDATE BBSEC2013_REPORTS
        SET Q19_MARKETING = V_MARKETING
        WHERE QUESTIONNARIE_ID = X.QUESTIONNARIE_ID;

    END IF;

    COMMIT;

END LOOP;

END;


text:
Q: I want to insert a record in DB and then need to return a row I want to insert a record in DB and then need to return a row. I created the query but how to use that in .cs (C# code)
This is my query
 @ledgerId numeric(18,0) ,
 @voucherNo varchar(MAX) ,
 @invoiceNo varchar(MAX) ,
 @date datetime ,
 @month datetime ,
 @totalAmount decimal(18,5) ,
 @narration varchar(MAX) ,
-- @extraDate datetime ,
 @extra1 varchar(MAX) ,
 @extra2 varchar(MAX) ,
 @suffixPrefixId numeric(18,0) ,
 @voucherTypeId numeric(18,0)
AS
DECLARE @UpdatedVoucherNo DECIMAL(18,0)

SET @UpdatedVoucherNo = (SELECT ISNULL( MAX(CAST (voucherNo AS NUMERIC(18,0))),0) + 1
 FROM tbl_SalaryVoucherMaster
 WHERE voucherTypeId=@voucherTypeId)

 IF (@UpdatedVoucherNo = @voucherNo )

 INSERT INTO tbl_SalaryVoucherMaster
 (
            /*salaryVoucherMasterId,*/
            ledgerId,
            voucherNo,
            invoiceNo,
            date,
            month,
            totalAmount,
            narration,
            extraDate,
            extra1,
            extra2,
            suffixPrefixId,
            voucherTypeId )
VALUES
 (
            /*@salaryVoucherMasterId, */
            @ledgerId,
            @voucherNo,
            @invoiceNo,
            @date,
            @month,
            @totalAmount,
            @narration,
            getDate(),
            @extra1,
            @extra2,
            @suffixPrefixId,
            @voucherTypeId)

            SELECT SCOPE_IDENTITY() AS [Identity],0 AS [UpdatedVoucherNo]

A: Command.ExecuteNonQuery(); is what you need, it returns the number(int) of rows affected in inserting and updating data,
here is an example to use it,
            string connetionString = null;
            SqlConnection cnn ;
            SqlCommand cmd ;
            string sql = null;

            connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
            sql = "Your SQL Statemnt Here";

            cnn = new SqlConnection(connetionString);

                cnn.Open();
                cmd = new SqlCommand(sql, cnn);
                int rowsAffected = cmd.ExecuteNonQuery();
                if (rowsAffected > 0)
                {
                    //do anything
                }
                cmd.Dispose();
                cnn.Close();
                MessageBox.Show (" ExecuteNonQuery in SqlCommand executed !!");

more information here

A: One way to do what you want is to modify @voucherNo to be an OUTPUT parameter, and add a new OUTPUT parameter to your query to return the value of SCOPE_IDENTITY().
@voucherNo varchar(max)
@ScopeIdentity numeric(38,0)

And modify that last SELECT statement to set the value of @ScopeIdentity parameter.
SELECT @ScopeIdentity = SCOPE_IDENTITY()

Then use SqlCommand.ExecuteNonQuery to execute the query, and on completion, read the values from the output parameters.
using (SqlCommand command = new SqlCommand(connection, commandText))
{
    int rowsAffected = command.ExecuteNonQuery();
    if (rowsAffected > 0)
    {
        var voucherNo = (string)command.Parameters["@voucherNo].Value;
        var identity = (decimal)command.Parameters["@ScopeIdentity"].Value;
    }
}


text:
Q: Plaid Oauth redirect_uri is not configured error I am trying to implement OAuth with Plaid-Link but keep on getting this error on the server-side:
plaid.errors.InvalidRequestError: OAuth redirect URI must be configured in the developer dashboard. See https://plaid.com/docs/#oauth-redirect-uris

I am running my application locally (sandbox mode), I have a backend server running on localhost:8000 and the client-side application running on localhost:3005
I have configured in the developer dashboard the redirect URLs (see image here)
I am using the Python SDK, here is an example of the CreateLink call in my server:
response = client.LinkToken.create({
'user': {
'client_user_id': str(client_user_id),
},
'client_name': 'XYZ Corporation',
'products': ['auth'],
'country_codes': COUNTRY_CODES,
'language': 'en',
'redirect_uri': 'http://locahost:3005/landing-rc-solo/link-bank'

})

Would you know what's the issue here?
Thanks a lot for your help!

A: Basically, since you're on localhost and just for development's sake, what I did was to remove the redirect altogether.
If this is fine for you then the error should go.

A: Assuming you haven't made a silly mistake like adding the redirect_uri to the developer dashboard for a different client_id, that all seems right to me. Would you mind filing a ticket with Plaid support so someone with the right access can dig into this a bit more closely?


text:
Q: Subgroups that can be proven? How do you show all subgroups of $A_5$ have order less or equal than 12?
I know you can use this lemma:
If G is a finite group, and H does not equal G is a subgroup of G such that oG $/|/$ i(H)! then H must contain a nontrivial normal subgroup of G. In particular, G cannot be simple.
/|/ means it is not |.
I know this proof. How would you do this example though. Can someone please show me?

A: I think the following theorem could help us:

Theorem: Let $G$ be a simple group and let $H<G$ be a subgroup of $G$. Then if $[G:H]=n$ then $G\hookrightarrow A_n$.

Now letting $G=A_5$ and any other subgroup with the order $>12$ make us a contradiction.
Edit: I didn't see the excluded case of non-abelian groups. So we assume that $G$ is non abelian group.

A: If you are looking for examples of all of its subgroups.
perhaps this link may help you


text:
Q: Handling TimeOutException in Kotlin retrofit with interceptor I have built my retrofit like this
    private fun <T> createAPI(apiClass: Class<T>, baseUrl: String, vararg interceptors: Interceptor): T {
        val clientBuilder = OkHttpClient().newBuilder()
            .connectTimeout(10, TimeUnit.SECONDS)
            .readTimeout(10, TimeUnit.SECONDS)
            .writeTimeout(10, TimeUnit.SECONDS)

        for (interceptor in interceptors) {
            clientBuilder.addInterceptor(interceptor)
        }
        val retrofit = Retrofit.Builder()
            .baseUrl(baseUrl)
            .addConverterFactory(JacksonConverterFactory.create(mapper))

            .client(clientBuilder.build())
            .build()
        return retrofit.create(apiClass)
    }

Api = createAPI(
            Api::class.java,
            BuildConfig.REST_URL,
            NoConnectionInterceptor(App.INSTANCE)
        )

also
I have been able to build the no internet interceptor like this
    /*No internet error interceptor*/
    private open class NoConnectionInterceptor(
        private val context: Context
    ) : Interceptor {
        override fun intercept(chain: Interceptor.Chain): Response {
            return if(!isInternetAvailable(context)) {
                throw NoInternetException()
            } else {
                chain.proceed(chain.request())
            }
        }
    }

class NoInternetException() : IOException() {
    override val message: String
        get() =
            "No internet available, connect to WIFi or Data"
}

is there a way to have an interceptor for timeOutException like that of NoInternetException?
This is because the retrofit throws an error message that "failed to connect to an endpoint after 10000ms" at random.


text:
Q: Нужна помощь с парсингом данных с сайта при помощи Selenium from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
import time

url = 'https://obnovi-oboi.ru/goods?category=oboi'
opts = Options()
#opts.add_argument("--headless")
browser = webdriver.Chrome(options=opts)

browser.get(url)
html = browser.find_element(by=By.TAG_NAME, value='html')
for i in range(4):
    html.send_keys(Keys.PAGE_DOWN)
time.sleep(2)
xpath = '/html/body/main/section/div/div[2]/button'
browser.find_element(by=By.XPATH, value=xpath).click()

time.sleep(3)
container = browser.find_element(by=By.CLASS_NAME, value="row items")
oboi_items = container.find_element(By.CLASS_NAME, value="card good-item")#Тут уже  много что попробовал...

browser.quit()

Тут код парсера , ссылка на сайт откуда я хочу взять картинку , цену и название обоев.
Прошу помочь, что я делаю не так?!

A: В этих строках ошибка:
container = browser.find_element(by=By.CLASS_NAME, value="row items")
oboi_items = container.find_element(By.CLASS_NAME, value="card good-item")#Тут уже  много что попробовал...

В Selenium с помощью локатора By.CLASS_NAME нельзя искать составные классы (в вашем случае это row items). Это описано в официальной документации. Т. е. вы можете искать или по row или по items, но не оба класса одновременно.
Попробуйте переписать локаторы на XPATH или CSS Selectors.


text:
Q: How to get git up to date on different servers, with individual one-off updates on them? I have several servers running with the same system, however over time we made several updates locally on each server so that the task was agile. But now we are having a hard time keeping everyone up to date keeping what has been updated locally, taking into account that I changed certain lines of code locally and in the main.
Could someone give me a light?

A: Well for your use case I would configure a central gitlab server or so, all servers pull and push to it, it manages the merge/pull requests and keep everything clean and in sync.
If you don't want that, it is possible to sync them, under the condition that all have access to some directory/location/path somewhere, this can act as a central repository so that the other repositories can push/pull to it.

*

*Let's call this location /path/to/central

*clone the repository to that /path/to/central

*add this central repository as a remote to the other versions you want to sync, for example if you have a repository on the path: /path/to/repo1, then:

cd /path/to/repo1
git remote add upstream /path/to/central
git checkout -b repo1-changes
git push upstream repo1-changes

now you have the changes from repo1 pushed to the central repository:
cd /path/to/central
git branch -a

# output will look like:
  repo1-changes
* master

do the same steps on the other versions you have on the different servers, and come back to the central repository.
All changes are now in a central location and you can merge it the way you like.
After merging everything into master on the central repository, go back to the servers an set master there to upstream/master after fetching it:
cd /path/to/repo1
git checkout master
git fetch upstream
git reset --hard upstream/master

This is a manual process but at the end all master branches should be the same on every server.
hope this helped somehow :)


text:
Q: Refreshing android Listview I am trying to reload the list view when the data has changed. But its not working.Here is the code I am using
localPits.clear();//
this.adapter.clear();
//Fetch new data and update the list
this.localPits.addAll(pl);
this.adapter.notifyDataSetChanged();
this.lst_Pits.invalidate();

Each time I call this portion of code existing values are successfully removed. But new values are not loaded in the list view.
How can I do this in android?
Thanks

A: It's not terribly clear, but I suspect the new values aren't being loaded because you're clearing the adapter without updating it.
Your 2nd line: this.adapter.clear();
You need to update and add the adapter before you call invalidate(). Or, at least, that's as far as I can gather.

A: this.adapter.clear(); should not be needed. It must reset the links between adapter and localPits.
If you need to keep this, update list adapter localPits.setAdapter(adapter);. It should fix your problem.


text:
Q: create and populate with DOM a checkbox list with array values in javascript I have an array of animals ... how do I manage to create a checkbox list in javascript and fill each with a name of the animals who are in animals array and display them in html.
My my attempt code:
var lengthArrayAnimals = animals.length;
for (var i= 0; pos < tamanhoArrayDiagnosticos; pos++) {
    var checkBox = document.createElement("input");
    checkBox.setAttribute("type", "checkbox");
    checkBox.name = diagnosticos[i];
}

A: Here's one way (pure JavaScript, no jQuery):
var animals = ["lion", "tigers", "bears", "squirrels"];

var myDiv = document.getElementById("cboxes");

for (var i = 0; i < animals.length; i++) {
    var checkBox = document.createElement("input");
    var label = document.createElement("label");
    checkBox.type = "checkbox";
    checkBox.value = animals[i];
    myDiv.appendChild(checkBox);
    myDiv.appendChild(label);
    label.appendChild(document.createTextNode(animals[i]));
}

https://jsfiddle.net/lemoncurry/5brxz3mk/

A: I hope this is what you expected.

$(document).ready(function(){
var animals=["cat","dog","pikachu","charmaner"];

$.each(animals,function(index,value){
 var checkbox=""+value+"<input type='checkbox' id="+value+" value="+value+" name="+value+">"
 $(".checkBoxContainer").append($(checkbox));
})

});


text:
Q: dart: reflect methods of a class, no luck with the reflect*() functions I'm trying to list the methods of a class, but neither reflectClass() nor reflectType() return anything useful. Has anyone done this already?
This is my code:
import 'package:mylib/mylib.dart' as mylib;
import 'dart:mirrors' as mirrors;

void main(List<String> arguments) {
  var reflectedMyClass = mirrors.reflectType(mylib.MyClass);
  // how to list the methods in MyClass here?
}

A: Ok, mirrors.reflectClass(someClass).declarations.values is the answer. This stuff was not visible in the debugger window where I was stuck, but a null _declarations instead. Going through completions sometimes seems more helpful than the debugger.


text:
Q: Aligned equations with comments/explanations In many cases I want to write some aligned equation that goes through multiple lines and add a comment for some of the lines (I think if the comments are short enough then it's clearer than explaining everything at the end of the equation). Ideally, all the comments should start on the same vertical line. This is achieved by what's shown in the following example:
\documentclass{article}
\usepackage{amsmath}

\begin{document}
    This is just some text to show where the margin is. Some more and more text yay text is good.
    \begin{align*}
    a + b + c + d + e &= an-expression \\
    &= some-very-longgggggggggg-expression && \text{comment} \\
    &= another-expression && \text{a little longer comment} \\
    &= 0
    \end{align*}
\end{document}

The problem is when some of the equation's lines are too long:

The second comment is inside the right margin, which should not be allowed.
I know it happens because the align environment creates a table and each & sign adds a column, so the second comment cannot be on a different column than the first comment (which is pushed by the equation on its row).
But still, what I would like to happen is that the second comment would end by the right margin. Is there a simple way to achieve that? If possible, I would prefer to not define too complicated commands, even if it means I'll not get exactly what I asked for, but something else that kinda solves the problem.

A: You cannot have all the comments vertically aligned at their left margin, because the wide equation and the wide comment simply don't fit the line.
You can save space by setting the first term on a line by itself and still have the look of a display, avoiding to go to the left margin:
\documentclass{article}
\usepackage{amsmath}

\begin{document}

This is just some text to show where the margin is.
Some more and more text yay text is good.
This is just some text to show where the margin is.
Some more and more text yay text is good.
\begin{align*}
\lefteqn{a + b + c + d + e}\quad \\
&= an-expression \\
&= some-very-longgggggggggg-expression && \text{comment} \\
&= another-expression && \text{a little longer comment} \\
&= 0
\end{align*}

\end{document}

With \lefteqn you hide the width of the term; I added \quad in order not to have the=` signs at the left margin and it turns out that still a tad of space is available.

Another possibility you can explore, but this depends on the actual equations and comments, is breaking the long comment across lines.
\documentclass{article}
\usepackage{amsmath}

\begin{document}

This is just some text to show where the margin is.
Some more and more text yay text is good.
This is just some text to show where the margin is.
Some more and more text yay text is good.
\begin{align*}
a + b + c + d + e
&= an-expression \\
&= some-very-longgggggggggg-expression && \text{comment} \\
&= another-expression && \begin{tabular}[t]{@{}l@{}}
                         a little \\
                         longer \\
                         comment
                         \end{tabular} \\
&= 0
\end{align*}

\end{document}

A: Well, the following is a very simple trick that "kinda solves the problem":
% My standard header for TeX.SX answers:
\documentclass[a4paper]{article} % To avoid confusion, let us explicitly
                                 % declare the paper format.

\usepackage[T1]{fontenc}         % Not always necessary, but recommended.
% End of standard header.  What follows pertains to the problem at hand.

\usepackage{amsmath}

\begin{document}

% \slshape % if uncommented, will the reference to the Magic Theorem be slanted?

Some text before the equation, to show where the right margin lies.  Oh, no,
that was not enough: \emph{now} it is enough!
\begin{flalign*}
    \textit{formula\_result} &= \textit{short\_term} \\
        &= \textit{muuuuch\_loooonger\_term} + \textit{another\_one}
                && \text{by \ldots} && \\
        &= x-x
                && && \makebox[0pt][r]{by the Magic Theorem} \\
        &= 0
\end{flalign*}
Some text after the equation, to show again the position of the right margin of
the text block.

\end{document}

This is the output I get (on a TeXLive 2016, sorry, but that's what I've got at the moment):

Addition:
An even simpler solution using \hidewidth, which, however, does not yield exactly the same printout as the previous one:
% My standard header for TeX.SX answers:
\documentclass[a4paper]{article} % To avoid confusion, let us explicitly
                                 % declare the paper format.

\usepackage[T1]{fontenc}         % Not always necessary, but recommended.
% End of standard header.  What follows pertains to the problem at hand.

\usepackage{amsmath}

\begin{document}

Some text before the equation, to show where the right margin lies.  Oh, no,
that was not enough: \emph{now} it is enough!
\begin{flalign*}
    \textit{formula\_result} &= \textit{short\_term} \\
        &= \textit{muuuuch\_loooonger\_term} + \textit{another\_one}
                & \text{by \ldots} & \\
        &= x-x
                & \hidewidth\text{by the Magic Theorem} & \\
        &= 0
\end{flalign*}
Some text after the equation, to show again the position of the right margin of
the text block.

\end{document}

Indeed, IMHO the output is actually better, with both explanations aligned along the right margin:

Second addition:
If you object to using plain TeX commands like \hidewidth, you can replace the second example with the following code
% My standard header for TeX.SX answers:
\documentclass[a4paper]{article} % To avoid confusion, let us explicitly
                                 % declare the paper format.

\usepackage[T1]{fontenc}         % Not always necessary, but recommended.
% End of standard header.  What follows pertains to the problem at hand.

\usepackage{amsmath}

\begin{document}

% \slshape

Some text before the equation, to show where the right margin lies.  Oh, no,
that was not enough: \emph{now} it is enough!
\begin{flalign*}
    \textit{formula\_result} &= \textit{short\_term} \\
        &= \textit{muuuuch\_loooonger\_term} + \textit{another\_one}
                & \text{by \ldots} & \\
        &= x-x
                & \makebox[0pt][r]{by the Magic Theorem} & \\
        &= 0
\end{flalign*}
Some text after the equation, to show again the position of the right margin of
the text block.

\end{document}

with no change in the output.

A: Googling \lefteqn from egreg's answer I found this answer which is about \MoveEqLeft - a command from mathtools (see 3.4.4 here). So the example becomes:
\documentclass{article}
\usepackage{amsmath}
\usepackage{mathtools}

\begin{document}
    This is just some text to show where the margin is. Some more and more text yay text is good.
    \begin{align*}
    \MoveEqLeft[1] a + b + c + d + e \\
    &= an-expression \\
    &= some-very-longgggggggggg-expression && \text{comment} \\
    &= another-expression && \text{a little longer comment} \\
    &= 0
    \end{align*}
\end{document}

Which yields the following output (same as egreg's):

I think this solution is a bit better than using \lefteqn since \MoveEqLeft was made specifically to solve this problem (according to the documentation).

A: Here are two possibilities, with the flalign* environment, and \mathrlap from mathtools, or with a simple align*  and  the fleqn environment from nccmath:
\documentclass{article}
\usepackage{mathtools, nccmath}
\usepackage{showframe}
 \renewcommand{\ShowFrameLinethickness}{0.3pt}

\begin{document}

    This is just some text to show where the margin is. Some more and more text yay text is good.
    \begin{flalign*}
   \mathrlap{ a + b + c + d + e} \\
    &= an-expression \\
    &= some-very-longgggggggggg-expression && \text{comment} \\
    &= another-expression && \text{a little longer comment} \\
    &= 0
    \end{flalign*}
Some other text and another possibility:
\begin{fleqn}
    \begin{align*}
    a + b &+ c + d + e\\
    &= an-expression \\
    &= some-very-longgggggggggg-expression && \text{comment} \\
    &= another-expression && \text{a little longer comment} \\
    &= 0
    \end{align*}
\end{fleqn}

\end{document}


text:
Q: SQL Server - Concatenate 3 different tables matching correspondent ID's of those columns I've been on this for hours trying to figure this one out. So I need to concatenate values in a single column based on its ID's.
I have 3 tables named Type, DeliverType and Platform. I need to get all the matching ID's in the table Platform and concatenate all of its values in another column of table Platform.
Example :
Table Type           Table DeliverType                  Table Platform
----------------------------------------------------------------------------------------
ID | Type            ID    | DeliverType                ID     | TypeID  |  DeliverType
----------------------------------------------------------------------------------------
1  | TestType1        1    | DeliverType1               9      |   3     |       1
2  | TestType2        2    | DeliverType2               9      |   4     |       2
3  | TestType3        3    | DeliverType3               23     |   2     |       4
4  | TestType4        4    | DeliverType4               23     |   1     |       3

These are my tables , I want to return the name of Type, the name of DeliverType and the ID of Platform
Expected Result
Table Platform

ID | NamesConcat
9  | TestType1,TestType2,TestType3,DeliverType1,DeliverType2,9
23 | TestType2,TesType3,TestType4,DeliverType3,DeliverType4,23

So it has only 1 ID which is 9 and all of the testTypes and DeliverTypes correspondant to that ID in table platform needs to be concat.
Here's my code so far:
SELECT DISTINCT p.ID,
    SUBSTRING(
        (
            SELECT ','+ d.DeliverType,a.Type  AS [text()]
            FROM dbo.DeliverType d
            INNER JOIN dbo.Type a ON a.ID = p.TypeID
            ORDER BY d.ID
            FOR XML PATH ('')
        ), 2, 1000) [NamesConcat]
FROM dbo.Platform p

Would appreciate some help on this one fellow programmers.
Thank you very much in advance.

A: From the sample data you show, I don't get the same expected result. I would expect the result:
Table Platform

ID
NamesConcat

9
TestType3,TestType4,DeliverType1,DeliverType2,9

23
TestType1,TestType2,DeliverType3,DeliverType4,23

If that is indeed the expected result and you want the strings concatenated by the Type first and then by DeliverType you can do that with this query:
SELECT DISTINCT pmain.ID,
(
    SELECT t.[Type] + ','
    FROM Platform p
    INNER JOIN Type t ON t.ID = p.TypeID
    WHERE p.ID = pmain.ID
    ORDER BY t.ID
    FOR XML PATH('')
) +
(
    SELECT d.DeliverType + ','
    FROM Platform p
    INNER JOIN DeliverType d ON d.ID = p.DeliverTypeID
    WHERE p.ID = pmain.ID
    ORDER BY p.ID
    FOR XML PATH('')
) +
CAST(pmain.ID AS VARCHAR(10)) AS NamesConcat
FROM Platform pmain

If you don't need the concatenated values in that order, you could do it with a shorter query:
SELECT DISTINCT pmain.ID,
(
    SELECT d.DeliverType + ',' + t.[Type] + ','
    FROM Platform p
    INNER JOIN DeliverType d ON d.ID = p.DeliverTypeID
    INNER JOIN Type t ON t.ID = p.TypeID
    WHERE p.ID = pmain.ID
    FOR XML PATH('')
) + CAST(pmain.ID AS VARCHAR(10)) AS NamesConcat
FROM Platform pmain

So that you can check the work, here is a simple script that I wrote to mimic your demo data and the result:
DECLARE @Type AS TABLE (
    ID INT IDENTITY(1,1) NOT NULL,
    [Type] VARCHAR(20) NOT NULL
);
INSERT INTO @Type([Type]) VALUES('TestType1'), ('TestType2'), ('TestType3'), ('TestType4');

DECLARE @DeliverType AS TABLE (
    ID INT IDENTITY(1, 1) NOT NULL,
    [DeliverType] VARCHAR(25) NOT NULL
);
INSERT INTO @DeliverType([DeliverType]) VALUES ('DeliverType1'), ('DeliverType2'), ('DeliverType3'), ('DeliverType4');

DECLARE @Platform AS TABLE (
    ID INT NOT NULL,
    TypeID INT NOT NULL,
    DeliverTypeID INT NOT NULL
);
INSERT INTO @Platform(ID, TypeID, DeliverTypeID) VALUES (9, 3, 1), (9, 4, 2), (23, 2, 4), (23, 1, 3);

SELECT DISTINCT pmain.ID,
(
    SELECT d.DeliverType + ',' + t.[Type] + ','
    FROM @Platform p
    INNER JOIN @DeliverType d ON d.ID = p.DeliverTypeID
    INNER JOIN @Type t ON t.ID = p.TypeID
    WHERE p.ID = pmain.ID
    FOR XML PATH('')
) + CAST(pmain.ID AS VARCHAR(10)) AS NamesConcat
FROM @Platform pmain

SELECT DISTINCT pmain.ID,
(
    SELECT t.[Type] + ','
    FROM @Platform p
    INNER JOIN @Type t ON t.ID = p.TypeID
    WHERE p.ID = pmain.ID
    ORDER BY t.ID
    FOR XML PATH('')
) +
(
    SELECT d.DeliverType + ','
    FROM @Platform p
    INNER JOIN @DeliverType d ON d.ID = p.DeliverTypeID
    WHERE p.ID = pmain.ID
    ORDER BY p.ID
    FOR XML PATH('')
) +
CAST(pmain.ID AS VARCHAR(10)) AS NamesConcat
FROM @Platform pmain

I hope this is what you were looking for!


text:
Q: Custom rendering when using server side processing I was wondering if the rendering of the table after receiving an ajax response can be modified. This seems related to the render function described here: https://www.datatables.net/manual/orthogonal-data.
My server returns Data like
{
    "name":
                       {
                        id: "123456",
                        value: "Tiger Nixon"
                        }
}

I want to add to each name cell the id of the name as data-attribute or as id for the td and want to add a .on( "click", handler ) for each cell.
Is this possible?
Thanks in advance

A: You can use DT_RowData or DT_RowAttr (requires DataTables 1.10.5 or higher) parameters in your returned data to assign attributes to <tr> element which you can later retrieve in click handler, see Server-side processing chapter in the manual.
Alternatively you can use render method but it may not be as effective. I assumed below that index of your name column is 0 and that you want to set data-id attribute.
var table = $('#example').DataTable({
   "columnDefs": [{
      "data": "name.value",
      "targets": 0,
      "render": function ( data, type, full, meta ) {
         if(type === 'display'){
            $('#example').DataTable().cell(meta.row, meta.col).nodes().to$().attr('data-id', full['name']['id']);
         }

         return data;
      }
   }]
});

You can add click event handler using the code below:
$(document).ready(function(){
    var table = $('#example').DataTable({
       // Define DataTables initialization options here
    });

    $('#example tbody').on('click', 'td', function(){

       // Use table to access various API function
       //
       // For example:
       // var data_cell = table.cell(this).data();

    });
});

A: This is possible by using the columns.createdCell function.
The answer of Gyrocode is correct for an old DataTables version.


text:
Q: OpenSSL alert number 40 A program I've been using for years to read my email stopped working when my provider updated their servers. Now, when I run my program, I get this failure when I call BIO_do_connect():
error:14094410:SSL routines:SSL3_READ_BYTES:sslv3 alert handshake failure:s3_pkt.c:1086:SSL alert number 40

The failure is identical under MacOS Yosemite and an old Linux distro.
By comparison, this command does not fail:
openssl s_client -connect mail.example.org:993

For reference, here's a minimal program that demonstrates the problem (I've obscured my server name).
Is there some parameter I'm missing?
/*
 * Under MacOS, compile with:
 * cc -o tester -I/opt/local/include tester.c -L/opt/local/lib -lssl -lcrypto
 *
 * Under Linux, compile with:
 * cc -o tester tester.c -lssl
 */

#define CERTS_DIR       "/etc/ssl/certs/"

#include <stdio.h>
#include <stdlib.h>

#include <openssl/bio.h>
#include <openssl/ssl.h>
#include <openssl/err.h>

int
main()
{
    BIO *bio, *rbio;
    SSL_CTX *ctx;
    SSL *ssl;
    const char *hostname = "mail.example.org";
    int port = 993;

    SSL_library_init();
    ERR_load_BIO_strings();
    SSL_load_error_strings();
    OpenSSL_add_all_algorithms();

    ctx = SSL_CTX_new(SSLv3_client_method());
    if (ctx == NULL) {
        ERR_print_errors_fp(stderr);
        return 3;
    }

    /* load trusted certs with SSL_CTX_load_verify_locations()? */
    if (!SSL_CTX_load_verify_locations(ctx, NULL, CERTS_DIR)) {
        fprintf(stderr, "Unable to load trusted SSL certs\n");
    }

    bio = BIO_new_ssl_connect(ctx);
    BIO_get_ssl(bio, &ssl);
    SSL_set_mode(ssl, SSL_MODE_AUTO_RETRY);
    BIO_set_conn_hostname(bio, hostname);
    BIO_set_conn_int_port(bio, &port);

    // Here is the call that fails
    if (BIO_do_connect(bio) <= 0) {
        fprintf(stderr, "cannot connect to %s:%d\n", hostname, port);
        ERR_print_errors_fp(stderr);
        BIO_free_all(bio);
        SSL_CTX_free(ctx);
        return 3;
    }

    printf("Success\n");

    return 0;
}

A: Well, after a lot of trial and error, I was able to make the problem go away by changing SSLv3_client_method() to SSLv23_client_method()


text:
Q: CSS for individual page PHP I have a site in php with account. I want to write a CSS for "profile.php/user" (for example: profile.php/benjamin). I tried to put this line in profile.php :
<link rel="stylesheet" type="text/css" href="profile.css">

But obviously doesn't work.
profile.php
<?php
session_start();

if($_SESSION['logged'] == true){
    $username = $_SESSION['login_username'] ;
    $username = strtoupper($username); //il facem uppercase
    echo "Welcome ".$username;
    echo "
Press here to go to the home page";
    echo "
Click  here  to log out.";
}
else {
echo "

You must login first to see this section ";
header("refresh:4;url=/index.php");
}
?>

     <meta name="viewport" content="width=device-width, initial-scale=1.0">
     <link rel="stylesheet" type="text/css" href="profile.css">

A: Assuming the CSS file is in the same directory as the script, it should be:
<link rel="stylesheet" type="text/css" href="../profile.css">

This is because as far as the browser is concerned, profile.php/ is a directory in the URL. To get back to that same level, you have to go up with ../ in the URL.
The browser doesn't know anything about the actual file locations, and which parts of the URL are directories, filenames, and parameters, it just parses it textually. / simply separates directory levels, and ../ removes a trailing directory level when parsing a relative URL.