text:
Q: Decompose to more classes and add constructors I want to ask you if is it possible to change/decompose my code to 2-3 classes, add constructors (if possible not empty) and/or add more methods. If need program can have more functions.
 public class Testing {

            public static void main(String args[]) throws Exception {
                Scanner input = new Scanner(System.in);
                System.out.println("Select word from list:");
                System.out.println();

                try {
                    FileReader fr = new FileReader("src/lt/kvk/i3_2/test/List.txt"); // this is list of words, everything all right here
                    BufferedReader br = new BufferedReader(fr);
                    String s;
                    while((s = br.readLine()) != null) {
                        System.out.println(s);
                    }
                    fr.close();
                    String stilius = input.nextLine();   // eneter word which I want to count in File.txt
                    BufferedReader bf = new BufferedReader(new FileReader("src/lt/kvk/i3_2/test/File.txt")); // from this file I need to count word which I entered before

                    int counter = 0;
                    String line;

                    System.out.println("Looking for information");
                    ArrayList<String> resultList = new ArrayList<String>();
                    String name = null;
            while (( line = bf.readLine()) != null){
                    if (line.trim().length() == 0) name = null;
                    else if (name == null) name = line;
                    int indexfound = line.indexOf(stilius);
                          if (indexfound > -1) {
                   counter++;
                   resultList.add(name);
   }
                    }
                    if (counter > 0) {
                        System.out.println("Word are repeated "+ counter + "times");}
                        else {
                        System.out.println("Error...");
                    }
                    bf.close();

                }
                catch (IOException e) {
                    System.out.println("Error:" + e.toString());
                    }
                }
            }

Program counting words (entered by keyboard) from file.txt and elect who repeated this word for ex.: if I enter word: One It shows:
Word One repeated 3 times by John, Elisa, Albert

file.txt looks like:
John //first line - name
One
Three
Four

Peter //first line - name
Two
Three

Elisa //first line - name
One
Three

Albert //first line - name
One
Three
Four

Nicole //first line - name
Two
Four

I don't know really if is possible to decompose this code to 2-3 classes. If someone could help me, thank you very much.

A: I would start by defining two classes:

*

*WordFile

*WordFileEntry

A WordFile-object should consist of a list of WordFileEntry-objects. A WordFileEntry consists of String name and List<String> words.
The counting of repetitions could be done by a WordFile-object itself. The logic of reading a file could be written in the WordFile-class or a separate class.


text:
Q: Put multiple values in a single attribute of a struct I need put multiple values in a single attribute of a struct, the attribute that will receive the values is LPSTR, I was trying to pass all this as a vector, compile, but it does not work as I would like.
My struct:
typedef struct _wfs_pin_caps
{
WORD                wClass;
WORD                fwType;
............More...............
BOOL                bIDConnect;
WORD                fwIDKey;
WORD                fwValidationAlgorithms;
WORD                fwKeyCheckModes;
LPSTR               lpszExtra; //This attribute must receive more than one value
} WFSPINCAPS, * LPWFSPINCAPS;

As I'm trying to do:
HRESULT WINAPI WFPGetInfo(HSERVICE hService, DWORD dwCategory, LPVOID   lpQueryDetails, DWORD dwTimeOut, HWND hWnd, REQUESTID ReqID) {

    ...

    result = WFMAllocateMore(sizeof(WFSPINCAPS), lpWFSResult, &lpWFSResult->lpBuffer);

    ...

    //This Values
    vector<LPSTR> Tokens;
        Tokens[1] = (LPSTR)"Value1";
        Tokens[2] = (LPSTR)"Value2";
        Tokens[3] = (LPSTR)"Value4";
        Tokens[4] = (LPSTR)"Value5";

        PinCapabilities.lpszExtra = (LPSTR)&Tokens; //Pass HERE

    memcpy(lpWFSResult->lpBuffer,&PinCapabilities,sizeof(WFSPINCAPS));

    ...
return WFS_SUCCESS;

A: Your question is very unclear, but if I understand it, the problem is that you are setting lpszExtra to a local vector Tokens (stored in the stack) and that will be destroyed at the end of that function.
One way would be creating the vector in the heap like this:
// Create a new vector in the heap of 5 elements (0..4)
vector<LPSTR> &Tokens = *new vector<LPSTR>(5);
Tokens[1] = (LPSTR) "Value1";
Tokens[2] = (LPSTR) "Value2";
Tokens[3] = (LPSTR) "Value4";
Tokens[4] = (LPSTR) "Value5";

PinCapabilities.lpszExtra = (LPSTR) &Tokens; //Pass HERE

// Assuming that lpBuffer has room for a WFSPINCAPS structure
memcpy(lpWFSResult->lpBuffer, &PinCapabilities, sizeof(WFSPINCAPS));

Now the ((LPWFSPINCAPS)lpWFSResult->lpBuffer)->lpszExtra contains a valid pointer to a vector that can be used in any other function like this:
LPWFSPINCAPS pPinCapabilities = (LPWFSPINCAPS) lpWFSResult->lpBuffer;
vector<LPSTR> &Tokens = *(vector<LPSTR> *) pPinCapabilities->lpszExtra;
LPSTR str = Tokens[3]; // Will get "Value4"

But don't forget that in some point you will have to release the vector's memory:
LPWFSPINCAPS pPinCapabilities2 = (LPWFSPINCAPS) lpWFSResult->lpBuffer;
delete (vector<LPSTR> *) pPinCapabilities2->lpszExtra;

And please next time try to create a Minimal, Complete, and Verifiable example to help us to help you.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to parse custom multiple Date formats in Java I want to parse custom multiple Date formats in Java. Here is my code
Scenario 1:
Order of patterns:

*

*yyMMdd'h'HH

*yyMMdd

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendOptional(DateTimeFormatter.ofPattern("yyMMdd'h'HH"))
.appendOptional(DateTimeFormatter.ofPattern("yyMMdd")).toFormatter();

Works:
String dateString1 = "201028h05";

LocalDateTime date1 = LocalDateTime.parse(dateString1, formatter);

Doesn't works:
String dateString2 = "201028";

LocalDateTime date1 = LocalDateTime.parse(dateString2, formatter);

Scenario 2:
Order of patterns:

*

*yyMMdd

*yyMMdd'h'HH

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendOptional(DateTimeFormatter.ofPattern("yyMMdd")).toFormatter();
.appendOptional(DateTimeFormatter.ofPattern("yyMMdd'h'HH"))

Doesn't Work:
  String dateString1 = "201028h05";

    LocalDateTime date1 = LocalDateTime.parse(dateString1, formatter);

Works:
String dateString2 = "201028";

LocalDateTime date1 = LocalDateTime.parse(dateString2, formatter);

How to make it work for both of the date patterns irrespective of any input pattern order. I don't want to use any external dependency for this.

A: You can use [] to define the optional parts within a pattern. Additionally you need to set defaults to not get an exception when no time is supplied.
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
        .appendPattern("yyMMdd['h'HH]")
        .parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
        .parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
        .parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
        .toFormatter();

String dateString1 = "201028h05";
LocalDateTime date1 = LocalDateTime.parse(dateString1, formatter);
System.out.println(date1);

String dateString2 = "201028";
LocalDateTime date2 = LocalDateTime.parse(dateString2, formatter);
System.out.println(date2);

Output:
2020-10-28T05:00
2020-10-28T00:00


text:
Q: how to remove the gridView extra space it give between widgets - Flutter i am working on this flutter app where i need to show the children in a grid view, so i used a column widget in side GridView.builder like shown below, i want to remove the sapcing where its marked in the red, and leave it to be responsive somehow...
GridView widget:
GridView.builder(
    gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(
      crossAxisSpacing: 10,
      mainAxisSpacing: 10,
      maxCrossAxisExtent: 450,
    ),
    primary: false,
    shrinkWrap: true,
    padding: const EdgeInsets.only(
      right: 25,
      left: 25,
      top: 20,
    ),
    itemCount: data.length,
    itemBuilder: (ctx, index) {
      return VideoWidget(
        oneVideoData: data[index],
      );
    },
  ),

VideoWidget:
Container(
      color: Colors.red,
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Container(
            width: double.infinity,
            decoration: BoxDecoration(
              ...
            ),
            child: Row(
              children: [
                ...
              ],
            ),
          ),
          Stack(
            alignment: AlignmentDirectional.center,
            children: [
              _videoPlayerControllerFFrame.value.isInitialized
                  ? AspectRatio(
                      aspectRatio:
                          _videoPlayerControllerFFrame.value.aspectRatio,
                      child: VideoPlayer(
                        _videoPlayerControllerFFrame,
                      ),
                    )
                  : Container(
                      height: 250,
                    ),
              _isVideoLoading
                  ? const CircularProgressIndicator(
                      color: Colors.yellow,
                    )
                  : IconButton(
                      onPressed: () {
                        showDialog(
                            context: context,
                            builder: (context) {
                              return VideoPlayerWidget(
                                oneVideoData: widget.oneVideoData,
                                videoController: _videoPlayerController,
                              );
                            });
                      },
                      icon: Icon(
                        Icons.play_arrow,
                        color: Theme.of(context).colorScheme.tertiary,
                        size: 50,
                      ),
                    ),
            ],
          ),
          Container(
            width: double.infinity,
            padding: const EdgeInsets.symmetric(
              horizontal: 10,
            ),
            ...
            ),
          ),
        ],
      ),
    );

this a screen shot of the output:

i want to get rid of the red space in the bottom.
Thanks in advance

A: Try below code hope its help to you.
GridView.builder(
  shrinkWrap: true,
  gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
    crossAxisCount: 2,
  ),
  itemCount: 6,
  itemBuilder: (BuildContext context, int index) {
    return Card(
      elevation: 5,
      shadowColor: Colors.grey,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(
          10,
        ),
      ),
      margin: EdgeInsets.all(5),
      child: Container(
        height: 200,
        width: 200,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            Padding(
              padding: EdgeInsets.all(2),
              child: Row(
                children: [
                  Container(
                    decoration: BoxDecoration(
                      shape: BoxShape.circle,
                      border: Border.all(
                        color: Colors.black,
                        width: 1.0,
                      ),
                    ),
                    child: CircleAvatar(
                      radius: 20,
                      backgroundImage: NetworkImage(
                        'https://miro.medium.com/max/1400/1*-6WdIcd88w3pfphHOYln3Q.png',
                      ),
                    ),
                  ),
                  SizedBox(
                    width: 10,
                  ),
                  Text('Person ${index.toString()}'),
                ],
              ),
            ),
            Expanded(
              child: Container(
                decoration: BoxDecoration(
                  image: DecorationImage(
                    fit: BoxFit.fill,
                    image: NetworkImage(
                      'https://miro.medium.com/max/1400/1*-6WdIcd88w3pfphHOYln3Q.png',
                    ),
                  ),
                ),
              ),
            ),
            Container(
              padding: const EdgeInsets.all(8.0),
              decoration: BoxDecoration(
                color: Colors.yellow,
                borderRadius: BorderRadius.only(
                  bottomLeft: Radius.circular(10.0),
                  bottomRight: Radius.circular(10.0),
                ),
              ),
              child: Text(
                'Awesome Product From Person ${index.toString()}',
              ),
            ),
          ],
        ),
      ),
    );
  },
),

