text:
Q: ArrayList, credit card summay I have most of the code for deterring the number of credit card holders, for a certain card type, balance, and avg, for some reason, something is not working. I am working in Java, bluejay, if that is a difference. code is below,
public String getCardSummary(String card){
    //return a String that summarizes the total number of cards and average debt for the requested card type.
    //Valide enters are: Discover, Visa, and MasterCard.
    //Return an appropriate error message if the card is not valid.
    //If there are no customers with the specific card, return a message indicationg that "Customers was not found"
    //User the NumberFormat class to help fromat the dollars and cnets outputs.
    //Sample result should look like:
    //Discover: 1981 cards with average balce of $3,735.20
    if(card.equalsIgnoreCase("Disvoer") || card.equalsIgnoreCase("Visa") || card.equalsIgnoreCase("MasterCard")){
        double runningSum = 0.0;
        int counter = 0;
        for(int i = 0; i < customers.size() - 1; i++){
            if(customers(i).getCard.equals(card)){
                runningSum += custumer(i).getBalance();
                counter ++;
            }
            else{
                System.out.println("Customers were not found.");
            }
        }
        double avg = runningSum / counter;
        System.out.println("" + Card + ": " + counter + " with average balance of " + fmt.format(avg));
    }
    else{
        System.out.println("Invalid Card type");
    }


text:
Q: NetBeans "link with editor" feature I use mostly Eclipse and have played around a little bit with NetBeans. The feature I have missed most is the "link with editor" which Eclipse has but I haven't found in NetBeans. The idea is that if I turn "link with editor" on, the editor window will always be in sync with the tree view on the left side (in Eclipse it's called "package explorer"). Is there such a feature in NetBeans?

A: In NetBeans 6.7 it's under View -> Synchronize Editor with Views.
In NetBeans 8.1 it's under View -> Synchronize Editor with Views.

A: From within the file you want to link, you can press Ctrl+Shift+1, +2, or +3. Pressing 1 navigates to the current file in the Projects tab/tree, 2 to the file in the Files tree, 3 to Favorites.
This can also be done from right click > Select in Projects, > Select in Files, > Select in Favorites, and from Navigate > Select in Projects etc.
I'm using NetBeans 6.5.1 (which doesn't have the View > Synchronize option).

A: In NetBeans 6.9.1, the synchronization between view and editor appear only after you show the file in editor.
If you have disable the "Synchronize Editor with Views" option, you must enable (with your shortkey for example), and two times CTRL+TAB for switch between other file and return to link file in editor !
So, there is no equivalent of the eclipse fonction "link with editor".

redpajama_set_name: RedPajamaStackExchange


text:
Q: Toggling menu in bootstrap stops  from working I tried adding a toggle to every link in my menu so the menu would close on mobile after pressing a link. I found a solution for this by adding data-toggle="collapse" data-target="#navbarSupportedContent" to the . Now this solution worked in bootstrap 3 but in bootstrap 4 it still closes the menu, but doesn't link to the text put in the  anymore.
Why does this stop from linking to the link and how do I solve this?
The following fiddle shows the problem, I added a comment above both the links without toggle and the links with toggle. Ignore everything around it, I'm pretty sure it issn't in any of the code around it.
code:

.block{
  height: 200px;
  padding: 100px;
  font-size: 30px;
  border-top: 3px solid gray;
}

.navbar li a {
  color: #bbb;
}

    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

    </button>

                block1

                block2

                block3

                block1 (with toggle+target)

                block2 (with toggle+target)

                block3 (with toggle+target)

block1

block2

block3

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

I'm also open for other solutions, like solutions in JavaScript or html.

A: Try this

             Menu Name 1

                Submenu 1-1
                 Submenu 1-2
                Submenu 1-3

             Menu Name 2

                 Submenu 2-1
                 Submenu 2-2
                 Submenu 2-3


text:
Q: If-else statements not working for model What I want
On a JPanel, I have a JButton and a JTextArea. Upon pressing JButton, certain text has to be printed inside the JTextArea. This certain text is determined by if-else statements. Conditions of if-else are based on an integer variable R.
Basically its a survey like question-answer thing I'm trying to make. I use the R to record answers from user. When a user clicks a choice, the value of R gets updated.
I use a String variable yourphone. If the value of R in the end is eg 120, then yourphone gets updated to a string eg. Xperia Z.
This final JPanel I'm talking about is where I display result. Total value of R is used in if-else statements.
Structure
I initiate variable like this
int R=0;
String yourphone;

Here is the code of JPanel
final JPanel result = new JPanel();
        result.setBackground(Color.BLACK);
        getContentPane().add(result, "name_17130054294139");
        result.setLayout(null);

        final JTextArea txtrphoneresult = new JTextArea();
        txtrphoneresult.setRows(5);
        txtrphoneresult.setBounds(68, 84, 285, 148);
        result.add(txtrphoneresult);

        JButton btnShowResult = new JButton("Show Result");
        btnShowResult.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                txtrphoneresult.setText(yourphone + R);

            }
        });
        btnShowResult.setBounds(68, 29, 103, 32);
        result.add(btnShowResult);

Here are what my if-else statements look like
if(R==1749)
        {
            yourphone = "Galaxy Mega 5.8";
        }
if(R==1726)
        {
            yourphone = "Xperia Z";
        }
else
            {
                    yourphone = "NO Result";
            }

Problem
Upon execution, no matter what the result is always "NO Result" which means that value of R is always something else than my predicted totals. But that cannot be right because I print the value of R alongside
txtrphoneresult.setText(yourphone + R);

And the result output is "NO Result 1749". Which is impossible because it indicates that value of R is updated. And if its 1749 then the output should be "Galaxy Mega 5.8". I don't know why its takes output of yourphone from the else statement when the if condition is clearly met.

A: You need to add else after first if:
if(R==1749) {
    yourphone = "Galaxy Mega 5.8";
} else if(R==1726) {
    yourphone = "Xperia Z";
} else {
    yourphone = "NO Result";
}

Otherwise, yourphone will be "NO Result" even if R == 1749.

A: if(R==1749)
  yourphone = "Galaxy Mega 5.8";
else if(R==1726)
  yourphone = "Xperia Z";
else
  yourphone = "NO Result";

this will solve your problem;

A: Your nested if-else statement is not correct. If-else condition should be
if(R==1749){
    yourphone = "Galaxy Mega 5.8";
}
else if(R==1726){
    yourphone = "Xperia Z";
}
else{
     yourphone = "NO Result";
}


text:
Q: How should we address local dependencies in sbt files for Spark I have this sbt file:
offline := true
name := "hello"
version := "1.0"
scalaVersion := "2.11.7-local"
scalaHome := Some(file("/home/ubuntu/software/scala-2.11.7"))
libraryDependencies += "org.apache.spark" %% "spark-core" % "1.5.0" % "provided"

How can I tell it to use this address for Spark rather than using web?
/home/ubuntu/software/spark-1.5.0-bin-hadoop2.6

Because it just tries to connect to internet for Spark dependencies and my VM doesn't have internet access due to security issues.
I eventually want to run this simple code:
import org.apache.spark.SparkContext._
import org.apache.spark.api.java._
import org.apache.spark.api.java.function.Function_
import org.apache.spark.graphx._
import org.apache.spark.graphx.lib._
import org.apache.spark.graphx.PartitionStrategy._
//class PartBQ1{

object PartBQ1{
val conf = new SparkConf().setMaster("spark://10.0.1.31:7077")
             .setAppName("CS-838-Assignment2-Question2")
             .set("spark.driver.memory", "1g")
             .set("spark.eventLog.enabled", "true")
             .set("spark.eventLog.dir", "/home/ubuntu/storage/logs")
             .set("spark.executor.memory", "21g")
             .set("spark.executor.cores", "4")
             .set("spark.cores.max", "4")
             .set("spark.task.cpus", "1")

val sc = new SparkContext(conf=conf)
val sql_ctx = new SQLContext(sc)
val graph = GraphLoader.edgeListFile(sc, "data2.txt")
}

A: I guess you could use something like (assuming spark is in your classpath)
run in Compile <<= Defaults.runTask(fullClasspath in Compile, mainClass in (Compile, run), runner in (Compile, run))

As suggested in
https://stackoverflow.com/a/21803413/1706351
https://github.com/sbt/sbt-assembly#-provided-configuration

A: These are the steps I took to resolve the issue with a new MVC 2 project and Spark 1.1:
1.Compile against MVC 2.0 - I double checked the references to make sure I was linking to MVC 2 and not MVC 1. Since this was a new project, this was not an issue.
2.Added System.Web.Mvc.Html - I added System.Web.Mvc.Html to the Spark configuration, to make sure that namespace was added to all views.
In Global.asax.cs Application_Start
var settings = new SparkSettings()
    .SetDebug(true)
    .SetAutomaticEncoding(true)
    .AddAssembly("Web")
    .AddNamespace("Web.Model")
    .AddNamespace("System.Collections.Generic")
    .AddNamespace("System.Linq")
    .AddNamespace("System.Web.Mvc")
    .AddNamespace("System.Web.Mvc.Html");

This can also be done in the webconfig in the Spark View Engine block.
3.Add the Typed Model - Make sure you type the Spark View Model. In aspx this is done with the Inherits in the page declaration, like this:
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<MyModelType>" %>

in Spark:
<viewdata model="MyModelType" />


text:
Q: Is there a way to find UMVUE without just guessing? We have $(X_1,...,X_n)$ random sample of distribution $N(m,1)$. I need to find UMVUE of $g(m)=e^m$.
The natural guess was that the unbiased estimator which I need to find may be something like $e^T$, where $T=\frac{1}{n} \sum\limits_{i=1}^n X_i$. So I calculated
$$\mathbb{E}[e^{T}]=exp \left[m+\frac{1}{2n}\right]$$
therefore the unbiased estimator that I was looking for is
$g(T)=e^{T-\frac{1}{2n}}.$
My question is: is there a way to get this result in any other way than just guessing?
I considered solving:
$$\mathbb{E}g(T)=e^m$$
so I would get
$$\int\limits_0^\infty g(t) \frac{1}{\sqrt{\frac{2 \pi}{n}}}e^{-\frac{(t-m)^2}{\frac{2}{n}}} dt=e^m$$ but that doesn't seem to get me anywhere.
What do you think?


text:
Q: Can I use current Timestamp as UUID in PostgreSQL 8.2 I know that PostgreSQL 9+ has module to generate UUID. But after a lot of search I couldn't find any solution to generate UUID in PostgreSQL 8.2. I also need to keep this version because lot of my customers are still using 8.2. I am thinking to use current Timestamp as UUID.
Running select extract(epoch from now()); query and getting a Timestamp like 1384396600.53923. I want to store it as character and use as UUID. Is there any possibility of generating duplicate Timestamp? Also will it be feasible to use Timestamp as UUID?

