text:
Q: Can I write bytes into audio output using Qt? There are examples on Qt website regarding using audio API, but frankly I don't really understand them at all.
What I was imagining is writing array of values (bytes, integers...) into some audio buffer and have the sound card "play" them (actually DAC them).
Pseudocode:
// Square wave?
const int values[] = {255,255,255,255, 0,0,0,0, 255,255,255,255 ...};
// Create output that will buffer the bytes and put them on digi to analog converter
RawAudioOutput output(BIT_RATE_CONSTANT, ... some other parameters ...);
output.start();
output.writeBytes(values, sizeof(values));

Can I accomplish something like that? How would I go about it? I know I can model square wave in Audacity (doesn't sound nice), so I guess it's possible. How?

A: In Qt, if you want to write an array of values into an audio buffer, the class for that is QAudioOutput. The format of the array of values can vary, the PCM format should be supported by all platforms.
Qt ships with an example that demonstrates the usage of QAudioOutput, have a look at that. In the example, the Generator::generateData() function creates the array of values that are then later sent to the audio device.
Of course playing audio from an array of values is quite low-level. With QMediaPlayer, Qt also provides a high-level class to play sound files (.wav, .mp3), video files and even streams.


text:
Q: Unusual Declaration Error This seems like a really easy fix, but I can't understand what it's coming from.
Any help fully appreciated!
The following 2 lines of code produce the following errors respectively.
vector <spades::player> players(4, player());
vector <spades::card> deck(52,card());

error: 'player' was not declared in this scope
error: 'card' was not declared in this scope

Below is my card.cpp
#include <iostream>
#include <sys/ioctl.h>
#include <cstdio>
#include <unistd.h>
#include <locale.h>
#include <ncursesw/ncurses.h>

#include "card.h"
namespace spades {
card::card()
{
    cardSuit = 0;
    cardNum = 0;
}

card::card(int suit, int number)
{
    cardSuit = suit;
    cardNum = number;
}
}

Below is my player.cpp
#include <iostream> // Stream declarations
#include <vector> //Vectors used to store deck and players hands
#include <string> //String declarations
#include <algorithm> //Shuffle Method
#include <sys/ioctl.h>
#include <cstdio>
#include <unistd.h>
#include <locale.h>
#include <ncursesw/ncurses.h>
#include "player.h"
namespace spades {
using namespace std;

player::player() {
    score =0; //total score
    bid = NULL; //bid for that round
    tricksTaken = 0; //score for thast round
    sandBag = 0; //the number of points you win, more than what you bid, every 10th bag = -100
    doubleNil = false;
    for(int i=0; i<13; i++)
        hand.push_back(card());
}

void player::addCard(spades::card b){
    for (int i=0; i<hand.size(); i++){
        //compare card being played to the ones in your hand to search and determine which one to erase
        if((hand.at(i).getCardNum() == 0) &&
            (hand.at(i).getSuit() == 0))
        {
            hand.at(i).setCardNum(b.getCardNum());
            hand.at(i).setSuit(b.getSuit());
            return;
        }
    }
}

void player::removeCard(spades::card a) {
    for (int i=0; i<hand.size(); i++){
        //compare card being played to the ones in your hand to search and determine which one to erase
        if((hand.at(i).getCardNum() == a.getCardNum()) &&
            (hand.at(i).getSuit() == a.getSuit()))
        {
            hand.at(i).setCardNum(0);
            hand.at(i).setSuit(0);
            return;
        }
    }
}
}

A: The compiler is actually complaining about the arguments you pass to vector constructors. You specified player() and card() in the constructor arguments, while it is obvious that your types are actually named spades::player and spades::card. You correctly specified the spades:: part in template parameters. Why did you omit the spades:: part from the constructor arguments?
It should be
vector <spades::player> players(4, spades::player());
vector <spades::card> deck(52, spades::card());

It should be noted though that the explicit argument is unnecessary, so you can just do
vector <spades::player> players(4);
vector <spades::card> deck(52);

and get the same result.

A: Also you don't need the
    namespace spades {

    }

block in player.cpp, only around you class definition in the header file.
Maybe you ment
    using namespace spades;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there a stochastic domination between "sub"Bernoulli random variables and Bernoulli ones? Given an $n$-element set $[n]$. Let $R$ be a random subset of $[n]$, whose distribution is unknown, especially we do not assume independence in it. But what we know is that for all subsets $S\subseteq [n]$ and for some $0<p<1$
$$P(S\subseteq R)\le p^{|S|}.$$
Let $X=Ber(n,p)$. Is it true that for any $x>0$
$$P(|R|\ge x)\le P(X\ge x)?$$
If the above is true, furthermore, let $\mathcal{F}$ be a collection of deterministic $k$-subsets of $[n]$. Is it true that for any $x>0$
$$P(|\{F\in \mathcal{F}:F\subseteq R\}|\ge x)\le P(|\{F\in \mathcal{F}:F\subseteq X\}|\ge x)?$$

A: My intuition would be that it's false because applying a simple union bound on $\mathbb{P}[|R|\ge x]$ gives an upper bound of $\binom{n}{x}p^x$ which looks meaningless in order to compare it to tails of binomials.
I suggest the following distribution: $\{1\}$ with probability $1/2$ and $\{2\}$ with probability $1/2$. It satisfies the property for $p=1/2$ but $\mathbb{P}[|R|\ge 1]=1$

A: The keyword that you are looking for is stochastic domination.
In general, the answer is no for general Bernoulli random fields (short BRF).
For Bernoulli product fields (short BPF), as asked in the comment, the answer only depends on the ordering between the vectors of single variable marginals. The construction of a dominating coupling is  trivial for one variable. Independence makes  the product of the dominating single-variable couplings a dominating coupling between the products.
There is a nice example in "Domination by product measures" by Liggett, Schonmann & Stacey , giving a translation-invariant BRF on $\mathbb{Z}$ with marginal probability $1/2$ and both $\mathbb{P}(X_1 = \dotso = X_n = 1)\in{}o(1/(n!))$ and $\mathbb{P}(X_1 = \dotso = X_n = 0)\in{}o(1/(n!))$. This means that it is neither dominated by a non-trivial BPF, nor dominates a non-trivial BPF.
For special kinds of BRFs there are some conditions known:

*

*Markov fields: see e.g. "Probability on Graphs" by Grimmett

*Fields with positive and negative association: see e.g. "Probability on Graphs" by Grimmett

*1-dependent BRFs: see "Domination by product measures" by Liggett, Schonmann & Stacey


text:
Q: how to get msgbox text from reference cell, which includes newline characters edit: all responses have missed my point, so i've removed any mention of special characters and just want to focus on the line break vbCrLf
i have a combobox populated from a range of cells, and i want a msgbox to pop up based on the user's selection in said combobox, such that the msgbox text is taken from a cell which corresponds to the user's selected cell (i.e. the cell linked to the user's cbox selection). for example:

user selection
msgbox text

scarf
It's 40 degrees.   Are you sure you want a scarf?

swimshorts
Don't forget your sunscreen!

so that's the reason for trying to fill the cbox from a cell, rather than from VB.
my problem is how to write the newline and special character in the reference cell and have msgbox format it correctly.
i.e. MsgBox "It's 40 degrees." & vbCrLf & "Are you sure you want a scarf?" does what i want, but if i place that text in a cell and then try to reference that cell with a msgbox, e.g. MsgBox Sheet1.Range("B2"), then the msgbox just prints the text without formatting.
e.g. https://imgur.com/a/Hi3HVWG
please, any help here would be greatly appreciated

A: To add a line feed in a cell, if you are entering it from the worksheet:
A1: ="abc" & CHAR(10) & "def"

For the linefeed character, you can type abcalt+enterdef

If you are entering it from VBA, then the code line would be:
Range("A1")  = "abc" & vblf & "def"


text:
Q: Retrieve data from lotus notes database view via Java I am trying to retrieve data from a Lotus Notes database within which I already have a view. I manage to create an ODBC connection and use this with MS Access or Excel but I'd like to create a scheduled job on a java application to inject the data in a MS SQL Server database.
I got a bit lost in all the documentation on Internet; Do
you guys have a sample of a Java code which would allow me to
1. Connect to the database
2. "Query" the view ("SELECT * FROM..."?)
3. Get a resultset which I can iterate through
I've read that I can avoid using the Lotus SQL driver by importing the notes.jar in my project...
Thank you for your help

A: The best and easiest way to connect to a Lotus Notes database is by using Notes API. All you need is to connect to the database, get the view and then traverse each document. You can accomplish this by including Notes API jar file into your Libraries and then you have all Notes classes at your disposal.


text:
Q: AVD setting for installing firefox and chrome on Android Emulator I want to know the settings for the AVD's if I want to install firefox and chrome on my Android Emulator.
What is the AVD setting for installing firefox and chrome. I have the following avd files chrome (com.android.chrome-2.apk) and firefox (fennec-10.0.3esr.multi.android-arm.apk)
Thanks,
parvez

A:
adb install com.android.chrome-2.apk

adb install fennec-10.0.3esr.multi.android-arm.apk

Run these commands from the directory  where you have downloaded the files.


text:
Q: Update bytea data with NULL in postgresql I have a bytea field which contains data I want to replace with NULL. I tried the following syntax:
update ir_act_report_xml set report_rml_content_data = E'\\000'::bytea, report_sxw_content_data = E'\\000'::bytea where id = 365;

But it then returns 00 instead of being NULL.
What is the correct syntax for updating the bytea field to NULL?

A: Just use the keyword NULL:
UPDATE ir_act_report_xml SET
   report_rml_content_data = NULL,
   report_sxw_content_data = NULL
 WHERE id = 365;


text:
Q: Extract values from a plot by mouse in bokeh I have a function y=f(x,a,b), where x,y are the independent and dependent variables and a,b are parameters.
I want to generate a two-panel figure [A,B], where A is the a-versus-b parameter space and B is the y-versus-x function line. I want to be able to use the mouse (say, by hovering over) in panel A to select a pair of (a,b) values and then update the y--x line in the panel B correspondingly.
What widget/method I need to achieve this? I did some research on bokeh hover tool but it generates a tooltip instead of a panel plot, plus I don't know how to extract the values from mouse other than the tooltips syntax in hover tool.
PS: I know this can be achieved by using two sliders (one for a, one for b), but using a panel and mouse gives more flexibility in probing the a-b phase space.

A: I think i found the solution of your problem.
I give you the entire code :
from bokeh.plotting import figure,show, ColumnDataSource, output_notebook
from bokeh.models import Label
from bokeh.models import CustomJS, HoverTool
import numpy as np
output_notebook()
TOOLS = "xpan,crosshair"

callback_js ="""
        var geometry = cb_data['geometry'];
        var x_data = geometry.x; // current mouse x position in plot coordinates
        var y_data = geometry.y; // current mouse y position in plot coordinates
        console.log("(x,y)=" + x_data+","+y_data); //monitors values in Javascript console
        date_label.text ='x=' + x_data.toFixed(2) + '    ' + 'y=' + y_data.toFixed(2)
        console.log(date_label.text)
    """

s = ColumnDataSource(data = dict(x=[0,1],y=[0,1])) #points of the line
p = figure(x_range=(0,1), y_range=(0,1),tools=TOOLS)
p.line(x='x',y='y',source=s)
date_label = Label(x=30, y=30, x_units='screen', y_units='screen',
                     text='', render_mode='css',
                     border_line_color='white', border_line_alpha=1.0,
                     background_fill_color='white', background_fill_alpha=1.0)

date_label.text = ""
p.add_layout(date_label)
callback=CustomJS(args={'date_label':date_label},code=callback_js)
p.add_tools(HoverTool(tooltips=None, callback=callback))
show(p)

Give me a feedback if you want to improve it.
Good Coding

A: PARTIAL SOLUTION
I found a very similar question with the answer on how to extract the value from the mouse hover tool. Combined with another example about changing a subplot from a callback in a different widget/subplot, here is a working solution with some major disadvantages listing below:
# my test
from bokeh.layouts import column
from bokeh.models import CustomJS, ColumnDataSource, HoverTool
from bokeh.plotting import Figure, output_notebook, show

output_notebook()

x0 = [x*0.005 for x in range(0, 200)]
y0 = x0
sB = ColumnDataSource(data=dict(x=x0, y=y0))
sA = ColumnDataSource(data = dict(x=[0],y=[0]))

callback = CustomJS(args=dict(sA=sA,sB=sB), code="""
    var geometry = cb_data['geometry'];
    var a = geometry.x; // current mouse x position in plot coordinates
    var b = geometry.y; // current mouse y position in plot coordinates
    var as = sA.get('data')['x'];
    var bs = sA.get('data')['y'];
    as[0] = a;
    bs[0] = b;
    sA.trigger('change');

    var data = sB.data;
    x = data['x']
    y = data['y']
    for (i = 0; i < x.length; i++) {
        y[i] = Math.pow(x[i], a+b) // have to convert python function to js here!!!
    }
    sB.trigger('change');
""")

hover_tool = HoverTool(callback=callback)
A = Figure(x_range=(0,1), y_range=(0,1), tools= [hover_tool,
                        "crosshair,box_zoom,wheel_zoom,pan,reset"])
A.circle(x='x',y='y',source=sA)
B = Figure(x_range=(0,1), y_range=(0,1), tools= ["crosshair,box_zoom,wheel_zoom,pan,reset"])
B.line(x='x',y='y',source=sB)
layout = column(A,B)
show(layout)

One MAJOR DRAWBACK of this solution is that it utilizes the javascript which I'm totally unfamiliar with and that I have to convert the function f(x,a,b) from python to javascript. I'd appreciate any better solution that can keep the original python function f or other workarounds?


text:
Q: не записывается данные в процесс сделал для примера такую программу.
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

int a[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

int get_num ( ) {
        static int index = 0;
        static int size = sizeof ( a ) / sizeof ( int );
        if ( index >= size ) index = 0;
        int num = a[index++];
        num = 10;
        return num;
}

int main ( ) {
        int i = 0;
        printf ( "pid: %d\n", getpid ( ) );
        while ( 1 ) {
                int num = get_num ( );
                printf ( "i:%d\n", num );
                sleep ( 1 );
        }
}

я точно не помню, но вроде в секцию кода нельзя делать записи, но это я читал так давно, что могу ошибаться. я видел некоторые примеры, и вроде бы они подтверждают что записать в процесс можно, но можно ли записать в чужой процесс? в общем с помощью objdump я посмотрел адрес где num = 10. вот он.
11d1:  c7 45 fc 0a 00 00 00    mov    DWORD PTR [rbp-0x4],0xa
для этого я написал такую программу. и захотел заменить 10 на 11. но не выходит. пишет ptrace poketext: Input/output error
.
#include <stdio.h>
#include <stdlib.h>
#include <sys/ptrace.h>

int main ( int argc, char **argv ) {
        if ( argc < 2 ) return -1;
        int pid = atoi ( argv[1] );

        int ret = ptrace ( PTRACE_ATTACH, pid, NULL, NULL );
        if ( ret == -1 ) perror ( "ptrace" );
        printf ( "ret: %d\n", ret );
        long addr = 0x00005555555551d4;
        long opcode = 0xb;
        ret = ptrace ( PTRACE_POKETEXT, pid, ( void * ) addr, ( void * ) opcode );
        if ( ret == -1 ) perror ( "ptrace poketext" );

        ptrace ( PTRACE_DETACH, pid, NULL, NULL );
}


text:
Q: Image sizes for different drawables I have a doubt about saving images in drawables for different device sizes. I want to ask that if I have an image of H:200,W:300 so for ldpi, mdpi, hdpi.xhdpi, xxhpdi and xxxhdpi, from which number we have to multiply in height and weight both for make it compatible for all size devices. Please reply me a simple answer, don't share any link.

A: You should not consider making every drawable in same proportion for every devices but for UI . If you want to here are the ratios
Android takes hdpi as a base to calculate ratios.
MDPI:HDPI = 2/3
XHDPI:HDPI = 3/2
XXHDPI:HDPI = 2
XXXHDPI:HDPI = 8/3


text:
Q: How do I flag a question as being on the wrong site when the correct site is not one of the flag options? I wanted to flag PNG images look blurry when scaled as being on the wrong site. I tried to flag it as belonging on computergraphics.stackexchange.com, but that was not one of the options.
So I flagged it as belonging on meta and left a comment.
How should we flag wrong site questions if the correct site is not listed as one of the flag options?

A: You can just use a custom flag (flag for moderator attention) and explain to which site it should be migrated.


text:
Q: Conditional rowMeans with dplyr I want to apply a conditional rowMeans to each group of IDs using dplyr.
The reproducible table follows:
dat <- as.Date("2021/08/04")
len <- 4
seq(dat, by = "day", length.out = len)

input <- data.frame(
  date = c(seq(dat, by = "day", length.out = len) , seq(dat, by = "day", length.out = len)),
  user_id = c(rep("aa",4),rep("bb",4)),
  var1 = c(1:4),
  var2 = c(4,7,23,9,0,0,0,0),
  var3 = c(0,0,0,0,4,8,2,7)
)

The logic is: For each ID, first select the columns which are numeric and their sum is =!0, and then compute the rowMean of the selected columns for that ID.
The desired output table follows:
 output = data.frame(
  date = c(seq(dat, by = "day", length.out = len) , seq(dat, by = "day", length.out = len)),
  user_id = c(rep("aa",4),rep("bb",4)),
  var1 = c(1:4),
  var2 = c(4,7,23,9,0,0,0,0),
  var3 = c(0,0,0,0,4,8,2,7),
  rowAverage = as.numeric(c(rowMeans(input[1:4,3:4]), rowMeans(input[5:8,c(3,5)])))
)

The lines that I came-up with follow, but I get some errors:
output = input %>%
    dplyr::group_by(user_id) %>%
    dplyr::mutate(rowAverage = rowMeans(select_if(function(x) {(is.numeric(x)) && (sum(x)=!0)})))

Could you please help me correct this? Thank you.

A: You're very close. You just need to supply the data to select_if(), too.
Use cur_data() for that.
input %>%
  group_by(user_id) %>%
  mutate(rowAverage = rowMeans(
    select_if(cur_data(), \(x) is.numeric(x) && sum(x) != 0)
  ))
#> # A tibble: 8 × 6
#> # Groups:   user_id [2]
#>   date       user_id  var1  var2  var3 rowAverage
#>   <date>     <chr>   <int> <dbl> <dbl>      <dbl>
#> 1 2021-08-04 aa          1     4     0        2.5
#> 2 2021-08-05 aa          2     7     0        4.5
#> 3 2021-08-06 aa          3    23     0       13
#> 4 2021-08-07 aa          4     9     0        6.5
#> 5 2021-08-04 bb          1     0     4        2.5
#> 6 2021-08-05 bb          2     0     8        5
#> 7 2021-08-06 bb          3     0     2        2.5
#> 8 2021-08-07 bb          4     0     7        5.5

A: Though the question is tagged dplyr, dplyr is not very good at processing by rows so here is a base R solution.
res <- by(input, input$user_id, \(X) {
  i <- sapply(X, \(x) is.numeric(x) && sum(x, na.rm = TRUE) != 0)
  X$rowAverage <- rowMeans(X[i])
  X
})
res <- do.call(rbind, res)
res
#>            date user_id var1 var2 var3 rowAverage
#> aa.1 2021-08-04      aa    1    4    0        2.5
#> aa.2 2021-08-05      aa    2    7    0        4.5
#> aa.3 2021-08-06      aa    3   23    0       13.0
#> aa.4 2021-08-07      aa    4    9    0        6.5
#> bb.5 2021-08-04      bb    1    0    4        2.5
#> bb.6 2021-08-05      bb    2    0    8        5.0
#> bb.7 2021-08-06      bb    3    0    2        2.5
#> bb.8 2021-08-07      bb    4    0    7        5.5

Created on 2022-10-21 with reprex v2.0.2


text:
Q: Hadoop crashed while running terasort? I am working with Hadoop single node, later may move on to multinode. Right now the same node is master as well as slave, hence namenode, datanode resource manager and node manager are running on the same PC.
Whenever I trigger terasort on seperate testing disk mounted on /home/hadoop/hdfs (here hadoop is user name), it fails with following errors:
INFO mapreduce.Job: Task Id : attempt_1429766544852_0001_m_001255_0, Status : FAILED
Error: org.apache.hadoop.util.DiskChecker$DiskErrorException: Could not find any valid local directory for attempt_1429766544852_0001_m_001255_0_spill_1.out
        at org.apache.hadoop.fs.LocalDirAllocator$AllocatorPerContext.getLocalPathForWrite(LocalDirAllocator.java:398)
        at org.apache.hadoop.fs.LocalDirAllocator.getLocalPathForWrite(LocalDirAllocator.java:150)
        at org.apache.hadoop.fs.LocalDirAllocator.getLocalPathForWrite(LocalDirAllocator.java:131)
        at org.apache.hadoop.mapred.YarnOutputFiles.getSpillFileForWrite(YarnOutputFiles.java:159)
        at org.apache.hadoop.mapred.MapTask$MapOutputBuffer.sortAndSpill(MapTask.java:1573)
        at org.apache.hadoop.mapred.MapTask$MapOutputBuffer.flush(MapTask.java:1467)
        at org.apache.hadoop.mapred.MapTask$NewOutputCollector.close(MapTask.java:699)
        at org.apache.hadoop.mapred.MapTask.runNewMapper(MapTask.java:769)
        at org.apache.hadoop.mapred.MapTask.run(MapTask.java:339)
        at org.apache.hadoop.mapred.YarnChild$2.run(YarnChild.java:162)
        at java.security.AccessController.doPrivileged(Native Method)
        at javax.security.auth.Subject.doAs(Subject.java:415)
        at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1491)
        at org.apache.hadoop.mapred.YarnChild.main(YarnChild.java:157)

15/04/23 11:36:07 INFO mapreduce.Job: Task Id : attempt_1429766544852_0001_m_001258_0, Status : FAILED
Error: java.io.IOException: No space left on device
        at java.io.FileOutputStream.writeBytes(Native Method)
        at java.io.FileOutputStream.write(FileOutputStream.java:345)
        at org.apache.hadoop.fs.RawLocalFileSystem$LocalFSFileOutputStream.write(RawLocalFileSystem.java:236)
        at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:82)
        at java.io.BufferedOutputStream.flush(BufferedOutputStream.java:140)
        at java.io.FilterOutputStream.flush(FilterOutputStream.java:140)
        at java.io.DataOutputStream.flush(DataOutputStream.java:123)
        at java.io.FilterOutputStream.flush(FilterOutputStream.java:140)
        at java.io.FilterOutputStream.flush(FilterOutputStream.java:140)
        at java.io.DataOutputStream.flush(DataOutputStream.java:123)
        at org.apache.hadoop.mapred.IFile$Writer.close(IFile.java:163)
        at org.apache.hadoop.mapred.MapTask$MapOutputBuffer.sortAndSpill(MapTask.java:1633)
        at org.apache.hadoop.mapred.MapTask$MapOutputBuffer.access$900(MapTask.java:852)
        at org.apache.hadoop.mapred.MapTask$MapOutputBuffer$SpillThread.run(MapTask.java:1510)

Error: java.io.IOException: No space left on device
        at java.io.FileOutputStream.writeBytes(Native Method)
        at java.io.FileOutputStream.write(FileOutputStream.java:345)
        at org.apache.hadoop.fs.RawLocalFileSystem$LocalFSFileOutputStream.write(RawLocalFileSystem.java:236)
        at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:82)
        at java.io.BufferedOutputStream.flush(BufferedOutputStream.java:140)
        at java.io.FilterOutputStream.flush(FilterOutputStream.java:140)
        at java.io.DataOutputStream.flush(DataOutputStream.java:123)
        at java.io.FilterOutputStream.flush(FilterOutputStream.java:140)
        at java.io.FilterOutputStream.flush(FilterOutputStream.java:140)
        at java.io.DataOutputStream.flush(DataOutputStream.java:123)
        at org.apache.hadoop.mapred.IFile$Writer.close(IFile.java:163)
        at org.apache.hadoop.mapred.MapTask$MapOutputBuffer.sortAndSpill(MapTask.java:1633)
        at org.apache.hadoop.mapred.MapTask$MapOutputBuffer.access$900(MapTask.java:852)
        at org.apache.hadoop.mapred.MapTask$MapOutputBuffer$SpillThread.run(MapTask.java:1510)