Result Screen->


text:
Q: Perl regular expressions compare text form of HTML I am very new in Perl.
Previously two texts are compared this way:
        if($arr1[$k1-1] eq $arr2[$k2-1])

Now, I am looking for a Perl regex solution to compare two strings with each other in the form that it

*

*ignores case sensitivity

*All punctuation symbols are ignored

*All HTML tags such as ,
, ,  are ignored

I also need the number of words that are different between two texts (regardless of aforementioned cases)
Is there any solution for that in Perl?

A: take a look on Text::WordDiff or String::Diff module (maybe Text::Diff is enough too).
Only by coding , I guess it's impossible to make in one single step.
without modules I should make the following steps:
First remove all html tags and punctuation (replace them with nothing or one space, depending on what you want, they are word separater or not) and after that you can compare them or count the differences.
1: remove html tags and punctuations:
$string =~ s/<[^>]+?>|[[:punct:] ]/ /igm; #replace with space in this case

after that remove multiple white spaces - not need if you use /x -  ($string =~ s/\s+/ /igm;) , and compare them with eq or regex ($string1 =~ //is;), using the /x modifier ( /x = Extended with whitespace and comments; and depends on regex motor which you use) .
after that you need a function to eliminate words present on both texts (I guess multiple presence is ignored too) and get the count of remaining array.
code examples you can find here
I hope this helps.

A: #subroutine to clean html tags, pontuation and spaces > 2
sub clean {
my ($string) = @_;
$string =~ s/(<.+?>|[^\w\s])//ig;
$string =~ s/[\s]{2,}//ig;
return $string;
}

#clean the strings
my $str1 = clean(',
, ,  test 123');
my $str2 = clean(',  test 123
, <im g src="aaaa.png" />, ');

#compare two strings
if($str1 eq $str2){
print "equal"
}else{
print "not equal";
}

LIVE DEMO


text:
Q: Can't render a cube with three.js, when I have prepared the OO-structure of my application To render a cube or any other geometric figure with three.js is as clear as a crystal, when your code is rather simple, but when you are going to prepare a future structure of your application with some module logic in OO-style, you may got some problems. So have I...
If you doubt about my possibilities to rotate a cube with a SIMPLE code, you view a link at CodeReview to begin trust me :)
https://codereview.stackexchange.com/questions/33375/webgl-three-js-simple-application-only-js-without-html-css
But this question is about other problem... I've prepared an application in protype OO-style (which I suppose is primarily correctly designed), but I have a trouble with a simple render :(
Full source code:
http://jsfiddle.net/85TXa/
There are NO errors in console, when I run it at localhost:

The part with requestAnimationFrame( opt... ) also didn't throw any exception to console:

And as you are able to see, the rendering required loop is able to be caught with the breakpoints... If to check the children collection of scene, there is a cube:

So... There is a mesh of cube geometry, which was successfully added. The loop with requestAnimationFrame/rendering process can be caught at any time.
I suggest... That may be a problem with the bind() function, which I've used in:
GC3D.Utils.prototype.renderScene = function() {
    // about bind()
    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
    requestAnimationFrame( GC3D.Utils.prototype.renderScene.bind( this ) );
    this.renderer.render( this.scene, this.camera );

    // for test purpose only
    this.scene.children.filter(function( item ) {
        if ( item instanceof THREE.Mesh ) item.rotation.x += 0.02;
    });
    //
};

Maybe there is a problem right here? Please give me a piece of advice!
Thank you
PS: the code I'm publishing is truly developed by myself (you may also reserve my nickname on SO, it's a hint :) ), I also have positive resolution from my company to make these sources public, so don't be afraid of comments in the beginning of the js file :)
UPDATE #1:
I've found, that I forgot to set a position of my Camera, I've added some code:
GC3D.Utils.prototype.setCameraPosition = function( camera, newPosition ) {
    if ( camera instanceof THREE.Camera ) camera.position.set( newPosition.x, newPosition.y, newPosition.z );
    else return -1;
};
...
this.utils.setCameraPosition( this.utils.camera, { x: 3, y: 3, z: 3 } );