A: i am not sure it is feasible.
but i suggest you not to use the Timestamp as UUID.
i don't konw how large concurrent your condition is.
if you are in a very much large concurrent condition,or in a very extreme condition by chance,i think it must will be give you two same  Timestamp,so there will be something wrong,right?
so,use some other way to make a "UUID".


text:
Q: are there any keyboard shortcuts for glimpse? Are there any keyboard shortcuts for glimpse?
I've checked their website http://getglimpse.com/Help and http://getglimpse.com/Help/Configuration as well as the twitter hashtag #glimpse, but I'm getting no love.
I'm looking for something similar to how firebug lite uses F12 to show their console.

A: There are not currently any keyboard shortcuts for Glimpse.
It is a great idea though - suggest it on the Glimpse User Voice page, or feel free to contribute.

A: There aren't any currently but I have implemented some of them myself using javascript so our developers could use keyboard shortcuts to turn on/ or star session. Something like
    <script type="text/javascript">
            $(document).ready(function () {
                $(document).keyup(function (event) {
                    var key = event.keyCode || event.charCode || 0;
                    if (key == 71 && event.altKey) {
                        document.cookie = 'glimpseState=On; path=/; expires=Sat, 01 Jan 2050 12:00:00 GMT;';
                        window.location.reload();
                    }
                    else if(key == 83 && event.altKey && event.ctrlKey) {
                        document.cookie = 'glimpseClientName=' + prompt('Client Name?') + '; path=/; expires=Sat, 01 Jan 2050 12:00:00 GMT;';
                        window.location.reload();
                    }
                });
            });
        </script>


text:
Q: Spark - Find most common words in dataset I have a Dataset below like:
+----------+-----------------------------------------------------------------------------+
|prediction|text                                                                         |
+----------+-----------------------------------------------------------------------------+
|1         |this is a important sentence important sentence                              |
|2         |this is a simple sentence, simple sentence and important sentence]           |
+----------+-----------------------------------------------------------------------------+

I want to find the most common N-words in each row (for example top 2 words).
Example:

*

*In row 1 most common words are "important" and "sentence".

*In row 2 most common words are "simple" and "sentence".

Finally make a new Dataset should look like below :
+----------+-----------------------------------------------------------------------------+-----------+
|prediction|text                                                                         | top terms
+----------+-----------------------------------------------------------------------------+-----------+
|1         |this is a important sentence important sentence                              | important,sentence
|2         |this is a simple sentence, simple sentence and important sentence]           | simple,sentence
+----------+-----------------------------------------------------------------------------+-----------+

Please show me a piece of code to solve it, I worked with java but the language you use does not matter because I'll converting it.
Thanks

A: # regex remove all nonalphanumeric characters, split by " " and explode words
# count each value group by 'prediction' and word
# add row number descending for counted words in each 'prediction'
# filter/select only top 2 words
# collect top terms to array using collect_list
# concat list values using array_join to return string