Error: java.io.IOException: Spill failed
        at org.apache.hadoop.mapred.MapTask$MapOutputBuffer.checkSpillException(MapTask.java:1540)
        at org.apache.hadoop.mapred.MapTask$MapOutputBuffer.access$300(MapTask.java:852)
        at org.apache.hadoop.mapred.MapTask$MapOutputBuffer$Buffer.write(MapTask.java:1352)
        at org.apache.hadoop.mapred.MapTask$MapOutputBuffer$Buffer.write(MapTask.java:1329)
        at java.io.DataOutputStream.writeByte(DataOutputStream.java:153)
        at org.apache.hadoop.io.WritableUtils.writeVLong(WritableUtils.java:273)
        at org.apache.hadoop.io.WritableUtils.writeVInt(WritableUtils.java:253)
        at org.apache.hadoop.io.Text.write(Text.java:323)
        at org.apache.hadoop.io.serializer.WritableSerialization$WritableSerializer.serialize(WritableSerialization.java:98)
        at org.apache.hadoop.io.serializer.WritableSerialization$WritableSerializer.serialize(WritableSerialization.java:82)
        at org.apache.hadoop.mapred.MapTask$MapOutputBuffer.collect(MapTask.java:1127)
        at org.apache.hadoop.mapred.MapTask$NewOutputCollector.write(MapTask.java:691)
        at org.apache.hadoop.mapreduce.task.TaskInputOutputContextImpl.write(TaskInputOutputContextImpl.java:89)
        at org.apache.hadoop.mapreduce.lib.map.WrappedMapper$Context.write(WrappedMapper.java:112)
        at org.apache.hadoop.mapreduce.Mapper.map(Mapper.java:124)
        at org.apache.hadoop.mapreduce.Mapper.run(Mapper.java:145)
        at org.apache.hadoop.mapred.MapTask.runNewMapper(MapTask.java:763)
        at org.apache.hadoop.mapred.MapTask.run(MapTask.java:339)
        at org.apache.hadoop.mapred.YarnChild$2.run(YarnChild.java:162)
        at java.security.AccessController.doPrivileged(Native Method)
        at javax.security.auth.Subject.doAs(Subject.java:415)
        at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1491)