But, no success! :( The box isn't shown... Console shows, that camera has new position, which I've set:

New full source code: http://jsfiddle.net/naFLN/

A: All is normally with the bind() function in GC3D.Utils.prototype.renderScene.
The actual problem was in forgetting appending renderer's DOM element to the body of document:
document.body.appendChild( this.utils.renderer.domElement );
this.utils.renderer.setSize( window.innerWidth, window.innerHeight );

The lines above repaired my application and now it works well!


text:
Q: Why am i getting this error? need help please I am getting this error.. code not submitting
need help thanks in advance

A: I believe your error is in finding the midpoint.
In python, if we use len(lst)/2 it will return float value.
The Index of list cannot be a floating point value.
Change your line to:
midpoint = len(lst)//2

This will return an Integer value as output.


text:
Q: How does this non-isolated buck converter work? I found this converter-circuit on the Internet. I will use it to power an IR2153, which contains a 15,6V zener.
I chose to use it because of the large losses of a resistive dropper.
The unmarked voltages are unknown.
Diodes- high speed (BA159, UF4007 etc.)

A: Very inefficiently: The 0.22uF cap and 100 ohm resistor create an RC oscillator, periodically turning on BUX85. The 4.7mH inductor smoothes out the voltage somewhat, and the zener tries to make it a regulated 15ish volts. Altogether it's an inefficient and dangerous design. Good luck getting it to pass UL.


text:
Q: Deselecting option from BindableRadioGroup in Xamarin.Forms I am using this control from XLabs project. Binding and selecting works fine, but I am using this control in some kind of survey and I would like to deselect the previous answer (option in this control) after client click Next button to see next question. Any ideas how to do this?
<controls:BindableRadioGroup
                ItemsSource="{Binding Answers}"
                SelectedIndex="{Binding AnswerSelected, Mode=TwoWay}"
                Style="{StaticResource radioGroupStyle}" />

The command binded to the button:
public IAsyncCommand NextCommand
    {
        get
        {
            return new AwaitableDelegateCommand(async () => await Next(), CanGoToNextQuestion);
        }
    }

and methods:
private async Task Next()
    {
        CurrentQuestionIndex++;

        AnsweredQuestions.Add(
            new QuestionDto
            {
                QuestionId = CurrentQuestion.QuestionId,
                QuestionText = CurrentQuestion.QuestionText,
                Answer = Answers.ElementAt(AnswerSelected).Value,
            });

            // some stuff here

        AnswerSelected = -1;
    }

    private bool CanGoToNextQuestion()
    {
        return AnswerSelected != -1;
    }

A: The answer is not very elegant and not in MVVM style but is working. Code posted below should be placed in CodeBehind in the View.
    void Handle_Clicked(object sender, System.EventArgs e)
    {
        ClearRadioGroup();
    }

    private void ClearRadioGroup()
    {
        foreach (var child in grupa.Children)
        {
            var radio = (CustomRadioButton)child;
            radio.Checked = false;
        }
    }


text:
Q: tr1::hash for uint64_t I'm trying to hash a 64 bit integer,
uint64_t temp = ...;
return tr1::hash<uint64_t>(temp);

However I get the error,
error: no matching function for call to 'std::tr1::hash<long long unsigned int>::hash(uint64_t&)'

Why doesn't this work?

A: hash is a class. You have to make an object:
return std::tr1::hash<uint64_t>()(temp);
//                            ^^^^


text:
Q: How write performance can be improved for RecordWriter Can anyone help me out finding correct API to improve write performance?
We use MultipleOutputs<ImmutableBytesWritable, Result> class to write data we read from a table, we use the newly created file as a backup. We face performance issue in write using MultipleOutputs, it takes nearly 5 seconds for every 10000 records we write.
This is the code we use:
  Result[]  results = // result from another table
  MultipleOutputs<ImmutableBytesWritable, Result>  mos = new MultipleOutputs<ImmutableBytesWritable, Result> ();
  for(Result res : results ){
    mos.write(new ImmutableBytesWritable(result.getRow()), result, baseoutputpath);
  }

We get a batch of 10000 rows and write them in a loop, with baseoutputpath changing depending on Result content.
We are facing performance dip when writing into MultipleOutputs, we suspect that it might be due to writing in a loop.
Is there any other API in maprdb or HBase which push data to database using fewer RPC calls by buffering upto certain limit.
We write data as records so no file system write class would work for us.
Please note that we use mapreduce job to do all of the above.


text:
Q: How can I play MusicXML file on Android? Are there any existing tools or libraries for this? I am currently trying to develop an application that can take an image of a sheet music and make it to a musicxml format and play the corresponding audio. And I am stuck on how to exactly play an audio from musicxml.

A: It's not free, but the SeeScore SDK will do this: http://www.seescore.co.uk/developers/seescore-sdk/

A: Some versions of JFugue can parse MusicXML.
There are Android ports of JFugue as well.
jfugue.org
JFugue-for-Android


text:
Q: Vertical alignment issue on browser width resize I have a webpage with a image placed onto it. the webpage the image is placed onto is a very long vertical page (4000px) for silly idea reasons.
The image I am placing is of a robot charging out of a city backdrop and I can hover over it and it fades into view. I've been testing out different browsers etc and the Firefox Mobile/Tablet scale view etc and it brought to my attention a few issues.
I've stabilized every other image in the webpage but 1. the robot: for some reason it just will not stay in one place when it resizes. When I Shift the Width scale of a window, the robot shrinks (as wanted) But also scales up or down from its original position.
I've been trying to suss it and no matter what solution, the robot will not stay in the same place and resize. It will always move up or down away from its original position due to resizing. I also cannot have the image at 100% as it's then far too large for the picture.
And because of it being a 4000px vertical screen, no matter how I resize the original image it will always stretch to suit the 4000px.
So I'm a bit stuck. Here is a little code to see if anybody can adjust this so the robot fits.

   <embed  src="menulista.html" style="position:fixed; top:0%;left:8.0%; width:100%; height:10%; z-index:100000;">

I am assuming that the issue is due to the large vertical image (4000px) throwing the size differential out of sync...
I can diagonally shift the window size and the image stays put in the correct position, but because of the large vertical backdrop. When i resize the width only of the image - i get the out of position issue... Thanks for any advice in advance.
http://jsfiddle.net/MgcDU/7239/
like this fiddle , but with a image that has to be at 40% size on a 4000px background image...Tricky . the 40% image just will not stay put... and i cant go 100% or the image is too big....

A: I sorted it, for those in the same position, it really is an easy fix... see code...

   <embed  src="menulista.html" style="position:fixed; top:0%;left:8.0%; width:100%; height:10%; z-index:100000;">


text:
Q: Python Overwrite Dictionary to Text File doesn't work... why?
I've been previously writing code for a quiz program with a text file that stores all of the participants' results. The code that converts the text file to a dictionary and the text file itself are shown below:
Code:
import collections
from collections import defaultdict
scores_guessed = collections.defaultdict(lambda: collections.deque(maxlen=4))
with open('GuessScores.txt') as f:
    for line in f:
        name,val = line.split(":")
        scores_guessed[name].appendleft(int(val))

for k in sorted(scores_guessed):
    print("\n"+k," ".join(map(str,scores_guessed[k])))

writer = open('GuessScores.txt', 'wb')

for key, value in scores_guessed.items():
    output = "%s:%s\n" % (key,value)
    writer.write(output)

The text file appears like this:
Jack:10
Dave:20
Adam:30
Jack:40
Adam:50
Dave:60
Jack:70
Dave:80
Jack:90
Jack:100
Dave:110
Dave:120
Adam:130
Adam:140
Adam:150

Now, when I run the program code, the dictionary appears like this:
Adam 150 140 130 50

Dave 120 110 80 60

Jack 100 90 70 40

Now, this arranges the dictionary into order of highest scores, and the top 4 scores!
I want the python IDLE to overwrite the GuessScores.txt to this:
Adam:150
Adam:140
Adam:130
Adam:50
Dave:120
Dave:110
Dave:80
Dave:60
Jack:100
Jack:90
Jack:70
Jack:40

BUT when I run the code, this error appears:
Traceback (most recent call last):
  File "/Users/Ahmad/Desktop/Test Files SO copy/readFile_prompt.py", line 16, in <module>
    writer.write(output)
TypeError: 'str' does not support the buffer interface

The GuessScores.txt file is empty because it cannot write to the file, since there is the error above.
Why is this happening? And what is the fix? I have asked this previously but there were numerous issues. I am running Python 3.3.2 on a Mac 10.8 Mavericks iMac, if that makes any help.
Thanks,
Delbert.

A: The first issue is that you are trying to write text to a file that you opened in binary mode. In 3.x, this will no longer work. "text" vs. "binary" used to mean very little (only affecting line-ending translation, so no difference at all on some systems). Now it means like what it sounds like: a file opened in text mode is one whose contents are to be treated like text with some specific encoding, and a file opened in binary mode is one whose contents are to be treated as a sequence of bytes.
Thus, you need open('GuessScores.txt', 'w'), not open('GuessScores.txt', 'wb').
That said, you really should be using with blocks to manage the files, and you're going to have to write code that actually formats the dictionary content in the way you want. I assume you intend to output in sorted name order, and you need to iterate over each deque and write a line for each item. Something like:
with open('GuessScores.txt', 'w') as f:
    for name, scores in sorted(scores_guessed.items()):
        for score in scores:
            f.write("{}:{}\n".format(name, score))

(Note also the new-style formatting.)
If necessary, you can explicitly specify the encoding of the file in the open call, with the encoding keyword parameter. (If you don't know what I mean by "encoding", you must learn. I'm serious. Drop everything and look it up.)

A: The writing problem has to do with the b in your open function. You've opened it in binary mode, so only bytes can be written. You can either remove the b or call bytes on output to give it the right type. You have a logic error anyway though. When I run it on Python 2.7, the output to GuessedScores.txt is this:

Dave:deque([120,110,80,60],maxlen=4)
   Jack:deque([100, 90, 70, 40], maxlen=4)
   Adam:deque([150, 140, 130, 50], maxlen=4)

So your values are the whole deques, not the individual scores. You'll have to format them, similar to how you did in your print statement.


text:
Q: Call monadic function inside transformer stack Took my first crack at Monad Transformers. Wrote a simple genetic algorithm for what my class calls the "facility location" problem. The algorithm is not so important.
I generally followed the format explained in this chapter of Real World Haskell.
My transformer stack looks like this
newtype FacilityApp a = MyA {
   runA :: RandT StdGen ( ReaderT Environment ( StateT (Population, Int) IO)) a
  } deriving (Monad, MonadIO, MonadReader Environment, MonadState (Population,Int),     MonadRandom)

runFacility :: FacilityApp a -> Input -> StdGen -> IO a
runFacility k input g =
  let env = mkEnv input defParms
      (pop, g') = runRand (genInitialPopulation env) g
      state = (pop, numRounds defParms)
      ra = runA k
      rr = runReaderT rrand env
      rs = evalStateT rr state
      rrand = evalRandT ra g'
  in rs

Later in my code, I define my main "step" action for running a round of mating and surviving. In my step action, I have no trouble generating a random number and using that. However, I'd like to move the randomness of a particular function out of the step action and into that function. Unfortunately I'm getting type errors, and need some schooling on both why this doesn't work, and how to make this work.
You probably don't really need this, but my mate function just stitches two vectors together:
mate :: CustomerService -> CustomerService -> Int -> CustomerService
mate a b split = (fst $ V.splitAt split a) V.++ (snd $ V.splitAt split b)

So, this works:
offspring' :: CustomerService -> CustomerService -> Int -> (CustomerService, CustomerService)
offspring' a b split = (mate a b split, mate b a split)

step :: FacilityApp [CustomerService]
step = do
  (pop, n) <- get
  env <- ask
  let e = (warehouses env, customers env)
  let sorted@(p1:p2:_) = sortBy (sortByCost e) $ filter (validSolution e) pop
  let (_:_:rest) = reverse sorted
-- these next two lines are of my concern
  split <- getRandomR (1, V.length p1)
  let (c1,c2) = offspring' p1 p2 split
-- eventually put the new children in the state and step again
  put (c1:c2:rest, (n-1))
  if n > 0 then step else return pop

BUT I would really rather define offspring like so:
offspring :: (RandomGen g) => CustomerService -> CustomerService -> Rand g (CustomerService, CustomerService)
offspring a b = do
  split <- getRandomR (1, V.length a)
  return (mate a b split, mate b a split)

However when I try to call this function in my step action with something like
(c1,c2) <- offspring p1 p2

The compiler yells at me that type Rand doesn't match expected type FacilityApp... which I guess makes sense to me, but I'm not sure how to make this work for me.
I think maybe this needs some type of lifting and returning? But I can't figure it out. Can someone walk me through the problem here?
As a side question, notice that I am using the StateT to hold my round counter. This is faster than adding an argument to step. Is there an even more efficient way to take care of this?

A: Your offspring function returns a Rand computation. Rand, however, is just a specific MonadRandom instance (is is RandT over Identity), and not your FacilityApp monad. You should either change Rand to FacilityApp or, given that you are only using MonadRandom functions, generalise the type to any MonadRandom:
offspring :: (MonadRandom m) => CustomerService -> CustomerService
          -> m (CustomerService, CustomerService)


text:
Q: Android Kotlin: " MISSING_PERMISSION_ACCESS_COARSE_LOCATION" I am currently on android SDK level 29. (Android 10/11)
In my android manifest I grant permissions as such:
    <uses-permission android:name="android.permission.BLUETOOTH"/>
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />

I also grant location permissions for MainActivity, which is the parent activity for the fragment that uses user location data as such:
    <application>

        <service
            android:name=".ui.MainActivity"
            android:foregroundServiceType="location"/>

    </application>

However, Compiler still says I am "MISSING_PERMISSION_ACCESS_COARSE_LOCATION"
Does this have something to do with the user having to grant location permissions in the runtime?
Also, the reason I need such permissions is for Google Nearby API, which might also need separate background location permissions.
However, as far as my knowledge goes, after adding the two pieces of code above in the Android Manifest, background location permissions should also be granted.
What could be the problem here?


text:
Q: jQuery get response from php file after posting I'm posting some data to a php file with jquery. The PHP file just saves the data and prints the success of fail message. I would like to get the message generated by php file and embed in a div. I'm unable to figure out how i can return the message from PHP file.
Here is my code:
jQuery:
$(document).ready(function(){

    $('#submit').click(function() {

        $.ajax({
            type : 'POST',
            url : 'post.php',
            data: {
                email : $('#email').val(),
                url   : $('#url').val(),
                name  : $('#name').val()
            },
        });
    });
});

PHP:
<?php
//save data
$message = "saved successfully"
?>

A: Try -
$(document).ready(function(){

    $('#submit').click(function() {

        $.ajax({
            type : 'POST',
            url : 'post.php',
            data: {
                email : $('#email').val(),
                url   : $('#url').val(),
                name  : $('#name').val()
            },
            success:function (data) {
                $("#yourdiv").append(data);
            }
        });
    });
});

This uses the success callback of the ajax function to return your data back to the page within the data parameter. The callback function then appends your data to a div on the page.
You'll also need to -
echo $message

In your php page to give jQuery some data to work with.

A: Did you look at the properties of the ajax method yet?
From the jQuery site:
$.ajax({
  url: 'ajax/test.html',
  success: function(data) {
    $('.result').html(data);
    alert('Load was performed.');
  }
});

Of course, your PHP need to echo something (a JSON object preferably) that returns to the script.


text:
Q: Looking for some Abstract Proof help about proving a number group is commutative I'm a bit confused on where to begin on this proof.  I understand that in order to prove a group, $G$, is commutative, I'd say $a,b \in G$, then show that $ab = ba$.
Here is the theorem: "If $g^{-1}=g$ for all $g\in G$, then $G$ is commutative."
However, I'm not entirely sure how I can use the inverse property provided in this theorem to show the commutative property.
Would my proof utilize the idea that $a * a^{-1} = 1$ and simply show that $a^{-1} * a = 1$ and then show the same for $b$ or am I looking at this the wrong way?
Thank you in advance for any insight you can provide! :)
Here is what I had submitted to my professor, which he quickly sent back for me to rework and resubmit:
Assume $g^{-1}=g$ for all $g \in G$. Then, we must show that $g(g^{-1}) = (g^{-1})g$.  From the definition of an inverse, we know that $g * g^{-1} = 1$. We also know that the inverse of $g^{-1}$ is $g$ and $g^{-1} * g  = 1$.  Hence, by substitution, we can express $g(g^{-1}) = (g^{-1})g$. Thus, we conclude that $G$ is commutative.

A: If $a,b\in G$, then $a^{-1},b^{-1}\in G$, and $(a^{-1}b^{-1})^{-1}=a^{-1}b^{-1}$. In other words, $ba=a^{-1}b^{-1}=ab$.

A: You need to prove $ab=ba$. You know $a=a^{-1}$ and $b=b^{-1}$. Then $ab=a^{-1}b^{-1}=(ba)^{-1}=ba$, which concludes the proof.


text:
Q: Nuget in Vs2010 throws a 'Arithmetic operation resulted in an overflow.' exception when I open my project If I open Vs2010 and then open the Package Manager Console host V 2.0 and 2.2 (tried both)
The console starts fine,
If I then open my soloution this error appears in the console
Arithmetic operation resulted in an overflow.
If I open my soloutionfirst, and then open the console I get the same error.
Any time I run a command I get the same error instantly.
If I load a different project, which my current project is a copy of, it loads fine.
Bad soloution Name
SpamisDataMigrationTestingTool
Good soloution Name
SAAS3G
The only obvious difference is the lenght of the soloution name... the bad sln is a copy of the good sln with the names changed, some files deleted and some new unit/integration tests added..
Does anyoe have any idea what might be causing this?
Any help is greatly appreicated.

A: The Nuget.Config got altered on copying and renaming the path "JCDCHelper.project" got changed to
"JcdcHelper.project"... this caused the arithmetic over flow exception
(Nuget.config pointed to a non existant path)


text:
Q: Qual é a diferença entre Codable e Decodable Estou com uma certa divida entre Codable e Decodable no Swift.
Em quais situações eu devo utilizar codable e o decodable.
Sou iniciante no Swift e os artigos que encontrei não me ajudaram tanto
Desde já agradeço!

A: O protoco Decodable é implementado para definir a decodificação (deserialização) do objeto a partir de uma representação externa, como JSON, XML ou Plist.
Já Encodable é exatemente o contrário, onde se define como codificar (serializar) o objeto.
Quando o tipo implementa Codable significa que este tem as duas capacidades descrevidas acima.
Criei um playground pra exemplificar a diferença.
O tipo User implementa Decodable, o que permite criar instancias a partir de um objeto JSON.
Book implementa Encodable, de forma que objetos desse tipo podem ser serializados, gerando um objeto do tipo Data.
Por fim, Job implementa Codable. No exemplo, codifiquei e depois decodifiquei um objeto desse tipo.
import Foundation

struct User: Decodable {
    var name: String
    var age: Int
}

let rawData = """
{
    "name": "Rafael",
    "age": 99
}
""".data(using: .utf8)!

let user = try JSONDecoder().decode(User.self, from: rawData)
print(user.name)
print(user.age)

struct Book: Encodable {
    var id: Int
    var title: String
    var available: Bool
}

let book = Book(id: 10, title: "Swift", available: true)
let encodedBook = try JSONEncoder().encode(book)
let JSONString = String(data: encodedBook, encoding: String.Encoding.utf8)
print(JSONString!)

struct Job: Codable, Equatable {
    var title: String
    var salary: Float
}

let job = Job(title: "iOS Engineer", salary: 20000)
let encodedJob = try JSONEncoder().encode(job)
let decodedJob = try JSONDecoder().decode(Job.self, from: encodedJob)
print(job == decodedJob)

Esse exemplo é bastante simplista, pois as chaves no JSON tem exatamente o mesmo nome dos atributos do objeto. Caso seja necessário (de)codificar o objeto com chaves diferentes é só definir a enum CodingKeys com o mapeamento entre chaves e atributos
enum CodingKeys: String, CodingKey { ...


text:
Q: Show that a series function is continuous in $\Bbb R$ I've been trying to solve this following question:

Prove that $f(x)= \sum_{n=1}^{\infty}\arctan(\frac{2x}{x^2+n^3})$ is continuous in $\Bbb R$.

I would really appreciate if someone can give me some direction on how to approach this problem.

A: You can change the arc function, with the same function without arctan, and just deal with a series $(2x/(x^2+n^3))$ since this series is always bigger, you prove that this series is bigger and by the supremum's rule you can prove that the arc uniformly converges.


text:
Q: Getting post id in for loop I have an existing for loop, which is necessary for the design and layout. Inside this for loop I need show post by post.
This is my code.
<?php for($i=$val;$i<=$cdn;$i++) { ?>
<div class="desc dsc<?php echo $dsc++; ?>" style="display: none">

            <?php echo get_the_title();?><?php the_field('designation'); ?>

        <?php get_template_part( 'post', 'content'); ?>

<?php } ?>

I need to get each post inside this for loop without affecting the structure. Please help
This is my full page code
<?php //Template Name: File get_header(); get_template_part( 'weblizar', 'breadcrumbs'); ?>

Meet our Team

        <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
        <?php get_template_part( 'post', 'content'); endwhile; else : get_template_part( 'nocontent'); endif; get_template_part( 'post-author'); ?>

        <?php //comments_template( '',true); ?>

            <?php wp_reset_query(); ?>

            <?php query_posts( array ( 'post_type'=>'our-team', 'posts_per_page' => -1 ) ); ?>

            <?php $count=0; $dsc=0 ; $ids=0 ; ?>
            <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
            <?php if ($count==0) : ?>

                <?php endif; ?>
                <?php if ($ids==3) : $val=0 ; $cdn=3 ; endif; ?>
                <?php if ($ids==7) : $val=3 ; $cdn=6 ; endif; ?>
                <?php if ($ids==11) : $val=7 ; $cdn=10; endif; ?>
                <?php if ($ids>11) : $val = 11; $cdn =14; endif; ?>

                    <img src="<?php echo wp_get_attachment_url( get_post_thumbnail_id());?>" title="<?php echo get_the_title();?>" alt="<?php echo get_the_title();?>">
                    <div class="hover-item ids<?php echo $ids++; ?>">

                                    <?php echo get_the_title();?><?php the_field('designation'); ?>

                                <?php get_template_part( 'post', 'content'); ?>

                            <?php $id=g et_field( 'facebook'); $id1=g et_field( 'twitter'); $id2=g et_field( 'linkedin'); $id3=g et_field( 'gplus'); $id4=g et_field( 'youtube'); if(!empty($id) || !empty($id1) || !empty($id2) || !empty($id3) || !empty($id4) ) { ?>

                                    <?php if( get_field( 'facebook') ): ?>

<a href="<?php the_field('facebook'); ?>">

                                    <?php endif; ?>
                                    <?php if( get_field( 'twitter') ): ?>

<a href="<?php the_field('twitter'); ?>">

                                    <?php endif; ?>
                                    <?php if( get_field( 'linkedin') ): ?>

<a href="<?php the_field('linkedin'); ?>">

                                    <?php endif; ?>
                                    <?php if( get_field( 'gplus') ): ?>

<a href="<?php the_field('gplus'); ?>">

                                    <?php endif; ?>
                                    <?php if( get_field( 'youtube') ): ?>

<a href="<?php the_field('youtube'); ?>">

                                    <?php endif; ?>

                            <?php } ?>

                <?php $count++; ?>
                <?php if ($count==4 ||$wp_query->found_posts==0) : ?>
                <?php $count=0; ?>

            <?php echo $cdn; for($i=$val;$i<=$cdn;$i++) { ?>
            <div class="desc dsc<?php echo $dsc++; ?>" style="display: none">
                <?php echo $post_id; ?>

                        <?php echo get_the_title($post_id);?><?php the_field('designation',$post_id); ?>

                    <?php get_template_part( 'post', 'content'); ?>

            <?php } ?>
            <?php endif; ?>
            <?php endwhile; ?>
            <?php endif; ?>
            <?php wp_reset_query(); ?>

 Contract

  Join FIFI

<?php get_footer(); ?>

A: If you're looking to get the post id to say add it to a div use the_ID()
<div id="post-<?php the_ID(); ?>">

A: Move the toggle-able code inside the main loop; put it inside the hover-item div. Get rid of all of the counting variables - $dsc, $ids, $cdn. Something like this:

    <img src="<?php echo wp_get_attachment_url( get_post_thumbnail_id());?>" title="<?php echo get_the_title();?>" alt="<?php echo get_the_title();?>">

                    <?php echo get_the_title();?><?php the_field('designation'); ?>

                <?php get_template_part( 'post', 'content'); ?>

                    <?php echo get_the_title();?><?php the_field('designation'); ?>

                <?php get_template_part( 'post', 'content'); ?>

Change the class for the .hover-item.ids1 (ect) to not have a number on it, just:

Update the script at the bottom to get rid of all the repeated stuff, and rewrite it like this:
$('.ids').click(function() {
    var $toggleable = $(this).find('.desc');
    $toggleable.toggle( "slow" );
});

You'll probably need to change how your css styles work because of how the html structure is changing.

A: You should seperate the number you're 'echoing' from the loop. here's an example from a recent site I've built:
<?php $startnum = 1;
$the_query = new WP_Query( array( 'cat' => 2 ) );
while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<div class="section-number-<?php echo $startnum; ?>">

the_title()

the_content()

<?php
$startnum++;
endwhile;
wp_reset_postdata(); ?>


text:
Q: converge in $\mu$ almost everywhere Let $(X, \mathcal{E}, \mu ) $ be a measurespace. Let $(f_n)_{n\in\mathbb{N}}$, $f$, $(g_n)_{n\in\mathbb{N}}$ and $g$ $\in \mathcal{M}(\mathcal{E})$. Let $\alpha, \beta \in \mathbb{R}$. Show, if:
$f_n \rightarrow f$ $\mu$-a.e and $g_n \rightarrow g$ $\mu$-a.e $\hspace{1mm}$ then: $\hspace{1mm}$  $\alpha f_n + \beta g_n \rightarrow \alpha f + \beta g$ $\mu$-a.e..
I dont want a solution for this exercise, but just some help or a hint. My idea is showing this $\sum_{n=1}^\infty \int_X |(\alpha f_n + \beta g_n) - (\alpha f + \beta g)| <\infty $. But I'm stuck, and I don't know how to prove this.
Any help is appreciated.

A: By assumption and your definition we have
$A=\{x\in X: \lim_{n\rightarrow\infty} f_n(x)\not=f(x)\}$
$B=\{x\in X: \lim_{n\rightarrow\infty} g_n(x)\not=g(x)\}$
Are sets of measure zero. For all $x\not\in A$ we have $\lim_{n\rightarrow\infty} f_n(x) = f(x)$ and so $\lim_{n\rightarrow\infty} \alpha f_n(x)=\alpha f(x)$. The same with $g$ and $x\not\in B$.
Now let $C=A\cup B$ we have for all $x\not\in A$ that both $\lim_{n\rightarrow\infty} \alpha f_n(x)=\alpha f(x)$ and $\lim_{n\rightarrow\infty} \alpha g_n(x)=\alpha g(x)$ which implies that $\lim_{n\rightarrow\infty} \alpha f_n+\beta g_n(x)=\alpha f(x)+\beta g(x)$.
Now $\mu(C)\leq \mu(A)+\mu(B)=0+0=0$. Hence by definition $\{x\in X:\lim_{n\rightarrow\infty} \alpha f_n+\beta g_n(x)\not =\alpha f(x)+\beta g(x)\}$ is a subset of $C$ which is of measure zero and so it is also of measure zero.


text:
Q: FileSystemException: Cannot copy file (OS Error: Operation not permitted, errno = 1) Since my migration to android 11, it is impossible for me to copy/move an image without using the "MANAGE_EXTERNAL_STORAGE" permission.
My code to store in tempDir:
void _takePicture() async {
    try {
      final p = await getTemporaryDirectory();

      print(p.path);
      final name = DateTime.now();
      print(name);
      final path = "${p.path}/$name.png";

      await controller.takePicture(path).then((value) {
        print('here');
        print(path);

        Navigator.push(
            context,
            MaterialPageRoute(
                builder: (context) => PreviewScreen(
                      imgPath: path,
                      fileName: "$name.png",
                      work: widget.work,
                      imgArr: widget.imgArr,
                    )));
      });
    } catch (e) {
      print(e);
    }
  }

My code when I try to copy the file from cache to Documents directory:
  upload(String imageFile, BuildContext ctx) async {
    try {
      // Temporary Image File
      File img = File(imageFile);
      bool exist = await img.exists();
      print(exist);
      // Output Directory
      Directory dir = await widget.work.getLocalPath();
      // Save the image in the allocated directory
      String path = dir.path + widget.fileName;
      File savedImage = await img.copy('$path');

      // Insert Into The List Of Current Recording Path
      widget.imgArr.add(savedImage.path);

      // Move to the wine view
      Navigator.pop(ctx);
      Navigator.pop(ctx, img);
    } catch (e) {
      print(e);
    }
  }

A:

/storage/emulated/0/Documents/myapp/folder/folder/97897897/records/2022-03-30 08:26:14.098976.png

There is no reason why you would not be able to create a file in those subdirectories of public Documents folder. Be it that you create those subdirectories first. Just the usual WRITE permission needed. So no MANAGE_EXTERNAL_STORAGE needed.
But a filename like ....08:26:14.098976.png will not go as it contains forbidden characters :.
Replace them by someting more suitable.


text:
Q: Netplan / systemd-networkd VLAN is missing I tried to add a additional virtual VLAN Interface, but it is not visible in ifconfig.
Netplan Config:
    network:
        version: 2
        renderer: networkd
        ethernets:
            enp0s31f6:
                addresses: [95.216.XX.XXX/32,"2a01:4f9:xx:XXXX::2/64"]
                gateway4: 95.216.xx.xx
                gateway6: fe80::1
                nameservers:
                    addresses: [192.168.122.1,213.133.98.98,213.133.99.99,"2a01:4f8:0:1::add:9999","2a01:4f8:0:1::add:10$
        vlans:
            enp0s31f6.4001:
                id: 4001
                link: enp0s31f6
                addresses: [192.168.3.20/24]
                mtu: 1400

Also networkctl don't know the VLAN Device:
~ # networkctl
IDX LINK             TYPE               OPERATIONAL SETUP
  1 lo               loopback           carrier     unmanaged
  2 enp0s31f6        ether              routable    configured

2 links listed.

~ # ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host
       valid_lft forever preferred_lft forever
2: enp0s31f6: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
    link/ether 90:1b:0e:f3:88:4d brd ff:ff:ff:ff:ff:ff
    inet 95.216.xx.xxx peer 95.216.xx.xx/32 scope global enp0s31f6
       valid_lft forever preferred_lft forever
    inet6 2a01:4f9:xx:xxxx::2/64 scope global
       valid_lft forever preferred_lft forever
    inet6 fe80::921b:eff:fef3:884d/64 scope link
       valid_lft forever preferred_lft forever

~ # ip link
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN mode DEFAULT group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
2: enp0s31f6: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP mode DEFAULT group default qlen 1000
    link/ether 90:1b:0e:f3:88:4d brd ff:ff:ff:ff:ff:ff

But the Run Files Contain the VLAN Device Configuration
==> /run/systemd/network/10-netplan-enp0s31f6.4001.netdev <==
[NetDev]
Name=enp0s31f6.4001
MTUBytes=1400
Kind=vlan

[VLAN]
Id=4001

==> /run/systemd/network/10-netplan-enp0s31f6.4001.network <==
[Match]
Name=enp0s31f6.4001

[Network]
Address=192.168.3.20/24

==> /run/systemd/network/10-netplan-enp0s31f6.network <==
[Match]
Name=enp0s31f6

[Network]
Address=95.216.xx.xxx/32
Address=2a01:4f9:XXX:XXX::2/64
Gateway=95.216.xx.xx
Gateway=fe80::1
DNS=192.168.122.1
DNS=213.133.98.98
DNS=213.133.99.99
DNS=2a01:4f8:0:1::add:9999
DNS=2a01:4f8:0:1::add:1010
DNS=2a01:4f8:0:1::add:9898
VLAN=enp0s31f6.4001

Can anyone help my solving my problem?
Kind Regards


text:
Q: generate java class using Simplexml I have an xml with the following structure:
<Items>
  <item>
    <IntItem>
      <value>1</value>
    </IntItem>
  </item>
  <item>
    <BoolItem>
      <value>true</value>
    </BoolItem>
  </item>
  <item>
    <StrItem>
      <value>word</value>
    </StrItem>
  </item>
</Items>

It is list of items, that can be different types (bool, int, string). Could you help me write java class with annotation for above xml structure?

A: Are you wanting to actually generate the 'java class' with an xml file? (That is what the title says)
If so, then you should look into some modeling frameworks that allow you to generate code from xml files (models). Acceleo and EMF are just a couple. But there are more.
BUT, if you are just wanting to populate fields in your class with an xml file... look into some xml parsers for android and parse the xml and just assign the values to the fields. SAX and DOM are two very popular parsers for Android.


text:
Q: Apache Storm Problem: "Unable to canonicalize address localhost/:2000 because it's not resolvable" When I launch a simple Strorm script on IntellijIdea or Eclipse i encounter this problem: "Unable to canonicalize address localhost/:2000 because it's not resolvable".
import org.apache.storm.*;
import org.apache.storm.generated.*;
import org.apache.storm.spout.SpoutOutputCollector;
import org.apache.storm.task.OutputCollector;
import org.apache.storm.task.TopologyContext;
import org.apache.storm.topology.OutputFieldsDeclarer;
import org.apache.storm.topology.TopologyBuilder;
import org.apache.storm.topology.base.BaseRichBolt;
import org.apache.storm.topology.base.BaseRichSpout;
import org.apache.storm.tuple.*;
import org.apache.storm.utils.Utils;

import java.util.Map;
import java.util.Random;

public class ExclamationExample {
    public static class TestWordSpout extends BaseRichSpout {
        private SpoutOutputCollector _collector;

        @Override
        public void open(Map map, TopologyContext topologyContext, SpoutOutputCollector spoutOutputCollector) {
            _collector = spoutOutputCollector;
        }

        @Override
        public void nextTuple() {
            Utils.sleep(100);
            final String[] words = new String[]{"nathan", "mike", "jackson", "golda", "bertels"};
            final Random rand = new Random();
            final String word = words[rand.nextInt(words.length)];
            _collector.emit(new Values(word));
            System.out.printf("Word spout: %s\n", word);
        }

        @Override
        public void declareOutputFields(OutputFieldsDeclarer outputFieldsDeclarer) {
            outputFieldsDeclarer.declare(new Fields("word"));
        }
    }

    public static class ExclamationBolt extends BaseRichBolt {
        private OutputCollector collector;

        @Override
        public void prepare(Map conf, TopologyContext context, OutputCollector collector) {
            this.collector = collector;
        }

        @Override
        public void execute(Tuple tuple) {
            String val = tuple.getString(0) + "!!!";
            collector.emit(tuple, new Values(val));
            System.out.printf("Exclamation bolt: %s\n", val);
            collector.ack(tuple);
        }

        @Override
        public void declareOutputFields(OutputFieldsDeclarer declarer) {
            declarer.declare(new Fields("word"));
        }
    }

    //TOPOLOGY
    public static void main(String[] args) throws Exception {
        Config conf = new Config();
        TopologyBuilder builder = new TopologyBuilder();

        builder.setSpout("word", new TestWordSpout(), 2);
        builder.setBolt("exclaim1", new ExclamationBolt(), 2).shuffleGrouping("word");
        builder.setBolt("exclaim2", new ExclamationBolt(), 2).shuffleGrouping("exclaim1");

        conf.setDebug(false);

        String topologyName = "test";

        conf.setNumWorkers(2);

        //If there are arguments, we are running on a cluster
        if (args != null && args.length > 0) {
            conf.setNumWorkers(3);
            topologyName = args[0];
            StormSubmitter.submitTopology(topologyName, conf, builder.createTopology());
        }

        try (LocalCluster cluster = new LocalCluster()) {
            cluster.submitTopology(topologyName, conf, builder.createTopology());
            Utils.sleep(600000); // wait [param] ms
            cluster.killTopology(topologyName);
            cluster.shutdown();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

What is a possible solution?

A: I resolved my problem. If can help someone i tell the solution. I ran the Java Application using Java SDK 17, this give me problem, then I created new project with JDK 1.8 and everything works!


text:
Q: eID REST interface with authentication in Typo3 I'm providing an eID page as an REST interface. Now I want to protect this page with an API key or similar. How can this be achieved in Typo3 8.7?
Actually it looks like this can only be done by logging in via frontend (FE) or backend (BE) and check the login status in the eID controller class.

A: For TYPO3 v8, you should check out the EXT:restler extension instead of using eID.
eID is meant for calls where you have to do basically everything on your own.
For TYPO3 v9, the PSR-15 middleware concept allows to individually build custom REST APIs and integrations with other solutions like SlimPHP:  https://github.com/b13/slimphp-bridge

A: You can expect a given URL-paramter, maybe even as a post param.
Put your eID-page-configuration (typoscript) in a condition requesting this paramter to be set. Otherwise genate an error-page.
If you want to handle multiple keys (maybe from a database table) you could use a userfunc for conditions.
If you want to handle a login in the call you need to initialize more from the TYPO3 frontend. then identify the paramters from the login form (some are hidden) and provide them. AFAIK POST and GEt paramaters work.


text:
Q: TCP close 2-way handshake with wirshark package I got a pcap package use tcpdump command. In this pcap, the TCP close in 2-way handshake!

Questions:

*

*In this picture, can anyone determine who initiated the signal to close the connection?

*why TCP close in 2-way handshake? it does not make sense!

A: This is only a half-close, initiated by the side that sent the FIN. A full close would require a FIN in the other direction, and a corresponding ACK.


text:
Q: Starting an Activity and finishing the previous Activity when using Material Transitions shows Home screen (finishAfterTransition not working) I am trying to start a Activity B after logging in in Activity A with Material transitions (specifically Fade). Android provides a finishAfterTransition() but this does not do what it says on the tin (Google seem to know this, and have been ignoring the issue for years) and many other people seem to complain about the issue. Therefore, whenever starting an activity and finishing the previous one, I always see the home page briefly because the old activity is finished before the new one is started. I thought about using a BroadcastReceiver and finishing Activity A from Activity B - but this goes against Activity behaviour. I also had a feeling running start and finish synchronously might work, but the thread just hangs on the startActivity (runBlocking dispatched to Main thread).
Does anyone have a nice, elegant work around solution for this, so I can make proper use of the Material Transitions that Android provide (but make it very difficult to use) and the navigation in my app between activities just looks pretty awful. Here's some sample code (the origin here is my Activity A):
if (params.finishOrigin) {
            params.origin.finishAfterTransition().apply {
                if (animateDialog) {
                    with(params.origin.window) {
                        enterTransition = Fade().apply {
                            duration = 200L
                        }
                        exitTransition = Fade().apply {
                            duration = 200L
                        }
                    }
                } else if (animate) {
                    params.origin.overridePendingTransition(
                        params.finishAnimationIn,
                        params.finishAnimationOut
                    )
                }
            }
        }

        params.origin.startActivity(
            Intent(params.origin, target).apply {
                if (params.finishOrigin) {
                    addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
                }
                data = params.originalIntent?.data
                params.block(this)
                if (animateDialog) {
                    with(params.origin.window) {
                        enterTransition = Fade().apply {
                            duration = 1200L
                        }
                        exitTransition = Fade().apply {
                            duration = 200L
                        }
                    }
                } else if (animate) {
                    params.origin.overridePendingTransition(
                        params.originAnimationIn,
                        params.originAnimationOut
                    )
                }
            },
            if (animateDialog) ActivityOptions.makeSceneTransitionAnimation(params.origin).toBundle() else null
        )

NOTE: The ordering of the start/finish has no effect, since they're called asynchronously.
I have also used different animations in overridePendingTransition but always see a white screen/flicker with any animation other than left-to-right slide in. These Material transitions actually look pretty nice as well, if they were even compatible with basic navigational tasks in Android.


text:
Q: How to display an image from postgrsql database in virtual machine to my local I'm  trying  to  display  an  image  from  PostgreSQL  database  and  I'm  retrieving  a  black  screen  .  in  the  field  store_fname  i'm  having  the  field  will  give  you  the  path  to  the  image  file  inside  my  Odoo
 filestore  in  the  form  'ab/abcdef0123456789'
<?php
$conn = pg_connect("user = admin password = admin host = 192.168.1.11 dbname = odoo");
$res = pg_query($conn, "SELECT id, store_fname FROM ir_attachment
WHERE res_model = 'res.partner' AND res_field = 'image' AND res_id = 3; ");
$raw = pg_fetch_result($res, 'store_fname');
header('Content-type: image/jpeg');
echo pg_unescape_bytea($raw);
?>


text:
Q: Flask SQLAlchemy select child object - return JSONB column I have a class with a one-many relationship. I would like to return all the parent's children in the relationship ; specifically I'd like to return all the JSONB objects in my children tables.
These are my class:
class Parent(db.Model):
    __tablename__ = 'parent220416'
    id = db.Column(db.Integer, primary_key=True)
    children = db.relationship('Child', backref='Parent', lazy='dynamic')

class Child(db.Model):
    __tablename__ = 'child220416'
    id = db.Column(db.Integer, primary_key=True)
    parentid = db.Column(db.Integer, db.ForeignKey('words220416.id'))
    data = db.Column(JSONB)

Then with Flask Restful, I'm trying to select all the child like this:
class ParentChild(Resource):
    def get(self, id):
           result = db.session.query(Parent).get(id)
           result_child = result.children
           return {'child': result_child}

There is an error:
raise TypeError(repr(o) + " is not JSON serializable")
TypeError: <sqlalchemy.orm.dynamic.AppenderBaseQuery object at 0x106178da0> is not JSON serializable

A: If you want to get all of the data objects for each Child of the Parent. you could do the following query:
result_child = db.session.query(Child.data).filter(Child.parentid == id).all()
If you want to use the children relationship, it is possible to iterate over it:
result_child = [child.data for child in result.children]


text:
Q: Jersey/JAX-RS client throwing exception on HTTP GET Please note: even though I'm using Groovy here, I think my exception is really about using the Jersey/JAX-RS API correctly.
Given the following code:
ClientConfig clientConfig = new DefaultClientConfig()
clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE)
Client jerseyClient = Client.create(clientConfig)
WebResource webResource = jerseyClient.resource("http://localhost:8080/location/")

Long id = 5L

Address address = webResource.path("address").path(id)
    .accept(MediaType.APPLICATION_JSON)
    .get(Long)

I am getting the following exception:
groovy.lang.MissingMethodException: No signature of method: com.sun.jersey.api.client.WebResource.path() is applicable for argument types: (java.lang.Long) values: [5]
Possible solutions: path(java.lang.String), put(), wait(long), put(com.sun.jersey.api.client.GenericType), put(java.lang.Class), put(java.lang.Object)
    at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:55)
    at org.codehaus.groovy.runtime.callsite.PojoMetaClassSite.call(PojoMetaClassSite.java:46)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:45)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:108)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:116)
    at com.me.myapp.Driver.run(Driver.groovy:43)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    <rest omitted for brevity>

I am trying to hit the following REST endpoint:
GET http://localhost:8080/location/address/{id}

Where am I going wrong?

A: You're calling the path method with a long, but it can only take a String. Your id is a long, but since the error message says the value is 1, I assume that LocationResourcePaths.ADDRESS_PATH is also a long with value 1, is that the case?


text:
Q: Performance tuning in spark I am running a spark job which processes about 2 TB of data. The processing involves:

*

*Read data (avrò files)

*Explode on a column which is a map type

*OrderBy key from the exploded column

*Filter the DataFrame (I have a very small(7) set of keys (call it keyset) that I want to filter the df for). I do a df.filter(col("key").isin(keyset: _*) )

*I write this df to a parquet (this dataframe is very small)

*Then I filter the original dataframe again for all the key which are not in the keyset
 df.filter(!col("key").isin(keyset: _*) ) and write this to a parquet. This is the larger dataset.

The original avro data is about 2TB. The processing takes about 1 hr. I would like to optimize it. I am caching the dataframe after step 3, using shuffle partition size of 6000. min executors = 1000, max = 2000, executor memory = 20 G, executor core = 2. Any other suggestions for optimization ? Would a left join be better performant than filter ?

A: All look right to me.
If you have small dataset then isin is okay.
1) Ensure that you can increase the number of cores. executor core=5
More than 5 cores not recommended  for each executor. This is based on a study where any application with more than 5 concurrent threads would start hampering the performance.
2) Ensure that you have good/uniform partition strucutre.
Example (only for debug purpose not for production):
  import org.apache.spark.sql.functions.spark_partition_id
  yourcacheddataframe.groupBy(spark_partition_id).count.show()