df.select('*,explode(split(regexp_replace('text,"[^a-zA-Z0-9 -]","")," ")).as("val"))
.groupBy('prediction,'val,'text)
.agg(count('val).as("val_cnt"))
.select('*,row_number.over(Window.partitionBy("prediction").orderBy('val_cnt.desc)).as("row_number"))
.where('row_number<=2)
.select('prediction,'text,'val)
.groupBy('prediction,'text).agg(collect_list('val).as("topterms"))
.select('prediction,'text,array_join('topterms,",").as("top_terms"))
.show(false)

output:
+----------+------------------------------------------------------------------+------------------+
|prediction|text                                                              |top_terms         |
+----------+------------------------------------------------------------------+------------------+
|1         |this is a important sentence important sentence                   |sentence,important|
|2         |this is a simple sentence, simple sentence and important sentence]|sentence,simple   |
+----------+------------------------------------------------------------------+------------------+


text:
Q: atlas lib symlink stuck in master-slave deadlock after a few rounds of installs and removes, trying to get Atlas and OpenBLAS to be friend with each other, i have this update-alternatives error, which i think is really a master-slave deadlock, ie. some symlink should to be a slave but is actually a master. Please advise how to fix this.
My setting : ubuntu 12.04
sudo apt-get -f install

Reading package lists... Done
Building dependency tree
Reading state information... Done
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
1 not fully installed or removed.
After this operation, 0 B of additional disk space will be used.
Setting up libatlas3gf-base (3.8.4-3build1) ...
update-alternatives: error: alternative libatlas.so.3gf can't be slave of libblas.so.3gf:     it is a master alternative.
dpkg: error processing libatlas3gf-base (--configure):
 subprocess installed post-installation script returned error exit status 2
Errors were encountered while processing:
 libatlas3gf-base
E: Sub-process /usr/bin/dpkg returned an error code (1)

sudo dpkg --configure -a

Setting up libatlas3gf-base (3.8.4-3build1) ...
update-alternatives: error: alternative libatlas.so.3gf can't be slave of libblas.so.3gf: it is a master alternative.
dpkg: error processing libatlas3gf-base (--configure):
 subprocess installed post-installation script returned error exit status 2
Errors were encountered while processing:
 libatlas3gf-base

EDIT :
$ update-alternatives --query libblas.so.3gf
update-alternatives: error: no alternatives for libblas.so.3gf.

$ update-alternatives --query libatlas.so.3gf
Link: libatlas.so.3gf
Status: auto
Best: /usr/local/lib/libopenblas.so
Value: none

Alternative: /usr/local/lib/libopenblas.so
Priority: 50

A: I fixed my own master-slave deadlock, and here is the magic line,
sudo dpkg --remove --force-remove-reinstreq libatlas3gf-base

after that i issued 'sudo apt-get -f install' no more complaint was seen.
Reading package lists... Done
Building dependency tree
Reading state information... Done
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.

NOTE : In a separate post (http://ubuntuforums.org/showthread.php?t=947124) someone suggested
"sudo dpkg --remove -force --force-remove-reinstreq package name"

The '-force' is really not needed.

A: I couldn't get horaceT's answer to work.  Instead I issued the following commands, which complained but stopped the apt-get install failing.
sudo update-alternatives --config liblapack.so.3gf
sudo update-alternatives --config libblas.so.3gf

A: Just for the memory: In this answer it is suggested to make
sudo update-alternatives --remove-all liblapack.so.3gf
sudo apt-get install -f

which helped in my case.


text:
Q: Marking fields as deprecated with graphql shorthand I'm using GraphQL shorthand to specify the types in a schema, eg
type Car {
  id: ID!
  make: String
  model: String
  description: String
}

Using this shorthand, is there a way to mark a field as deprecated? Say I wanted to mark description as deprecated. Here's my wild guess on how to do this.
type Car {
  id: ID!
  make: String
  model: String
  @deprecated
  description: String
}

But no dice. Is field deprecation achievable in GraphQL shorthand?
Thanks!

A: You can deprecate like this
directive @deprecated(
  reason: String = "No longer supported"
) on FIELD_DEFINITION | ENUM_VALUE

type ExampleType {
  newField: String
  oldField: String @deprecated(reason: "Use `newField`.")
}

for more info plz refer to apollo server documentation

A: Yup, you can mark fields as deprecated like this:
type Car {
  id: ID!
  make: String
  model: String
  description: String @deprecated(reason: "Field is deprecated!")
}


text:
Q: x264 encoded frames into a mp4 container with ffmpeg API I'm struggling with understanding what is and what is not needed in getting my already encoded x264 frames into a video container file using ffmpeg's libavformat API.
My current program will get the x264 frames like this -
while( x264_encoder_delayed_frames( h ) )
{
    printf("Writing delayed frame %u\n", delayed_frame_counter++);
    i_frame_size = x264_encoder_encode( h, &nal, &i_nal, NULL, &pic_out );
    if( i_frame_size < 0 ) {
            printf("Failed to encode a delayed x264 frame.\n");
            return ERROR;
        }
    else if( i_frame_size )
    {
        if( !fwrite(nal->p_payload, i_frame_size, 1, video_file_ptr) ) {
            printf("Failed to write a delayed x264 frame.\n");
            return ERROR;
        }
    }
}

If I use the CLI to the ffmpeg binary, I can put these frames into a container using:
ffmpeg -i "raw_frames.h264" -c:v copy -f mp4 "video.mp4"

I would like to code this function into my program using the libavformat API though. I'm a little stuck in the concepts and the order on which each ffmpeg function is needed to be called.
So far I have written:
        mAVOutputFormat = av_guess_format("gen_vid.mp4", NULL, NULL);
        printf("Guessed format\n");

        int ret = avformat_alloc_output_context2(&mAVFormatContext, NULL, NULL, "gen_vid.mp4");
        printf("Created context = %d\n", ret);
        printf("Format = %s\n", mAVFormatContext->oformat->name);

        mAVStream = avformat_new_stream(mAVFormatContext, 0);
        if (!mAVStream) {
            printf("Failed allocating output stream\n");
        } else {
            printf("Allocated stream.\n");
        }

        mAVCodecParameters = mAVStream->codecpar;
        if (mAVCodecParameters->codec_type != AVMEDIA_TYPE_AUDIO &&
            mAVCodecParameters->codec_type != AVMEDIA_TYPE_VIDEO &&
            mAVCodecParameters->codec_type != AVMEDIA_TYPE_SUBTITLE) {
            printf("Invalid codec?\n");
        }

        if (!(mAVFormatContext->oformat->flags & AVFMT_NOFILE)) {
            ret = avio_open(&mAVFormatContext->pb, "gen_vid.mp4", AVIO_FLAG_WRITE);
            if (ret < 0) {
              printf("Could not open output file '%s'", "gen_vid.mp4");
            }
          }

        ret = avformat_write_header(mAVFormatContext, NULL);
        if (ret < 0) {
          printf("Error occurred when opening output file\n");
        }

This will print out:
Guessed format
Created context = 0
Format = mp4
Allocated stream.
Invalid codec?
[mp4 @ 0x55ffcea2a2c0] Could not find tag for codec none in stream #0, codec not currently supported in container
Error occurred when opening output file

How can I make sure the codec type is set correctly for my video?
Next I need to somehow point my mAVStream to use my x264 frames - advice would be great.
Update 1:
So I've tried to set the H264 codec, so the codec's meta-data is available. I seem to hit 2 newer issues now.
1) It cannot find the device and therefore cannot configure the encoder.
2) I get the "dimensions not set".
mAVOutputFormat = av_guess_format("gen_vid.mp4", NULL, NULL);
printf("Guessed format\n");

// MUST allocate the media file format context.
int ret = avformat_alloc_output_context2(&mAVFormatContext, NULL, NULL, "gen_vid.mp4");
printf("Created context = %d\n", ret);
printf("Format = %s\n", mAVFormatContext->oformat->name);

// Even though we already have encoded the H264 frames using x264,
// we still need the codec's meta-data.
const AVCodec *mAVCodec;
mAVCodec = avcodec_find_encoder(AV_CODEC_ID_H264);
if (!mAVCodec) {
    fprintf(stderr, "Codec '%s' not found\n", "H264");
    exit(1);
}
mAVCodecContext = avcodec_alloc_context3(mAVCodec);
if (!mAVCodecContext) {
    fprintf(stderr, "Could not allocate video codec context\n");
    exit(1);
}
printf("Codec context allocated with defaults.\n");
/* put sample parameters */
mAVCodecContext->bit_rate = 400000;
mAVCodecContext->width = width;
mAVCodecContext->height = height;
mAVCodecContext->time_base = (AVRational){1, 30};
mAVCodecContext->framerate = (AVRational){30, 1};
mAVCodecContext->gop_size = 10;
mAVCodecContext->level = 31;
mAVCodecContext->max_b_frames = 1;
mAVCodecContext->pix_fmt = AV_PIX_FMT_NV12;

av_opt_set(mAVCodecContext->priv_data, "preset", "slow", 0);
printf("Set codec parameters.\n");

// Initialize the AVCodecContext to use the given AVCodec.
avcodec_open2(mAVCodecContext, mAVCodec, NULL);

// Add a new stream to a media file. Must be called before
// calling avformat_write_header().
mAVStream = avformat_new_stream(mAVFormatContext, mAVCodec);
if (!mAVStream) {
    printf("Failed allocating output stream\n");
} else {
    printf("Allocated stream.\n");
}

// TODO How should codecpar be set?
mAVCodecParameters = mAVStream->codecpar;
if (mAVCodecParameters->codec_type != AVMEDIA_TYPE_AUDIO &&
    mAVCodecParameters->codec_type != AVMEDIA_TYPE_VIDEO &&
    mAVCodecParameters->codec_type != AVMEDIA_TYPE_SUBTITLE) {
    printf("Invalid codec?\n");
}

if (!(mAVFormatContext->oformat->flags & AVFMT_NOFILE)) {
    ret = avio_open(&mAVFormatContext->pb, "gen_vid.mp4", AVIO_FLAG_WRITE);
    if (ret < 0) {
      printf("Could not open output file '%s'", "gen_vid.mp4");
    }
  }
printf("Called avio_open()\n");

// MUST write a header.
ret = avformat_write_header(mAVFormatContext, NULL);
if (ret < 0) {
  printf("Error occurred when opening output file (writing header).\n");
}

Now I am getting this output -
Guessed format
Created context = 0
Format = mp4
Codec context allocated with defaults.
Set codec parameters.
[h264_v4l2m2m @ 0x556460344b40] Could not find a valid device
[h264_v4l2m2m @ 0x556460344b40] can't configure encoder
Allocated stream.
Invalid codec?
Called avio_open()
[mp4 @ 0x5564603442c0] Using AVStream.codec to pass codec parameters to muxers is deprecated, use AVStream.codecpar instead.
[mp4 @ 0x5564603442c0] dimensions not set
Error occurred when opening output file (writing header).


text:
Q: Selenium and Python can't click href="javascript:void(0);" with .click() I have been stuck on trying to click the href="javascript:void(0);" on a page.
My problem is that I am not able to select this using selenium, and my end goal is to click on one. The page is fully loaded, and this is what all the links on the page have as the href.
my code is this:
a = soup.find_all('a')
for names in a:
    try:
        print (names['href'])
        if names['href'] == "javascript:void(0);":
            print "IM IN HUR"
            names.click()
            break
    except:
        continue

But the "name.click()" statement never works.I have not found any way to click on javascript:void(0). Any help would be much appreciated.

A: You have to use Selenium WebDriver to interact with web browser. Your variable names is an object of Beautiful Soup which is a Python package for parsing HTML/XML, it cannot interact with web browser. Try code below:
aElements = browser.find_elements_by_tag_name("a")
for name in aElements:
    if(name.get_attribute("href") is not None and "javascript:void" in name.get_attribute("href")):
        print("IM IN HUR")
        name.click()
        break


text:
Q: JavaScript highlight table cell on tab in field I have a website laid out in tables. (a long mortgage form)
in each table cell is one HTML object. (text box, radio buttons, etc)
What can I do so when each table cell is "tabbed" into it highlights the cell with a very light red (not to be obtrusive, but tell the user where they are)?

A: Use jQuery to make your life easier, and you can do something like this:
$('#mytableid input').focus( function() {
    $(this).addClass('highlight');
}).blur( function() {
    $(this).removeClass('highlight');
});

This is basically saying when any input element in your table is under focus add the "highlight" class to it, and once it loses focus remove the class.
Setup your css as:
input.highlight { background-color: red; }

and you should be set.

A: This is the table I tested my code on:

    <input type="text" value="hello" />
    <input type="checkbox" name="foo" value="2" />
    <input type="button" value="hi" />

Here is the code that worked:
// here is a cross-browser compatible way of connecting
// handlers to events, in case you don't have one
function attachEventHandler(element, eventToHandle, eventHandler) {
    if(element.attachEvent) {
       element.attachEvent(eventToHandle, eventHandler);
    } else if(element.addEventListener) {
       element.addEventListener(eventToHandle.replace("on", ""), eventHandler, false);
    } else {
    element[eventToHandle] = eventHandler;
  }
}
attachEventHandler(window, "onload", function() {
  var myTable = document.getElementById("myTable");
  var myTableCells = myTable.getElementsByTagName("td");
  for(var cellIndex = 0; cellIndex < myTableCells.length; cellIndex++) {
    var currentTableCell = myTableCells[cellIndex];
    var originalBackgroundColor = currentTableCell.style.backgroundColor;
    for(var childIndex = 0; childIndex < currentTableCell.childNodes.length; childIndex++) {
      var currentChildNode = currentTableCell.childNodes[childIndex];
      attachEventHandler(currentChildNode, "onfocus", function(e) {
        (e.srcElement || e.target).parentNode.style.backgroundColor = "red";
      });
      attachEventHandler(currentChildNode, "onblur", function(e) {
        (e.srcElement || e.target).parentNode.style.backgroundColor = originalBackgroundColor;
      });
    }
  }
});

There are probably things here you could clean up, but I whipped this together quickly. This works even if there are multiple things in each cell.
This would be much easier, it should go without saying, if you used a library to assist you in this work - jQuery and MochiKit are the two I favor, though there are others that would work just as well.

Between the time I started writing this answer and the time I posted it, someone posted code that shows how you would do something like this in jQuery - as you can see, much shorter! Although I love libraries, I know some people either can't or will not use a library - in those cases my code should do the job.

A: Possibly:

<input type="..." onfocus="getParent(this,'td').style.backgroundColor='#400';" onblur="getParent(this,'td').style.backgroundColor='';">


text:
Q: how to include single sign on using 3rd party oauth server in Node-RED? I want to include a 3rd party authentication server in my node red application. The flow should be such that when anyone enters the link, it redirects them to the server, there they will enter credentials and on validation, they are transferred back to application. I have the client ID, authorization/token end point for that server.

A: For implementing 3rd part SSO in your application there are variety of packages that can help you . One of the most popular package is passport.js . It provides support for multiple Identity providers and you can choose any package that you want
2 steps you should follow :

*

*Create an application on any IDP (Identity Provider) developer's portal to get AppID , AppSecret

*Create a setup.js file for setting up the required configuration

Have a look at this for detailed explanation https://www.freecodecamp.org/news/learn-how-to-handle-authentication-with-node-using-passport-js-4a56ed18e81e/
While setting up the application on developer's account there are few things like RedirectURI , what is means is "this is the URL on which the access token after Authorization will be sent"
Do read about sessions and how passport helps you to easily configure this


text:
Q: With Django REST framework, how do I parse a RESTful string parameter? I'm using Python 3.9 with
Django==3.1.4
djangorestframework==3.12.2

I want to pass a restful param ("author" string) to my GET method.  In my urls.py file I have
urlpatterns = [
    ...
    path('user/<str:author>', views.UserView.as_view()),

And then in my UserView class (defined in my views.py file), I have
class UserView(APIView):
    def get(self, request):
        ...
        author = self.kwargs.get('author', None)

but when i execute
GET http://localhost:8000/user/myauthor

I get the error
TypeError: get() got an unexpected keyword argument 'author'

What else do I need to do to properly access my RESTful param in the URL?

A: get() method should accept url parameters too, you can use *args and **kwargs syntax to make sure it works no matter how you name your parameter:
class UserView(APIView):
    def get(self, request, *args, **kwargs):
        ...
        author = self.kwargs.get('author', None)

A: To use the path params added in the url pattern, you must add the **kwargs as an extra parameter to the get() method. Your view should look like this:
class UserView(APIView):
    def get(self, request, **kwargs):
       ...
       author = kwargs.get('author', None)


text:
Q: PDF file open but cannot load Laravel I'm new with create file (php laravel) and I have a problem with pdf load (Failed to load the PDF document in the browser). When I decode my base64 code in my Controller and make a pdf file with it, the pdf result code is unfamiliar.

I think this is where the problem come from. This is the code to create and load the pdf file.
public function fileload(Request $request) {
    $name = time().'.' . explode('/', explode(':', substr($request->pdf, 0, strpos($request->pdf, ';')))[1])[1];
    $data = base64_decode($request->pdf);
    $file_create = file_put_contents('files/projects/'.$name,$data);

    $file = public_path()."/files/projects/".$name;
    return response()->download($file,$name);
}

Vue.js(script) code where pdf in base64 is set
data(){
    return{
        form: new Form({
              file:'',
              filetype:'',
              pdf:'',
            })
        }
    },

methods: {
    onInputChange(e){
      let file = e.target.files[0];
      let reader = new FileReader();

      if(file['size'] < 211177555){
          reader.onloadend = (file) => {
            //console.log('RESULT',reader.result)
            this.form.file = e.target.files;
            this.form.pdf = reader.result;
          }
          reader.readAsDataURL(file);
       }else{
         this.$toastr.e('Your file exceeds 2MB.');
       }
    },

Vuejs (template)
<form @submit.prevent="addFile(form.file)">
  <input type="file" id="file"  @change="onInputChange">
  <input type="submit" name="">
</form>

The output of this.form.pdf is a base64 I checked.
data:application/pdf;base64,JVBERi0xLjMKJcfsj6IKMzAgMCBvYmoKPDwvTGVuZ3RoIDMxIDAgUi9GaWx0ZXIgL0ZsYXRlRGVjb2RlPj4Kc3RyZWFtCnic7X3dkyW3be/7/BVT9yVOVfa4+U0mTzeJ45uUXXFspZKHvNgrS3K8K9mSJcf56y9+ALqbPY2ew9N7ZmVZm1SiBaabDYIAiC/y/P....

A: Seems to me $request->pdf is not base64, but rather a Data URI scheme, which may use Base64 in it's composition but is not Base64 and will not be parsed properly by base64_decode().
What gives it away is that not only you're looking for symbols like : and ; in the data, but apparently you are finding them. Base64 does not contain those symbols.
$request->pdf is probably data:application/pdf;base64,FileSerializedInBase64.
This is not base64! Only the last part is.
If you throw this as is to base64_decode() to parse it will output garbage, which is exactly what you are seeing.


text:
Q: Cannot connect to service through traefik ingress on k3s Using default k3s installation with vcluster I want to expose my service of type clusterIP to the world with ingress.
curl 172.18.62.21/some_endpoint
<!DOCTYPE html>

<meta charset="utf-8">
<title>Error</title>

Cannot GET /some_endpoint

curl 10.42.0.39:8080
<!DOCTYPE html>

    <title>Hello Kubernetes!</title>
    <link rel="stylesheet" type="text/css" href="/css/main.css">
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Ubuntu:300" >

  Hello world!

      namespace:
      -

      pod:
      aida-temp-env-aida-api-deployment-c8092f93-f55885d6-zk9sk

      node:
      - (Linux 5.15.0-60-generic)

  paulbouwer/hello-kubernetes:1.10.1 (linux/amd64)

k describe ingress:
Handling connection for 12042
Name:             aida-temp-env-ingress-c8343d74
Labels:           <none>
Namespace:        default
Address:          172.18.62.21,172.18.62.22,172.18.62.23
Ingress Class:    traefik
Default backend:  aida-temp-env-aida-api-service-c86c8a2d:80 (10.42.0.39:8080)
Rules:
  Host        Path  Backends
  ----        ----  --------
  *
              /some_endpoint   aida-temp-env-aida-api-service-c86c8a2d:80 (10.42.0.39:8080)
Annotations:  <none>
Events:       <none>

yaml:
kind: Secret
metadata:
  name: aida-temp-env-dockerconfig-secret-c845f04c
immutable: false
stringData:
  .dockerconfigjson: *****
type: kubernetes.io/dockerconfigjson
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: aida-temp-env-aida-api-deployment-c8092f93
spec:
  minReadySeconds: 0
  progressDeadlineSeconds: 600
  replicas: 1
  selector:
    matchLabels:
      cdk8s.io/metadata.addr: aida-temp-env-aida-api-deployment-c80a799a
  strategy:
    rollingUpdate:
      maxSurge: 25%
      maxUnavailable: 25%
    type: RollingUpdate
  template:
    metadata:
      labels:
        cdk8s.io/metadata.addr: aida-temp-env-aida-api-deployment-c80a799a
    spec:
      automountServiceAccountToken: false
      containers:
        - image: paulbouwer/hello-kubernetes:1
          imagePullPolicy: Always
          name: main
          ports:
            - containerPort: 8080
          resources:
            limits:
              cpu: 1500m
              memory: 2048Mi
            requests:
              cpu: 1000m
              memory: 512Mi
          securityContext:
            allowPrivilegeEscalation: false
            privileged: false
            readOnlyRootFilesystem: true
            runAsNonRoot: true
            runAsUser: 2000
      dnsPolicy: ClusterFirst
      imagePullSecrets:
        - name: aida-temp-env-dockerconfig-secret-c845f04c
      restartPolicy: Always
      securityContext:
        fsGroupChangePolicy: Always
        runAsNonRoot: true
      setHostnameAsFQDN: false
---
apiVersion: v1
kind: Service
metadata:
  name: aida-temp-env-aida-api-service-c86c8a2d
spec:
  externalIPs: []
  ports:
    - port: 80
      targetPort: 8080
  selector:
    cdk8s.io/metadata.addr: aida-temp-env-aida-api-deployment-c80a799a
  type: ClusterIP
---
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: aida-temp-env-ingress-c8343d74
spec:
  defaultBackend:
    service:
      name: aida-temp-env-aida-api-service-c86c8a2d
      port:
        number: 80
  rules:
    - http:
        paths:
          - backend:
              service:
                name: aida-temp-env-aida-api-service-c86c8a2d
                port:
                  number: 80
            path: /some_endpoint
            pathType: Prefix

Initially I wanted to expose the service using LoadBalancer servcie, but it's external ip would stay in pending state forever. I then added a MetalLB and it succesfully provided an external ip(I then got rid of it in favor of clipperlb)
EDIT:
I also did run the k logs traefic and the output is:
level=error msg="Skipping service: no endpoints found" namespace=vcluster-aida-api-pr-112 serviceName=aida-temp-env-aida-api-service-c86c8a2d-x-default-x--bcdba98931 servicePort="&ServiceBackendPort{Name:,Number:80,}" providerName=kubernetes ingress=aida-temp-env-ingress-c8343d74-x-default-x-aida-api-pr-112
I also did check k get endpoints aida-temp-env-aida-api-service-c86c8a2d-x-default-x--bcdba98931 -n vcluster-aida-api-pr-112, output:
aida-temp-env-aida-api-service-c86c8a2d-x-default-x--bcdba98931   10.42.0.39:8080   6h5m


text:
Q: Why is dangerouslySetInnerHTML property returning Uncaught Invariant Violation error? I am trying to build a simple markdown previewer using react and marked.js. Feel like I am almost there - I can console.log the markdown, but for some reason I get an error when trying to insert the HTML. Here is the code:
//import { useState } from 'react';
const {useState} = React

//MAIN APP
function App(){
  const [text, setText]=useState("Test")

  function editorHandler(event){
    setText(event.target.value)
  }

  return(

 MARKDOWN PREVIEWER

      <Editor onChange={editorHandler} markDown={text}/>
      <Preview previewText={text}/>

  )
}

ReactDOM.render(<App/>, document.getElementById("App"))

// EDITOR COMPONENT
function Editor(props){
  return(

editor

    <textarea id="editor" value={props.markDown} onChange={props.onChange} placeHolder="Write something here"> </textarea>

  )
}

// PREVIEW COMPONENT
function Preview(props){

 console.log(marked(props.previewText))  // works, outputs:
Test

  function getMarkDownText() {
    const rawMarkup = marked(props.previewText)
    return {__html: rawMarkup};
  }

  return(

previewer

  )
}

The problem seems to be with that last div (id preview). I get the following error message which is not very helpful: "Uncaught Invariant Violation: Minified React error #60"
Codepen is here if easier: https://codepen.io/rpollock03/pen/RwWvYQb?editors=1011
Grateful for an explanation of what I'm doing wrong. I am learning React so apologies if this is something silly! I've tried reading the docs - the marked.js ones weren't very clear in my opinion.

A: Replace

with

This will solve it.
Codepen uses minified react-dom (react-dom.production.min.js). Hence you are not clearly seeing the error. In the minified production build of React, they avoid sending down full error messages in order to reduce the number of bytes sent over the wire.
But if you open browser console, you will find the following message

Invariant Violation: Minified React error #60; visit
  https://reactjs.org/docs/error-decoder.html?invariant=60 for the full
  message or use the non-minified dev environment for full errors and
  additional helpful warnings.

And once you go to the link in above message, you will get actual error, which is

Can only set one of children or props.dangerouslySetInnerHTML.

As children are not allowed (and also not required) when dangerouslySetInnerHTML is used, to solve this issue, we removed the children by replacing

 with


text:
Q: vi command line equivalent to CTRL-]? I'm trying to map my own shortcuts in vi.
I want to be able to open a splitted window containing the declaration of the function I'm calling the shortcut on.
something like this in my vimrc:
nmap <unique> <silent> <Leader>tg :exe 'vsplit'\| equivalent of <C-]>
but what's the equivalent of C-] in command mode ?

A: See :help CTRL-]:

CTRL-]   Jump to the definition of the
  keyword under the    cursor.  Same as
  ":tag {ident}", where {ident} is the
     keyword under or after cursor.

Edit
Not sure if there is a built-in for this, but the following seems to match the keyword "under or after" the cursor:
matchstr(getline('.'), '\%'.col('.').'c\s*\zs\k\+')

A: To open vim at the line containing the tag foobar type this at the shell commandline:
vim -t foobar

To jump to the same tag on the vim commandline type:
:tag foobar

If you want to split the window and jump to the tag in the new window type this in vim's commandline:
:stag foobar

If you want a keystroke that specifies "the word under the cursor", then according to this question, you can use the CTRL+R CTRL+W to get that:
:tag CTRL+R CTRL+W
You can also use :
:nmap <leader>w :tag <c-r>=expand("<cword>")<c-r>

Now typing <leader>+w (which is \ in my setup, so I'd press \w) will be the same as typing :tag <word under the cursor>

A: you could also write (to map it for example to Ctrl-Q):
:nmap <C-Q> <C-]>

you could also consider :nn[oremap] in such cases to avoid nested/recursive mappings.

A: You can jump to the definition of the word under the cursor with exe "tag " . expand("<cword>"). The expand function replaces special tokens with their meaning - this includes a filename under the cursor, the current file name, etc.  See Vim's help for the expand() function for the full set.
Alternatively you could use the :normal command, which lets you execute normal-mode key sequences from an :ex command.


text:
Q: adding corners to my tabs background in android coding I was implementing a drawable file to add a background to my tabs but i want it to have corners . I've used a shape and corners tags all embedded into a selector tag but it has no  effects to my background corners . May I please get your help ? here's the code i've implemented :
    <?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@color/bleue_sky" android:state_selected="true">
        <shape android:shape="rectangle">
            <corners
                android:bottomLeftRadius="15dp"
                android:bottomRightRadius="15dp"
                android:topLeftRadius="15dp"
                android:topRightRadius="15dp"
                />

        </shape>
    </item>
    <item android:drawable="@color/blackTransparent"/>

</selector>

A: Try This
<com.google.android.material.tabs.TabLayout
                android:id="@+id/tabLayout"
                android:layout_width="match_parent"
                android:layout_height="?actionBarSize"
                android:background="@drawable/main_tab_bg"
                android:paddingHorizontal="10dp"
                android:visibility="visible"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent"
                app:tabBackground="@drawable/tab_layout_background"
                app:tabIndicator="@drawable/tab_layout_indicator"
                app:tabIndicatorColor="@null"
                app:tabIndicatorFullWidth="true"
                app:tabIndicatorGravity="center"
                app:tabMode="auto"
                app:tabRippleColor="@null"
                app:tabSelectedTextColor="#FFFFFF"
                app:tabTextColor="#000000" />

res/drawable/main_tab_bg.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <solid android:color="#DDDDDD"/>
        </shape>
    </item>
    <item android:top="1dp" android:bottom="1dp">
        <shape android:shape="rectangle">
            <solid android:color="#FFFFFF"/>
        </shape>
    </item>
</layer-list>

res/drawable/tab_layout_background.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:top="9dp"
        android:bottom="9dp">
        <shape android:shape="rectangle">
            <solid android:color="@color/transparent" />
            <corners android:radius="15dp" />
            <size android:height="30dp"/>
        </shape>
    </item>
</layer-list>

res/drawable/tab_layout_indicator.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:top="9dp"
        android:bottom="9dp">
        <shape android:shape="rectangle">
            <corners android:radius="15dp" />
            <solid android:color="#000000" />
            <size android:height="30dp"/>
        </shape>
    </item>
</layer-list>

output like this


text:
Q: Selenium webscraping TimeoutException with stacktrace of pointers I am currently using selenium to web-scrape for articles on the RSC corpus. I keep running into an error due to the line:
wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '.capsule.capsule--article')))