Basically, spill failed, Disk checker, no space left etc.
When I looked into the issue, keep running df -h in separate terminal gave the clue that it is using / directory for some internal operations as the job was in progress. When no space left on / the job failed.
I tried changing hadoop.tmp.dir to some other mounted disk. It worked fine but again failed as that disk was also not having enough space.
My question is why is it happening, can we avoid this issue at all? Or, what exact parameters be configured in .xml config files so that to restrict it to within RAM or use disk space but make sure not to fail the job and use whatever space it has but dont crash due to any error which I have mentioned?
Thanks in advance.
PS: I have studied about alomst all config parameters and gone thourgh roughly all kinds of hit & trial but still it failed. Hence, I thought of asking here, hope you may help.

A:
My question is why is it happening

So to give you a better understanding, Mapper's as soon as their task is complete the intermediate output is spilled to disk (specified by yarn.nodemanager.local-dirs whose default value is ${hadoop.tmp.dir}/nm-local-dir), of course if the data does not fit in memory of the Mapper then also a spill is made and is merged at the end of the task and written back eventually to disk.
Similarly the reducer has to copy the intermediate data from Mapper's local filesystem to it's own local filesystem to process the data.
So, for example if you are running terasort on 100G of data with 4 mapper's & one reducer then assuming your mapper's have generated 25G of intermediate data, then the reducer has to have 100G free space on its local filesystem to processing it.

can we avoid this issue at all?

In your case increasing task's wouldn't help as it's a single machine.
Only way to avoid the problem is to add more NodeManager's so that you could get more disk space from that node's to process the job.

what exact parameters be configured in .xml config files so that to restrict it to within RAM

You cannot restrict the MapReduce job to just use RAM as for the shuffle process to happen data has to be written to disk.

or use disk space but make sure not to fail the job and use whatever space it has but don't crash due to any error which I have mentioned?

You have to have enough disk space for intermediate task's output on your cluster for the job to get processed.


text:
Q: The new IOS apple maps I have implemented the IOS maps "turn by turn" feature on my current application with the current code:
Class itemClass = [MKMapItem class];
if (itemClass && [itemClass respondsToSelector:@selector(openMapsWithItems:launchOptions:)]) {
    MKMapItem *currentLocation = [MKMapItem mapItemForCurrentLocation];
    MKMapItem *toLocation = [[MKMapItem alloc] initWithPlacemark:[[MKPlacemark alloc] initWithCoordinate:to addressDictionary:nil]];
    toLocation.name = @"Destino";
    [MKMapItem openMapsWithItems:[NSArray arrayWithObjects:currentLocation, toLocation, nil]
                   launchOptions:[NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:MKLaunchOptionsDirectionsModeDriving, [NSNumber numberWithBool:YES], nil]
                                                             forKeys:[NSArray arrayWithObjects:MKLaunchOptionsDirectionsModeKey, MKLaunchOptionsShowsTrafficKey, nil]]];

My question is, how can i return to my app after i use the maps? It was possible with google by using a webView, but i cant make it work on apple maps.
Thanks in advance and sorry for my bad english.

A: I'm afraid what you're looking to achieve isn't possible. You can pass in various launch options when you trigger the maps app (such as which map to use, where to center the map, etc), but what you can't do is pass a callback to 'return' the user back to your when they are done. The user will have to manually navigate back to your app themselves.
You might want to consider filing a feature request with Apple if you think this feature would be particularly worthwhile.


text:
Q: Transferring Noticing Script from arcpy.mapping to arcpy.mp I am trying to reconfigure a script I have been using in ArcMap into ArcGIS Pro and have discovered the whole arcpy.mapping vs arcpy.mp. I am stuck on a section that is trying to list layers.
Here is the original script under arcpy.mapping
# Get the map document, data frame, and layers
# arcpy.AddMessage("MXD Path: " + mxd_file)
    mxd = arcpy.mapping.MapDocument("CURRENT")
    df = arcpy.mapping.ListDataFrames(mxd)[0]
    layers = arcpy.mapping.ListLayers(mxd)
    for l in layers:
        if l.name == "Subject Property":
            subject_layer = l
        elif l.name == "Zoning":
            zoning_layer = l
        elif l.name == "General Plan":
            gp_layer = l
        elif l.name == "Basemap":
            baselayer = l

Here is my attempt to update it:

 # Get the map document, data frame, and layers
 # arcpy.AddMessage("MXD Path: " + mxd_file)
    aprx = arcpy.mp.ArcGISProject("Current")
    df = aprx.listMaps("Map")[0]
    for l in df.listLayers():
        if lyr.name == "Subject Property":
            subject_layer = l
        elif lyr.name == "Zoning":
            zoning_layer = l
        elif lyr.name == "General Plan":
            gp_layer = l
        elif lyr.name == "Basemap":
            baselayer = l

This is the error I am getting:

public_notice working
=====================
Parameters

Project Address     2600 W TAYLORSVILLE BLVD
Parcel IDs     21094510720000
Noticing Distance     300 Feet
Output Folder     N:\GIS\Projects\Public Notice
CSV Out     N:\GIS\Projects\Public Notice\Mailing_Labels.csv
Zoning Out
GP Out
Site Out
Vicinity Out
Messages Out     Verifying Parcel ID(s)...
Creating mailing list...
Writing CSV...
Setting up mxd for mapping...
list index out of range
=====================
Messages

Start Time: Monday, June 13, 2022 4:27:25 PM
Verifying Parcel ID(s)...
Creating mailing list...
Writing CSV...
Setting up mxd for mapping...
PYTHON ERRORS:
Traceback info:
  File "C:\Users\kkerdolff\Desktop\public_notice_maps_work.py", line 118, in <module>

Error Info:
list index out of range

ArcPy ERRORS:

Failed script public_notice working...
Failed to execute (PublicNotice1).
Failed at Monday, June 13, 2022 4:27:34 PM (Elapsed Time: 9.32 seconds)


text:
Q: Google Script return value from one sheet to another sheet This is my first Google Script and I'm struggling a little bit while trying to bring back the values from a specific cell & sheet to another sheet.
I have a total of 18 columns, being the first one the ID which is going to be the input that the user would need to add in order to retrieve the data from one sheet to another. As the first one is the ID, and will be already be inputted by the user, I would need to retrieve the data from columns 2 to 18
Here is my code:
function SearchID() {
  var columnIndex = 0;
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var formS = ss.getSheetByName("Manual Costs App"); // App sheet

  var str = formS.getRange("D6").getValue(); // The ID to search will be inputted here
  var dataS = ss.getSheetByName("Inputs").getDataRange().getValues(); // Retrieving the data based on the user input
  for (var i = 0; i<=dataS.length; i++) {
    var row = dataS[i];
    if (row[columnIndex] == str) {
      formS.getRange("D9").setValue(row[1]);
      formS.getRange("D13").setValue(row[2]);
      formS.getRange("D14").setValue(row[3]);
      formS.getRange("D15").setValue(row[4]);
      formS.getRange("D16").setValue(row[5]);
      formS.getRange("D18").setValue(row[6]);
      formS.getRange("D19").setValue(row[7]);
      formS.getRange("D20").setValue(row[8]);
      formS.getRange("D21").setValue(row[9]);
      formS.getRange("D22").setValue(row[10]);
      formS.getRange("D23").setValue(row[11]);
      formS.getRange("D25").setValue(row[12]);
      formS.getRange("D26").setValue(row[13]);
      formS.getRange("D27").setValue(row[14]);
      formS.getRange("D28").setValue(row[15]);
      formS.getRange("D29").setValue(row[16]);
      formS.getRange("D30").setValue(row[17]);
      break;
    }
  }
}

The link to a sample spreadsheet of what I'm building is here
Update: Everything is fixed now! What I did was removing the space in the for loop. After that, it retrieved the data but a TypeError: Cannot read property '0'. Also solved it adding a break after the loop to avoid it.

A: It's a type in your for loop, notice how spelled length:
for (var i = 1; i <= values.lenght; i++)

You also don't want to set values line by line like you do, get a longer range and set the values with setValues() rather than setValue(). There's quite a bit of refactoring to do there actually.