This is will print spark partition number and how many records
exists in each partition. based on that you can repartition, if you wanot more parllelism.
3) spark.dynamicAllocation.enabled could be another option.
For Example :
spark-submit --conf spark.dynamicAllocation.enabled=true --conf spark.dynamicAllocation.cachedExecutorIdleTimeout=100 --conf spark.shuffle.service.enabled=true

along with all other required props ..... thats for that job. If you give these props in spark-default.conf it would be applied for all jobs.
With all these aforementioned options your processing time might lower.

A: spark.dynamicAllocation.enabled is enabled
partition sizes are quite uneven (based on the size of output parquet part files) since I am doing an orderBy key and some keys are more frequent than others.
keyset is a really small set (7 elements)

A: On top of what has been mentioned, a few suggestions depending on your requirements and cluster:

*

*If the job can run at 20g executor memory and 5 cores, you may be able to fit more workers by decreasing the executor memory and keeping 5 cores

*Is the orderBy actually required? Spark ensures that rows are ordered within partitions, but not between partitions which usually isn't terribly useful.

*Are the files required to be in specific locations? If not, adding a

df.withColumn("in_keyset", when( col('key').isin(keyset), lit(1)).otherwise(lit(0)). \
write.partitionBy("in_keyset").parquet(...)

may speed up the operation to prevent the data from being read in + exploded 2x. The partitionBy ensures that the items in the keyset are in a different directory than the other keys.


text:
Q: Setting Underline Thickness in CSS I'm redesigning my website and wish to have certain paragraphs styled like in the below image.

I thought this would be fine but now it's suddenly just hit me... there's no way to set the thickness of an underline! Or at least I don't think there is?
Of course there is the border property, but then I would only have a border at the bottom of the whole paragraph and not under each line.
Can anyone think of a workaround for this?

A: An example of this would be:
h4 {border-bottom: 10px solid #000;}
I found this from another stack exchange question found here:
Edit line thickness of CSS 'underline' attibute

A: You can turn your paragraph into an inline display: DEMO
This way you can even set a border-style to your underline'like:
p {
  display:inline;
  border-bottom:3px double;
}

Single <p>aragraphs in between title


text:
Q: Change Sharepoint Icon So I am using SharePoint 2013, and am trying to change the icon for my SharePoint. If I look at it from Office 365, the link to reach it has the icon  want:

However, the second I follow the link to go to my SharePoint, I end up with this icon instead:

I have tried the solution from here but unfortunately, the look and feel portion of my site won't let me change the icon in any way.
I have changed the siteIcon.jpg file using SharePoint Editor 2013, but that only changed the first Icon, not the Icon you see when you're actually using the website.
What else can I do?

EDIT: I found the problem. They System will reset the Icon every time I log out.
Here is the version history:

The System account versions are all the ugly TE, while the ones I put up are all the correct icon...
How can I make the System stop screwing up my icon?

A: Here are steps I have followed.

*

*Go to the SiteAssets library.

*You will find a __siteIcon__.jpg file.

*Replace your logo with the same name.

*Clear cache it does affect. I had the same problem when I updated a logo but (CTRL + F5) get this affected immediately.


text:
Q: Why does Perl evaluate code in ${...} during string interpolation? Why does the following snippet work at all? And what evil might be possible using this? But seriously, is there any reason, the code in ${} gets evaluated at all and then used as scalar reference?
use strict;
no strict 'refs';

our $message = "Hello world!";
print "${ lc 'MESSAGE' }\n";

A: From the "Using References" section of the perlref documentation:

Anywhere you'd put an identifier (or chain of identifiers) as part of a variable or subroutine name, you can replace the identifier with a BLOCK returning a reference of the correct type. In other words, the previous examples could be written like this:
$bar = ${$scalarref};
push(@{$arrayref}, $filename);
${$arrayref}[0] = "January";
${$hashref}{"KEY"} = "VALUE";
&{$coderef}(1,2,3);
$globref->print("output\n");  # iff IO::Handle is loaded

Admittedly, it's a little silly to use the curlies in this case, but the BLOCK can contain any arbitrary expression, in particular, subscripted expressions:
&{ $dispatch{$index} }(1,2,3);    # call correct routine

Because of being able to omit the curlies for the simple case of $$x, people often make the mistake of viewing the dereferencing symbols as proper operators, and wonder about their precedence. If they were, though, you could use parentheses instead of braces. That's not the case. Consider the difference below; case 0 is a short-hand version of case 1, not case 2:
$$hashref{"KEY"}   = "VALUE";     # CASE 0
${$hashref}{"KEY"} = "VALUE";     # CASE 1
${$hashref{"KEY"}} = "VALUE";     # CASE 2
${$hashref->{"KEY"}} = "VALUE";   # CASE 3

Case 2 is also deceptive in that you're accessing a variable called %hashref, not dereferencing through $hashref to the hash it's presumably referencing. That would be case 3.

Later in "Symbolic references":

We said that references spring into existence as necessary if they are undefined, but we didn't say what happens if a value used as a reference is already defined, but isn't a hard reference. If you use it as a reference, it'll be treated as a symbolic reference. That is, the value of the scalar is taken to be the name of a variable, rather than a direct link to a (possibly) anonymous value.

A: It's ok, unless you use symbolic references. Suppose the following code:
my %messages = (hello => "Hello world!", bye => "Bye-bye, world!");
sub get_message_ref { return \$messages{$_[0]} }; # returns scalarref
print "${ get_message_ref('bye') }\n";

Agree, its usefulness is not obvious with scalarrefs, but it is very useful with arrayrefs.
print "keys: @{[keys %messages]}\n";

A: We explain this in depth in Intermediate Perl.
The general syntax for variable lookups is:
 SIGIL  BLOCK  INDEXY-THING

For a simple scalar that looks like:
 print $   { foo };

You have probably seen this when you need to separate a variable name from things surrounding it:
 print "abc${foo}def\n";

If you just have a Perl identifier in the block and no surrounding mess, you can leave off the braces, which is the common case:
 print $foo;

However, this is the same thing for dereferencing a reference:
 SIGIL  BLOCK-RETURNING-REFERENCE  INDEXY-THINGS

If the thing that you get in the block is a reference, Perl tries to dereference it like you asked it too:
 my $ref = \ '12345';
 print $     { $ref };

That's a real block though, and not just sugar. You can have as many statements as you like in there:
 print $     { my $ref = \ '1234'; $ref };

Now you're not just specifying a Perl identifier, so Perl doesn't assume that you're giving it an identifier and it executes code and uses the result as a reference. Consider the difference between these almost identical say statements:
    use 5.010;
our $foo = "I'm the scalar";

sub foo { \ "I'm the sub" }

say ${foo};
say ${foo;};

In that second say Perl sees the semi-colon, realizes it's not an identifier, interprets the code inside the braces as text, and returns the result. Since the result is a reference, it uses the ${...} to dereference it. It doesn't matter where you do this, so that you do it inside a double-quoted string is not special.
Also, notice the our there. That's important now that you're going to consider something a bit more tricky:
    use 5.010;
our $foo = "I'm the scalar";

sub foo { \ "I'm the sub" }
sub baz { 'foo' }

say ${foo};
say ${foo;};
say ${baz;};

Perl intreprets that last say as code and sees the result is not a reference; it's the simple string foo. Perl sees that it's not a reference but it's now in a dereferencing context so it does a symbolic reference (as Greg Bacon describes). Since symbolic references work with variables in the symbol table, that $foo had to be a package variable.
Since it's easy to mess this up, strict has a handy check for it. However, when you turn it off, don't be surprised when it bites you. :)


text:
Q: Error: expected type-specifier before Class I am a java dev, learning c++. This following sample code doesn't compile and I couldn't find a clue.
#include <iostream>
#include <cstdlib>
#include <string>
#include <stdexcept>

using namespace std;

template <class T>
class MyObj {

  public:
  T value;
  MyObj(T a){
      this.value = a;
  }
};

template <class T>
inline MyObj<T> const& sum(MyObj<T> const& a, MyObj<T> const& b)
{
    // append copy of passed element
    T result = a.value+b.value;
    MyObj<T> obj = new MyObj(result);

    return obj;
}

int main()
{
    try {
        MyObj<int> s1 = new MyObj(1);
        MyObj<int> s2 = new MyObj(3);

        MyObj<int> s3 = sum(s1,s2);

        cout << s3.value <<endl;
    }
    catch (exception const& ex) {
        cerr << "Exception: " << ex.what() <<endl;
        return -1;
    }
}

It returns -

main.cpp:31:29: error: expected type-specifier before 'MyObj'
           MyObj s1 = new MyObj(1);

and

main.cpp:32:29: error: expected type-specifier before 'MyObj'
           MyObj s2 = new MyObj(3);

Any help would be appreciated.

A: With new you are allocating memory on the heap, and so you need a pointer to point to that newly allocated memory: MyObj<int>* s1 = new MyObj(1);
Next, MyObj is a template class, so you have to specify T when you call the construtor: MyObj<int>* s1 = new MyObj<int>(1);
Because s1and s2 are now pointers, sum can't accept them as pointers, you have deference them to get the values: sum(*s1, *s2);
As @rgettman  pointed out, this is a pointer, and so must be acessed using-> and not ..


text:
Q: Example code for populating a tensor? I have no idea how to populate a tensor.  The API is not documented very well...
I'd like to have a function kind of like this.
std::tuple<std::string, double> CNNLocalizer::runImage()
{
  std::tuple<std::string, double> result;
  result.get<0> = "none";
  result.get<1> = 0.0;

  if (g_got_image_)
  {
    std::string label;

    // create a tensorflow::Tensor with the image information
    tensorflow::TensorShape image_shape;
    image_shape.AddDim(g_img_height_);
    image_shape.AddDim(g_img_width_);

    tensorflow::Tensor input_image(tensorflow::DT_INT8, image_shape);
    // I have no idea how to make this work right now.  Copying data is very confusing..
    for (uint i = 0; i < g_img_height_; i++)
    {
      for (uint j = 0; j < g_img_width_; j++)
      {
        // ??  Populate a matrix or something?
      }
    }
    // Copy the matrix into the tensor?
    // input_image.matrix<float>()() = z;
  }

  return result;
}

Any idea how to populate the matrix part of the Tensor?  I found a matrix() function that returns some kind of typedef'd Eigen Tensor object - is that the way to go?
Any help would be appreciated!  Thanks!

A: You can use Tensor::FromProto. Otherwise, it's probably best for you to use Tensor::flat<int8>. There are examples for CSV or PNG.


text:
Q: Error while installing Activiti BPM Engine on Ubuntu - MySql I am trying to install activiti engine in ubuntu 14 LTS and Tomcat & MySql. I haven't alterterd any settings so far it is the default war which I deployed in tomcat. How ever when I am trying to access activiti-explorer I am getting below error. It works perfectly fine in the local landscape with same configuration but when I try to deploy it in client landscape this is the error I am getting. Can any one please help with this?
org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'explorerApp': Scope 'session' is not active for the current   thread;
consider defining a scoped proxy for this bean if you intend to refer to it from a singleton; nested exception is java.lang.IllegalStateException:
No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread?
If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet:
In this case, use RequestContextListener or RequestContextFilter to expose the current request.
com.vaadin.terminal.gwt.server.AbstractApplicationServlet.handleServiceException(AbstractApplicationServlet.java:1010)

A: If anybody out looking there for answer, I got it resolved by replacing the Tomee Server to tomcat. It seems there are some version conflict with activiti latest version and Tomee Server latest version. It works properly with Tomcat 8.


text:
Q: Best way to inject/access a thread safe singleton in java I am completely puzzled by this code because I know the intent is to have thread safe access to a single instance of the object DataService but I don't know if it achieves that.
It just stands out to me
Caller class:
protected final DataService dataService = DataService.getInstance();

Singleton class method:
private static DataService dService=null;
public static synchronized DataService getInstance() {
    if (dService == null)
        dService = new DataService();
    return dService;
}

What is achieved by using protected final modifiers in the calling class?
Are they necessary and a good practice?

A: The protected and final modifiers on your first line are not contributing anything to the singleton nature you're referring to.
Protected is just the access modifier, and final determines whether the variable can be reassigned.
What is truly making this a singleton, by the definition of singleton is the fact that you only ever create one dService object (through new DataService()) and since the method is synchronized you are guaranteed that the method will not be called at the same time which could result in two separate objects created erroneously.

A: As Brian Benzinger said, the protected and final modifiers do not contribute to the thread safety of the singleton class. Protected defines the visibility of the field in the Caller class, i.e. the field can be accessed by other classes in the package. The final modifier indicates that the field must be definitely assigned at instantiation and cannot be reassigned later.
Although there are many ways to implement the singleton pattern in Java, this is the best implementation that I know of:
class Foo {
    private static volatile Bar bar = null;
    public static Bar getBar() {
        if (bar == null) {
            synchronized(Foo.class) {
                if (bar == null)
                    bar = new Bar();
            }
        }
        return bar;
    }
}

A: So i ended up digging myself.
I found one inefficiency in this way of doing singleton referred to as
Double checked locking.
"In software engineering, double-checked locking (also known as "double-checked locking optimization") is a software design pattern used to reduce the overhead of acquiring a lock by first testing the locking criterion (the "lock hint") without actually acquiring the lock. Only if the locking criterion check indicates that locking is required does the actual locking logic proceed.
"
"
Since synchronizing a method could in some extreme cases decrease performance by a factor of 100 or higher
"
The best way as mentioned there for java 1.5+ is usage of the volatile.
class Foo {
    private volatile Helper helper;
    public Helper getHelper() {
        Helper result = helper;
        if (result == null) {
            synchronized(this) {
                result = helper;
                if (result == null) {
                    helper = result = new Helper();
                }
            }
        }
        return result;
    }

    // other functions and members...
}

"the volatile field is only accessed once (due to "return result;" instead of "return helper;"), which can improve the method's overall performance by as much as 25 percent
"


text:
Q: Fetching user data from api using user id I'm working on a chat system, each message belongs to a user, who sent it . In the database of messages I store just the user id, and I have a problem with fetching the users names, and replace it in the message.
This is the way I tried to fetch the username, by creating a method which takes the users id, and after fetching from api returns the users name, but the return doesn't work :

   @{{ getUserDetails(message.user_id) }}

@{{ message.message }}

    methods: {
        getUserDetails(id) {
            fetch('/api/user/' + id)
                .then(res => res.json())
                .then(res => {
                    return res.name;
                })
        }
    },

I hope you understand my problem, sorry for my bad english, is not my native language ...

A: The problem occurs because you are actually not return anything in getUserDetails function.
You are trying to return from a then() callback. But when you return a value from that, the next then() is called with that value. The parent function getUserDetails still returns nothing.
To solve your problem, I think you should use another object to store the usernames. This way, you would not overwhelm the server by doing a request to get the username for every message.
Something like this should work:

   @{{ getUsername(message.user_id) }}

@{{ message.message }}

data () {
  return {
    listUsername: {}
  }
},
methods: {
  getUsername(id)  {
    if (!this.listUsername[id]) {
      this.getUserDetails(id)
      return 'Unknown'
    }
    return this.listUsername[id]
  },
  getUserDetails(id) {
    fetch('/api/user/' + id)
      .then(res => res.json())
      .then(res => {
        this.$set(this.listUsername, id, res.name)
      })
  }
}


text:
Q: How to make captions in ggplot2 more aesthetically pleasing? I tried to add captions in some plots that will be shown in a .rmd file, but the captions added are not very aesthetically pleasing. It will look much better if I just include the captions in the .rmd file instead of the plot. Are there any ways to make the captions look prettier in ggplot2?
library(ggplot2)

data <- data.frame(col = c("left", "right"),
                   row = c("first", "second", "third", "fourth"),
                   x = rep.int(1,4),
                   y = rep.int(1,4))
data$col <- as.character(data$col)
data$row <- as.character(data$row)

caption <- paste(strwrap("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.", width = 170), collapse = "\n")

ggplot(data = data) +
  facet_grid(row~col) +
  labs(x = "x", y = "y", caption = caption) +
  theme_bw(base_size = 16) +
  theme(legend.position = "bottom",
        plot.margin = margin(15, 15, 15, 15),
        plot.caption = element_text(size = 10, hjust = 0))

The captions that I added

A: library(ggplot2)

data <- data.frame(col = c("left", "right"),
                   row = c("first", "second", "third", "fourth"),
                   x = rep.int(1,4),
                   y = rep.int(1,4))
data$col <- as.character(data$col)
data$row <- as.character(data$row)

caption <- paste(strwrap("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.", width = 170), collapse = "\n")

library(extrafont)
font_import(prompt=FALSE) # This installs the fonts. Only run this once!
loadfonts(device="win") # Loads the fonts

fonts_lookup = t(data.frame(windowsFonts())) # font lookup table

ggplot(data = data) +
  facet_grid(row~col) +
  labs(x = "x", y = "y", caption = caption) +
  theme_bw(base_size = 16) +
  theme(legend.position = "bottom",
        plot.margin = margin(15, 15, 15, 15),
        plot.caption = element_text(size = 12, hjust = 0.5,
                                    family = "Garamond", color = "blue", face = "bold"))

Maybe change the font family, color, or face, or all at the same time? You can refer to this question for fonts: Changing fonts in ggplot2. The extrafont package let's you install a lot more fonts than what is already available. windowsFonts() let's you check what fonts are already loaded. I've created fonts_lookup for easy lookup of fonts and their respective names. As for which font is the "prettiest", that's very subjective.


text:
Q: How to add or manipulate http header in a webservice call in java There is a requirement to add a new http header key value pair in a soap request. Something like below.
 HTTP/1.1 200 OK
 Cache-Control: no-cache
 Pragma: no-cache
 Content-Type: text/xml; charset=utf-8
 New-Key: Some dynamic value

 <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
 <soapenv:Body>

How can I add a new key value pair (New-Key: Some dynamic value) in http header while making a soap request? Value will later get extracted by server from http header. As a requirement new field should neither be added in soap header nor in soap body.
We are using IBM wsdl2java tool, which implements the IBM JAX-RPC specification to generate the Java clients and invoke the SOAP web service calls.

A: Ans at
https://www-01.ibm.com/support/knowledgecenter/SSAW57_8.5.5/com.ibm.websphere.base.doc/ae/rwbs_transportheaderproperty.html
public class MyApplicationClass {
// Inject an instance of the service's port-type.
@WebServiceRef(EchoService.class)
private EchoPortType port;

// This method will invoke the web service operation and send and receive transport headers.
public void invokeService() {

    // Set up the Map that will contain the request headers.
    Map<String, Object>requestHeaders = new HashMap<String, Object>();
    requestHeaders.put("Cookie", "ClientAuthenticationToken=FFEEBBCC");
    requestHeaders.put("MyHeaderFlag", new Boolean(true));

    // Set the Map as a property on the RequestContext.
    BindingProvider bp = (BindingProvider) port;
    bp.getRequestContext().put(com.ibm.websphere.webservices.Constants.REQUEST_TRANSPORT_PROPERTIES, requestHeaders);

    // Set up the Map to retrieve transport headers from the response message.
    Map<String, Object>responseHeaders = new HashMap<String, Object>();
    responseHeaders.put("Set-Cookie", null);
    responseHeaders.put("MyHeaderFlag, null);

    // Invoke the web services operation.
    String result = port.echoString("Hello, world!");

    // Retrieve the headers from the response.
    String cookieValue = responseHeaders.get("Set-Cookie");
    String headerFlag = responseHeaders.get("MyHeaderFlag");
}

}


text:
Q: Lighttpd regex to redirect all pages matching a pattern except for one Using lighttpd I'm successfully redirecting all pages that begin with:
http://www.domain.com/cgi-bin/MDM/

to the corresponding secure version using this:
$HTTP["scheme"] == "http" {
   $HTTP["host"] == "www.domain.com" {
   url.redirect = ( "^/cgi-bin/MDM/(.*)" => "https://www.domain.com/$1" )
   }
}

and this works great. But now I've discovered one such page can't be served as HTTPS because of a 3rd party script that links to non-HTTPS elements. So I want to exclude that one page which is:
http://www.domain.com/cgi-bin/MDM/page.html

I've tried a number of things but can't seem to cook up the right rule. Any thoughts would be appreciated.

A: You could use != to exclude any URLs from redirecting:
$HTTP["scheme"] == "http" {
  $HTTP["host"] == "www.domain.com" {
    $HTTP["url"] != "/cgi-bin/MDM/page.html" {
      url.redirect = ( "^/cgi-bin/MDM/(.*)" => "https://www.domain.com/$1" )
    }
  }
}


text:
Q: How to insert rows into dataframes in pandas python? I'm very new to pandas and dataframes.
I have two lists in python which contains columns and values that needs to be inserted for that columns in a row.
For Ex:
col_list = ['column1', 'column3', 'column4', 'column6', ...]
val_list = ['value1', 'value3', 'value4', 'value6', ...]

How can I insert these values from val_list in columns in col_list for a specific row.
And I need to iterate multiple times.
These value and column list will change for every iteration but the order of column1 - value1, column2 - value2 doesn't change.
If the ith element in col_list is col-i, then ith element in val_list will be val-i.
How can I enter data in only specific columns that are in col_list into pandas dataframe.

A: my_pd = pd.DataFrame(np.array(val_list)).T
my_pd.columns = col_list
pd.concat([a, my_pd], ignore_index=True)

I don't really see this in other answers, but here is a way to use concat to join your list to the end of the pandas dataframe. It's tricky though, usually it's best to iterate through all the list you want to join, create a new DataFrame off that and then joining those 2 df together, it will be much easier and faster.


text:
Q: Not modify package.json when doing npm audit fix I've updated my npm version, and I think npm audit is a new feature. When I run npm audit fix some of my packages versions are changed from package.json. I just want keep the packages as same as my coworkers

A: npm audit fix is not must to get your app up and running. I use this command when I want to make sure that there is no potential security vulnerability so that git hub won't have any object against my project. In case you still want to use audit fix without changing rest files, try this commands
Run audit fix without modifying node_modules, but still updating the pkglock:
 $ npm audit fix --package-lock-only

Skip updating devDependencies:
  $ npm audit fix --only=prod

Do a dry run to get an idea of what audit fix will do, and also output install information in JSON format:
$ npm audit fix --dry-run --json

Check out this link for your future reference:
https://docs.npmjs.com/cli/audit

A: To answer the original question, if you really want to skip auditing completely when installing (for whatever reason, in my case I wanted to troubleshoot an exception when installing) you can use --no-audit flag:
npm install --no-audit