I have tried both EC.presence_of_element_located and EC.visibility_of_element_located, and both give me the same TimeoutException error. I am not sure what else I can try to get rid of the TimeoutException, as the CSS selector is correct, and the URL properly loads the query on RSC.
Here is my stacktrace:
Traceback (most recent call last):
  File "rsc.py", line 40, in <module>
    main(url, query, page, location)
  File "rsc.py", line 22, in main
    dois = scraper.get_doi(query=query, page=page)
  File "/home/ssarrouf/Documents/GitHub/WaterRemediationParser/batterydataextractor-main/batterydataextractor/scrape/rsc.py", line 62, in get_doi
    _ = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '.capsule.capsule--article')))
  File "/home/ssarrouf/.pyenv/versions/3.8.16/lib/python3.8/site-packages/selenium/webdriver/support/wait.py", line 95, in until
    raise TimeoutException(message, screen, stacktrace)
selenium.common.exceptions.TimeoutException: Message:
Stacktrace:
#0 0x55e10fae5d93 <unknown>
#1 0x55e10f8b42d7 <unknown>
#2 0x55e10f8f0caa <unknown>
#3 0x55e10f8f0db1 <unknown>
#4 0x55e10f92e8f4 <unknown>
#5 0x55e10f91461d <unknown>
#6 0x55e10f92c619 <unknown>
#7 0x55e10f914353 <unknown>
#8 0x55e10f8e3e40 <unknown>
#9 0x55e10f8e5038 <unknown>
#10 0x55e10fb398be <unknown>
#11 0x55e10fb3d8f0 <unknown>
#12 0x55e10fb1df90 <unknown>
#13 0x55e10fb3eb7d <unknown>
#14 0x55e10fb0f578 <unknown>
#15 0x55e10fb63348 <unknown>
#16 0x55e10fb634d6 <unknown>
#17 0x55e10fb7d341 <unknown>
#18 0x7f0fad5a9b43 <unknown>