A: The user did found the answer and updated it on the question.
Posting here as community wiki so it can be seen more clearly.
User's answer:
Update: Everything is fixed now! What I did was removing the space in the for loop. After that, it retrieved the data but a TypeError: Cannot read property '0'. Also solved it adding a break after the loop to avoid it.
function SearchID() {
  var columnIndex = 0;
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var formS = ss.getSheetByName("Manual Costs App"); // App sheet

  var str = formS.getRange("D6").getValue(); // The ID to search will be inputted here
  var dataS = ss.getSheetByName("Inputs").getDataRange().getValues(); // Retrieving the data based on the user input
  for (var i = 0; i<=dataS.length; i++) {
    var row = dataS[i];
    if (row[columnIndex] == str) {
      formS.getRange("D9").setValue(row[1]);
      formS.getRange("D13").setValue(row[2]);
      formS.getRange("D14").setValue(row[3]);
      formS.getRange("D15").setValue(row[4]);
      formS.getRange("D16").setValue(row[5]);
      formS.getRange("D18").setValue(row[6]);
      formS.getRange("D19").setValue(row[7]);
      formS.getRange("D20").setValue(row[8]);
      formS.getRange("D21").setValue(row[9]);
      formS.getRange("D22").setValue(row[10]);
      formS.getRange("D23").setValue(row[11]);
      formS.getRange("D25").setValue(row[12]);
      formS.getRange("D26").setValue(row[13]);
      formS.getRange("D27").setValue(row[14]);
      formS.getRange("D28").setValue(row[15]);
      formS.getRange("D29").setValue(row[16]);
      formS.getRange("D30").setValue(row[17]);
      break;
    }
  }
}


text:
Q: Why or() queries are not using index in Datastax DSE 5.0.x Graph? I have created an index on User and on uuid
if I do:
schema.vertexLabel("User").describe()

I get:
schema.vertexLabel("User").index("byUuid").materialized().by("uuid").add()

When I am running:
g.V().hasLabel("User").has("uuid","oneUuid")

The index is picked up properly..
but when I do the following:
g.V().or(__.hasLabel("User").has("uuid","oneUuid"), __.hasLabel("User").has("uuid","anotherUUID"))

I am getting:

org.apache.tinkerpop.gremlin.driver.exception.ResponseException: Could
  not find an index to answer query clause and graph.allow_scan is
  disabled:

Thanks!

A: or() is not easily optimizable as you can do much more complicated things like:
g.V().or(
    hasLabel("User").has("uuid","oneUuid"),
    hasLabel("User").has("name","bob"))

...where one or more condition could not be answered by an index lookup. It is doable and will likely be done in future versions, but afaik none of the currently available graph databases is trying to optimize the OrStep.
Anyway, your sample query can easily be rewritten so that it actually uses the index:
g.V().hasLabel("User").has("uuid", within("oneUuid", "anotherUUID"))


text:
Q: Symfony first page - The autoloader expected class […] to be defined in file I have checked similar issues but posted by others but I still cannot see what is wrong in my code.
I just copied it from the documentation - https://symfony.com/doc/3.4/page_creation.html
<?php

// src/AppBundle/Controller/LuckyController.php
namespace AppBundle\Controller;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

class LuckyController
{
    /**
     * @Route("/lucky/number")
     */
    public function numberAction()
    {
        $number = mt_rand(0, 100);

        return new Response(
            'Lucky number: '.$number.''
        );
    }
}

The autoloader expected class "App\Controller\LuckyController" to be
  defined in file "E:\projektai\php
  projektai\htdocs\mokomieji\weather_demo_3\vendor\composer/../../src\Controller\LuckyController.php".
  The file was found but the class was not in it, the class name or
  namespace probably has a typo in E:\projektai\php
  projektai\htdocs\mokomieji\weather_demo_3\config/services.yaml (which
  is loaded in resource "E:\projektai\php
  projektai\htdocs\mokomieji\weather_demo_3\config/services.yaml").

So it says file was found but the class was not found. How can class be not found? I see it. How does it try to search for it?
composer.json
{
    "type": "project",
    "license": "proprietary",
    "require": {
        "php": "^7.0.8",
        "symfony/console": "^3.4",
        "symfony/flex": "^1.0",
        "symfony/framework-bundle": "^3.4",
        "symfony/lts": "^3",
        "symfony/yaml": "^3.4"
    },
    "require-dev": {
        "symfony/dotenv": "^3.4"
    },
    "config": {
        "preferred-install": {
            "*": "dist"
        },
        "sort-packages": true
    },
    "autoload": {
        "psr-4": {
            "App\\": "src/"
        }
    },
    "autoload-dev": {
        "psr-4": {
            "App\\Tests\\": "tests/"
        }
    },
    "scripts": {
        "auto-scripts": {
            "cache:clear": "symfony-cmd",
            "assets:install --symlink --relative %PUBLIC_DIR%": "symfony-cmd"
        },
        "post-install-cmd": [
            "@auto-scripts"
        ],
        "post-update-cmd": [
            "@auto-scripts"
        ]
    },
    "conflict": {
        "symfony/symfony": "*"
    },
    "extra": {
        "symfony": {
            "id": "01C16444CCZTY1MPPEE5GJZ63G",
            "allow-contrib": false
        }
    }
}

A: In my case, I hadn't used php in a while, I also copy/pasted from the tutorial, but I actually forgot to add
<?php

at the beginning of the file. Results in the same error message.

A: Based on that structure you are probably using Symfony Flex, so your namespace should be namespace App\Controller;
try switching to 4.0 version of documentation.


text:
Q: Adding padding between cells in a video gallery I'm trying to add padding between the videos in the following code. Any pointers or tips?:

Battle of Whitehall by Rockinpaddy, London

Which Side Are You On by Rockinpaddy, London

A: Try putting some padding on the td element like this:

td {
  padding: 0 10px;
}

Battle of Whitehall by Rockinpaddy, London

Which Side Are You On by Rockinpaddy, London


text:
Q: Is gRPC a good choice for my scenario? Im starting to develop a visually-simple but infrastructural-ly robust real time multiplayer game to show off my backend skills and hopefully get a job at Blizzard or something like that.
The game is simple: a multiplayer snake game.
I'm aiming to have a game session supporting up to 8 players, all connecting to a single dedicated server.
Because of the high "latency-sensitiveness" of the game I was wondering if a duplex gRPC is a good choice for communication channel, or if perhaps there's a better/more-recommended way to handle this?
Is that so or there is a better approach?


text:
Q: How to save an Image emitted by Jetpack Compose as a Bitmap I am using GlideImage with Jetpack compose, once the image is finished loading I would like to save it as a Bitmap. In XML this was quite straight forward, we would do something like this:
val bmp: Bitmap = image_view.drawToBitmap() //image_view is the XML id of the ImageView

What is the jetpack compose equivalent of this?


text:
Q: Google Font "Merriweather" Is not showing up in Chrome.? At the top of my code I have:
< link href=" https://fonts.googleapis.com/css?family=Merriweather&display=swap" rel="stylesheet" >
And in my CSS I have:
font-family: 'Merriweather', ;
But it is not showing up. I'm not sure what the reasoning is. It seems so simple and yet nothing is working.
Any help would be appreciated.
Here is the top of my HTML:
 <link rel = "stylesheet"
   type = "text/css"
   href = "stylesheet.css" />

<link href="https://fonts.googleapis.com/css?family=Merriweather&display=swap" rel="stylesheet">

<title>Jesse | Personal Chef </title>

  <meta charset="UTF-8">
  <meta name="description" content="Jesse Personal Chef">
  <meta name="keywords" content="Food, Chef, Wilmington, NC, North Carolina Food, In Home Chef, Personal Chef, Chef For Hire, Jesse,">
  <meta name="author" content="Cal & Jen T.">
  <meta name="viewport" content="width=device-width, initial-scale=1">

This is my CSS, saved in as stylesheet.css:

Thank you

A: One little fix needed:
Change this:
font-family: 'Merriweather', ;

To this:
font-family: 'Merriweather', serif;

The serif portion is the fail-over font in case it can't find Merriweather.
Test it in this snippet:

  <link href=" https://fonts.googleapis.com/css?family=Merriweather&display=swap" rel="stylesheet" />

Test

You can also just apply the font-family style to the  tag and all child elements will inherit that font-family.

A: *

*Check fonts link:

*

*if you use @font-face rule check link to the folder with fonts and be sure that font files is present in this folder, also check fonts name in @font-face rule and in font-family they must be equal;

*if you use CDN - check the link to the CDN;

*Open Dev Tools in your browser(Ctrl(Command) + Shift + I) and in the tab Network check whether your font is downloaded or not: https://prnt.sc/r9x8ab;


text:
Q: Two check boxes in one data grid view column How to add two checkboxes in the data grid view column?

A: OK, that's not the simple task. But can be done :)
Simple user control is not the solution.
You have to create proper template for a cell and then create a control (may be user control) with proper interface.
First, you have to create new control type. I think that it can be simple usercontrol with some additional stuff:
class CheckBoxesState
{
    public bool Ch1Checked {get;set;}
    public bool Ch2Checked {get;set;}
}

class CheckBoxesControl: UserControl, IDataGridViewEditingControl
{
    DataGridView dataGridView;
    private bool valueChanged = false;
    int rowIndex;
    CheckBoxesState state;

    // Implements the IDataGridViewEditingControl.EditingControlFormattedValue
// property.
    public object EditingControlFormattedValue
    {
        get { return state; }
        set
        {
            if(value is CheckBoxesState)
            {
                state = value;
                //change checkboxes state in you user control
            }
        }
    }

    // Implements the
    // IDataGridViewEditingControl.GetEditingControlFormattedValue method.
    public object GetEditingControlFormattedValue(
    DataGridViewDataErrorContexts context)
    {
        return EditingControlFormattedValue;
    }

    // Implements the
    // IDataGridViewEditingControl.ApplyCellStyleToEditingControl method.
    public void ApplyCellStyleToEditingControl(
        DataGridViewCellStyle dataGridViewCellStyle)
    {
        this.Font = dataGridViewCellStyle.Font;
    }

    // Implements the IDataGridViewEditingControl.EditingControlRowIndex
    // property.
    public int EditingControlRowIndex
    {
        get
        {
            return rowIndex;
        }
        set
        {
            rowIndex = value;
        }
    }

    // Implements the IDataGridViewEditingControl.EditingControlWantsInputKey
    // method.
    public bool EditingControlWantsInputKey(
        Keys key, bool dataGridViewWantsInputKey)
    {
        return !dataGridViewWantsInputKey;
    }

    // Implements the IDataGridViewEditingControl.PrepareEditingControlForEdit
    // method.
    public void PrepareEditingControlForEdit(bool selectAll)
    {
        // No preparation needs to be done.
    }

    // Implements the IDataGridViewEditingControl
    // .RepositionEditingControlOnValueChange property.
    public bool RepositionEditingControlOnValueChange
    {
        get
        {
            return false;
        }
    }

    // Implements the IDataGridViewEditingControl
    // .EditingControlDataGridView property.
    public DataGridView EditingControlDataGridView
    {
        get
        {
            return dataGridView;
        }
        set
        {
            dataGridView = value;
        }
    }

    // Implements the IDataGridViewEditingControl
    // .EditingControlValueChanged property.
    public bool EditingControlValueChanged
    {
        get
        {
            return valueChanged;
        }
        set
        {
            valueChanged = value;
        }
    }

    // Implements the IDataGridViewEditingControl
    // .EditingPanelCursor property.
    public Cursor EditingPanelCursor
    {
        get
        {
            return base.Cursor;
        }
    }

    protected override void OnValueChanged(EventArgs eventargs)
    {
        // Notify the DataGridView that the contents of the cell
        // have changed.
        valueChanged = true;
        this.EditingControlDataGridView.NotifyCurrentCellDirty(true);
        base.OnValueChanged(eventargs);
    }
}

Next, you have to create new cell type.
public class CheckBoxesCell : DataGridViewCell
{

    public CheckBoxesCell()
        : base()
    {

    }

    public override Type EditType
    {
        get
        {
        // Return the type of the editing control that cell uses.
        return typeof(CheckBoxesControl);
        }
    }

    public override Type ValueType
    {
        get
        {
            // Return the type of the value that Cell contains.

            return typeof(CheckBoxesState);
        }
    }

    public override object DefaultNewRowValue
    {
        get
        {
            // Use the current date and time as the default value.

            return new CheckBoxesState();
        }
    }
}

The next thing you should create is new column type for data grid:
public class CheckBoxesColumn : DataGridViewColumn
{
    public CheckBoxesColumn() : base(new CheckBoxesCell())
    {
    }

    public override DataGridViewCell CellTemplate
    {
        get
        {
            return base.CellTemplate;
        }
        set
        {
        // Ensure that the cell used for the template is a CheckBoxesCell.
            if (value != null &&
                !value.GetType().IsAssignableFrom(typeof(CheckBoxesCell)))
            {
                throw new InvalidCastException("Must be a CheckBoxesCell");
            }
            base.CellTemplate = value;
        }
    }
}

And that should be all.
Now you only have to create CheckBoxesColumn and add it to your datagrid.
Everything is shown here: https://learn.microsoft.com/en-us/dotnet/framework/winforms/controls/how-to-host-controls-in-windows-forms-datagridview-cells


text:
Q: Seagate HDD successfully boots a to a new Windows 7 installation but wont boot a new Linux installation? I have wanted to install Linux (specifically Linux mint x64 maya) on an older Seagate HDD (Model: ST3160812AS, Serial: 5LSDP211, Firmware: 3.AAE) I had acquired.
With various Linux distributions installations (Mint, LMDE and Ubuntu 12.04) I get the error directly at boot:
Loading operating system...
Read error
I have tried multiple partition settings using the installers and Gparted but each produces the same error.
I carried out a CHKDSK on windows with no errors received.
I also carried out a test on Linux using the disk manager on Mint.
No test yet has show me any problem with the drive except when I booted in Daraks boot and nuke. It suggested the disk may have dead sectors and denied to load Daraks boot and nuke any further.
I was surprised when a single install of Windows 7 can successfully boot without problems.
I hope someone can point me in the right direction as to why Linux wont boot but windows will?
Is there a way to fix such an issue?
Please note:
I currently have 5 other HDD's with other Operating systems installed. All work well and do not have any problems.
I have also ran a memory test on my ram using memtest86+ (no errors were found)

A: Very weird! I ended up fixing it by changing the bios settings as Peter suggested.
To do this I changed my HDD mode to: IDE, once this was done I rebooted and installed Linux mint as usual to a single HDD.
After the installation was complete I was able to boot into Linux using both IDE mode and then ACHI mode aswell.


text:
Q: WebView not showing results If I am typing incorrect query, like this: dfgkjdfkjg in address bar I want my WebView to show user a page as Chrome does:

But it just not loading a url with this query and stays on the home page.
My query looks like this: https://www.google.com/search?q=dfgkjdfkjg.
My code looks like this: webView.loadUrl("https://www.google.com/search?q=dfgkjdfkjg")
Thank you in advance for any help.

A: You can override onReceivedFunction and load custom page.
 @Override
    public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error){
          // Load custom error page as you want.
    }

