text:
Q: How to define dojo module for reference by onClick in HTML? I'm trying to follow the latest Dojo1.9 best AMD practices when defining a separate javascript module to be referenced by the JSP markup.  I used to have a large javascript section in the same JSP file, MyJayEsspEe.jsp, where the javascript section defined functions that were called by various element onClick properties.  Now I am separating the javascript into a new file called MyCallbacks.js using the Dojo define mechanism.
The format of the MyCallbacks.js looks like:
define(["dojo/dom", "dojo/dom-style", "dojo/has", "dijit/registry", "dojo/on"],
 function (dom, domStyle, dojoHas, registry, on) {
...
   function clickedOnButton1() {
      console.log("Clicked on button1");
   }
   function clickedOnLinkTwo() {
      console.log("Clicked on second link");
   }
...
   return {
      clickedOnButton1: clickedOnButton1,
      clickedOnLinkTwo: clickedOnLinkTwo
   }
});

and in the MyJayEsspEe.jsp file I currently have working ugly markup that includes:
...
    <button data-dojo-type="dijit/form/Button" type="button" onclick="require(['commonjs/MyCallbacks'], function(mycallbacks) {mycallbacks.clickedOnButton1();});">First Button</button>

    Link Two
...

but I'm hoping there's a way to define the module and require it such that in the markup I could have cleaner callbacks like so:
...
    <button data-dojo-type="dijit/form/Button" type="button" onclick="mycallbacks.clickedOnButton1();">First Button</button>

    Link Two
...

I've been reviewing the Dojo reference documentation for defining modules and callbacks but so far haven't found a pointer to the clean solution that I'm looking for.  Is there a cleaner solution than the one I've been using?
Thanks for your time,
Gregor

A: If you cannot create a full widget on the JS side and use the template to attach events,
using your current example you can write it like that:
<button data-dojo-type="dijit/form/Button" type="button" onclick="require('commonjs/MyCallbacks').clickedOnButton1();">First Button</button>

Link Two

Your JS look a bit strange through, in how you return your functions. Usually it would be written like that:
define(["dojo/dom", "dojo/dom-style", "dojo/has", "dijit/registry", "dojo/on"],
   function (dom, domStyle, dojoHas, registry, on) {

      var MyCallbacks={};

      MyCallbacks.clickedOnButton1 = function() {
         console.log("Clicked on button1");
      };

      MyCallbacks.clickedOnLinkTwo = function() {
         console.log("Clicked on second link");
      };
      ...
      return MyCallbacks;
});

A: As a best practice it is always advised to encapsulate the behaviour of a widget in itself. All callbacks that a widget is supposed to handle should be defined within the widget. Defining all the callbacks in a single module breaks the modularity and portability of your modules.
To answer your question:

Link Two


text:
Q: number of characters needed to separate conjugacy classes It is very well-known that, if $G$ is a finite group, then the (complex) characters of $G$ separate the conjugacy classes; that is, if $g, h \in G$ are not conjugate, then there exists a character $\chi$ such that $\chi(g) \ne \chi(h)$. However, I have been wondering about the minimal number of characters needed to separate all the classes.
Consider the (very basic) example $G=C_n$, a cyclic group of order $n$. Then it is possible to find a single character $\chi$ which is injective on $G$, so the answer is $1$ in this case.
Looking at a few character tables using GAP, it seems the answer is often 1.
Is there any literature on this? Any reason why this number could be much easier to determine than I think? Is it always 1 ? I may very well have overlooked something simple.
Note that the answer would be different if you only allowed irreducible characters (then for $C_2\times C_2$, it is 2); it's also different if you allow virtual characters, I guess.
Thanks!
Pierre