My code in the "get_doi" method:
def get_doi(self, query, page):
      """
        Get a list of dois from query massages and the exact page.
        :param query: the query text (e.g. battery materials)
        :param page: the number of page
        :return: a list of dois of the relevant query text and page.
        """

        if self.driver is None:
            driver = webdriver.Chrome()
        else:
            driver = self.driver

        if self.url is None:
            url = "http://pubs.rsc.org/en/results?searchtext="
            url = url + query
        else:
            url = self.url
        driver.get(url)
        wait = WebDriverWait(driver, self.max_wait_time)
        # To make sure we don't overload the server
        sleep(1)
        next_button = wait.until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "a[class^=paging__btn]")))[1]
        page_string = """document.querySelectorAll("a[class^=paging__btn]")[1].setAttribute("data-pageno", \""""\
                      + str(page) + """\")"""
        driver.execute_script(page_string)
        next_button.click()
        sleep(1)
        _ = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '.capsule.capsule--article')))
        doi_lists = driver.find_elements(By.PARTIAL_LINK_TEXT, 'https://doi.org')
        dois = [doi.text for doi in doi_lists]
        return dois

My code for downloading the articles:
    def download_doi(self, doi, file_location):
    """
    Download the html paper of the doi
    :param doi: doi of the paper
    :param file_location: the saving location
    :return:
    """
    doi = doi.split("org/")[-1]
    r = requests.get('http://doi.org/' + doi, headers={'User-Agent': 'Mozilla/5.0'})
    result = re.findall(r'https://pubs.rsc.org/en/content/articlehtml/.*?"', r.text)
    url = result[0][:-1]
    web_content = requests.get(url, headers={"User-Agent": "Mozilla/5.0"}).content

    result = self.get_rsc_abstract(web_content)
    exact_date = result['date'].split("/")
    doi = result['doi'].replace("/", "_")
    if len(exact_date) == 3:
        name = exact_date[0] + exact_date[1] + exact_date[2] + '_' + doi
    else:
        name = result['online_date'].replace("/", "") + '_' + doi

    with open(file_location + name + '.html', 'wb') as f:
        f.write(web_content)
    return

And the main method I am calling for the web-scraping:
def main(url, query, page, file_location):
    """
    RSC web-scraper runner
    :param url: the scraping url (or default)
    :param query: query text (e.g. battery materials)
    :param page: the page number of the query pages
    :param file_location: saving location
    :return:
    """
    scraper = RSCWebScraper(url=url)
    dois = scraper.get_doi(query=query, page=page)
    for doi in dois:
        try:
            scraper.download_doi(doi, file_location)
        # Some papers don't have html access
        except:
            continue
    return

if __name__ == "__main__":
    # Download papers within a certain date range
    url = "https://pubs.rsc.org/en/results/all?Category=All&AllText=water%20remediation&IncludeReference=false&Select" \
          "Journal=false&DateRange=true&SelectDate=true&DateToYear={}&DateFromYear={}&DateFromMonth={}&DateTo" \
          "Month={}&PriceCode=False&OpenAccess=false".format("2022", "2021", "06", "01")
    query = "water remediation"
    location = r"/home/ssarrouf/Documents/webscrape/to_date_papers/rsc/"
    for page in range(1, 120):
        main(url, query, page, location)

Changing the method for
wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '.capsule.capsule--article')))