You should look to the error codes in the below and catch them in the onReceivedError for wrong url.

WebViewClient.ERROR_AUTHENTICATION
WebViewClient.ERROR_BAD_URL
WebViewClient.ERROR_CONNECT
WebViewClient.ERROR_FAILED_SSL_HANDSHAKE
WebViewClient.ERROR_FILE
WebViewClient.ERROR_FILE_NOT_FOUND
WebViewClient.ERROR_HOST_LOOKUP
WebViewClient.ERROR_IO
WebViewClient.ERROR_PROXY_AUTHENTICATION
WebViewClient.ERROR_REDIRECT_LOOP
WebViewClient.ERROR_TIMEOUT
WebViewClient.ERROR_TOO_MANY_REQUESTS
WebViewClient.ERROR_UNKNOWN
WebViewClient.ERROR_UNSUPPORTED_AUTH_SCHEME
WebViewClient.ERROR_UNSUPPORTED_SCHEME


text:
Q: ggplot: why does order on x-axis not level instead of printing alphabetically? I have this plot

With
> str(a)
'data.frame':   150 obs. of  2 variables:
 $ study: Factor w/ 7 levels "A","S","H","D",..: 7 2 4 5 3 1 7 2 2 4 ...
 $ n    : Factor w/ 6 levels "N0","N1","N2a",..: 1 1 2 4 1 1 2 1 1 1 ...