A: Obviously Peter Müller's argument is perfectly fine. Here is a different way of doing it.
This algorithm yields a character that separates the conjugacy classes. It is terrible to compute with.
Index a set of representatives of the conjugacy classes $\{g_i\}$. Associate to every character $\chi$, the set of ordered pairs
$$D(\chi) = \left\{ (g_i,g_j): g_i \neq g_j, { \mathrm {but } }\  \chi(g_i) = \chi(g_j)\right\}.$$
Now we show that if $D(\chi)$ is nonempty, there exists an irreducible character $\chi'$ and a positive integer $N$ (depending on $\chi$ and $\chi'$) such that $D(N\chi + \chi')$ is strictly contained in $D(\chi)$.
To see this, set $s $ to be the infimum of $|\chi(g_i) - \chi(g_j)|$ over all pairs of distinct representatives $(g_i,g_j)$ that are not in $D(\chi)$
(this is an infimum over a finite set of nonzero numbers). Pick $(g,h) \in D(\chi)$; there exists an irreducible $\chi'$ such that $\chi'(g) \neq \chi'(h)$. Select $N$ a positive integer so large that $Ns > 2\chi'(1)$, and set $\psi = N\chi + \chi'$, a character.
If $\chi(g) \neq \chi(g')$, then $\psi (g) -\psi(g') = \left( N(\chi(g) - \chi(g')\right) + (\chi' (g) - \chi(g'))$; the first parenthesized term has absolute value at least $Ns$, while the second one has absolute value at most $2 \chi'(1)$. Hence $D(\psi)$ is contained in $D(\chi)$.
On the other hand, $(g,h)$ is not in $D(\psi)$, since $\psi(g) - \psi (h) =
\chi'(g) - \chi'(h)$.
This process (begin with any nontrivial character, and continue) must terminate, resulting in a character $\rho$ with empty $D(\rho)$, which is exactly what we want.

A: You always find a character which distinguishes between the distinct conjugacy classes. Let $\delta_k$ be the characteristic function of the $k$-th conjugacy class. Set $f=\delta_1+2\delta_2+3\delta_3+\dots$. Then clearly $f$ distinguishes the conjugacy classes. As a class function, $f$ is a complex linear combination of the irreducible characters. Write $f=a+ib$, where $a$ and $b$ are real linear combinations of irreducible characters. Then, for a suitable real number $\lambda$, $g=a+\lambda b$ also distinguishes the conjugacy classes. Now $g$ is a real linear combination of the irreducibles. Replacing the real coefficients by sufficiently good rational approximations, we still have the separating property. Now multiply by an integer to obtain a virtual character, and finally add a suitably large multiple of the regular character to obtain the required character.
Note added: The question actually doesn't have much to do with character theory, since the following far more general fact holds: If in a complex matrix there are no two equal columns, then there is a nonnegative integral linear combination of the rows such that the entries are pairwise distinct. This can for instance be proven by induction on the number of columns.

A: Here is a contribution (answering a weaker question, and certainly not definitive, but it might suggest a direction for others to pursue). For the symmetric group, a single virtual character will do the job ( for a general finite group $G$, a single algebraic integer combination of characters of $G$ will do the job).
Let $G$ be a finite group and $\{x_{1},x_{2},\ldots, x_{k} \}$ be a full set of representatives for the distinct conjugacy classes of $G$. For $ 1 \leq i \leq k,$ let $\theta_{i} = \sum_{\chi \in {\rm Irr}(G)}\chi(x_{i}^{-1})\chi,$ which is an algebraic integer combination of characters of $G$. By the orthogonality relations, we have $\theta_{i}(x_{j}) = \delta_{ij}|C_{G}(x_{i})|.$
Let $\{p_{1},p_{2}, \ldots,p_{k} \}$ be a set of distinct primes, each greater than $|G|$. Let $\psi = \sum_{i=1}^{k} p_{i} \theta_{i},$ which is an integer-valued algebraic integer combination of irreducible characters of $G.$ Note that whenever $i \neq j,$ the integer $\psi(x_{i})$ is divisible by $p_{i},$ but $\psi(x_{j})$ is not. Hence $\psi$ takes $k$ distinct values.
In the case that $G$ is the symmetric group $S_{n},$ the irreducible characters of $G$ are all rational-valued, so that $\psi$ is a virtual character of $G.$

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get rid of null values in my GridDB database? I have a GridDB container for the sqllite database I am implementing into my Student Management app, but I need to GET RID of the NULL values on the database. How can I delete the rows and not make them appear on the app?
I have tried to
Here is an image of a sample of how the app looks like.Five rows showing two NULL values
import pandas as pd
import griddb_python as griddb
from kivy.metrics import dp
from kivy.uix.anchorlayout import AnchorLayout
from kivymd.app import MDApp
from kivymd.uix.datatables import MDDataTable
from kivymd.uix.label import MDLabel
import sqllite3

factory = griddb.StoreFactory.get_instance()

try:
    gridstore = factory.get_store(host="127.0.0.1", port="8080",
            cluster_name="Cluster12", username="root",
            password="")
    conInfo = griddb.ContainerInfo("Students_DB",
                    [
                     ["Student ID", griddb.Type.INTEGER],
                     ["First Name", griddb.Type.STRING],
                     ["Last Name", griddb.Type.STRING],
                     ["Gender", griddb.Type.STRING,
                     ["DOB", griddb.Type.STRING],
                     ["Current Year", griddb.Type.INTEGER],
                     ["CGPA", griddb.Type.FLOAT],
                    ],
                    griddb.ContainerType.COLLECTION, True)
    con = gridstore.put_container(conInfo)
    # Reading Database into a Pandas DataFrame
    container = sqlite3.connect("StudentsDB.db")
    df = pd.read_sql_query("SELECT * from best_students", container)

    # Adding the database
    for i in range(len(df)):
        ret = con.put(df.iloc[i, :])

except Exception as e:
    print(e)

sql_statement = ('SELECT * FROM Students_DB')
sql_query = pd.read_sql_query(sql_statement, con)

class Students(MDApp):
    def build(self):
        layout = AnchorLayout()
        title = MDLabel(
                            text = "Students Record Management(SRM)",
                            theme_text_color = "Custom",
                            text_color = (0, 0, 0, 1),
                            pos_hint = {"center_x": .5, "center_y": .8},
                            size_hint_x = 1,
                            halign = "center"
            )
#...

A: I am not sure at what place you would like to remove the NULL values.
But griddb syntax accepts removing null using this syntax in the query:
SELECT * from best_students where <columnName> IS NOT NULL
Remember changing columnName to what ever column you prefer removing NULL from.
[EDIT] I saw you image later on.
If you like to remove NULL from Last Name you should write like this:
SELECT * from best_students where 'Last Name' IS NOT NULL


text: Q: LineChart lines get cut off or trucating at values of zero iam using mpandroidchart lib and i used rendererLeftYAxis to draw the lines line chart is trucating or cut off at zero line i used extraspacing bottom but it is not useful i tried a lot


text:
Q: How would one calculate binary statistics in perl? I am essentially seeking to do what a typical/good hex editor can do:
https://www.hhdsoftware.com/doc/hex-editor/statistics-statistics-tool-window.html
I wish to be able to count the occurrence of each byte and put it into a table so I can determine the % of say '00' compared to 'FF'.
I have managed to get entropy, and the other statistics such as mean, median and mode are kind of redundant once I have the above complete.
There is also an issue that the binary files I am compiling statistics on are quite large, 32mb+.
Any suggestions?

A: use List::Util qw( sum );

use constant BLOCK_SIZE => 4*1024*1024;

open(my $fh, '<:raw', $qfn)
   or die("Can't open \"$qfn\": $!\n");

my @counts = (0) x 256;
while (1) {
   my $rv = sysread($fh, my $buf, BLOCK_SIZE);
   die($!) if !defined($rv);
   last if !$rv;

   ++$counts[$_] for unpack 'C*', $buf;
}

my $N = sum @counts;

A: Heres another way to do it:
use strict;
use warnings;
use Time::HiRes qw( time );

$/ = \1;

open my $file, '<', shift;
binmode $file;

my %seen;

my $start = time();
my $n;

while (<$file>) {
    $seen{$_} ++;
    $n++;
}
my $end = time();

for ( sort keys %seen ) {
    printf( "%s%s%.2f%s\n", uc( unpack( 'H*', $_ ) ), " seen $seen{$_} times - ", $seen{$_} / $n * 100, "%" );
}

printf( "took %.3f seconds!\n", $end - $start );

output:
...
...
F8 seen 46475 times - 0.28%
F9 seen 46611 times - 0.28%
FA seen 46703 times - 0.28%
FB seen 48902 times - 0.29%
FC seen 46829 times - 0.28%
FD seen 47707 times - 0.28%
FE seen 47276 times - 0.28%
FF seen 1752333 times - 10.44%
took 2.374 seconds!

This is (WSL in windows) perl 5.22.1 built for x86_64-linux-gnu-thread-multi
(with 69 registered patches)
Same thing in C - https://github.com/james28909/count/blob/master/count.c
EDIT:
Actually here is another, BETTER, example given by BrowserUK at perlmonks - https://www.perlmonks.org/?node_id=1159266 - It seems to run faster than both examples/answers given.
use strict;
use Time::HiRes qw[ time ];

my $start = time;

open I, '<:raw', $ARGV[ 0 ];

my @seen;

while( read( I, my $buf, 16384  ) ) {
    ++$seen[$_] for unpack 'C*', $buf;
}
printf "Took %f secs\n", time() - $start;


text:
Q: Sampling from columns of ys stacked over values of x in R (visual provided) Background
I have a two variables called x and y (please see R code below the picture). When I plot(x, y), I obtain the top-row plot (see below). y values are stacked over the top of each x value.
Question
I am wondering WHY when I sample from y values that are separately stacked over the top of each x value (e.g., y-values stacked over the top of x value of "0"), I get some sampled y values that are outside their range of their mother sample!? (please see the bottom-row table to see this).

HERE IS MY R CODE:
 #############  Input Values ###################
                      each.sub.pop.n = 150;
                      sub.pop.means = 20:10;
                      predict.range = 0:10;
                      sub.pop.sd = .75;
                      n.sample = 2;
 #############################################
  par( mar = c(2, 4.1, 2.1, 2.1) )

  m = matrix( c(1, 2), nrow = 2, ncol = 1 ); layout(m)

  Vec.rnorm <- Vectorize(function(n, mean, sd) rnorm(n, mean, sd), 'mean')

  y <- c( Vec.rnorm(each.sub.pop.n, sub.pop.means, sub.pop.sd) )

  x <- rep(predict.range, each = each.sub.pop.n)

  plot(x, y)

  ## Unsuccessfull Sampling ##
  x <- rep(predict.range, each = n.sample)

  y <- sample(y , length(x), replace = TRUE)

  plot(x, y)

A: It seems to me that your sample is not conditional on x in your unsuccessful sampling piece. In the below, I split the y data by x and then sampled two cases from each. The result seems to work.
sample <- lapply(split(y, x), function(z) sample(z, n.sample, replace = TRUE))
sample <- data.frame(y = unlist(sample),
                     x = as.numeric(rep(names(sample), each = n.sample)))
plot(sample$x, sample$y)

A: You can use the stratified sampling implemented in the sampling package with the strata function:
  par( mar = c(2, 4.1, 2.1, 2.1) )
  m = matrix( c(1, 2), nrow = 2, ncol = 1 ); layout(m)
  Vec.rnorm <- Vectorize(function(n, mean, sd) rnorm(n, mean, sd), 'mean')
  y <- c( Vec.rnorm(each.sub.pop.n, sub.pop.means, sub.pop.sd) )
  x <- rep(predict.range, each = each.sub.pop.n)
  plot(x, y)

  library(sampling)
  df <- data.frame(x,y)
  set.seed(123)
  stratif_sampl <- strata(df,"x",rep(2,11))
  idx <- stratif_sampl$ID_unit
  plot(x[idx], y[idx])


text:
Q: How to use all records from another table as counting columns? I have 4 tables:
location:
location_id   name
------------------------
1             France

device:
device_id     location_id    model_id
-------------------------------------
1             1              1
2             1              2
3             1              3

model:
model_id      family_id      name
-------------------------------------
1             1              C-max
2             1              S-max
3             2              Vectra

and family:
family_id    name
---------------------
1            Ford
2            Opel

I need to build a complicated SQL query now. As the result, I would like to receive this:
location_id    name      Ford      Opel
------------------------------------------
1              France    2         1

Is it possible to do it in SQL at all? I see there there problems:

*

*About using other table records as columns in the query

*About nested tables

*About counting the elements (count function?)
Any comments/reference materials will be for me helpful. I do not await the final code.

A: In SQL queries the columns are fix. You get more or less rows depending on data, not columns. But that doesn't matter, because SQL is about to get data not to display it. The latter is a task for the GUI layer.
So get the desired data, which is the number of models per location and family mainly.
select l.location_id, l.name as location_name, f.name as family_name, count(*) as models
from location l
join device d on d.location_id = l.location_id
join model m on m.model_id = d.model_id
join family f on f.family_id = m.family_id
group by l.location_id, l.name, f.name
order by l.location_id, l.name, f.name;

This is all you need from the database. How to show the data is a task for your programm, a Delphi app in your case. So use Delphi to read the data with above query and fill your grid in a simple loop.

A: Thank you all for your helpful tips.
I solved my problem using the static method and the code published by @Matt. Because somebody else may looking for the solution, I paste here my working query for PostgreSQL:
SELECT DISTINCT t.location_id, t.name, SUM(t.ford) AS ford, SUM(t.opel) as opel
FROM(
SELECT l.location_id, l.name,
(SELECT COUNT(m.family_id) WHERE m.family_id = '1') AS ford,
(SELECT COUNT(m.family_id) WHERE m.family_id = '2') AS opel
FROM location l
INNER JOIN device d ON l.location_id = d.location_id
INNER JOIN model m ON d.model_id = m.model_id
INNER JOIN family f ON m.family_id = f.family_id
GROUP BY l.location_id, l.name, m.family_id
) t
GROUP BY t.location_id;


text:
Q: How to manage network in android I want to downloading image from instagram or picasa, during the downloading the network is disconnected. I want it should be start re downloading when the network connected again. downloading start from where the network was gone.
plz give some idea or any reference link.
Thanks

A: Register a broadcast for listening to network events. Please check android network events.
This is already solved  in many other posts like link


text:
Q: how to combine two same class object into one? I made a one class that named Phrases that includes some strings and integers.
public class Phrases {
    public class PhraseData {
        public string text { get; set; }
        public string htmlColor { get; set; }
        public int position { get; set; }
    }

    public PhraseData intro { get; set; }
    public PhraseData credit { get; set; }
    public PhraseData general { get; set; }
    /* and more PhraseDatas... */
}

/* ... */

and I have a two json file. one is only have text data of PhraseData, another one have a every data except text data. so If I deserialize these json files. I'll get two Phrases class objects like this.
Phrases onlyTextFilled;
Phrases everyDataFilledExceptText;

I want to combine these two class objects into one. there is any good way to solve this problem?
help me guys!

A: Quick and dirty. Overload the '+' operator. For the inner class and the main one. Also add attributes to ignore default and null values for your properties (if using Newtonsoft.Json for instance). Another wild thought, you could use the decorator pattern.
public class Phrases
{
    public class PhraseData
    {
        [JsonProperty(NullValueHandling = NullValueHandling.Ignore, Order = 1, DefaultValueHandling = DefaultValueHandling.Ignore)]
        public string text { get; set; }

        [JsonProperty(NullValueHandling = NullValueHandling.Ignore, Order = 2, DefaultValueHandling = DefaultValueHandling.Ignore)]
        public string htmlColor { get; set; }

        [JsonProperty(NullValueHandling = NullValueHandling.Ignore, Order = 3, DefaultValueHandling = DefaultValueHandling.Ignore)]
        public int position { get; set; }

        public static PhraseData operator + (PhraseData pd1, PhraseData pd2)
        {
            var pd = new PhraseData();
            pd.text = (pd1.text == null) ? pd2.text : pd1.text;
            pd.htmlColor = (pd1.htmlColor == null) ? pd2.htmlColor : pd1.htmlColor;
            pd.position = (pd1.position == 0) ? pd2.position : pd1.position;
            return pd;
        }
    }

    public PhraseData intro { get; set; }
    public PhraseData credit { get; set; }
    public PhraseData general { get; set; }

    public static Phrases operator + (Phrases p1, Phrases p2)
    {
        return new Phrases() {
            intro = p1.intro + p2.intro,
            credit = p1.credit + p2.credit,
            general = p1.general + p2.general
        };
    }
}


text:
Q: how to use admob native ads without NativeAppInstallAdView or NativeContentAdView we would like to use the native ads feature of admob and display them in our own UI.
the NativeContentAd provides access to different properties, like image, logo, text, but we cannot access the call to action url.
all samples use NativeAppInstallAdView or NativeContentAdView.
is there a way to do that, to have our own UI without NativeAppInstallAdView or NativeContentAdView?
thanks.

A: You can define your own layout xml, and wrap it with an NativeAppInstallAdView or NativeContentAdView.
The wrapper view adds the ad-choices icon on the top-right corner over your custom design.
See: https://developers.google.com/admob/android/native#the_ad_view_classes


text:
Q: Vuejs: How to use `v-b-modal directive` in BootstrapVue? Here's my code (ERROR):
<template lang="pug">
  .component-root
    b-btn(v-b-modal.myModal)
      i.fa.fa-calendar
    b-modal#myModal
      span Hello this is my modal!
</template>

it outputs an error message:
[Vue warn]: Property or method "v" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://v2.vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.

When I use $refs method to create modal, it works :
<template lang="pug">
  b-button(@click="showModal")
    i.fa.fa-calendar
  b-modal(ref="myModalRef" hide-footer title="some title")
    span Hello form my modal
</template>

<script>
  ...
  methods: {
    showModal() {
      this.$refs.myModalRef.show();
    },
  }
  ...
</script>

Here's my main App.js with BootstrapVue installed
import 'bootstrap-vue/dist/bootstrap-vue.css';
import 'font-awesome/css/font-awesome.min.css';

import Vue from 'vue';
import Moment from 'vue-moment';
import BootstrapVue from 'bootstrap-vue';
import DatePicker from 'vue2-datepicker';

import './assets/bootstrap.cosmo.min.css';

import App from './App';
import router from './router';

Vue.config.productionTip = false;
Vue.use(BootstrapVue);
Vue.use(Moment);
Vue.use(DatePicker);

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>',
});

I just following the manual here: https://bootstrap-vue.js.org/docs/components/modal/
So far I have problem until I want to show some modal.
What's wrong with me?

A: The problem is pug. In:
<template lang="pug">
  .component-root
    b-btn(v-b-modal.myModal)
      i.fa.fa-calendar
    b-modal#myModal
      span Hello this is my modal!
</template>

The line:
b-btn(v-b-modal.myModal)

Messes things up. Use:
b-btn(v-b-modal.myModal="")

Reason:
b-btn(v-b-modal.myModal) creates <b-btn v-b-modal.myModal="v-b-modal.myModal">, which makes Vue search for that falue. Using b-btn(v-b-modal.myModal="") creates <b-btn v-b-modal.myModal=""> which solves the problem.
More: https://github.com/pugjs/pug/issues/370#issuecomment-2399051


text:
Q: ajax controlling in rails Hey guys I need to know the answers to some questions. First of all how do I handle ajax call when I am not returning anything from the controller because it always ask me for the view for the called function but since I have called that function using ajax how can it have a view.(I am using it in ROR(ruby on rails))
bookmark.html.erb

        <input type="hidden" id="bookmarked_against_req_id" value=<%= @data2%> />
        <%
        if @requests != nil
         @requests.each.with_index do |request,index|

          if request != nil
          %>

          <a href="#" onclick="ajax_bookmark('<%= request.id %>' , '<%=@request_id%>')" >

<%= request.title  %>

<%= request.is_service%>

            <%= request.description%>

          <% if @tag[index] != nil
              @tag[index].each do |cat| %>
                 <%= cat.title %>
             <%end%>
          <%end%>

Syed Muhammad Ali Gardezi

          <time><%= request.created_at %></time>

          <%end%>
          <button class="button tiny">Schedule Meeting</button>

  <%end%>
  <%end%>

  $('#book-title').html("<%=@book.title%>");
<%end%>

And in your view, close to the link above, this will then change the text inside a html-tag with I'd book-title.

Second:
I do not understand what you mean by

...need to return something...

Can you add an example?
Hope that this can help you a bit.
Edit:
This is my try to understand what you want to do:
In your view:
<%= hidden_field_tag :bookmarked_against_req_id, value: @data2 %>
  <% if @requests != nil %>
    <% @requests.each.with_index do |request,index| %>
      <% if request.present? %>
        <%= link_to 'Bookmark it', bookmark_request_path(request), remote: true %>
        <%= request.title  %>
        <%= request.is_service%>
        <%= request.description%>
        <% if @tag[index].present? %>
          <% @tag[index].each do |cat| %>
            <%= cat.title %>
          <%end%>
        <%end%>
        <%= request.created_at %>
       <%end%>
  <%end%>
 <%end%>

In your controller:
def bookmark_request()
  request_bookmarked = Request.getRequest(params[:id]) # the params[:id] should be set in the request.
  bookmarked_agains_Request = Request.getRequest(params[:bookmarked_against_req_id) # This is defined in your hidden_field_tag

When your action bookmark_requestis done. If the request was AJAX you will render the JavaScript-file bookmark_request.js.erb
Here you should have the script you put in your view:
If the resource is saved, you should put JavaScript to render 'Success' or if it failed you should do otherwise.
The flash[:notice] = "Request has been bookmarked successfully."will not be understood by your AJAX-request.

A: You'll probably want to take a look at the rails guides - they're a great source of general grounding: http://guides.rubyonrails.org. For returning different responses based on the request format (ajax vs. html), see http://guides.rubyonrails.org/action_controller_overview.html#rendering-xml-and-json-data and @davidwessman's answer above.
Generally, you'll typically return JSON data from an ajax request; so, for instance, in the controller you might say
respond_to do |format|
  format.js {render json: @my_ojects.to_json}
end

Note that there are several ways to render json, including the gems like rabl. If you're returning json like that, you don't need to render a rails view (unless you're using a view to build your json, like rabl does or is hinted at in davidwessman's answer with js.erb).
Hope that helps.


text:
Q: Ipaddress does not show up on netstat Why would a ipaddress not show up in foreign address when I do netstat -atp tcp?
Here is a list of my foreign address that are not showing up. How can I find out where they are going to?
  Proto  Local Address          Foreign Address        State           Offload State

  TCP    192.168.0.184:58137    server3005:5938        ESTABLISHED     InHost
  TCP    192.168.0.184:58142    bn3sch020010558:https  ESTABLISHED     InHost
  TCP    192.168.0.184:58204    HPD89D67DFAC36:8080    ESTABLISHED     InHost
  TCP    192.168.0.184:58245    ou-in-f188:5228        ESTABLISHED     InHost
  TCP    192.168.0.184:58398    HPD89D67DFAC36:8080    ESTABLISHED     InHost
  TCP    192.168.0.184:58542    cache:https            ESTABLISHED     InHost
  TCP    192.168.0.184:58544    234-255-73-208:http    TIME_WAIT       InHost
  TCP    192.168.0.184:58545    a23-78-241-168:http    TIME_WAIT       InHost
  TCP    192.168.0.184:58547    yts2:https             ESTABLISHED     InHost
  TCP    192.168.0.184:58548    234-255-73-208:http    ESTABLISHED     InHost


text:
Q: How can I save an array character at the same index in another array? There must be an easy way to replace an element of an array in Ruby. I don't want to use regular expressions.
while @word_array.include? c do
  idx = @word_array.index(c)
  @currently_found[idx] = c
  @word_array.index(idx) = " "
end

I want to save the char c at the same index but in another array.

A: Just use the return value of Array#index. For example:
an_array     = %w[a b c]
new_array    = []
chars        = ['b']
chars.each do |char|
  new_array[an_array.index(char)] = char if an_array.include? char
end
new_array
=> [nil, "b"]

A: Not sure what you want it for (do you really want to change @word_array to contain a space?), but this should do it (except for additional nil's at end of array, don't know if that's a problem):
@currently_found = @word_array.map { |w| w == c ? c : nil }


text:
Q: How to do Data Flow Task from/to the same table? I am using SQL Server 2005 SSIS and we are using the Data Flow Task to move data from one table to another. This works well. Now we have another requirement to do data update from the same table using this approach.
Is this possible to use the same approach for as follow:

*

*We have a dataset from Table A based on complex query

*We update back to the Table A

The normal query UPDATE INTO is not an option due it takes awhile to process and we can't see the data movement like we did for Data Flow Task.
Any guidance or anything that will be good.
Thanks

A: either:

*

*write it to a temporay table and do the update into with a single SQL task after you processed everything

*break it down into smaller chunks based on SSIS variables and OFFSET and use a FOR/FOREACH LOOP

A: Read the data with a data source in a data flow task, and use ole db command in the data flow to update the data in the same table. If there is no locking when you read and only row-level locking when you update, that should work


text:
Q: alert when focus is in text box only I am getting an alert when i skip the text box but an alert is also coming wherever I click on page. How can I show an alert when the focus will be on the text box? The alert is also coming even when I open a new tab. Is there a way to solve this? Many thanks.
$(function() {
    $("input").blur(function() {
    if(!this.value) {
      alert("Text box " + ($(this).index() + 1) + " cannot be empty.");
      this.focus(); //Keep focus on this input
    }
});

body section
<input type="text" id="textbox1"/>
<input type="text" id="textbox2"/>
<input type="text" id="textbox3"/>
<input type="text" id="textbox4"/>

A:   $(function() {
        $('input:text').blur(function() {
if(!this.value) {
    alert("Text box " + ($(this).index() + 1) + " cannot be empty.");
    this.focus(); //Keep focus on this input
}
});
});

also visit http://api.jquery.com/text-selector/
hope it helps.

A:   <script type="text/javascript">
        function getAlert(txt) {
                if (!txt.value) {
                    alert("Text box cannot be empty.");
                    txt.focus(); //Keep focus on this input
                }

        };
    </script>

<input type="text" id="textbox1" onfocus="getAlert(this)"/>

I hope that this resolved your problem.

A: try this,
$(function() {
   $("input[type=text]").blur(function() {
       if (!this.value && $(document.activeElement).attr("type") == "text")
          alert("Text box " + ($(this).index() + 1) + " cannot be empty.");
          this.focus();
       }
    });
});

document.activeElement will get you current selected element and then you can compare if the selected element is a textbox.
hope this helps.........


text:
Q: JPA @Past Date/Calendar validation In a spring-boot based project i have a simple DTO object:
public class ExpenseDTO {

    @Min(value = 1, message = "expense.amount.negative")
    private int amount;

    @Past
    private Calendar createdAt;

    // setters/getters/constructor are omitted
}

and such rest controller:
public class ExpenseController {

private final ExpenseService expenseService;

    @Autowired
    public ExpenseController(ExpenseService expenseService) {
        this.expenseService = expenseService;
    }

    @RequestMapping(value = ADD_EXPENSE, method = POST)
    public ResponseEntity addExpense(@Valid @RequestBody ExpenseDTO expenseDTO, Principal principal) {
        expenseService.addExpense(expenseDTO, principal.getName());
        return ResponseEntity.ok().build();
    }
}

From a client i'm gonna send a current date: {"createdAt": "2017-01-27T21:32:19.183Z"} but during validation on the back end the date will be parsed as "2017-01-28T01:30:00.000+0200" so the result is wrong and validation fails. I was trying to play around with @JsonFormat but with no result.
NOTE: i'm using H2 db and if remove @Past from the DTO object everything works just fine, but i have to disable future date.
So how can i validate the date without timezone, i mean i need the exactly the same date on the back end as it was send from a client?!

A: It might be because of the TimeZone set in your local machine. You can set it to UTC in the application startup, e.g.:
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));

Also, you need to set the TimeZone in the SimpleDateFormat instance that is being configured inside ObjectMapper (if you are configuring ObjectMapper as a bean), e.g.:
@Bean
public ObjectMapper objectMapper(){
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    objectMapper.setSerializationInclusion(Include.NON_NULL);

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSS'Z'");
    simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    objectMapper.setDateFormat(simpleDateFormat);
    return objectMapper;
}

If it still does not work, I would recommend creating a custom deserializer for Calendar and manually setting TimeZone in new instance, e.g.:
@Component
public class CalendarDeserialiser extends JsonDeserializer<Calendar>{

    TimeZone UTC = TimeZone.getTimeZone("UTC");
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSS'Z'");

    @Override
    public Calendar deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {

        Calendar calendar;
        try{
            calendar = Calendar.getInstance(UTC);
            calendar.setTime(dateFormat.parse(p.getText()));
        }catch(Exception e){
            throw new IOException(e);
        }
        calendar.setTimeInMillis(p.getLongValue());
        return calendar;
    }
}

And annotate your Calendar field with @JsonDeserialize(using = CalendarDeserialiser.class).


text:
Q: Scrape the data from a website that loads the data from JavaScript / JSON Array (POST request) using Python I am trying to scrape the data from this link
I have tried this way
from bs4 import BeautifulSoup
import urllib.request
import csv

# specify the url
urlpage =  'https://www.ikh.se/sysNet/getProductsJSON/getProductsJSONDB.aspx?' \
'sua=1&lang=2&navid=19277994'

# query the website and return the html to the variable 'page'
page = urllib.request.urlopen(urlpage)
# parse the html using beautiful soup and store in variable 'soup'
soup = BeautifulSoup(page, 'html.parser')
tag = soup.find('div', attrs={'class':'dnsCell'})
text = (''.join(tag.stripped_strings))
print (page)

I got the HTML dom but the product list dom are missing. Actually I guess the product list dom manages by a JSON array that requests from this link but I am not sure about the product list dom load method. I am right or wrong.
I want to scrape the all product details from this site and export in Excel.

A: The requests library does not load the Javascript. If you want to download completely rendered website, use selenium library : https://selenium-python.readthedocs.io/


text:
Q: Force Download MP3 with PHP Be honest : I found the way to donwload mp3 files from s******d but Im not able to donwload the MP3 directly all the music is streaming in the browser.
I already try with someting like this
Download the mp3

but my donwload link is not .mp3, this is my line of code to donwload a file
href="<?php echo $val['stream_url']?>?client_id=67739332564a7130c3a05f90f2d02d2e">Descargar.

When I use the the option
direct_download.php?file=

just donwload one file with the name
client_id=05b4f2000dad27aa9fc48d08915d7830.html

The complete php code that I use is
<?php
$file = $_GET['file'];
header ("Content-type: octet/stream");
header ("Content-disposition: attachment; filename=".$file.";");
header("Content-Length: ".filesize($file));
readfile($file);
exit;
?>

Which can be accessed in any anchor like this:
Download the mp3

Could you please help me, or if you have a better ide, thank you guys

A: if you are using html5 you can use download option
Download the mp3

otherwise, you can use javascript
function saveAs(url) {
  var filename = url.substring(url.lastIndexOf("/") + 1).split("?")[0];
  var xhr = new XMLHttpRequest();
  xhr.responseType = 'blob';
  xhr.onload = function() {
    var a = document.createElement('a');
    a.href = window.URL.createObjectURL(xhr.response);
    a.download = filename;
    a.style.display = 'none';
    document.body.appendChild(a);
    a.click();
    delete a;
  };
  xhr.open('GET', url);
  xhr.send();
}

Call it from your link
Download the mp3


text:
Q: What is the most efficient PHP way to read first and last line of a file? I'm trying to open a file and determine if it is valid. It's valid if the first line is START and the last line is END.
I've seen different ways of getting the last line of a file, but it does not pay particular attention to the first line either.
How should I go about this? I was thinking of loading the file contents in an array and checking $array[0] and $array[x] for START and END. But this seems to be a waste for all the junk that could possibly be in the middle.
If its a valid file, I will be reading/processing the contents of the file between START and END.

A: Don't read entire file into an array if it is not needed. If file can be big you can do it that way:
$h = fopen('text.txt', 'r');
$firstLine = fgets($h);
fseek($h, -3, SEEK_END);
$lastThreeChars = fgets($h);

Memory footprint is much lower

A: That's from me:
$lines = file($pathToFile);
if ($lines[0] == 'START' && end($lines) == 'END') {
    // do stuff
}

A: Reading whole file with fgets will be efficient for small siles. iF ur file is big then:

*

*open It and read first line

*use tail (i didn't check it but it looks OK)  function I found in php.net in fseek documentation


text:
Q: Conditional expectation in Basic Linear Unobserved Effects Panel Data Model I want to see that $ E[u_t|X_t,c] \Rightarrow E[X_t' u_t]$ in a Panel Data Models

A: First step, notice that
$$
E[U_t | X_t] = E[ E[U_t|X_t,c] ] = 0
$$
where first equality is the Law of iterated expectations and the second equality holds because $E[U_t|X_t,c]=0$.  Then,
$$
E[X_t U_t] = E[ X_t E[U_t | X_t] ] = 0
$$
where the first equality uses the law of iterated expectations and the second from the top result.


text:
Q: Powershell throws terminating error on reg import but operation completes successfully Both this stack post as well as this one looked similar but I couldn't find my solution there. I'm having an issue understanding the difference between the behaviour in reg export versus reg import.
When running reg export inside powershell, it returns "operation completed successfully" but reg import throws a terminating error saying "operation completed successfully". The registry file is correctly imported even though it is thrown as an error. An example:
PS C:\Windows\System32> reg export HKLM\Software\MySoftware C:\Scripts\MyFile.reg
The operation completed successfully.

PS C:\Windows\System32> reg import C:\Scripts\MyFile.reg
reg : The operation completed successfully.
At line:1 char:1
+ reg import C:\Scripts\MyFile.reg
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (The operation completed successfully.:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError

Microsoft's documentation of the reg import command says that the return codes are 0 for Success and 1 for Failure. Why would Powershell return the success as a regular success message for reg export, but throw it as a terminating error for reg import?
I'm running Powershell as an Admin and the logged in user is a local administrator on the server. Any assistance is appreciated.

A: Your "problem" is, you are using PowerShell in ISE. Try using PowerShell directly. The difference? Two strange things first:

*

*reg export writes its output on success to stdout. reg import writes its output on success to stderr (I would consider that as "strange").

*ISE throws an exception, if an external program writes to stderr. PowerShell does not do that.

In conclusion, ISE throws an error on an actual success message, because it has been written to stderr. You can prevent that, using the Start-Process cmdlet:
Start-Process reg -ArgumentList "import C:\Scripts\MyFile.reg"

Because stdout and stderr of the external program are then not forwarded to your terminal. Instead, you can access them through the parameters -RedirectStandardOutput and -RedirectStandardError, if needed.
If you want to evaluate the exit code, you can do it like this:
$process = Start-Process reg -ArgumentList "import C:\Scripts\MyFile.reg" -PassThru -Wait
$process.ExitCode


text:
Q: Optimizing query in Postgresql for group by and inner join using an index I need some help with Postgresql 9.6 regarding performance.
A very simple example of the tables I have are as follows
CREATE TABLE invoice
(
   id bigserial primary key,
   some_field character varying(200)
);

CREATE TABLE invoice_item
(
    id serial primary key,
    invoice_id bigint,
    article_number character varying(50),
    quantity numeric(19,2) NOT NULL,
    CONSTRAINT invoice_item_fk FOREIGN KEY (invoice_id)
      REFERENCES invoice (id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION
);
CREATE INDEX invoice_some_field_idx ON invoice (some_field);

CREATE INDEX invoice_item_article_number_idx ON invoice_item (article_number);

I used around 500 000 rows in invoice table and 1.5 million in invoice_item.
Running the following query is really fast
SELECT ii.article_number,
       SUM(ii.quantity)
FROM invoice i INNER JOIN
     invoice_item ii
     ON i.id = ii.invoice_id
GROUP BY ii.article_number;

With index on article_number, the query goes from ~7 seconds to ~55 ms.
Now the problem is when using group by on a column from the parent table.
SELECT i.some_field, SUM(ii.quantity)
FROM invoice i INNER JOIN
     invoice_item ii
     ON i.id = ii.invoice_id
GROUP BY i.some_field;

This query will take the same amount of time (~5 seconds) regardless if there is an index on some_field.
I feel like I'm missing something very obvious here.
--- EDIT ----
I'm quite new to this query planning and of course, when doing more testing on tables above, I got very different results compared the actual code.
Here are the actual table definitions
CREATE TABLE receipt2
(
  id serial NOT NULL,
  version bigint NOT NULL,
  store_number integer NOT NULL,
  address1 character varying(200),
  date_created timestamp without time zone NOT NULL,
  round_off numeric(19,2) NOT NULL,
  date_created_by_cash_register timestamp without time zone NOT NULL,
  address2 character varying(200),
  receipt_number integer NOT NULL,
  application_version character varying(50),
  control_box_serial_number_original character varying(200),
  last_updated timestamp without time zone NOT NULL,
  cash_register_user_id uuid NOT NULL,
  control_code_copy character varying(200),
  cash_register_number integer NOT NULL,
  control_code_original character varying(200),
  zip_code character varying(50),
  receipt_footer character varying(20000),
  phone_number character varying(50),
  control_box_serial_number_copy character varying(200),
  corporate_identity character varying(50) NOT NULL,
  city character varying(200),
  money_back numeric(19,2) NOT NULL,
  number_of_copies_printed integer NOT NULL,
  cash_register_user_username character varying(50) NOT NULL,
  company_name character varying(200) NOT NULL,
  email character varying(200),
  website character varying(200),
  CONSTRAINT receipt2_pkey PRIMARY KEY (id),
  CONSTRAINT uk9f6f61365739562846c491f21efb UNIQUE (corporate_identity, store_number, cash_register_number, receipt_number)
)
WITH (
  OIDS=FALSE
);

CREATE INDEX receipt2_cash_register_user_id_idx
  ON receipt2 USING btree (cash_register_user_id);

CREATE INDEX receipt2_date_created_by_cash_register_idx
  ON receipt2 USING btree (date_created_by_cash_register);

CREATE INDEX receipt2_store_number_idx
  ON receipt2 USING btree (store_number);

CREATE INDEX receipt2corpidx
  ON receipt2 USING btree (corporate_identity COLLATE pg_catalog."default");

CREATE INDEX receipt2corpstoreidx
  ON receipt2 USING btree (store_number, corporate_identity COLLATE pg_catalog."default");

CREATE TABLE receipt_item2
(
  id serial NOT NULL,
  version bigint NOT NULL,
  cost_excluding_vat numeric(19,2) NOT NULL,
  account_number integer,
  receipt_item_type character varying(255) NOT NULL,
  article_group_id uuid,
  supplier_number integer,
  purchase_price_excluding_vat numeric(19,2) NOT NULL,
  receipt_id bigint NOT NULL,
  text character varying(20000),
  promotion_id uuid,
  price_including_vat numeric(19,2) NOT NULL,
  discount_type character varying(255) NOT NULL,
  profit_excluding_vat numeric(19,2) NOT NULL,
  price_excluding_vat numeric(19,2) NOT NULL,
  discount_amount_including_vat numeric(19,2) NOT NULL,
  article_type character varying(255),
  article_number character varying(50),
  cost_including_vat numeric(19,2) NOT NULL,
  purchase_cost_excluding_vat numeric(19,2) NOT NULL,
  hidden boolean NOT NULL,
  row_index integer NOT NULL,
  quantity numeric(19,2) NOT NULL,
  discount numeric(19,2) NOT NULL,
  discount_amount_excluding_vat numeric(19,2) NOT NULL,
  description character varying(200),
  vat numeric(19,2) NOT NULL,
  CONSTRAINT receipt_item2_pkey PRIMARY KEY (id),
  CONSTRAINT fksohgmt8ntavcgj10ha2duc8lb FOREIGN KEY (receipt_id)
      REFERENCES receipt2 (id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION
)
WITH (
  OIDS=FALSE
);

CREATE INDEX receipt_item2_article_number_idx
  ON receipt_item2 USING btree (article_number COLLATE pg_catalog."default");

Query 1 with explain. This will be very fast. Around 55ms.
SELECT
  article_number,
  sum(quantity) AS "quantity",
  sum(cost_excluding_vat) AS "costExcludingVat",
  sum(cost_including_vat) AS "costIncludingVat",
  sum(purchase_cost_excluding_vat) AS "purchaseCostExcludingVat",
  sum(profit_excluding_vat) AS "profitExcludingVat"
FROM receipt2 receipt INNER JOIN receipt_item2 receipt_item ON receipt.id = receipt_item.receipt_id
WHERE
  date_created_by_cash_register BETWEEN '2017-01-01' AND '2017-12-31'
  AND receipt_item_type = 'ARTICLE'
GROUP BY article_number
LIMIT 100;

"Limit  (cost=0.85..4821.60 rows=100 width=167)"
"  ->  GroupAggregate  (cost=0.85..948001.24 rows=19665 width=167)"
"        Group Key: receipt_item.article_number"
"        ->  Nested Loop  (cost=0.85..925058.77 rows=1500000 width=35)"
"              ->  Index Scan using receipt_item2_article_number_idx on receipt_item2 receipt_item  (cost=0.43..196242.77 rows=1500000 width=43)"
"                    Filter: ((receipt_item_type)::text = 'ARTICLE'::text)"
"              ->  Index Scan using receipt2_pkey on receipt2 receipt  (cost=0.42..0.48 rows=1 width=4)"
"                    Index Cond: (id = receipt_item.receipt_id)"
"                    Filter: ((date_created_by_cash_register >= '2017-01-01 00:00:00'::timestamp without time zone) AND (date_created_by_cash_register <= '2017-12-31 00:00:00'::timestamp without time zone))"

Query 2 with explain. This query will take 2.3 seconds regardless if there is an index on cash_register_user_id or nor.
SELECT
  cash_register_user_id AS "userId",
  sum(quantity) AS "quantity",
  sum(cost_excluding_vat) AS "costExcludingVat",
  sum(cost_including_vat) AS "costIncludingVat",
  sum(purchase_cost_excluding_vat) AS "purchaseCostExcludingVat",
  sum(profit_excluding_vat) AS "profitExcludingVat"
FROM receipt2 receipt INNER JOIN receipt_item2 receipt_item ON receipt.id = receipt_id
WHERE
  date_created_by_cash_register BETWEEN '2017-01-01' AND '2017-12-31'
  AND receipt_item_type = 'ARTICLE'
  AND receipt.store_number = 1
GROUP BY cash_register_user_id
LIMIT 100;

"Limit  (cost=154761.00..154761.45 rows=20 width=176)"
"  ->  HashAggregate  (cost=154761.00..154761.45 rows=20 width=176)"
"        Group Key: receipt.cash_register_user_id"
"        ->  Hash Join  (cost=28135.00..132261.00 rows=1500000 width=44)"
"              Hash Cond: (receipt_item.receipt_id = receipt.id)"
"              ->  Seq Scan on receipt_item2 receipt_item  (cost=0.00..57133.00 rows=1500000 width=36)"
"                    Filter: ((receipt_item_type)::text = 'ARTICLE'::text)"
"              ->  Hash  (cost=18955.00..18955.00 rows=500000 width=20)"
"                    ->  Seq Scan on receipt2 receipt  (cost=0.00..18955.00 rows=500000 width=20)"
"                          Filter: ((date_created_by_cash_register >= '2017-01-01 00:00:00'::timestamp without time zone) AND (date_created_by_cash_register <= '2017-12-31 00:00:00'::timestamp without time zone) AND (store_number = 1))"

A bit of topic for this question but whatever comes out of this, the next problem would be to have it sorted. The holy grail is to be able to sort on the aggregated values quantity, cost etc...

A: The real answer is to look at the execution plans.  But this might give you an idea of what might be happening.  The first query can essentially be rewritten as:
SELECT ii.article_number, SUM(ii.quantity)
FROM invoice_item ii
WHERE EXISTS (SELECT 1 FROM invoice i WHERE i.id = ii.invoice_id)
GROUP BY ii.article_number;

This, in turn, can be resolved by scanning the index on invoice_item(article_number).  The information can be compiled for each group, with no hashing or sorting -- just a lookup for each row.
There is no equivalent way in the second query to avoid doing work for the aggregation.


text:
Q: Recursively going through array and counting pixels I'm tasked with creating a method that is given a position (int x, int y) and it expands from that position and finds all pixels within the array that have the same color as the original position. I am supposed to find this position recursively, but I'm continuously getting the error:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3

Code:
public int sizeOfConnectedComponent(Position p) {
    if ((rows > pixels.length || cols > pixels[0].length) || (rows < 0 || cols < 0)) {
        return 0;
    } else if (!pixels[rows][cols] || visited[rows][cols]) {

        return 0;
    } else {

        visited[rows][cols] = true;

        sizeOfConnectedComponent((new Position(rows - 1, cols)));
        sizeOfConnectedComponent((new Position(rows + 1, cols)));
        sizeOfConnectedComponent((new Position(rows, cols - 1)));
        sizeOfConnectedComponent((new Position(rows, cols + 1)));
        {
            if (visited[rows][cols] == true){
                total++;
            }
        }
    }
    return total;
}

The error occurs on the line if (!pixels[rows][cols] || visited[rows][cols]). Any ideas why this happens and how to fix it?

A: In your code, you have the line:
if ((rows > pixels.length || cols > pixels[0].length) || (rows < 0 || cols < 0))

With the code as it is, it's possible for rows and cols to be the same length as the array itself, which could cause the ArrayIndexOutOfBoundsException.
For example:
int rows = 3;
int[] pixels = new int[3];

if (rows > pixels.length) { // This evaluates to false and won't return.
    return 0;               // 'rows > pixels.length' is the same as '3 > 3' which equals false.
}

pixels[rows]; // Then, when you try to use 'rows' as the index, you get an error because
              // the maximum array index is always array.length-1

So instead of:
(rows > pixels.length || cols > pixels[0].length)

it should be:
(rows >= pixels.length || cols >= pixels[0].length)

Also, you don't check if the rows and cols are out of bounds for your visited array.


text:
Q: Report builder probably showing incorrect error I am using "Microsoft SQL Server Report Builder 3.0" on "SQL Server Reporting Services 2012".
From a main report main.rdl I am calling a drillthrough report detail.rdl and passing three parameters (@var_1, @var_2 and @column) to run detail.rdl
The main.rdl report has a table and each text box of this table is clickable and drillthrough action. When user clicks on any text box the detail.rdl report is called. One parameter that is passed to detail.rdl report is used as a column name in the SQL. This SQL fetches data needed for detail.rdl report.
The SQL is:
DECLARE @SQL varchar(max)

SET @SQL =
'SELECT
[table_name].[col_5]
,[table_name].[col_13]
,[table_name].[col_4]
,[table_name].[col_21]
,[table_name].[col_9]
,[table_name].[col_28]
,[table_name].[col_11]
,' + @column + /*the value in this variable is an existing column name from table table_name*/
' FROM
[table_name]
WHERE
([table_name].[col1] LIKE '@var_1')
AND ([table_name].[col2] LIKE '@var_2')
AND (' + @column + ' is null OR ' + @column + ' = '''' OR ' + @column + ' = ''N/A'' OR ' + @column + ' = ''Unknown'')' /*I want to use same column name here as well*/

exec (@SQL)

When I run this query I get error:

An error occurred while executing the query. Incorrect syntax near
  '@var_1'. (Microsoft SQL Server Report Builder)

I can't find out why am I getting this error as the error itself is not very informative.
Any clues on what might be the reason of this error would be very helpful.

A: The error is correct, your code is syntactically incorrect.
Likely, you need to change your code to something like this:
DECLARE @SQL varchar(max) -- , @column varchar(max), @var_1 varchar(max), @var_2 varchar(max)

SET @SQL =
'SELECT
[table_name].[col_5]
,[table_name].[col_13]
,[table_name].[col_4]
,[table_name].[col_21]
,[table_name].[col_9]
,[table_name].[col_28]
,[table_name].[col_11]
,' + @column + /*the value in this variable is an existing column name from table table_name*/
' FROM
[table_name]
WHERE
([table_name].[col1] LIKE ''%' + @var_1 + '%'')
AND ([table_name].[col2] LIKE ''%' + @var_2 + '%'')
AND (' + @column + ' is null OR ' + @column + ' = '''' OR ' + @column + ' = ''N/A'' OR ' + @column + ' = ''Unknown'')' /*I want to use same column name here as well*/

exec (@SQL)

You need to use + to concat the strings together in all the right places.


text:
Q: mongodb (>=1.4.1) and php: connection pooling Is connection pooling with a actual php mongo driver (>= 1.4.1) possible? The Mongo and MongoPool Classes are deprecated or not implemented in the new version.

A: The PHP MongoDB driver does persistent connections, not connection pooling, as of the 1.3.0 release.
The MongoPool class is only kept around for few minor versions in case people were using them, and we didn't want to break peoples code "just because". It is however scheduled for removal soon, so if you see an application that uses it.. Please remove it :)
The Mongo class is deprecated, and you should use the MongoClient class.
This is due to the fact we want to have WriteConcern enabled by default, which we couldn't do without "maybe" breaking peoples code that were using the Mongo class.
Now, for pooling vs persistence, the PHP architecture doesn't work well with connection pooling - thats just not beneficial in PHP. However, persistent connections make much sense and will do all you need from "connection pooling" in reality.


text:
Q: How to implement auth flow in react native with react navigation? Hi guys need help over Login flow, I write a code for auth flow but facing some weird issue like.
Right now what is happening I have login page while clicking on signIn button, I am sending the user to auth screen but if user click on back button then he moves to login screen again, and this is wrong, if user is login then why it's again move to login screen.
Here is code for it this is my route.js
import React from 'react';
import { StackNavigator, DrawerNavigator } from 'react-navigation'

import loginScreen from '../containers/login/loginScreen'
import todo from '../containers/todo/todo'
import addTodo from '../components/addTodoTask'
import SideBar from '../components/sideBar/sideBar'
import DashBoard from '../components/common/dashboardWidget'
import signUp from '../containers/signUp'
import editTodo from '../containers/todo/editTodo'

const authScreen = DrawerNavigator({
    DashBoard: { screen : DashBoard },
    Todo: { screen: todo }
},{
    drawerPosition: 'left',
    contentComponent: props => <SideBar {...props} />
},);

export const SignedOut = StackNavigator({

    LoginScreen : {
        screen : loginScreen,
        navigationOptions : {
            mode: "card",
            title: "Sign in",
            headerMode: "Screen",
            header : null
        }
    },
    signUp : { screen : signUp }
},{
    headerMode: 'none'
},);

export const SignedIn = StackNavigator({
    rootnavigator : { screen : authScreen },
    addTodo : { screen : addTodo },
    editTodo: { screen : editTodo }
},{
    headerMode: 'none'
},);

export const createRootNavigator = (signedIn = false) => {
  return StackNavigator(
    {
      SignedIn: {
        screen: SignedIn,
        navigationOptions: {
          gesturesEnabled: false
        }
      },
      SignedOut: {
        screen: SignedOut,
        navigationOptions: {
          gesturesEnabled: false
        }
      }
    },
    {
      headerMode: "none",
      mode: "modal",
      initialRouteName: signedIn ? "SignedIn" : "SignedOut"
    }
  );
};

and here is login button code
signIn() {

axios.post(BACKEND_URL+'/api/User/login', {
  userName: this.state.userName,
  password: this.state.password
})
.then( (response) => {
  if(response.data.message == 'Success'){
    // Set up root Auth Token and Headers
    axios.defaults.headers.common['Authorization'] = "bearer "+response.data.data.accessToken;
    axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
    AsyncStorage.setItem('@userData:', JSON.stringify(response.data.data));
    onSignIn().then(() => { this.props.navigation.navigate('SignedIn') });
    this.setState({ isLoading: false });
  }
})
.catch( (error) => {
  alert("Please check your crendentials")
});

}

A: Instead of navigation.navigate try to navigation.dispatch to reset the routes to SignedIn StackNavigator. As,
Import NavigationActions from react-navigation. and use below code to dispatch your new route after user signedin.
onSignIn().then(() => { this.props.navigation.dispatch(
    NavigationActions.reset({
        index: 0,
        key: null,
        actions: [
            NavigationActions.navigate({ routeName: 'SignedIn' })
        ]
   })
)});

For more info read this Reset Navigation Action.


text: Q: Какие микропаттерны программирования вы используете? Я имею в виду шаблонные техники написания кода для решения определенных задач: например, в кэшировании данных мы используем мемоизацию, при валидации данных - так называемые "калитки" из условий из конструкций if/else на входе метода. К микропаттернам можно отнести и рекурсию, и принцип "разделяй и властвуй", т.е. то, что не относится к высокоуровневым шаблонам проектирования GoF, а применяется на более низком внутриклассовом уровне программирования.


text:
Q: How can i download body canvas image? html2canvas(document.body).then(function(canvas) {
            document.body.appendChild(canvas);
        });

I get screen shot using this method how can i download that image. i didn't wont to assign src tag for this.. i simply need download this image.

A:             html2canvas(document.body, {
                onrendered: function(canvas) {
                    document.body.appendChild(canvas);
                    var dataURL=canvas.toDataURL("image/jpeg");
                    $.ajax({
                      type: "POST",
                      url: "upload.php",
                      data: {image: dataURL}
                    }).done(function( respond ) {
                        window.opener.location.href ='http://Your_url/download.php?file_name='+respond+' ';
                     });
                }

You have to upload image and then after Download the image using php code


text:
Q: "team of engineers IS standing by" or "team of engineers ARE standing by"? Which is correct: "Our team of engineers is standing by" or "Our team of engineers are standing by"?

A: The answer depends on whether your regional English considers "team" a plural noun or a singular noun.
The subject of the sentence is "team", and "of engineers" is just a descriptive addition. So the verb should be the one appropriate for the subject "team": is if you consider it singular, and are if you consider it plural.
In American English, it is (generally) correct to say "Our team of engineers is standing by," since "team" is usually singular.
In British or other types of English, it might be are, if "team" is used as a plural.

A: Is, since the word team is singular.


text:
Q: Setup: command not found. Cannot run installer I'm installing Abaqus on Ubuntu. I have extracted the rar files into a directory. In terminal, I navigate to the directory and run the setup file using "sudo /directory_name/setup". Terminal gives me the following error
"Setup: command not found". I have installed csh and tcsh on my system. Could it potentially be a problem with these?

A: It seems you must run first the csh terminal, and only then you can run the setup file. Insert the command csh to run the csh terminal first. There is a tutorial here. I don't know what versions of Abaqus and Ubuntu you have.


text:
Q: Karma coverage HTML coverage report is empy I am new to Karma with Angular 8. I have few queries and I am not getting correct result.
My queries are:
1) I have karma conf file where I have configured for code Coverage to view in HTML coverage directory was created but I am not seeing statement percentage and etc in the HTML page.
Here is my karma-config code
 config.set({
  basePath: '',
  frameworks: ['jasmine', '@angular-devkit/build-angular'],
  plugins: [
    require('karma-jasmine'),
    require('karma-chrome-launcher'),
    require('karma-jasmine-html-reporter'),
    require('karma-coverage-istanbul-reporter'),
    require('@angular-devkit/build-angular/plugins/karma')
  ],
  client: {
    clearContext: false // leave Jasmine Spec Runner output visible in browser
  },
  coverageIstanbulReporter: {
    dir: require('path').join(__dirname, '../coverage/my-app'),
    reports: ['html', 'lcovonly', 'text-summary'],
    fixWebpackSourcePaths: true
  },
  reporters: ['progress', 'kjhtml'],
  port: 9876,
  colors: true,
  logLevel: config.LOG_INFO,
  autoWatch: true,
  browsers: ['Chrome'],
  singleRun: false
});

2) As I am new to unit testing I want to understand how to do unit testing for the below method
navigateToStudy(row){
 this.favoriteUserId = row.id;
 this.router.navigate(['studydetails', row.id]);
}

Here is what I am trying for this code.
My Spec
describe('navigatetoStudy', () => {
   it('should navigate', () =>{
    const navigate  = navigateToStudy();
    expect(navigate).toBe
   });
});

I am getting error at navigatetoStudy.


text:
Q: Display date and time according to the user's time zone in Coldfusion I need to display datetime values in my application according to the logged in user's local timezone. I would like my app to be able to detect the user's timezone automatically then display the adjusted server date and time accordingly.
How do you do this in Coldfusion?
I am looking for a solution that does NOT prompt the user to select their time zone at any point, like Facebook.
Thanks

A: ColdFusion is a server side language. So you can't determine the timezone of a client in a direct way.
You can use JavaSript on the client side, find out the timezoneoffset and send it via an Ajax request to ColdFusion.
JavaScript:
var clienttime = new Date();
var time = clienttime.getTimezoneOffset()/60;

Then on the server side you can use the offset to calculate the date you want to show the user.
You can also lookup the country of the client using the client IP, but then you have to use an external service to get the country for a certain IP and you have to deal with problems like daylight savings and multiple timezones per country.

A: Instead of having CF do the formatting, I would push a standardized date representation (like UTF( and have JavaScript format the date.  That way, the date is formatted to whatever timezone is set on the computer.
This avoids wrong lookups near zone change areas, dealing with daylight savings vs. areas where it isn't observed, and people traveling (formatting to "home time" vs. "local time").
Added:
This dumps the current time in a long format.  It's semi-off-the-cuff, so you'll want to look at the JavaScript Date Object's methods for more formatting options.
<cfset n = dateconvert("local2utc",now())>
<script>
 d = new Date();
 d.setUTCFullYear(#dateformat(n, "yyyy")#);
 d.setUTCMonth(#dateformat(n, "m")#);
 d.setUTCDate(#dateformat(n, "d")#);
 d.setUTCHours(#timeformat(n, "H")#);
 d.setUTCMinutes(#timeformat(n, "m")#);
 document.write(d.toLocaleString());
</script>

A: It would be quicker and more accurate if you did just ask your user to specify their timezone as part of their login profile; set once and forget.
Otherwise, you're looking at doing an IP address look up and determining where that IP address is based, determining the timezone and then displaying the time accordingly. Even if you store the information in a cookie or session variable, its a bit of a faff when you could just ask your user what timezone they are in.

A: if you're using cfwheels.org and your users doesnt mind to see "yesterday" or "10 minutes ago"... then the TimeAgoInWords() is what you need.


text:
Q: An aggregate may not appear in a computed column expression or check constraint. error while using MAX function I am receiving

An aggregate may not appear in a computed column expression or check constraint error

while using MAX function for a date column to create a table. Here is the code I'm using to create the table:
Create table Bills
(
  BillNo INT NOT NULL,
  MeterNo INT NOT NULL,
  FirstDate datetime NOT NULL,
  FirstDateReading INT NOT NULL,
  CurrentDate as MAX(FirstDate),
  CurrentDateReadng INT NOT NULL,
  LastDate as DATEADD(m,-1,CurrentDate),
  LastDateReading INT NOT NULL,
  Usageinm3 as (CurrentDateReadng-LastDateReading),
  Usageinlitres as (Usageinm3 * 1000),
  TotalBill as (UsageinLitres * 3)
  Primary Key (BillNo),
  Foreign Key (MeterNo) References MeterReading(MeterNo)
);

A: Since you are defining the table structure, you should put the data type for each column, not the value.
Create table Bills
(
  BillNo INT NOT NULL,
  MeterNo INT NOT NULL,
  FirstDate datetime NOT NULL,
  FirstDateReading INT NOT NULL,
  CurrentDate as DATE, <--should be the data type
...

If you are creating a table based on other tables, you should use something like
SELECT billno,
       meterno,
       firstdate,
       firstdatereading,
       MAX(firstdate)
...
  INTO Bills
  FROM sourcetable
 WHERE conditions
 GROUP BY billno,
          meterno,
          firstdate,
          firstdatereading
...


text:
Q: Bar graphs on a website I'm by no means a web designer, so I'd like as detailed help as you're willing to give.
I'd like to make a website that that tracks some data I enter using a bar graph from 0-100%. I'd enter the maximum number the graph could go to and then some data point would be updated occasionally, which the completion bar graph would reflect.
How would I go about doing this?
I know basic HTML and PHP, but have not used either in a very long time.

A: I think most of the suggestions are overkill. No need to have an extra library / dependency when all you need is some simple bargraphs. Plain HTML/CSS should do...
PS: quick code sample, only tested in Firefox 3.x

You can change the width of individual bars easily with javascript (just change the width).

A: I know you said you're new, but you should take a look at the google visualization api. It's got some good stuff to do the kind of thing you might want.
http://code.google.com/apis/visualization/

A: There are two ways you could tackle this problem; generate the graph on the backend (probably using PHP in your case) or do it on the client side using javascript.
I'm not sure the specifics of doing it in PHP, as I don't really know the language, but I'm sure there is alot of info out there on graph generation in PHP.
For the javascript approach, I've used both flot (for jquery) and flotr (for prototype) before.  I like them alot, and there is some good documentation and examples for both libraries on how to generate all kinds of charts, including bar charts.


text:
Q: ¿Cómo recuperar un objeto de una Lista de objetos mediante stream? estoy intentando recuperar un objeto(Usuario) utilizando stream y no lo consigo.
Cada usuario tiene un código único, y lo que quiero es recuperar el usuario con el código "tal".
Si casteo, cuando ejecuto la App, me da una classCastException.
public Usuario findUser(List<?extends Usuario> usuarios, String codigo)
{
  return (Usuario)usuarios.stream()
 .filter(usuario -> usuario.getCodigo().equals(codigo));
}

Imagino que no habrá que castear y que me faltara codigo,
muchas gracias de antemano por la ayudita.
EDITADO:
esta es lo que he hecho y me ha funcionado:
public Alumno findAlumno(List<Alumno> alumnitos, String codigo) {

  return alumnitos.stream()
        .filter(alumno -> alumno.getCodigo().equals(codigo))
        .findFirst().orElse(null);
}

Abajo un compañero tiene una solución que también funciona y es muy muy parecida a esta, casi la misma, hay sutiles diferencias.
Pero quiero dejar constancia de lo que yo he hecho y me ha funcionado por si a alguien le interesa.
Considero que su solución no es la misma que la mía, porque, entre otras cosas, el usa un "optional" y hace un "casteo", a mi no me ha hecho falta
Muchas gracias

A: Cuando transformas una lista a un stream, necesitas hacer el paso opuesto después:
public Usuario findUser(List<?extends Usuario> usuarios, String codigo) {
    return usuarios.stream()
       .filter(usuario -> usuario.getCodigo().equals(codigo))
       .collect(Collectors.toList()).get(0);
}

Pero ya que estás seguro de que sólo hay un elemento, podrías hacer:
public Usuario findUser(List<?extends Usuario> usuarios, String codigo) {
    Optional<Usuario> temp= usuarios.stream()
       .findAny(usuario -> usuario.getCodigo().equals(codigo));

    return temp.orElse(null); //si el opcional está vacío devuelve null
}


text:
Q: Color numbers based on their value Given some number between 0 and 1:
RandomReal[1, 100]

I'm trying to color the values based on their size. I tried it like this:
numbersColored =
 Table[Style[numbers[[x]], Darker[Red, 1 - numbers[[x]]]], {x, 1,
   Length@numbers}]

which uses red and Darker. I was wondering, however, if there is a more elegant way (without using Table for example) of doing this that also lets me choose some color function?

A: Style[#, ColorData[3, "ColorList"][[Round[10 #]]]] & /@ numbers


text:
Q: Reproducing a crown with tikz I'm trying to adapt the following crown:

What I've come up with so far is this sketch:

\documentclass[tikz]{standalone}
\usepackage{tikzpagenodes}
\usetikzlibrary{arrows.meta}
\usepackage{xcolor-material}
\usepackage{graphicx}
\usepackage{fontspec}

\tikzstyle{linha} = [line width=7pt,MaterialGrey300]
\tikzstyle{linhafina} = [line width=3pt,MaterialGrey300]

\begin{document}

\begin{tikzpicture}
[every node/.append style={text=MaterialGrey300,
font=\Huge},]
%\clip[fill=MaterialGrey800] (0,0) rectangle (20,20);
\fill[MaterialGrey800] (0,0) rectangle (20,20);
\draw[help lines,xstep=1,ystep=1] (0,0) grid (20,20);
\foreach \x in {0,1,...,20} { \node [anchor=north] at (\x,0) {\normalsize\x}; }
\foreach \y in {0,1,...,20} { \node [anchor=east] at (0,\y) {\normalsize \y}; }

%%%% crown %%%%%
\draw[linhafina%,{Round Cap[]}-{Round Cap[]}
] (8.75,14) -- (11.25,14);
\draw[linha,yshift=-6] (9,14) -- (11,14);
\draw[linhafina%,{Round Cap[]}-{Round Cap[]}
,yshift= -12] (8.75,14) -- (11.25,14);

\draw[linhafina,-{Circle[length=5pt,yellow!80!black]}] (10,14) -- (10,15.15);
\draw[linhafina,line width=2pt] (9.6,14) -- (10,15);
\draw[linhafina,line width=2pt] (10.4,14) -- (10,15);
\draw[linhafina,line width=1.5pt] (10,14.3) -- (10.5,15);
\draw[linhafina,line width=1.5pt] (10,14.3) -- (9.5,15);

\draw[linha,line width=1.5pt,-{Circle[length=3pt]}] (10,14.1) -- (9,15);
\draw[linha,line width=1.5pt,-{Circle[length=3pt]}] (10,14.1) -- (11,15);

\draw[linhafina,line width=1.5pt,-{Circle[length=3.5pt]}] (10,14.3) -- (10.5,15);
\draw[linhafina,line width=1.5pt,-{Circle[length=3.5pt]}] (10,14.3) -- (9.5,15);

\draw[linha,line width=1pt,-{Circle[length=3pt]}] (10,14.1) -- (9.3,14.9);
\draw[linha,line width=1pt,-{Circle[length=3pt]}] (10,14.1) -- (10.7,14.9);

\draw[linha,line width=1pt,-{Circle[length=3pt]}]  (9.6,14) -- (8.75,15);
\draw[linha,line width=1pt]  (9.25,14) -- (8.75,15);
\draw[linha,line width=1pt,-{Circle[length=3pt]}] (10.4,14) -- (11.25,15);
\draw[linha,line width=1pt] (10.75,14) -- (11.25,15);
\draw[linha,line width=1.5pt] (9.6,14) -- (9,15);
 \draw[linha,line width=1.5pt] (10.4,14) -- (11,15);

 \draw[linha,line width=1pt] (10.4,14) -- (10.7,14.9);
  \draw[linha,line width=1pt] (9.6,14) -- (9.3,14.9);

\draw[linha,line width=1pt] (10.4,14) -- (10.45,14.95);
\draw[linha,line width=1pt] (9.6,14) -- (9.3,14.9);
%%%%%%%%%%%%

\end{tikzpicture}

\end{document}

I believe there is also an easier way to draw the lines using nodes, but what's bothering me at the moment is that the tip of the lines slightly bulge out of the circles (you can notice if you zoom in the image).
A cross on top, like the model image (or even a fleur de lys, would also be great), although it's not my priority right now.
Any tips would be much appreciated.

A: I am not claiming this is a perfect reproduction but would like to draw your attention to pics, which arguably can help a lot when drawing things that are (more or less) repetitive.
\documentclass[tikz,border=3mm]{standalone}
\begin{document}
\begin{tikzpicture}[line join=round,pics/corona/.style={code={
 \draw[line width=2.5mm,fill]
  (-8,0) -- (-10,5)-- (-6+#1,0) -- (-5+#1,5) -- (0,0) -- (5-#1,5)-- (6-#1,0) -- (10,5) --
  (8,0) -- (9.4,4) -- (6-#1,0) -- (4.8-#1,4) -- (0,0) -- (-4.8+#1,4) -- (-6+#1,0) --
  (-9.4,4) -- cycle foreach \X in {-10,\the\numexpr-5+#1,\the\numexpr5-#1,10}
  {(\X,5) circle[radius=3mm]};}},
  pics/bar/.style={code={\draw (-0.4,0) -- (0.4,0);}}]
  \path pic{corona=0} pic[scale=0.8]{corona=2};
  \draw[line width=3mm,fill] (-5,0) -- (0,6) -- (5,0) -- (0,5) -- cycle;
  \draw[line width=7mm] (0,0) -- (0,5.5);
  \fill (-8.4,0.2) -- (8.4,0.2) |- (8,-1) |- (8.4,-2) |- (-8.4,-3) |- (-8,-2)
  |- (-8.4,-1) -- cycle;
  \draw[line width=2mm]  (0,6) -- (0,8)  pic[pos=0.2]{bar} pic[pos=0.8]{bar}
   (-1,7) -- (1,7) pic[pos=0.2,rotate=90]{bar} pic[pos=0.8,rotate=90]{bar};
\end{tikzpicture}
\end{document}


text:
Q: gedit problem when open by terminal when I open terminal and run the command sudo gedit first.cpp it shows this error in terminal:
(gedit:24589): IBUS-WARNING **: The owner of /home/bonny/.config/ibus/bus is not root!
(gedit:24589): Gtk-WARNING **: Calling Inhibit failed: GDBus.Error:org.freedesktop.DBus.Error.ServiceUnknown: The name org.gnome.SessionManager was not provided by any .service files"

A: it's because you are running the application in foreground of you'r terminal
press ctrl + z
then type jobs command and check the number of that gedit first.ccp process
type bg [the number you checked in jobs command ]
you won't see those warnings anymore.

A: The reason for the warning is that you are running a GUI app with sudo - this can lead to several problems (one of them: you might not be able to log in again, because your Xauthority file belongs to root).
There used to exist a "graphical" sudo - gksudo or gksu or kdesu which prevented that problem.
With current Ubuntu versions the proper way to execute GUI apps with root permissions is a three step process:
sudo -i
gedit first.cpp
....
exit

eplanation:

*

*create a shell with root permissions

*execute the desired command as root

*Don't forget to close that shell again.

Upon rereading your question I see that you are using sudo just to edit a file in your home directory -- don't  do that, is is neither necessary nor useful.


text: Q: Show only icons when sidenav is closed in shinymaterial I am using shinymaterial and the corresponding materialize.css file to customise an app. I wanted to show icons only when the sidenav is closed. I have read a few posts related to material design lite but am not familiar with this and the differences (if any). However, still can't make it work. If anyone has implemented this in shinymaterial apps, any help much appreciated. If this can be done in css that would be great too.


text:
Q: Mysql: partial index on varchar I want to do some index optimizations in a db.
I see there is an index on field varchar 32, an index on field of varchar 100.
For example varchar 32 contains an id (maybe the user id or whatever, like this string 60c487df-38e8-1c79-da00-561799874092), varchar 100 contains short string as pluto or pippo for example. (I know, this field have to be reduced in size)
First question) For these fields, drop the index and create a partial index is correct?
For example, reduce the size of the index on the varchar 32 to the first 8 char, help mysql to find the row faster? (analyzing a smaller index).
Are there drawback ?
Second question) Field x varchar 100 has a full index (not partial), how mysql works when I add a row with a x="pippo"? Will Mysql fill (or reserve) all the 100 bytes for index of that column?
Thanks in advance.

A: I doubt there is any reason to further "optimize" your indexes.  Reducing the size of the fields in an index does reduce the size of the index.  But, unless you are in a memory constrained environment, they just add unnecessary complexity.
A partial index is not going to allow MySQL to "find a row faster".  Only comparing the first 8 bytes is not sufficient for finding a row, so MySQL would have to do much more work to find a given row.
The varchar() data type is a varying length character field.  That means that it stores only the data in the string, plus a length in the first byte or two.  This is true whether the values are in a table or in an index.
You should keep the indexes that you have and look for other ways to optimize your system -- if performance is an issue.

A: *

*A prefix index would help only because the index would be smaller.  But you loose uniqueness, if that matters.  Often prefix indexes are useless; beware.

*A UUID is of fixed length of 36 characters, not 32, nor 100.

*Since you have Type 1 UUID, you can rearrange the bits to make them chronological, thereby perhaps providing better "locality of reference".  See link below.

*Packing the 36 characters into 16 bytes would save a bunch of space.  That leads to better cacheablility (especially for huge tables), hence better speed.  See link.

Link


text:
Q: How can I speed up using Pytorch DataLoader? I had a dataset including about a million of rows. Before,  I read the rows, preprocessed data and created a list of rows to be trained. Then I defined a Dataloader over this data like:
train_dataloader = torch.utils.data.DataLoader(mydata['train'],
        batch_size=node_batch_size,shuffle=shuffle,collate_fn=data_collator)

Preprocessing could be time consuming, so I thought to define an IterableDataSet with __iter__ function. Then I could define my Dataloader like:
train_dataloader = torch.utils.data.DataLoader(myds['train'],
        batch_size=node_batch_size,shuffle=shuffle,collate_fn=data_collator)

However, still to begin training it seems that it calls my preprocessing function and creates an Iteration over it. So, it seems I didn't gain much speed up.
Please guide me how could I use speed up in this case?
Here is my part of my class:
    def __iter__(self):
        iter_start = self.start
        iter_end = self.num_samples
        worker_info = torch.utils.data.get_worker_info()
        if worker_info is None:  # single-process data loading, return the full iterator
             iter_start = self.start
             iter_end = self.num_samples
        else:  # in a worker process
             # split workload
             per_worker = int(math.ceil((self.num_samples - self.start) / float(worker_info.num_workers)))
             worker_id = worker_info.id
             iter_start = self.start + worker_id * per_worker
             iter_end = min(iter_start + per_worker, self.num_samples)
        if self.flat_data:
            return iter(self.flat_data)
        else:
            return iter(self.fill_data(iter_start, iter_end))

    def fill_data(self, iter_start, iter_end, show_progress=False):
        flat_data = []
        if iter_end < 0:
            iter_end = self.num_samples
        kk = 0
        dlog.info("========================== SPLIT: %s", self.split_name)
        dlog.info("get data from %s to %s", iter_start, iter_end)
        dlog.info("total rows: %s", len(self.split_df))
        if show_progress:
            pbar = tqdm(total = self.num_samples)

        for index, d in self.split_df.iterrows():
            if kk < iter_start:
                dlog.info("!!!!!!!!! before start %s", iter_start)
                kk += 1
                continue
            rel = d["prefix"]
            ...
            # preprocessing and adding to returned list

A: I did preprosessing in the fill_data or __iter__ body. However, I can use a map for preprocessing. Then the preprocessing is called during training and for every batch and not before training.
import pandas as pd
import torch

class MyDataset(torch.utils.data.IterableDataset):
    def __init__(self, fname, until=10):
        self.df = pd.read_table("atomic/" + fname)
        self.until = until
    def preproc(self, t):
        prefix, data = t
        text = "Preproc: " + prefix + "|" + data
        print(text) # to check when it is called
        return text

    def __iter__(self):
        _iter = self.df_iter()
        return map(self.preproc, _iter)

    def df_iter(self):
        ret = []
        for idx, row in self.df.iterrows():
             ret.append((row["prefix"],row["input_text"]))
        return iter(ret)


text:
Q: Нужен совет как вытянуть данные из PDF Есть PDF фаил, в котором есть таблица с данными.
Таблица вида "Name - Data" и так в столбик. Фото прилагается
Пытаюсь найти способ реализации как по ячейке с именем вытянуть её данные.
PDF я весь считал пытался как то через регулярки вытянуть. Но косяк в том что понять где его данные и какие данные вытягивать не понятно т.к pdf считывается и выдает обычный текст (данные могут менятся в Data). Пробовал как то декомпрес pdf сделать но что то не удачно. Софта мало на эту тему. А узнать внутрение теги не могу. Кто что знает подскажите :) Буду очень блогодарен
Например есть ячейка Supplier надо вытянуть её данные Aker Solution...

A: С pdf все плохо. Перепробовал все что можно - конвертацию в Word, в Excel, текстовый файл. Самый многообещающий способ - конвертация в html и парсинг с помощью web-драйвера selenium.

A: Для работы с PDF я использовал опенсорсную библиотеку iTextSharp. Очень мощная, но чтобы что-то вытащить из PDF приходится глубоко вникать, как устроена его структура. Если у вас разовая задача - возможно, это будет чересчур, но если нужно настроить импорт данных на регулярной основе - самое то, что нужно.


text:
Q: How will i able check trained model prediction on new data I build a model with the help of Scikit library in python and trained and test using cross-validation method.But now i want to test the model accuracy with more new data,how can i able to test with new data after building it.

A: After you train your data you can use predict() multiple times. So you can test new data with same model. You can also save the model you have built using pickle.
Refer to this in their documentation
http://scikit-learn.org/stable/modules/model_persistence.html


text:
Q: What does it mean when one branch is ahead of another? I am testing a scenario where devs create feature branches and push them into a dev branch (which is my compare branch). Once per week, we then merge dev into main, which triggers our CI/CD pipeline.
My intention was that main and dev should always match up. However, currently main is showing ahead of dev.
We don't work out of or push to our main branch, so how would it be ahead of our compare branch?

A: This is because you have merge commit. Your branches will have equal contents. But if you merge dev->master you always create one additional merge commit.

A: In Azure DevOps, there are 4 merge types to choose from:

*

*Merge (no fast forward): Merge with a non-linear history that preserves all commits.

*Squash commit: Merge with a linear history that combines all source commits into a single commit on the target, or squash merges the PR. Be aware that a new commit will be created for the target branch without keeping the commit history from the source branch.

*Rebase and fast-forward: Rebase the source commits onto the target and fast-forward.

*Semi-linear merge: Rebase source commits onto the target and create a two-parent merge.

When your source branch is a shared branch, such as dev or main, (usually) the only sensible option to use is #1, "Merge", and in this case you will be creating a new merge commit on main when completing a Pull Request from dev into main.
Given that, you have a few options that you can consider:

*

*If for some reason you really don't want to see the merge commit on main, you could theoretically avoid it by selecting merge type #3 (rebase and fast-forward). This is slightly dangerous though because if dev isn't fully up to date with main at the time of the merge, then dev will get re-rewritten. If it is fully up to date, it won't touch dev and you'll effectively do a merge with fast-forward (if possible, and it would by definition be possible).1

*Allow, the merge commit, and then immediately afterwards merge main back into dev with a regular merge. Now dev would be 1 commit ahead of main instead, but this is fine since the norm for your workflow is for dev to be ahead of main anyway. Note that if you ever have a hotfix into main, you'd need to also merge main back down to dev, so the rule here is something like "Anytime new commits appear on main, merge them back down into dev."

*You could setup a pipeline job that does the merge of dev into main for you. It could be setup to do a fast-forward merge into main, and then push it out when it's finished. (Assuming you've protected main, you'll also need to give the account that runs the pipeline permission to bypass pull requests.)

1 In AzDO Server, I've seen semi-linear merge fail to even attempt a rebase when more than 25 commits would be rebased. It wouldn't surprise me if that's also true for rebase and fast-forward, however, someone should check whether the number of commits matters when a rebase isn't necessary. If you can't have more than 25 commits regardless of whether a rebase is necessary or not, then this may sometimes thwart the idea to do a fast-forward type merge by cheating with option 3.


text:
Q: How do I change the direction (or side) of the footnote line? I saw those questions:

*

*How can I change the footnote line (thickness, length)

*Add indent to \footnoterule
But I don't find the answer there...
So I'll be glad if you will tell me what I need to put at the preamble (I'm using LyX) to move the footnote rule from the left side of the page to the right side of the page...
Thank you!!
And here is a file for example:
#LyX 2.2 created this file. For more info see http://www.lyx.org/
\lyxformat 508
\begin_document
\begin_header
\save_transient_properties true
\origin unavailable
\textclass heb-article
\begin_preamble
\newfontfamily\hebrewfont[Script=Hebrew]{David CLM}
\newfontfamily\hebrewfonttt[Script=Hebrew]{Miriam Mono CLM}
\newfontfamily\hebrewfontsf[Script=Hebrew]{Simple CLM}
\end_preamble
\use_default_options true
\maintain_unincluded_children false
\language hebrew
\language_package default
\inputencoding cp1255
\fontencoding global
\font_roman "default" "default"
\font_sans "default" "default"
\font_typewriter "default" "default"
\font_math "auto" "auto"
\font_default_family default
\use_non_tex_fonts true
\font_sc false
\font_osf false
\font_sf_scale 100 100
\font_tt_scale 100 100
\graphics default
\default_output_format default
\output_sync 0
\bibtex_command default
\index_command default
\paperfontsize default
\spacing single
\use_hyperref false
\pdf_bookmarks true
\pdf_bookmarksnumbered false
\pdf_bookmarksopen false
\pdf_bookmarksopenlevel 1
\pdf_breaklinks false
\pdf_pdfborder true
\pdf_colorlinks true
\pdf_backref false
\pdf_pdfusetitle true
\papersize a4paper
\use_geometry false
\use_package amsmath 1
\use_package amssymb 1
\use_package cancel 1
\use_package esint 1
\use_package mathdots 1
\use_package mathtools 1
\use_package mhchem 1
\use_package stackrel 1
\use_package stmaryrd 1
\use_package undertilde 1
\cite_engine basic
\cite_engine_type default
\biblio_style plain
\use_bibtopic false
\use_indices false
\paperorientation portrait
\suppress_date false
\justification true
\use_refstyle 1
\index Index
\shortcut idx
\color #008000
\end_index
\secnumdepth 3
\tocdepth 3
\paragraph_separation indent
\paragraph_indentation 0bp
\quotes_language english
\papercolumns 1
\papersides 1
\paperpagestyle fancy
\tracking_changes false
\output_changes false
\html_math_output 0
\html_css_as_file 0
\html_be_strict false
\end_header

\begin_body

\begin_layout Standard
שלום
\begin_inset Foot
status open

\begin_layout Plain Layout
שלום
\end_layout

\end_inset

\end_layout

\end_body
\end_document

A: Add the following code to Settings > LaTeX Preamble:
\AtBeginDocument{
\renewcommand\footnoterule{%
  \kern -3pt
  \hbox to \textwidth{\hfill\vrule height 0.4pt width .4\textwidth}
  \kern 2.6pt
}}

You can of course change the dimension, but the total height of the construction must be 0pt. In the above example it is -3pt+0.4pt+2.6pt=0pt.


text: Q: Pyqt4: Can you share an object between threads? so I am working with an API that has an object that connects to another machine and dose some proprietary magic to get information and is used to change it. Lets call this object a scheduler. Now I can only have one of these objects in my application, however I have multiple threads that need access to this object. Can I "Share" this object between my threads with pyqt? If so how do I access it? If I have multiple threads trying to access it at the same time will the thread hang till it is able or will it fail out my app?


text:
Q: Are Microservices Architecture and a Single Customer View able to co-exist? Given the microservices pattern is the decomposition of software by business capability with ownership of state, and a single customer view is an aggregated, central, "single" data store of all customer data that can be used to drive application functionality, are these two patterns able to live together or are they incompatible? If they can live alongside each other, how do you reconcile the apparent contradiction between mono (SCV) vs poly (MSA)?
EDIT:
An example of what needs reconciling, you could have a service responsible for contact information, holding your Customer's postal address. A SCV by definition holds all customer data, which pretty much could cover the entire estate of data and all state owned by micro services - most data is linked to a customer. Should I query the micro service - the owner of the state and business behaviour - for the customer's address or should I query the SCV which has aggregated all data associated to a customer. What would be the advantage of having both of these systems in place given the increased complexity and duplication?

A: Yes, they can co-exist.
Both things exist for different, non-contradictory reasons. Microservices exists usually for scaling purposes, either organizationally or technically. To do this, the microservices have to be as independent as possible, optimally with no communications between them, each handling their respective functionality completely on their own. Integrating through the UI for example, or at the worst case have only off-line fire-and-forget type communications.
Having a unified store of customer data is for requirements in the area of data mining / machine learning, etc. This could be easily off-line wrt the services. I.e. microservices can transmit different types of data (live, historic, static, etc.) completely without impacting their functionality i.e. without compromising on their independence.
Again, your architecture should be shaped by your requirements. There is no inherent "advantage" to any of this. If your requirements demand you to do either or both, then you are "justified" in doing it.


text:
Q: Xcode dependency anaylsis error On my Xcode project, I tried to compile. But I couldn't do that because of some errors
Those are like as follows.
Unable to run command 'CpResource XXX.app' - this target might include its own product.
Unable to run command 'Touch XXX.app' - this target might include its own product.
So I tried to clean project, but I couldn't do that also.
How can I fix these errors?
Hope your help. Thanks.

A: In Xcode, go to your Products folder and make sure your .app file has no Target Memberships in the file inspector. Nothing should be checked. I had the same issue and that fixed it for me.


text:
Q: How does PHP count objects in multidimensional arrays? While I was learning about a count function for arrays and looking at some examples I noticed something I don't understand. Can you clarify me the behavior in the example below.
I read how count function works in PHP manual and I know that the second parameter in function means that it will recursively count the array.
<?php
$fruits = array ("apple", "orange", array("pear" , "mango"), "banana");
echo (count($fruits,1));

So the result without 1 as the second parameter should be 4 and with it should be 5, yet I get 6 as the output.

A: $fruits = array("apple", "orange", array(), array("pear", "mango"), "banana");
echo (count($fruits, 1));

The answer is simple. The output of this code is 7.
1) apple
2) orange
3) array()
4) array()
5) pear
6) mongo
7) banana

If I want to explain it accurately and simply:
<?php
$arr = ['a', 'b', array('c', 'd')];
$cnt = count($arr);
foreach($arr as $item) {
    if(is_array($item)) {
        $cnt += count($item);
    }
}
echo $cnt;


text:
Q: How to restore the initial state of
*? I have some  list like this:

First

Second

Third

I want to be capable to restore that list after some manipulation in future, so I save that:
let ul_list = document.getElementById('list');
let items = document.getElementsByTagName('li');
let li_items = [];
for (var i = 0 ; i < items.length; i++) {
        let li = document.createElement('li');
        let text = document.createTextNode(items[i].innerHTML);
        li_items.push(li.appendChild(text));
    }

and I create function to restore:
function restoreList(){
    while (ul_list.firstChild) {
        ul_list.removeChild(ul_list.firstChild)
    };

    for (var i = 0 ; i < li_items.length; i++) {
        ul_list.appendChild(li_items[i])
    };
}

But using this function I don't get marked list, only three words in a row:

FirstSecondThird

A: i think the problem are when creating the DOM, right in the li_items.push you shouldn't put the append child inside the .push, because it will return DocumentFragment.
for (var i = 0 ; i < items.length; i++) {
    let li = document.createElement('li');
    let text = document.createTextNode(items[i].innerHTML);
    li.appendChild(text)
    li_items.push(li);
}

A: The problem is that when you write:
li_items.push(li.appendChild(text));

you are pushing to the array li_items the return value of the appendChild(text) function.
From the appendChild() docs:

Return value
A Node that is the appended child (aChild), except when
aChild is a DocumentFragment, in which case the empty DocumentFragment
is returned.

So, what you are really pushing to the array (and afterwards inserting again inside
) is not the whole
 element but only the textNode.
Simply change your loop to:
for (var i = 0 ; i < items.length; i++) {
    let li = document.createElement('li');
    li.innerHTML = items[i].innerHTML;
    li_items.push(li);
}