``` did not give me any results, and I also changed the query / url text to various months and years to ensure that the request was properly loading. These did nothing and I got TimeoutExceptions for each attempt.


text:
Q: issus in memory managemant with json object I have a memory management problem at "Odoo_database_json"  when I sync it from odoo server as it receives a huge JSON object from the odoo server that includes an image, giving me an out of memory error.
I have tried things like garbage collection, trimming memory, and bitmap recycle().
public class Databasetask extends AsyncTask<Void, Void, Void> {

    @Override
    protected Void doInBackground(Void... params) {
        // TODO Auto-generated method stub

        try {
            Odoo o = new Odoo("http://10.0.2.2:8089");
            JSONArray database_list = o.getDatabaseList();
            Log.e("database_list.", database_list.toString());

            // Log.e("qqqqqqqqqq.", j1.toString());
            o.authenticate("admin", "a", "demo");// =========>aa set karvanu
            // che

            JSONArray fields = new JSONArray();
            fields.put("city");
            fields.put("name");
            fields.put("phone");
            fields.put("image");
            fields.put("create_date");
            fields.put("write_date");

            // android.os.Debug.dumpHprofData("com.serpentcs.AIOS8.hprof");
            // Debug.dumpHprofData("com.serpentcs.AIOS8.hprof");
            // System.gc();

            JSONObject jsonParams = new JSONObject();
            jsonParams.put("fields", fields);

            // Odoo_database_json=null;
            //==================================================================Error at here because of heap momory is full when i sync data from Odoo server
            Odoo_database_json = o.search_read(Modle, jsonParams); //<==error at here

            jsonArray_items = Odoo_database_json.getJSONArray("records");

            // int x = TRIM_MEMORY_COMPLETE;
            // Log.e("x....",""+x);

            // table exxist ...if u change filed pls..remove it
            tableExist = exists("res_partner");
            Log.e("table", "" + tableExist);
            // if exist does not create table
            if (tableExist) {
                Log.e("Log.....", "Table is exist");

            } else {
                Log.e("Log.....", "Table is not exist");
                JSONObject a = jsonArray_items.getJSONObject(1);

                Iterator<?> key_fields = a.keys();// ===givs fields

                myhelper = new OdooHelper(Listview_contect.this);
                myhelper.makeTable(key_fields);

            }

            // // ==get the records and put it into database..
            //
            publishProgress();
            // //uncaughtException
            // // Log.e("qqqqqqqqqq.", "fgh");

        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (OVersionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (OutOfMemoryError e) {
            // TODO: handle exception
            e.printStackTrace();
        }

...........................
sorry i dont know how to add new code because i m new ..user..pls any one edit it ..
 10-30 13:14:50.692: E/dalvikvm-heap(1419): Out of memory on a 2097168-byte allocation.
10-30 13:14:50.692: I/dalvikvm(1419): "AsyncTask #1" prio=5 tid=11 RUNNABLE
10-30 13:14:50.692: I/dalvikvm(1419):   | group="main" sCount=0 dsCount=0 obj=0xb4e89628 self=0xb767e758
10-30 13:14:50.692: I/dalvikvm(1419):   | sysTid=1435 nice=10 sched=0/0 cgrp=apps/bg_non_interactive handle=-1217926224
10-30 13:14:50.702: I/dalvikvm(1419):   | state=R schedstat=( 22190000000 5900000000 5215 ) utm=2068 stm=151 core=0
10-30 13:14:50.702: I/dalvikvm(1419):   at java.util.Scanner.expandBuffer(Scanner.java:~2067)
10-30 13:14:50.702: I/dalvikvm(1419):   at java.util.Scanner.readMore(Scanner.java:2031)
10-30 13:14:50.702: I/dalvikvm(1419):   at java.util.Scanner.findDelimiterAfter(Scanner.java:2009)
10-30 13:14:50.702: I/dalvikvm(1419):   at java.util.Scanner.setTokenRegion(Scanner.java:1923)
10-30 13:14:50.702: I/dalvikvm(1419):   at java.util.Scanner.hasNext(Scanner.java:541)
10-30 13:14:50.702: I/dalvikvm(1419):   at java.util.Scanner.hasNext(Scanner.java:519)
10-30 13:14:50.702: I/dalvikvm(1419):   at odoo.Odoo.convertStreamToString(Odoo.java:1140)
10-30 13:14:50.702: I/dalvikvm(1419):   at odoo.Odoo.requestData(Odoo.java:460)
10-30 13:14:50.702: I/dalvikvm(1419):   at odoo.Odoo.search_read(Odoo.java:726)
10-30 13:14:50.702: I/dalvikvm(1419):   at odoo.Odoo.search_read(Odoo.java:771)
10-30 13:14:50.702: I/dalvikvm(1419):   at com.serpentcs.client.Listview_contect$Databasetask.doInBackground(Listview_contect.java:188)
10-30 13:14:50.702: I/dalvikvm(1419):   at com.serpentcs.client.Listview_contect$Databasetask.doInBackground(Listview_contect.java:1)
10-30 13:14:50.702: I/dalvikvm(1419):   at android.os.AsyncTask$2.call(AsyncTask.java:288)
10-30 13:14:50.702: I/dalvikvm(1419):   at java.util.concurrent.FutureTask.run(FutureTask.java:237)
10-30 13:14:50.702: I/dalvikvm(1419):   at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
10-30 13:14:50.712: I/dalvikvm(1419):   at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
10-30 13:14:50.712: I/dalvikvm(1419):   at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
10-30 13:14:50.712: I/dalvikvm(1419):   at java.lang.Thread.run(Thread.java:841)
10-30 13:14:50.712: W/System.err(1419): java.lang.OutOfMemoryError
10-30 13:14:50.712: W/System.err(1419):     at java.util.Scanner.expandBuffer(Scanner.java:2067)
10-30 13:14:50.722: W/System.err(1419):     at java.util.Scanner.readMore(Scanner.java:2031)
10-30 13:14:50.722: W/System.err(1419):     at java.util.Scanner.findDelimiterAfter(Scanner.java:2009)
10-30 13:14:50.722: W/System.err(1419):     at java.util.Scanner.setTokenRegion(Scanner.java:1923)
10-30 13:14:50.722: W/System.err(1419):     at java.util.Scanner.hasNext(Scanner.java:541)
10-30 13:14:50.732: W/System.err(1419):     at java.util.Scanner.hasNext(Scanner.java:519)
10-30 13:14:50.732: W/System.err(1419):     at odoo.Odoo.convertStreamToString(Odoo.java:1140)
10-30 13:14:50.732: W/System.err(1419):     at odoo.Odoo.requestData(Odoo.java:460)
10-30 13:14:50.732: W/System.err(1419):     at odoo.Odoo.search_read(Odoo.java:726)
10-30 13:14:50.732: W/System.err(1419):     at odoo.Odoo.search_read(Odoo.java:771)
10-30 13:14:50.732: W/System.err(1419):     at com.serpentcs.client.Listview_contect$Databasetask.doInBackground(Listview_contect.java:188)
10-30 13:14:50.732: W/System.err(1419):     at com.serpentcs.client.Listview_contect$Databasetask.doInBackground(Listview_contect.java:1)
10-30 13:14:50.732: W/System.err(1419):     at android.os.AsyncTask$2.call(AsyncTask.java:288)
10-30 13:14:50.732: W/System.err(1419):     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
10-30 13:14:50.732: W/System.err(1419):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
10-30 13:14:50.732: W/System.err(1419):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
10-30 13:14:50.732: W/System.err(1419):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
10-30 13:14:50.732: W/System.err(1419):     at java.lang.Thread.run(Thread.java:841)


text:
Q: Problem with Ajax Helper in Cake PHP I am trying to implement the Ajax feature in the comments section of my blog. I have downloaded prototype-1.6.0.3.js and have placed it in the js folder inside webroot.
I have made the following changes in the layout file(default.ctp)
$javascript->link(array('prototype'));

Also, following code has been added to controllers
var $helpers = array('Html', 'Form', 'Ajax','Javascript');

This is my code in the posts_controller.php file
function view($id = null) {
        if (!$id) {
            $this->Session->setFlash(__('Invalid Post.', true));
            $this->redirect(array('action'=>'index'));
        }
        $post = $this->Post->read(null,$id);
        $comments = $this->Post->Comment->find('all',
array('conditions'=>array('Post.id'=>$id)));
        $this->set(compact('post','comments'));
    }

My code in view.ctp file

Comments

<?php foreach($comments as $comment): ?>

<?php echo $comment['Comment']['name']; ?>

<?php echo $comment['Comment']['content']; ?>

<?php endforeach; ?>
<?php echo $ajax->form('/comments/add','post',array('update'=>'comments'));?>
   <?php echo $form->input('Comment.name');?>
   <?php echo $form->input('Comment.content');?>
   <?php echo $form->input('Comment.post_id',array('type'=>'hidden','value'=>$post['Post']['id']));?>
   <?php echo $form->end('Add Comment');?>

I have added the following function in the comments_controller.php
function add() {
        if (!empty($this->data)) {
            $this->Comment->create();
            if ($this->Comment->save($this->data)) {
                $comments = $this->Comment->find('all',array('conditions'=>array('post_id'=>$this->data['Comment']['post_id']),'recursive'=>-1);
                    $this->set(compact('comments'));
                    $this->render('add_success','ajax');
                    } else {
                    $this->render('add_failure','ajax');
                    }
                 }
             }

And following is the code in the add_success.ctp file
<?php foreach($comments as $comment): ?>

<?php echo $comment['Comment']['name'];?>

<?php echo $comment['Comment']['content'];?>

<?php endforeach;?>

Now the problem is that I am not able to add comments. Nothing happens when I click on the add comments button. I have manually added comments in the databse and that works. But I am having problems when I am trying the Ajax Helper.
Where is the problem??And guys, sorry for such a long question.[:(]

A: Do you have firebug installed so you can test to see if it is making the ajax request?
Perhaps try doing $form->submit('Add Comment'); to generate the button and see if it makes a difference and actually performs the ajax request.
Do you get any javascript errors?

A: it looks like you're following the example from "Beginning CakePHP" I think I made the same error too
it's not mentioned in the book, but the name of the .js file (in webroot/js) must match the helper function argument, so do one of these:
1) rename prototype-1.6.0.3.js  (inside your webroot/js folder) to prototype.js
OR
2) change the helper function to
$javascript->link(array('prototype-1.6.0.3'));

A: If i remember correctly, you also need to include scriptaculous for the built in ajax functions to work correctly too...

A: This is not really an Answer but I thought its worth mentioning that I  too ran into this problem. And Yes I am using that book mentioned by @smchacko. I am using Prototype Version 1.7:
//this is how I called it and renamed it to prototype
<?php echo $javascript->link( array('prototype')); ?>

Interestingly enough to mention that I have fire bug as well as web Developer tool bar. Firebug does not return any errors but Chris Pederic's  plug-in has several warnings... Its too many to mention. This appears on the top right of your screen


text:
Q: i cant access data from my properties in java spring boot i have properties named application-QA1.properties
#Endpoint
web.loginPage=https://www.phptravels.net/

#login data
common.data.username=tes
common.data.password=tes

#Default Param
param.storeId=10001
param.channelId=tes-web
param.clientId=10001
param.requestId=RANDOM
param.businessChannel=web
param.requestParams={}
param.test=true

and i put it in:
src/test/resources

and i create class as instance for that properties named WebProperties.java
package com.project.automation.ui.properties;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Data
@Component("com.project.automation.ui.properties.WebProperties")
@ConfigurationProperties(prefix = "web")
public class WebProperties {
    private String loginPage;
}

and i put it in:
src/main/java/mypackage/properties

and i want to access that class variable on LoginPage.java
package com.project.automation.ui.pages;

import com.project.automation.ui.models.xpath.CommonXpathModel;
import com.project.automation.ui.properties.CommonProperties;
import com.project.automation.ui.properties.WebProperties;
import lombok.Data;
import net.serenitybdd.core.pages.PageObject;
import org.openqa.selenium.By;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Data
@Component("com.project.automation.ui.pages.LoginPage")
public class LoginPage extends PageObject {

  @Autowired
  CommonPage commonPage;

  @Autowired
  CommonXpathModel commonXpathModel;

  @Autowired
  WebProperties webProperties;

  @Autowired
  CommonProperties commonProperties;

  public void openPage(){
    //on this code i want to get that properties value through its class instance
    getDriver().get(webProperties.getLoginPage());
  }
}

the page i put it in:
src/main/java/mypackage/pages

and this is my pom.xml located in root of my project.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.project.automation.ui</groupId>
    <artifactId>wina</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.6.RELEASE</version>
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <serenity.version>1.9.45</serenity.version>
        <maven.failsafe.plugin>2.22.0</maven.failsafe.plugin>
        <selenium.version>3.14.0</selenium.version>
        <buildDirectory>${project.basedir}/target</buildDirectory>
        <serenity.testlink.integration.version>3.4.5</serenity.testlink.integration.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mustache</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>${selenium.version}</version>
        </dependency>
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-api</artifactId>
            <version>${selenium.version}</version>
        </dependency>
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-server</artifactId>
            <version>${selenium.version}</version>
        </dependency>
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-chrome-driver</artifactId>
            <version>${selenium.version}</version>
        </dependency>
        <dependency>
            <groupId>com.googlecode.lambdaj</groupId>
            <artifactId>lambdaj</artifactId>
            <version>2.3.3</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.8</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>net.serenity-bdd</groupId>
            <artifactId>serenity-core</artifactId>
            <version>${serenity.version}</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>net.serenity-bdd</groupId>
            <artifactId>serenity-cucumber</artifactId>
            <version>1.9.45</version>
        </dependency>
        <dependency>
            <groupId>net.serenity-bdd</groupId>
            <artifactId>serenity-spring</artifactId>
            <version>${serenity.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>net.serenity-bdd</groupId>
            <artifactId>serenity-rest-assured</artifactId>
            <version>${serenity.version}</version>
        </dependency>
        <dependency>
            <groupId>io.rest-assured</groupId>
            <artifactId>rest-assured</artifactId>
            <version>3.0.2</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <directory>${buildDirectory}</directory>
        <testOutputDirectory>${buildDirectory}/test-classes</testOutputDirectory>
        <outputDirectory>${buildDirectory}/classes</outputDirectory>
        <resources>
            <resource>
                <directory>src/test/resources</directory>
                <filtering>true</filtering>
                <includes>
                    <include>**/*.properties</include>
                </includes>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.2</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>test-jar</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-failsafe-plugin</artifactId>
                <version>${maven.failsafe.plugin}</version>
                <executions>
                    <execution>
                        <id>integration-test</id>
                        <goals>
                            <goal>integration-test</goal>
                            <goal>verify</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <includes>
                        <include>**/CucumberRunner.java</include>
                    </includes>
                    <systemPropertyVariables>
                        <cucumber.options>--junit,--step-notifications</cucumber.options>
                        <spring.config.location>classpath:/application-QA1.properties</spring.config.location>
                    </systemPropertyVariables>
                </configuration>
            </plugin>
            <plugin>
                <groupId>net.serenity-bdd.maven.plugins</groupId>
                <artifactId>serenity-maven-plugin</artifactId>
                <version>${serenity.version}</version>
                <executions>
                    <execution>
                        <id>serenity-reports</id>
                        <phase>post-integration-test</phase>
                        <goals>
                            <goal>aggregate</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

but it keeps return null.
please help me, i already read many tutorial but still no luck, beside i am beginner at spring boot. thank you

A: The problem is naming convention of properties file, Since you named it as application-QA1.properties it becomes profiles specific properties file Profile-specific properties and you can load those properties by making profile active in application.properties like here
spring.profiles.active=QA1

Or through command line
java -jar myproject.jar --spring.profiles.active=QA1

And another information, value in @Component annotation indicates the bean name

he value may indicate a suggestion for a logical component name, to be turned into a Spring bean in case of an autodetected component.

A: You indicated that the location of your properties file is:
<spring.config.location>classpath:/application-QA1.properties</spring.config.location>

But you put the properties file inside a package directory...
src/main/java/mypackage/properties

So when you build the project, the properties file is not going to end up in the root of your classpath... It is going to end up in the same package directory of your classpath. See for yourself.


text:
Q: Create variable over ssh in bash #!/bin/bash -x

ssh -T root@jumpbox ssh -T root@IP << EOF
YY=$(date +'%y')
echo $YY
EOF

OUTPUT:
Trying tunnel from jumpbox...
Pseudo-terminal will not be allocated because stdin is not a terminal.
-bash: line 6: YY: command not found

The variable I need to assign is more complex, it's not about year number as shown in my description.

A: When you don't quote the EOF in <<EOF, expansions are perfomed by the local shell inside the here document (so the $(date ...) is expanded by the local date and $YY is expanded to the value in the local shell (empty unless you have assigned a value earlier)). If you the content of the here-document to be passed verbatim to the remote shell, you need to quote the EOF one way or another:
ssh -T root@IP << 'EOF'
YY=$(date +'%y')
echo "$YY"
EOF


text:
Q: data Binding in lightning web component I am having two component databindingparent and databindingchild. I have input text in child when I enter value I am getting the value and on click of button firing event passing to parent and showing it.But on the onclick I am getting all the value as undefined.Either i need to handle on change of the lightning-input and store it and handle the on click of button and fire the event?.
/*Parent*/<template>
Hello! {name}
<c-databindingchild  onchangehandle={selectedname}></c-databindingchild>
</template>

/* eslint-disable no-console */
import { LightningElement,track,api } from 'lwc';
export default class DatabindingParent extends LightningElement {
@api recordId;
@track name;
selectedname(event) {
    console.log('eve---'+event.detail);
    this.name = event.detail;
}
}

/*child*/<template>
<lightning-input label="Name" value={name} name='nameValue'></lightning-input>
<lightning-button variant="base" label="Base" title="Event Button" onclick={handleClick} ></lightning-button>

/* eslint-disable no-console */
import { LightningElement,api} from 'lwc';
export default class Databindingchild extends LightningElement {
@api nameValue;
@api name;
handleClick(event) {
    console.log('going here----'+this.nameValue);
    console.log('going here----'+this.template.name);
    console.log('going here----'+this.name);
    console.log('going here----'+event.target.name);
    console.log('going here----'+event.target.value);
    event.preventDefault();
    const selectedEvent = new CustomEvent('changehandle', { detail: this.nameValue});
    this.dispatchEvent(selectedEvent);
}
}

A: Unlike aura which has two way bindings, lightning web components only have one way data binding. You will have to attach an event handler for the lightning-input for value change as shown below and populate the variable .
From the documentation note the below

The data binding between components for property values is one-way.
To communicate down from a parent component to a child component, set a property or call a method on the child component.
To communicate up from a child component to a parent component, send an event.

code for the child component is as below to make sure your properties are binded when input changes ,
 <template>
    <lightning-input label="Name" type="text" value={inputvalue} onchange={handleChange} name={inputboxname}></lightning-input>
    <lightning-button variant="base" label="Base" title="Event Button" onclick={handleClick}></lightning-button>
 </template>

The js code is below
import { LightningElement, api} from 'lwc';
export default class Databindingchild extends LightningElement {

  constructor() {
   super();
   this.inputboxname = 'Test Input';
  }

@api inputvalue;
@api inputboxname;

handleClick(event) {
    console.log('going here----'+this.inputvalue);
    console.log('going here----'+this.inputboxname);
    const selectedEvent = new CustomEvent('changehandle', { detail: this.inputvalue});
    this.dispatchEvent(selectedEvent);
 }

 handleChange(event) {
    this.inputvalue = event.target.value;
    this.inputboxname = event.target.name;
  }
 }

The console.log should return values .
Check for the sample in the playground .

A: LWC is designed with a one way data binding approach. Initially this can feel frustrating, especially for people who have come to love the simplicity of two way .Lightning web components allow one way binding but aura support two way binding.
One way binding follows from controller to view but vice versa is not possible.
One way binding means that the model is rendered in the view, but in order to update the model if the view changes, you must fire an event and handle that event to update the code in your controller.
One way binding example
Sample.html
<template>
   {firstname}
   <lightning-input type="text" label="name" value={firstname} onchange={handlechange}></lightning-input>
</template>

Sample.js
import { LightningElement, track, api } from 'lwc';
export default class Sample extends LightningElement {
   @api firstname="hello";
   handlechange(event){
  console.log(this.firstname);  // This will not change even we change the view text data.
   }
}

To make this two way binding we use event
import { LightningElement, track, api } from 'lwc';
export default class Sample extends LightningElement {
   @api firstname="hello";
   handlechange(event){
Vaar targetval=event.target;
this.firstname=targetval.value;
   }
}

A: /* eslint-disable no-console */
import { LightningElement,api} from 'lwc';
export default class Databindingchild extends LightningElement {
@api nameValue;
@api name;
handleClick(event) {
console.log('going here----'+this.nameValue);
console.log('going here----'+this.template.name);
console.log('going here----'+this.name);
console.log('going here----'+event.target.name);
console.log('going here----'+event.target.value);
event.preventDefault();
const selectedEvent = new CustomEvent('changehandle', { detail: this.nameValue});
this.dispatchEvent(selectedEvent);
}
}


text:
Q: Deploying a SOAP Webservice implementation from the module directory in JBoss Wildfly I've been experiencing issues deploying a SOAP webservice implementation which class files live inside of a Wildfly Module.  The module is a global module which the Web Application has access to (I know b/c it is able to access other classes stored within the module) and no deployment errors occur.  However, I also never receive a log stating "Adding service endpoint metadata" as it would under normal circumstances and a wsdl is never generated.
For reference, I have 3 other SOAP webservices deployed in the same container but all of their implementation classes exist inside of a jar residing within their corresponding web application.  Is their a known issue with storing the webservice implementation within a Module?  For reasons I cannot disclose, this needs to not be an issue.  Any help would be greatly appreciated.

A: After conversing with @federico-sierra we found the issue to be with the dependency declaration in /META-INF/MANFIEST.MF of the web application.
My original manifest file appeared as such:
Manifest-Version: 1.0
Dependencies: org.webservice.impl.library, org.apache.log4j
Built-By: usera
Build-Jdk: 1.7.0_55
Created-By: Apache Maven 3.2.2
Archiver-Version: Plexus Archive

When the dependency line should have contained 'annotations' next to my webservice classpath:
Dependencies: org.webservice.impl.library annotations, org.apache.log4j

Furthermore, after making this change my webservice implementation jar needed to be recompiled with the maven jandex plugin so the required jandex.idx would get generated inside of the jar.  The maven plugin description is location at: https://github.com/wildfly/jandex-maven-plugin.  Note: There is an ANT plugin available if needed.


text:
Q: Selenium c# wait.until(expectedconditions)... function fails to find objects/elements on screen I am new to using selenium Webdriver and writing c#. I was using lots of thread.sleep() commands in my script to make sure Selenium didn't try and click too quick. Upon lots of research I found this is frowned upon and there are "better" ways to do it, so I started to use:-
wait.Until(ExpectedConditions.ElementToBeClickable(By.Id("FieldId")));

Wait is defined in another class as:-
wait = new WebDriverWait(driver, new TimeSpan(0, 0, 0, 10));

I can only get this to work 2/10 times of running the script without getting :

No such element exception: cannot locate element......

I have tons of examples of this problem now I have stopped using thread.sleep. After lots of research I always come to find this is the advised way but it seems totally unreliable. Have I missed something? The element is always there after 2 seconds and the error occurs before 10sec has passed. I have read at least 10 other posts which sound similar but none of them have a solution which works...except Thread.Sleep(5000) !

A: Try adding the NoSuchElementException type to the IgnoreExceptionTypes of the waiter after you create it.
wait = new WebDriverWait(driver, new TimeSpan(0, 0, 0, 10));
wait.IgnoreExceptionTypes(typeof(NoSuchElementException));
wait.Until(ExpectedConditions.ElementToBeClickable(By.Id("FieldId")));

In general, if the waiter is returning before the timeout you indicate is expired, it's because an exception occurred that is not currently ignored.
The WebDriverWait class is derived from the DefaultWait class. Both of which  you can review on github which I found really helpful in understanding how to use it.


text:
Q: Is there a reason to use Link instead of NavLink in React Router? Since NavLink just have extra possible style than Link in React Router, can we always use NavLink? Is there a reason why we would use Link instead of NavLink?

A: See the documentation
Basically, NavLink and Link are exactly the same except NavLink adds the styling attributes when appropriate. It should be safe to always use NavLink. I prefer to only use NavLink for menu's but to each their own.


text:
Q: "buildozer android update" fails I have installed kivy(v:1.10.0) and buildozer on my mint.
I have my kivy app working fine.
I am following "installing buildozer with python3 support" to compile my apk file.
But I am facing error in step 5 while executing buildozer android debug deploy run in terminal.
The output is:
Check configuration tokens
Ensure build layout
Check configuration tokens
Preparing build
Check requirements for android
Install platform
Command failed: git clone -b stable --single-branch
https://github.com/kivy/python-for-android.git python-for-android-new-toolchain

Buildozer failed to execute the last command
If the error is not obvious, please raise the log_level to 2
and retry the latest command.
In case of a bug report, please add a full log with log_level = 2

Can anyone help, please?

A: That repository no longer include a branch name stable.
See the list of branches here.
Try and modify that step using a different branch name: master.
Change it in kivy/buildozer /buildozer/default.spec


text:
Q: Writing and reading data error java Exception in thread "main" java.lang.NullPointerException
    at MovieSeating.assignCustomerAt(MovieSeating.java:27)
    at Assignment8.main(Assignment8.java:84)
After I pull data from a txt file with a list of first and last names, it gives and error after I try and assign the name to a certain element that IS within the bounds of the 2d array
Thanks!

    public class Customer
     {
       private String lastName;
       private String firstName;

       // This constructor sets the first name and last name to "???�
       public Customer()
       {
              lastName = "???";
              firstName = "???";
       }

      // This constructor constructs a Customer object  given the last name and first name
       public Customer(String customerInfo)
       {
             int space = customerInfo.indexOf(" ");
             firstName = customerInfo.substring(0, space).trim();
             lastName = customerInfo.substring(space+1).trim();

       }

       // This constructor cConstructs a Customer object using the string containing customer's info.
       // It uses the StringTokenizer to extract first name, last name, id, the number of matinee tickets,
       // and the number of normal tickets.
       public Customer(String lName, String fName)
       {
             lastName = lName;
             firstName = fName;

       }

       // This method sets the last name.
       public void setLastName(String lName)
       {
             lastName = lName;
       }
       // This method sets the first name.
       public void setFirstName(String fName)
       {
             firstName = fName;
       }

       // This method returns the last name.
       public String getLastName()
       {
             return lastName;
        }
       // This method returns the first name.
       public String getFirstName()
       {
             return firstName;
       }

       // This method checks if a customer object passed as a parameter and itself (customer object)
       // are same using their last names and first names.
       public boolean equals(Customer other)
       {
             if (lastName.equals(other.lastName) && firstName.equals(other.firstName))
                 return true;
             else
                 return false;
       }

       // This method returns a string containing a customer's initials
       // (first characters of firstName and lastName.)
       public String toString()
       {
               String result = firstName.charAt(0) + "." + lastName.charAt(0) + ".";
               return result;
       }

     } // end of the class Customer

    class MovieSeating
    {
        private String[][] Seats;
        public MovieSeating(int rowNum, int columnNum)
        {
            String [][] Seats = new String[rowNum][columnNum];
            for (int r = 0; r < rowNum; r++)
            {
                for (int c = 0; c < columnNum; c++)
                {
                    Seats[r][c] = "?.?";
                }
            }
        }

        private Customer getCustomerAt(int row, int col)
        {
            System.out.println("Customer at row " + row + " and col " + col + "." );
            System.out.println(Seats[row][col]);

        }

        public boolean assignCustomerAt(int row, int col, Customer tempCustomer)
        {
            if (Seats[row][col].equals("?.?"))
            {
                tempCustomer = Seats[row][col];
                return true;
            }
            else {
                System.out.println("Seat taken..");
                return false;
            }

        }

        public boolean checkBoundaries(int row, int col)
        {
            if (col < 0 || row < 0)
            {
                return false;
            }
            else {
                return true;
            }
        }
    }

    import java.io.*;
    import java.util.*;

    public class Assignment8
    {
       public static void main(String[] args) throws IOException
       {

           MovieSeating theatreSeating;
           Customer tempCustomer;
           int requestedRow, requestedCol, row, col, rowNum, columnNum;
           String line, fileName;

           // to read input from a KEYBOARD.
           Scanner stdin = new Scanner(System.in);

           // Ask a user to enter a number of rows for a movie theatre seating from a KEYBOARD.
           System.out.println("Please enter a number of rows for a movie theatre seating.");
           rowNum = stdin.nextInt();

           // Ask a user to enter a number of columns for a movie theatre seating from a KEYBOARD.
           System.out.println("Please enter a number of columns for a movie theatre seating.");
           columnNum = stdin.nextInt();

           // instantiate a MovieSeating object
           theatreSeating = new MovieSeating(rowNum, columnNum);

           // get a file name read from a KEYBOARD.
           System.out.println("Please enter a file name");
           fileName = stdin.next();

           // create FileReader and BufferedReader object to
           // read from a file.
           FileReader fr = new FileReader (fileName);
           BufferedReader inFile = new BufferedReader (fr);

           /*** reading a customer's information from a FILE ***/
           line = inFile.readLine();

           /*** we will read line by line until we read the end of a given file ***/
           while (line != null)
           {
               System.out.println("\nA customer information is read from a file.");
               // printing information read from a file.
               System.out.println(line);

               // creating a customer object using information from a file
               tempCustomer = new Customer(line);

               // Ask a user to decide where to seat a customer by asking for row and column of a seat
               System.out.println("Please enter a row number where the customer wants to sit.");
               requestedRow = stdin.nextInt();
               row = requestedRow -1;

               System.out.println("Please enter a column number where the customer wants to set.");
               requestedCol =  stdin.nextInt();
               col = requestedCol -1;

               // Checking if the row number and column number are valid (exist in the theatre that we created.)
               if (theatreSeating.checkBoundaries(row, col) == false)
               {
                    System.out.println("\nrow or column number is not valid.");
                    System.out.println("A customer " + tempCustomer.getFirstName() + " " + tempCustomer.getLastName() + " is not assigned a seat.");
               }
               else
               {
                  // Assigning a seat for a customer
                  if (theatreSeating.assignCustomerAt(row, col, tempCustomer) == true)
                  {
                    System.out.println("\nThe seat at row " + row + " and column " + col + " is assigned to the customer " + tempCustomer.toString());
                    System.out.println(theatreSeating);
                  }
                  else
                  {
                    System.out.println("\nThe seat is taken.");
                  }
                }
               // Read next line in a FILE
               line = inFile.readLine();

           }//end of the while loop
             // Closing the file
           inFile.close();

         }

      }

A: O.K., here's your problem:
You have an array called seats. It is of the type String. So it could hold strings like "???" or "free seat". However, you try to put customers in it. That's exactly what the error message says: error: incompatible types tempCustomer = Seats[row][col]; ^ required: Customer found: String 1 error
Now you have a couple of options. A very simple one would be to change the type of the array to Customers. Instead of putting "???" on the free seats, put nothing to them. After creating an array, each "slot" is null, which actually means "nothing".
BTW: You are violating many recommended rules for writing Java code. This are just simple things and don't affect your code (it will run anyway ;). But it is a good practice to respect these unwritten rules (like put the { in the same line as the function-head or naming variables no with an upper-case letter).

A: As the error message itself say you are trying to assign String to Customer. At line 27
tempCustomer = Seats[row][col];

Seats is an String array and will return String which are trying to assign to Customer

A: The code to put a customer to the seat should be:
private Customer getCustomerAt(int row, int col)
{
    System.out.println("Customer at row " + row + " and col " + col + "." );
    System.out.println(Seats[row][col]);
            /** return customer */
    return new Customer(Seats[row][col]);
}

public boolean assignCustomerAt(int row, int col, Customer tempCustomer)
{
    if (Seats[row][col].equals("?.?"))
    {
       /** put a customer to the seat */
        Seats[row][col] = tempCustomer.toString();
        return true;
    }
    else
    {
        System.out.println("Seat taken..");
        return false;
    }
}


text:
Q: JHipster first application I'm a complete JHipster beginner and I want to create my first own JHipster application, but I got a problem that I'm not able to solve.
Firstly, I generated my app with following settings:
-Monolithic application
then I chose a base name and  a default Java package of my app and HTTP Session Authentication.
Later, I chose following:
-SQL, MYSQL, MYSQL, Yes, with ehcache, Gradle, CSS preprocessor : Yes, Internationalization: Yes, Testing framework: Gatling
And to that moment everything looked fine , then I wanted to create my entity as follows:
Yo jhipster:entity activitylist
and I added three fields:
-activityname (String), acitivitydate (LocalDate) and rating (Integer) and then I added relationship with entity user, type: many to one.
Afterwards
I used yo jhipster:entity user and I added following fields: login(String), name(String), surname(String) and added relationship one to many with field user.
However, everytime when I tried to run it with docker I got compile Java Failure and following warnings:
warning: Unmapped target property: "authorities".
    UserDTO userToUserDTO(User user);
error: Unknown property "password" in return type.
    User userDTOToUser(UserDTO userDTO);
I would appreciate any help.

A: The problem with your app is the name of your entity: user.
You need to change the name of this entity because when You name it as following You create a new Java class : User, however JHipster has its own built-in User Java class which is located in src/main/java/domain folder.
This class has its own getter, setter methods and mapper which operation is affected when your entity "user" is created.
You can notice this fact in Your warnings when compiler informs You that it encountered unknown properties in Your return type in User userDTOToUser. I would strongly recommend You changing name of the user entity and everything else should work fine.


text:
Q: How to report progress to all clients using MVC and self host signalr I am very new to SignalR.
I am trying to create a simulated conveyor that many clients can view the position of the conveyor (the simulated conveyor is a jQuery ui progressbar).
What I have (and posted below) works across many clients - but the more clients you open, the faster the conveyor runs.  it almost seems that each push to the client in turn posts back to the server and so on.
My question is how can I have multiple clients viewing this simulated conveyor and not have the conveyor increment faster base on number of clients viewing it?
Hub code
 public class ConveyorHub : Hub
{
    public static  int ConveyorPosition { get; set; }
    private Timer _timer;
    public override Task OnConnected()
    {
        Initialize();
        return base.OnConnected();
    }

    private void Initialize()
    {
        ConveyorPosition = 0;
        if (_timer == null)
        {
            _timer = new Timer(1000);
            _timer.Elapsed += (s, e) => Clients.All.reportConveyorMovement(ConveyorPosition++);
            _timer.Start();
        }
    }
}

Index.cshtml

Simulated Conveyor

Loading...

<link rel="stylesheet" href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css">

Any help would greatly be appreciated.

A: The problem is this line:
_timer.Elapsed += (s, e) => Clients.All.reportConveyorMovement(ConveyorPosition++);

Try this instead, the problem is that you are telling for each client to increment the conveyor position.  In this way you increment precisely once:
_timer.Elapsed += (s, e) => {
       ++ConveyorPosition;
       Clients.All.reportConveyorMovement(ConveyorPosition);
};