I would like the x-axis to arrange by sample size, i.e. level = c("all", "S", "H", "B", "C", "A", "K", "D")
As you can see, the order is printed alphabetically.
I have tried specifying as ... aes(x=factor(nystudie, level=c(...), but that does not work. What am I doing wrong? I followed this post
library(tidyverse)
colsze <- c("#E1B930", "#2C77BF", "#E38072", "#6DBCC3", "grey40",  "black",   "#8B3A62")

 a %>%
  as_tibble() %>%
  mutate(nystudie=as.factor(study),
         n.seven=as.factor(n)) %>%
  bind_rows(., mutate(., nystudie="all")) %>%
  count(nystudie, n.seven, .drop=F) %>%
  ggplot(aes(x = factor(nystudie, level = c("all", "S", "H", "B", "C", "A", "K", "D")),
             n, color = n.seven, fill= n.seven, label=n))  +
  geom_col(position = position_dodge2(preserve = "single", padding = 0.1))+
  geom_text(aes(label=n),position = position_dodge2(0.9), vjust=-0.25, fontface=2, cex=4.5, show.legend = F) +
  scale_fill_manual(values = alpha(colsze, .2),
                    name="Stage", label=c("N0", "N1", "N2a", "N2b", "N2c", "N3")) +
  scale_color_manual(values = colsze,
                     name="Stage", label=c("N0", "N1", "N2a", "N2b", "N2c", "N3")) +
  scale_x_discrete(name = "", label=c("All\n(n=1,905)",
                                      "A\n(n=221)",
                                      "B\n(n=234)",
                                      "C\n(n=232)",
                                      "D\n(n=108)",
                                      "H\n(n=427)",
                                      "K\n(n=221)",
                                      "S\n(n=462)")) +
  scale_y_continuous(name="",
                     breaks=seq(0,950,100)) +
  coord_cartesian(ylim = c(0,950)) +
  guides(fill = guide_legend(nrow = 1)) + theme(axis.text.x = element_text(color = "grey20", size =15),
                                                legend.text=element_text(size=16), legend.title=element_text(size=16, face="bold"),
                                                legend.position="top")

Data sample
a <- structure(list(study = structure(c(7L, 2L, 4L, 5L, 3L, 1L, 7L,
2L, 2L, 4L, 4L, 6L, 2L, 5L, 3L, 7L, 1L, 1L, 2L, 6L, 1L, 3L, 2L,
7L, 2L, 2L, 6L, 6L, 6L, 2L, 1L, 2L, 6L, 1L, 2L, 2L, 3L, 4L, 2L,
3L, 2L, 5L, 2L, 3L, 6L, 5L, 3L, 2L, 4L, 3L, 5L, 6L, 2L, 7L, 2L,
3L, 3L, 3L, 7L, 7L, 3L, 4L, 1L, 1L, 2L, 2L, 6L, 2L, 3L, 2L, 3L,
2L, 1L, 2L, 3L, 5L, 3L, 1L, 1L, 1L, 7L, 4L, 3L, 2L, 4L, 3L, 3L,
3L, 2L, 6L, 7L, 3L, 2L, 2L, 6L, 2L, 2L, 6L, 7L, 3L, 3L, 3L, 6L,
2L, 2L, 7L, 7L, 1L, 1L, 6L, 3L, 3L, 7L, 1L, 2L, 7L, 1L, 1L, 7L,
4L, 4L, 4L, 2L, 3L, 3L, 6L, 1L, 4L, 6L, 3L, 5L, 5L, 3L, 3L, 7L,
5L, 3L, 6L, 3L, 5L, 2L, 3L, 7L, 6L, 2L, 1L, 6L, 5L, 1L, 6L), .Label = c("A",
"S", "H", "D", "K", "C", "B"), class = "factor"), n = structure(c(1L,
1L, 2L, 4L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 2L, 1L, 4L, 2L, 1L, 2L,
3L, 2L, 2L, 4L, 4L, 4L, 2L, 4L, 1L, 2L, 4L, 1L, 1L, 4L, 1L, 1L,
1L, 1L, 1L, 1L, 2L, 4L, 1L, 1L, 4L, 2L, 1L, 1L, 4L, 1L, 1L, 2L,
1L, 5L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 4L, 1L, 1L, 4L, 1L, 2L, 1L,
4L, 1L, 1L, 1L, 1L, 6L, 1L, 2L, 5L, 4L, 2L, 6L, 1L, 4L, 2L, 4L,
2L, 1L, 1L, 4L, 1L, 2L, 1L, 1L, 4L, 4L, 4L, 1L, 4L, 2L, 1L, 1L,
4L, 2L, 1L, 2L, 1L, 5L, 5L, 1L, 4L, 1L, 2L, 2L, 4L, 1L, 1L, 1L,
2L, 4L, 4L, 1L, 5L, 2L, 1L, 5L, 2L, 4L, 1L, 1L, 1L, 4L, 4L, 1L,
1L, 4L, 4L, 4L, 1L, 4L, 4L, 1L, 4L, 5L, 4L, 5L, 1L, 5L, 1L, 1L,
4L, 2L, 1L, 2L, 4L), .Label = c("N0", "N1", "N2a", "N2b", "N2c",
"N3"), class = "factor")), row.names = c(NA, -150L), class = "data.frame")

A: The levels are being changed again at scale_x_discrete step. Try :
library(dplyr)
library(ggplot2)

a %>%
  mutate(nystudie=as.factor(study),
         n.seven=as.factor(n)) %>%
  bind_rows(., mutate(., nystudie="all")) %>%
  count(nystudie, n.seven, .drop=F) %>%
  mutate(nystudie = factor(nystudie,
                           level = c("all", "S", "H", "B", "C", "A", "K", "D"),
                           labels = c("All\n(n=1,905)", "S\n(n=462)", "H\n(n=427)", "B\n(n=234)",
                                      "C\n(n=232)", "A\n(n=221)", "K\n(n=221)", "D\n(n=108)"))) %>%
  ggplot(aes(x = nystudie,
             n, color = n.seven, fill= n.seven, label=n))  +
  geom_col(position = position_dodge2(preserve = "single", padding = 0.1))+
  geom_text(aes(label=n),position = position_dodge2(0.9), vjust=-0.25, fontface=2, cex=4.5, show.legend = F) +
  scale_fill_manual(values = alpha(colsze, .2),
                    name="Stage", label=c("N0", "N1", "N2a", "N2b", "N2c", "N3")) +
  scale_color_manual(values = colsze,
                     name="Stage", label=c("N0", "N1", "N2a", "N2b", "N2c", "N3")) +
  scale_x_discrete(name = "") +
  scale_y_continuous(name="",
                     breaks=seq(0,950,100)) +
  coord_cartesian(ylim = c(0,950)) +
  guides(fill = guide_legend(nrow = 1)) +
  theme(axis.text.x = element_text(color = "grey20", size =15),
        legend.text=element_text(size=16),
        legend.title=element_text(size=16, face="bold"),
        legend.position="top")


text:
Q: Getting Chrome to display text files containing backspace characters How do I get Chrome to display a text file containing backspace characters?
I have a static text file on a server that contains backspace characters (ASCII code 08), and when I navigate the file's URL in Chrome (or Safari), the browser downloads the file to a folder instead of viewing the file's text in the browser window.
I've confirmed that the Content-type header is sent correctly, and if I remove the backspace characters, it works correctly again and displays in the browser.
I don't care if the browser shows an odd glyph or code where the backspace is, or if it dutifully removes characters preceding the backspaces, but I do want to view the file in the browser.
I have control of the server, so I can send custom headers if that helps. Also a browser plugin/extension would be okay.


text:
Q: Why ping outbound to gateway, but no other hosts, nor inbound I just setup a new 18.04 server install with one nic as DHCP from the gateway using netplan which appears as follows:
network:
    version: 2
    renderer: networkd
    ethernets:
        enp1s0:
            dhcp: true

I don't want to use NetworkManager as I will be assigning other statics, but this one is just trying to get access to the machine on the network. Problem is, when the machine boots, it seems to hang on:
"Starting Initial cloud-init job (pre-networking)..."

At this point, both lights on the NIC are inactive and I hit enter go continue.
I did set "network: {config: disabled}" in /etc/cloud/cloud.cfg.d/... file, but that didn't seem to do anything.
After it boots, enp1s0 is UP and it does have an IP assigned, but I can only ping the gateway 192.168.10.1, but cannot ping any of the other computers on the network, and the gateway cannot ping back to this machine.
Firewalls are disabled.
Thoughts?
Update:
$ sudo journalctl /usr/sbin/dnsmasq
-- No entries ---
$ ip route
192.168.10.0/24 dev enp1s0 proto dhcp src 192.168.10.206 metric 100
192.168.10.0/24 dev enp0s31f6 proto kernel scope link src 192.168.10.199
192.168.10.0/24/dev enp1s0 proto kernel scope link src 192.168.10.206
192.168.10.1 dev enp1s0 proto dhcp scope link src 192168.10.206 metric 100

A: You have routes for the 192.168.10.0/24 subnet going out THREE interfaces (enp1s0, enp0s31f6 and enp1s0 again), plus a route for 192.168.10.1 to enp1s0. You have THREE IP addresses on enp1s0, and NO default route.
What are you trying to do?
I don't understand what "I don't want to use NetworkManager as I will be assigning other statics, but this one is just trying to get access to the machine on the network" means, or why you don't want to use NetworkManager, or why a "static" (whatever that is) is trying to get access.
Pretend you are a TCP/IP packet with a destination in the 192.168.10.0/24 subnet. Which interface do you use?
Pretend you are a TCP/IP packet with a destination NOT in the 192.168.10.0/24 subnet (e.g. 8.8.8.8). Which interface do you use?
I'm sorry this didn't resolve your problem, but you really need to suck back, reload and start again. Read man ip;man ip-route to start.


text:
Q: Hit Test rotated view I need to write a function that will return true if given point is inside any of subviews hierarchy of view A. A can be transformed (rotated), and has clipToBounds disabled. It's subviews also can have clipToBounds disabled, and true must returned if any of subviews is tapped. I have something that almost works, but fails when view is rotated. Can someone suggest how to fix this?
extension UIView {

    func hitTestIgnoringBounds(_ point: CGPoint) -> Bool {

        guard !isHidden && alpha > 0 else { return false }

        let subPoint = frame.origin - point
        return frame.contains(point) || subviews.contains {
            return $0.hitTestIgnoringBounds(subPoint)
        }

    }

}

A: I knew it should have been easy, but could not make it work. I made a stupid mistake - my code was adding sublayers instead of subviews. When I switched to subviews, everything worked fine:
func viewOrSubviewsContaintPoint(_ point: CGPoint) -> Bool {
    let convertedPoint = convert(point, from: superview)
    let containsPoint = bounds.contains(convertedPoint)

    var subviewsContainsPoint: Bool {
        return subviews.contains { $0.viewOrSubviewsContaintPoint(convertedPoint) }
    }

    return containsPoint || subviewsContainsPoint
}


text:
Q: Send email confirmation after registration django Im sending an email confirmation after a registration process in my django application. I need to find out for security reasons how can i validate the code im sending in the url without adding a new code field in the user model. So far im sending a random code in the url and the username which is validated but not the code.
Registration VIEW
def registrar_usuario_view(request):
alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
code = ''.join(random.choice(alphabet) for i in range(16))
print code
if request.method == 'POST':
    f = RegisterForm(request.POST)
    if f.is_valid():
        usuario = f.cleaned_data['usuario']
        email = f.cleaned_data['email']
        clave = f.cleaned_data['clave']
        confirmar_clave = f.cleaned_data['confirmar_clave']
        captcha = f.cleaned_data['captcha']
        u = User.objects.create_user(username = usuario, email = email, password = clave)
        u.is_active = False
        u.save()
        # Mandamos mail de activacion
        to = email
        html_content = """
Bienvenido Sr/a: %s

Para confirmar su registro en el sitio Margonari Servicios Inmobiliarios le solicitamos haga click en el siguiente
        enlace de confirmacion

Gracias por formar parte de Margonari Servicios Inmobiliarios.

        Este es un mensaje enviado automaticamente. Por favor no responda a esta direccion de mail."""%(usuario, code, usuario)
        msg = EmailMultiAlternatives('Administracion Margonari', html_content, 'from@server.com', [to])
        msg.attach_alternative(html_content, 'text/html') #Definimos el contenido como html
        msg.send() #Enviamos el correo

        messages.add_message(request, messages.SUCCESS, """Los datos han sido ingresados correctamente. Le enviamos un correo de confirmacion
            a la direccion que nos proporciono. Por favor verifique su casilla de correo no deseado. Muchas gracias.""")
        ctx = {'form':f}
        return render_to_response('users/registrar_usuario.html', ctx, context_instance = RequestContext(request))
    else:
        ctx = {'form':f}
        return render_to_response('users/registrar_usuario.html', ctx, context_instance = RequestContext(request))

f = RegisterForm()
ctx = {'form':f}
return render_to_response('users/registrar_usuario.html', ctx, context_instance =    RequestContext(request))

Confirmation VIEW
def confirmacion_view(request, code, user):
user = User.objects.get(username = user)
user.is_active = True
user.save()
return HttpResponseRedirect('/')

URL
url(r'^confirmacion/(?P.*)/(?P<user>.*)/$', 'confirmacion_view', name = 'vista_confirmacion'),

A: Django provides a token creation mechanism, there is no need to reinvent the wheel.
Since I don't use function based views and the point here is not to refactor your code (I would do it in CBVs anyway), I will just output a sample on how you can use it.
from django.contrib.auth.tokens import default_token_generator
from django.utils.http import urlsafe_base64_encode
from django.utils.encoding import force_bytes

new_user = User.objects.create_user(username=usuario,
                                    email=email,
                                    password=clave)
new_user.save()
token = default_token_generator.make_token(new_user)
uid = urlsafe_base64_encode(force_bytes(new_user.pk))

You can then email the token to the user, the token url should look like:
url(r'^users/validate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
    activationview,
    name='user-activation-link')

Somewhere in your activationview:
from django import http

uidb64 = request.GET.get('uidb64')
token = request.GET.get('token')

if uidb64 is not None and token is not None:
    from django.utils.http import urlsafe_base64_decode
    uid = urlsafe_base64_decode(uidb64)
    try:
        from django.contrib.auth import get_user_model
        from django.contrib.auth.tokens import default_token_generator
        user_model = get_user_model()
        user = user_model.objects.get(pk=uid)
        if default_token_generator.check_token(user, token) and user.is_active == 0:
            # Do success stuff...
            return http.HttpResponseRedirect(a_success_url)
    except:
        pass

return http.HttpResponseRedirect(a_failure_url)


text:
Q: Change wordpress meta tag description using WP functions I do apprecciate this may sound like the usual question, but it is not. Just to let you understand I do not need to install one of the many SEO Plugin and change it on the box before content is published.
My scenario is the following:
I have a page which Querystring may change the content shown on page and I'd like to do the same with meta description and title if that would the the case.
In a normal template file I would probably look for the querystring and stick an if condition. Problem is that template is not mine and when it will be updated my changes will be lost. So I thought to a slightly more complicate solution.
Using the Wordpress php_exec plugin I will embed the php lines in the content section delegating to them the task, but using normal Wordpress core functions. This is a must, because I can't use a simple if condition in the content area, not without having two meta descriptions or title in the page, with the latter added in the wrong place.
So what I need to do is understanding how Wordpress is adding both the meta in the final HTML.
Is this something related to the add_action('wp_head', ... something here)?
As additional info, I am not using Yoast SEO plugin, so I can't rely on any of his additional function.
Thanks for your help Andrea

A: I don't understand your attempt to use PHP_Exec, especially by embedding it in the content section of the page. That is going to run much too late to alter anything in the <head> of the document. Here is the problem you are facing, starting from what looks to be your primary question:

So what I need to do is understanding how Wordpress is adding both the
  meta in the final HTML. Is this something related to the
  add_action('wp_head', ... something here)?

WordPress doesn't add the meta tags to the <head> of your document, at least not most of them. It does add a few things-- the admin bar stylesheet, meta generator, some feed stuff-- but not the title, not the description, not most of the meaty bits. Your theme does that, and may or may not do it in a way that you can manipulate easily. Ideally, you can use  a few different hooks-- wp_head, the_title, couple of others maybe-- to add and subtract content to/from the <head> part of the document but some themes do not make it that easy. Sometimes things are hard coded into the theme.
Assuming everything is in your favor you can alter the title with:
function alter_title_wpse_82196($title) {
  global $_GET;
  // if condition for you parameter
  if (...) {
     $title = 'whatever';
  }
  return $title;
}
add_filter('the_title','alter_title_wpse_82196');

And add the description with something similar.
function add_descr_wpse_82196() {
  global $_GET;
  // if condition for you parameter
  if (...) {
     $description = 'properly constructed meta description tag';
  }
  echo $description;
}
add_action('wp_head','add_descr_wpse_82196');

But that is a rough guide. Theme peculiarities may cause trouble.


text:
Q: Pass property of generic class as parameter in AutoMoq What I'm trying to do is generalize making repositories using AutoFixture and Moq. I have a method called 'add' that adds fake records to a list. The list is called records and is global to the class. The generic M is a model to be mocked. The method returns 'this' so the method can be chained.
public Repo<M> add(string prop, string val) {
    var a = fixture.Build<M>().With(m => m.GetProperty(prop), val).Create();
    records.Add(a);
    return this;
}

with the extension class (I found this searching SO):
public static class MyExtensions
{
    public static object GetProperty<T>(this T obj, string name) where T : class
    {
        Type t = typeof(T);
        return t.GetProperty(name).GetValue(obj, null);
    }
}

The error I'm getting is "ArgumentException occurred in Ploeh.AutoFixture.dll".
My question is: How can one pass a property of a generic object in as a parameter on a method when the model is unknown at compile time?

A: With method requires Expression<Func<T, TProperty>> parameter not PropertyInfo.
You can change your add method to take Expression<Func<T, TProperty>> instead of string :
public Repo<M> add<T>(Expression<Func<M, T>> propertyPicker, T val)
{
   var a = fixture.Build<M>().With(propertyPicker, val).Create();
   records.Add(a);
   return this;
}

and this is the usage :
add(foo => foo.Name, "abc");

A: Many thanks to Arkadiusz for the correct answer. I just want to add this method I added (inspired by several SO posts) to create the Expression so that the usage would be:
add("username","me")
private Expression<Func<M,T>> makeExpression<T>(string prop, T val)
{
    var m = Expression.Parameter(typeof(M), "m");
    Expression columnExpr = Expression.Property(m,typeof(M).GetProperty(prop));

    return Expression.Lambda<Func<M, T>>(columnExpr, m);
}

Then, in the add method, I changed propertyPicker to makeExpression(property,val), property being the name of the property as a string.


text:
Q: Can not save changes to properties.settings I'm trying to use properties.settings for the first time in a C# WPF project.
I have this code:
Settings.Default.comPort = "";
Settings.Default.baudRate = 9600;
Settings.Default.startUp = false;
Settings.Default.taskBar = true;
Settings.Default.desktopNotif = false;
Settings.Default.reset = false;
Settings.Default.Save();

But it didn't work and the settings wasn't saved. So I added this line
Console.WriteLine("test");

after that part, to check if it goes through the code, and it executed fine.
So It seems that it just jumps over those lines without execution or even throwing any exceptions.

A: Thanks to Panagiotis Kanavos I eventually found the problem. The code was correct, but when the program runs inside the visual studio, every time the settings are being overwritten. After building, I ran the .exe file in the bin/release folder and it worked just fine.


text:
Q: Why is %s faster than %d for integer substitution in python? I am going through the examples mentioned here, and am looking at this example. I ran a sample example below on ipython, and the result is consistent, i.e., "%d" is slower than "%s":
In [1]: def m1():
   ...:     return "%d" % (2*3/5)

In [2]: def m2():
   ...:     return "%s" % (2*3/5)

In [4]: %timeit m1()
1000000 loops, best of 3: 529 ns per loop

In [5]: %timeit m2()
1000000 loops, best of 3: 192 ns per loop

In [6]: from dis import dis

In [7]: dis(m1)
  2           0 LOAD_CONST               1 ('%d')
              3 LOAD_CONST               5 (6)
              6 LOAD_CONST               4 (5)
              9 BINARY_DIVIDE
             10 BINARY_MODULO
             11 RETURN_VALUE

In [9]: dis(m2)
  2           0 LOAD_CONST               1 ('%s')
              3 LOAD_CONST               5 (6)
              6 LOAD_CONST               4 (5)
              9 BINARY_DIVIDE
             10 BINARY_MODULO
             11 RETURN_VALUE

Both the code blocks are similar, and even the output of disassembler is same, so why is "%s" faster than "%d"?

A: This was discussed in hacker news, I am just formatting @nikital answer for SO:
The function PyString_Format in Objects/stringobject.c does the formatting for the % operator. For %s it calls _PyObject_Str which in turn calls str() on the object. For %d it calls formatint (located in the same file).
The str() implementation for ints is in int_to_decimal_string in (Objects/intobject.c)  and it's incredibly simple:
do {
    *--p = '0' + (char)(absn % 10);
    absn /= 10;
} while (absn);

The code for formatint is way more complex, and it contains two call to the native snprintf:
PyOS_snprintf(fmt, sizeof(fmt), "%s%%%s.%dl%c",
              sign, (flags&F_ALT) ? "#" : "",
              prec, type);
// ...
PyOS_snprintf(buf, buflen, fmt, -x);

The native snprintf is heavier because it handles precision, zero-padding and stuff like that.
I believe this is why %d is slower. %s is a straight "divide-by-10-and-subtract" loop while %d are two library calls to the full-blown sprintf. However I didn't actually profile the code because I don't have a debug build, so I might be completely wrong.


text:
Q: Conecting AWS Lambda to Redshift - Times out after 60 seconds I created an AWS Lambda function that:

*

*logs onto Redshift via JDBC URL

*runs a query

Locally, using Node, I can successfully connect to the Redshift instance via JDBC, and execute a query.
var conString = "postgresql://USER_NAME:PASSWORD@JDBC_URL";
var client = new pg.Client(conString);
client.connect(function(err) {
  if(err) {

      console.log('could not connect to redshift', err);

  }

// omitted due to above error

However, when I execute the function on AWS Lambda (where it's wrapped in a async#waterfall block), AWS Cloudwatch logs tells me that the AWS Lambda function timed out after 60 seconds.
Any ideas on why my function is not able to connect?

A: I find it's either you open your Redshift security group public to all sources, or none. Because a Lambda function isn't running on a fixed address or even a fixed range of IP addresses, which is completely transparent to users (AKA server-less).
I just saw Amazon announced the new Lambda feature to support VPC yesterday. I guess if we can run a Redshift cluster in a VPC, this could solve the problem.

A: If you are using serverless-framework v1.5.0, you should add:

iamRoleStatements:
    - Effect: Allow
      Action:
        - ec2:CreateNetworkInterface
      Resource: '*'
    - Effect: Allow
      Action:
        - ec2:DeleteNetworkInterface
        - ec2:DescribeNetworkInterfaces
      Resource: 'arn:aws:ec2:${self:provider.region}:*:network-interface/*'

Also should add all securityGroupIds to Inbounds Rules, like below:

More info: https://serverless.com/framework/docs/providers/aws/guide/functions/#vpc-configuration


text:
Q: ReferenceError: "$" is not defined in  I am trying to call a javascript function from java code.
This is my java code
public static void main(String[] args) throws Exception{

  ScriptEngineManager manager = new ScriptEngineManager();
  ScriptEngine engine = manager.getEngineByName("JavaScript");
  // read script file
  engine.eval(Files.newBufferedReader(Paths.get("f:/workspace/timsnew/WebContent/js/ipam/report_utils.js"), StandardCharsets.UTF_8));

  Invocable inv = (Invocable) engine;
  // call function from script file
  inv.invokeFunction("generatePdf", "abc@gmail.com","cloudInstanceProvisioningTemplAudit","cloudInstanceProvisioningTemplAuditGrid","Cloud Instance Provisioning Template Audit","a3","l","shahzad","hussain");

}

This is my JavaScript code
function generatePdf(email_id,reporttype,gridId,mailsHeading,pagesize,pageformat,contact_first_name,contact_last_name){

  //var source=('#'+gridId)[0];
  //**loadingPopup**("Sending Email to the selected contact."+'

'+"Please Wait...");
  tableToJson(**$**('#'+gridId).get(0),mailsHeading,pagesize,pageformat,contact_first_name,contact_last_name);
}

I am also getting error for loadingPopup is not defined.
Below error is seen
Exception in thread "main" javax.script.ScriptException: ReferenceError: "$" is not defined in <eval> at line number 558
    at jdk.nashorn.api.scripting.NashornScriptEngine.throwAsScriptException(NashornScriptEngine.java:467)

How do I fix this issue?

A: So in that case use vanilla javascript. You should replace this:
** $ ** ('#' + gridId).get(0)

with:
document.querySelector('#' + gridId)

I am not familiar with this Java syntax, but previous snippet is equivalent to $('#' + gridId).get(0) when jQuery is loaded.


text:
Q: Is it a code smell if you are frequently creating an object just to call a method on it I inherited a code base where there is a lot of code that goes something like this:
SomeDataAdapter sda = new SomeDataAdapter();
sda.UpdateData(DataTable updateData);

And then sda is never used again.
Is that a code smell that indicates that those methods should actually be static class methods instead?

A: I think this problem goes even deeper than that. Even if you do refactor it into a static method, then you get code where you call single static method all over the place. Which in my opinion is code smell in itself. It might indicate you are missing some important abstraction.  Maybe you want to create a code that will do some pre and post-processing while allowing you to change what happens in between. That pre and post-processing will contain the common calls while the in between will depend on concrete implementation.

A: Kind of. It usually means you want to pass a function around and your language of choice won't let you. It's kind of clumsy and inelegant, but if you're stuck in a language without first-class functions, there's not a whole lot you can do.
If none of those objects are getting passed as arguments to other functions, you could turn them into static methods and nothing would change.

A: I would consider it an architecture smell in that UpdateData probably should belong to a 'service' class.
Where the data is an Apple.
Where AppleAdapter is service/business-intelligence class.
Where AppleService is a Singleton reference to an AppleAdapter that exists outside of the current method.
private static volatile AppleAdapter _appleService = null;
private static object _appleServiceLock = new object();
private AppleAdapter AppleService
{
    get
    {
        if (_appleService == null)
        {
            lock (_appleServiceLock)
            {
                if (_appleService == null)
                    _appleService = new AppleAdapter();
            }
        }
        return _appleService;
    }
}

public SomeAppleRelatedMethod(Apple apple)
{
    AppleService.UpdateData(apple);
}

I don't think what you are doing is wrong necessarily but if SomeDataAdapter does indeed represent some kind of stateless business service, then a singleton would be the best practice for it.
Hope that helps! The example provided is fancy way to ensure no contention of the _appleService if it happened to be both null and accessed at exactly the same time by two or more threads.
You know what? If SomeDataAdapter is an ADO IDbDataAdapter (which it almost certainly is), disregard this entire response!
:P
I don't have permission to add a comment to the original question, but if you could specify where this code exists.
If this code represents a custom implementation of an IDbDataAdapter, and UpdateData is creating an IDbConnection, IDbCommand, and wiring it all up behind the scenes, then no I wouldn't consider that a code smell because now we're talking about streams and other things that need to be disposed of when we're done using them.

A: If holding state makes a given class more utilitarian, functional … re-usable then no. For some reason the command design pattern comes to mind; that reason certainly is not a desire to have Robert Harvey drown.

A: Define "frequently." How often do you instantiate the object? A lot - probably not?
There are likely bigger problems to worry about in your system. Going static will communicate more clearly to the programmer that internal state of the object isn't changing - great.
If state is being messed with though, and you have to start making other things static to make the first thing static, then you have to ask what parts need to be static and what parts don't.
Yes it's a code smell, just a small one.

A: Make it a static method and move on. There is nothing wrong with static methods. Once a pattern of use emerges then you can worry about abstracting the pattern.

A: The smell here is that this is procedural code wrapped (minimally) in objects.
There must be a reason why you want to perform that operation on the data table, but rather than modelling that operation with other related operations that share some semantics (i.e. have a common meaning), the author just spun up a new procedure inside a new class & called it.
In a functional language, that's how you'd do things ;) but in the OO paradigm, you'd want to model some abstraction that included that operation. Then you'd use OO techniques to flesh out that model and provide a set of related operations that preserve some semantics.
So the main smell here is that the author is using classes, probably because the compiler requires it, without organizing operations into a conceptual model.
BTW watch out anytime you see the program being modeled instead of the problem space. It's a sign that the design could benefit from more thought. In other words, watch out for classes all being "xAdaptor" and "xHandler" and "xUtility", and usually tied to an anemic domain model. It means someone is just bundling code up for convenience, as opposed to actually modelling the concepts they want to implement.


text:
Q: Logback rolling file appender - can I zip many logs into one file? My current logback config looks like this:
<appender name="rolling" class="ch.qos.logback.core.rolling.RollingFileAppender">
  <file>${log.dir}/${log.package}.log</file>
  <encoder>
    <Pattern>${log.pattern}</Pattern>
  </encoder>
  <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
    <fileNamePattern>${log.dir}/${log.package}.%d{yyyy-MM-dd}.%i.log.zip</fileNamePattern>
    <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
      <!-- or whenever the file size reaches 1MB. -->
      <maxFileSize>1MB</maxFileSize>
    </timeBasedFileNamingAndTriggeringPolicy>
    <!-- Keep no more than 3 months data. -->
    <maxHistory>90</maxHistory>
    <cleanHistoryOnStart>true</cleanHistoryOnStart>
  </rollingPolicy>
</appender>

This works fine but irritatingly creates multiple zip file ...1.zip ...2.zip etc.
Is there any way I can specify the zip file name as ${log.dir}/${log.package}.%d{yyyy-MM-dd}.log.zip but the name of the files in the zip file as ${log.dir}/${log.package}.%i.log? I.e. make one zip file per day but each time the file reaches 1mb I zip it as ....1.log, ...2.log etc.

A: Yes you can add multiple files into a zip file using rollingfileappender with FixedWindowRollingPolicy.
<appender name="ErrorLogs"
        class="ch.qos.logback.core.rolling.RollingFileAppender">
        <target>System.err</target>
        <file>${log_location}{Error_filename}</file>

        <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
            <fileNamePattern>${log_location}{ERR_Zip}</fileNamePattern>
            <minIndex>1</minIndex>
            <maxIndex>3</maxIndex>
        </rollingPolicy>
        <triggeringPolicy
            class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
            <maxFileSize>${maxFileSize}</maxFileSize>
        </triggeringPolicy>
        <encoder>
            <pattern>${Default_Pattern}</pattern>
        </encoder>
    </appender>

since you cannot use both timebased rolling and sizebased rolling my suggestion would be to set high value for maxfilesize so that neither of these constraint can be minimalised


text:
Q: Authentication failure in onedrive I am getting Authentication Failure message to login to OneDrive. Here Is My Code:
public async static void Login()
{
    try
    {
        var scopes = new[] {
          "onedrive.readwrite",
          "onedrive.appfolder",
          "wl.signin"
    };

        _client = Microsoft.OneDrive.Sdk.OneDriveClient.GetMicrosoftAccountClient("d5f4ce5f-116a-4b77-a5a7-bd81802cdc7e","urn:ietf:wg:oauth:2.0:oob", scopes, null, null, null);
        OnedriveClient._client = _client;
        var session = await _client.AuthenticateAsync();
       // AppSettings.SkyDriveLogin = true;

        var AccessToken = _client.AuthenticationProvider.CurrentAccountSession.AccessToken;
        //REST API to request info about the signed-in user
        var uri = new Uri($"https://apis.live.net/v5.0/me?access_token={AccessToken}");

Here Is My Error:


text:
Q: Examples of UI heavy Object Oriented Javascript apps I'm fairly new developer who's been using Javascript in procedural way for nearly a year. In the company I'm working, we develop UI rich web apps with lots of interactions (dropdowns, sliders, modals, animations). I've noticed, that when project gets bigger it turns out to unmaintainable mess.
I've come to conclusion that it would be great to start developing apps in object oriented way, but I cannot find any good tutorials on how to do it. All I can find is some basic examples with Cat extending Animal object and so on.
I'd like to ask you for some github links to open source projects with lots of UI elements which uses Object Oriented Javascript. That way I can get a grasp of how it's supposed to be done correctly. Also it would be ideal, if it was pre ES6 as our projects are written in ES5.
Thanks in advance


text:
Q: What does the throbber speed indicate in Chrome and Firefox? Based on a lifetime of using web browsers, I expect that when a browser has an active throbber, it's downloading a page.  I've never seen multiple throbbers, though, and I just noticed that Chrome has (at least) two.
Out of five open tabs, three were static and just sitting open in the background, so they displayed favicons as expected.  The other two were loading, but one had a slow counter-clockwise throbber while the other had a fast clockwise throbber.  What's the difference between the two (and any others that may exist)?
Update:
Firefox 4 has been released, and it has the same behavior (or at least a similar-looking behavior). I still haven't found documentation.

A: I've always assumed that the slow anti-clockwise throbber was indicating that an http request had been sent, and once data started to be received back it changed to the faster clockwise version.
Multiple tabs, multiple requests, hence separate throbbers.

A: Here's what I think it's like
Backwards:
Chrome: "hey Wikipedia, I want to visit your page"
Wikipedia: notices Chrome's call
Goes forward
Wikipedia: Here is the page Chrome


text:
Q: how can i change my checkout button? Good day! I'm a newbie in magento 2, i would like to change my placeorder that whenever i click that button.  . It should routed me in my dragonpay(Gcash) with provided merchant ID and Password and auto get the order price. instead here
Hope someone will help me. thank you


text:
Q: Error 91 in VBA using classes I'm currently trying to implement a Clark & Wright Savings Heurisitc in VBA, but I'm currently facing some problem. I'm fairly new to VBA, and this error (91) keeps apearing on similar situations, which lead me to believe I'm missing some crucial knowledge. Next I present you the code:
    Public Sub CWsavings()

Dim i As Integer
Dim j As Integer
Dim k As Integer
Dim aux As Integer
Dim d As Integer
Dim r As Integer

Dim Cu(200) As customer
Dim De(12) As Depot

For i = 1 To 200

    Set Cu(i) = New customer

    Cu(i).custID = i
     Cu(i).longitude = ThisWorkbook.Sheets("Folha1").Cells(i + 1, 2)
     Cu(i).latitude = ThisWorkbook.Sheets("Folha1").Cells(i + 1, 3)
     Cu(i).lt = ThisWorkbook.Sheets("Folha1").Cells(i + 1, 4)
     Cu(i).et = ThisWorkbook.Sheets("Folha1").Cells(i + 1, 5)
     Cu(i).weekdemand = ThisWorkbook.Sheets("Folha1").Cells(i + 1, 6)
     Cu(i).peakdemand = ThisWorkbook.Sheets("Folha1").Cells(i + 1, 7)
     Cu(i).D1 = ThisWorkbook.Sheets("Folha1").Cells(i + 1, 8)
     Cu(i).D2 = ThisWorkbook.Sheets("Folha1").Cells(i + 1, 9)
    Next i

For j = 1 To 12

    Set De(j) = New Depot

    De(j).depotID = j
    De(j).Dname = ThisWorkbook.Sheets("Folha1").Cells(i + 1, 13)
    De(j).latitude = ThisWorkbook.Sheets("Folha1").Cells(i + 1, 14)
    De(j).longitude = ThisWorkbook.Sheets("Folha1").Cells(i + 1, 15)
    De(j).ncust = ThisWorkbook.Sheets("Results").Cells(j, 7)
    De(j).nroute = 0

    For k = 1 To De(j).ncust
        aux = ThisWorkbook.Sheets("Results").Cells(j + 1, 10 + k)
       Call De(j).SetCustomer(Cu(aux), k)
    Next k

Next j

For d = 1 To 12

    Dim M(30, 30) As Double
    Dim maxsav As Double
    Dim maxpos(2) As Integer
    Dim connorder(676, 2) 'order of connections for routing
    Dim it As Integer

    it = 0

For i = 1 To De(d).ncust
    For j = 1 To De(d).ncust
      M(i, j) = CalcSavings(De(d), De(d).customer(i), De(d).customer(j))   ' error here
    Next j
Next i

itbegin:

    maxsav = 0
    maxpos(1) = 0
    maxpos(2) = 0

    For i = 1 To De(d).ncust
        For j = 1 To De(d).ncust
            If i <> j Then
                If M(i, j) > maxsav Then
                    maxsav = M(i, j)
                    maxpos(1) = i
                    maxpos(j) = j
                End If
            End If
        Next j
    Next i

    it = it + 1

    connorder(it, 1) = maxpos(1)
    connorder(it, 2) = maxpos(2)

    If it < De(d).ncust * De(d).ncust - ncust Then
        M(maxpos(1), maxpos(2)) = 0

        GoTo itbegin
    End If
Next d

End Sub

Public Function CalcSavings(d As Depot, C1 As customer, C2 As customer)

Dim id As Double
Dim dj As Double
Dim ij As Double

id = DeptDist(C1, d)
dj = DeptDist(C2, d)
ij = CustDist(C1, C2)

CalcSavings = id + dj - ij

End Function

The class Depot:
        Public depotID As Integer
Public Dname As String
Public latitude As Double
Public longitude As Double
Private customers(200) As customer
Public ncust As Integer
Private routes(500) As route
Public nroute As Integer

Public Sub addcust(C As customer)

    ncust = ncust + 1
    Set customers(ncust) = C

End Sub

Public Sub addroute(R As route)

    nroute = Me.nroute + 1
    Set routes(Me.nroute) = R

End Sub

Public Property Get customer(i As Integer) As customer

    customer = customers(i)

End Property

Public Sub SetCustomer(C As customer, i As Integer)

   Set customers(i) = C

End Sub

Public Property Get route(i As Integer) As route

    route = routes(i)

End Property

Public Sub SetRoute(R As route, i As Integer)

   Set routes(i) = R

End Sub

(Class depot Updated)
And the class Customer:
Public custID As Integer
Public latitude As Double
Public longitude As Double
Public lt As Double
Public et As Double
Public weekdemand As Integer
Public peakdemand As Integer
Public D1 As Integer
Public D2 As Integer

I'm sorry for the long post, any help would be appreciated.

A: Final answer...
VERY ODDLY, (not that odd, when you really look at it, but) you need to use Set even in your Get properties. I guess the reason behind this is because you're returning an object, and even though that object may already exist, you're not going to use that very object. A copy is used instead and Set becomes vital to initialize that copy.
For example, here's what your "get customer" should look like :
Public Property Get customer(i As Integer) As customer

    Set customer = customers(i)

End Property

I guess it all makes sense; your array is private, and therefore you wouldn't want to pass the exact object that is contained inside that array, or it'd be counter-logic.

I think I found it... again...!
Try this :
Public Sub SetCustomer(C As customer, i As Integer)

   Set customers(i) = C

End Sub

Notice customer(i) was replaced by customers(i)
EDIT : Deleted previous answer, as I was mostly fishing.


text:
Q: How can I capture video while playing Red Alert 2? I like FRAPS, but it fails when recording while I play Red Alert 2. During the first American mission the game always crashes at the same second – after Statue of Liberty ruins and Romanov begins to talk.
I have tried using Google to find information about this problem but I can't find solution.
How can I capture video while playing Red Alert 2?

A: You may try Taksi which is the open source alternative to FRAPS, and see if it works. This is my detailed post about Taksi.

A: My solution for 2011 year, Windows 7.

*

*Trial version of Growler Cam. While fighting with its presets and finding, which of them work, this program crashes so often, that that's why I called it 'Complex Solution'. But at least, it doesn't need supermegaCPU.
After capturing in special format you should export to avi, but program can't handle >4gb avi even on NTFS disk, so you have to export into several avis. Also avis will lack of some 'index info', what can be fixed by Virtual Dub.
I have no success to record audio with Growler Cam, so:

*Audacity should be launched parallel to it.

*Then Virtual Dub to merge avis with mp3. Use Audio->Interleaving to crop first seconds of audiostream, which were recorded, while you switched to RA2 and started videocapturing.

A: My solution for 2020 year, Windows 10.
(AMD Radeon specific)

*

*In the Radeon drivers settings enable the ReLive. Run the game in windowed mode (alt+enter) because ReLive seems to be unable to record in 65k color depth (or because it's DirectDraw). There enable the Region Recording Hotkey and Borderless Region Capture. Enable Show Overlay in the main settings tab. Then when you use the Region Recording Hotkey it shows the overlay where you chose the Red Alert 2 application and it starts recording. Weird thing is that the recorded file has your screen resolution even while the window was smaller.

*Since modern monitors have much higher DPI game details are too small and hard to see so I use the Windows Magnifier. In the RA2.ini settings file I set the resolution as 1/2 of my native monitor resolution:
[Video]
ScreenWidth=1280
ScreenHeight=720

Now move the game window to the corner of the screen with Win+Right, Win+Down keys. It breaks the size of the window so I Alt+Tab to unstick the mouse from the game and drag the left top corner of the game window to restore the correct window size. This procedure positions the window right in the bottom right corner so now when you move the mouse there and press Win+"+" several times it zooms perfectly to the borders of the game window. Also disable the "follow mouse" in the Magnifier settings.
This all also might need the CnC DirectDraw patch to be unpacked into the game folder.
So unlike the previous solution I don't need to record audio and video separately. The modern hardware accelerated recording technology easily records games in full resolution and fps.
But the solution is still a bit complex. The issue I might face is that Steam and Windows Notifications appear in that corner so maybe for the game I'll have to move the Windows Taskbar from the left border of the screen to the right one and place the game at the bottom left but I'm not sure the notifications won't switch the corner too. Needs testing. I've asked the question about Magnifier at Super User.

UPD: new Radeon drivers have much complex interface and you might need to search for all these options using the search field. My approach is that the Windows taskbar is on the right, the game window is in the left bottom corner and instead of recording the specified window I use to record the full desktop after zooming with Magnifier while holding the mouse in the bottom left corner -- it takes just a second or two to start the process, not as difficult as you can imagine from looking at the size of this answer. If you prefer to start recording before you zoom in (if you want to see the Radeon drivers notification that the recording has been started) then just use Avidemux after that to cut the first seconds from the video (use the "Copy" options on Video and Audio streams so it will not reencode but just cut the seconds out).

A: An alternative, generic solution is using the Game Bar (default hotkey Win+g), which is a standard feature of Windows 10.
You can record and broadcast and take screenshots of anything on your desktop, quickly adjust volume, while keeping an eye on the resources used:

A: I used HyperCam 2 free video capturing software, i used this to capture glitches in RA2.