Q: Converting BNF to EBNF confused about the difference between left and right recursion I have this BNF rule:
<S> ->   b |  b <C>
 ->  a | a
<C> ->  c | <C> c

i want to turn it into EBNF rule however i am confused about the left and right recursion in the  and <C>, how will it differs in EBNF or they will be the same?
Here is what i did:
To convert: <S> ->  b |  b <C> to EBNF
1.   <S> ->  b |  b <C>
2.   <S> ->  b [<C>]
3.   <S> ->  b (<C>)?
To convert:  - >  a | a  to EBNF
1.   - >  a | a
2.   - >  a | a{a}
3.   - >  a | a{a}+
4.    - > a+
To convert: <C> -> c | <C> c to EBNF
1.  <C> -> c | <C> c
2.  <C> -> c | {c} c
3.  <C> -> c | {c}+ c
4.  <C> -> c+

A: They'll be the same.  For example, <C> will match all of the following:
c
c c
c c c
c c c c c c c c c c c c c c c c c c c c c

And  will match all of the following:
a
a a
a a a
a a a a a a a a a a a a a a a a a a a a a

As a result, the EBNF for both will match.  In general, if the left recursion is at the very beginning and the right recursion is at the very end, they will look similar:
 -> a | a
<C> -> c | <L> c

EBNF:
 -> a | a a*
 -> a+
<C> -> c | c* c
<C> -> c+

What this EBNF grammar doesn't express is how the expression is parsed.  In converting from BNF to EBNF, you lose the expressiveness.  However, you can make it explicit by avoiding +:
 -> a a*
<C> -> c* c

Of course, the fact that both reduce to E+ means you can parse them as left-recursive or right-recursive, and the result won't matter.  That's not always true—(2-3)-4 ≠ 2-(3-4)—but you do have the option of converting <C> to a right-recursive production, and the result will be the same.


Q: cdap sandbox won't start - Unable to read transaction state version I have installed the binaries for the CDAP sandbox using the recipe found here.   I was building a plugin and may have had a debugger blocking work.  I rebooted my Linux PC on which the sandbox was running and now when I try and start the CDAP sandbox we end up with an error:
2020-10-04 09:05:57,507 - ERROR [main:o.a.t.s.SnapshotCodecProvider@122] - Unable to read transaction state version:
java.io.EOFException: null
        at org.apache.tephra.snapshot.BinaryDecoder.readByte(BinaryDecoder.java:106) ~[org.apache.tephra.tephra-core-0.15.0-incubating.jar:0.15.0-incubating]
        at org.apache.tephra.snapshot.BinaryDecoder.readInt(BinaryDecoder.java:48) ~[org.apache.tephra.tephra-core-0.15.0-incubating.jar:0.15.0-incubating]

My gut is saying that the last time CDAP ran, it didn't get the opportunity to write transaction state for an in-flight run and now I have corrupted some state.  Since I'm only sandbox testing now, I'm happy to cold start CDAP.  Unfortunately I haven't found any recipe for this yet.  Has anyone seen anything similar or have a recipe for a cold start of CDAP sandbox?

A: As you have mentioned in the comment, deleting the data and logs directory will solve the problem, but it will reset the sandbox. CDAP sandbox is running on a single java process so it does not have High Availability (HA). When the process is killed suddenly, it may end up in a corrupted state.

A: I'had the same isue. To solve the problem you have to delete or rename the tx.snapshot directory in the directory called data. It's ok for me without any reset.


Q: Input, Process, and Output pairs of data We have a text file that contains drug administration data.  Each line contains a patient ID, an administration date and a drug name, formatted as follows:
A234,2014-01-01,5FU
A234,2014-01-02,adderall
B324,1990-06-01,adderall
A234,2014-01-02,tylenol
B324,1990-06-01,tylenol
...etc.

Using an input file of this format, produce a list of pairs of drugs that were administered together (i.e. administered to the same patient on the same day) at least twenty-five different times.  In the above sample, adderall and tylenol appear together twice, but every other pair appears only once. Output each qualifying pair as a comma-separated tuple, one per line.
Assuming that the adderall-tylenolcombination occurred 50 times and tylenol-5FU combination occurred 10 times, the output file should look something like this:
           drug_used frequency
    adderall-tylenol        50
Note that because the tylenol-5FU combination occurred less than 25 times, it's not included on the final output.

A: Using library(data.table) we can do
dt[, paste(drug, collapse = '-'), by = .(id,date)]
#      id       date               V1
# 1: A234 2014-01-01              5FU
# 2: A234 2014-01-02 adderall-tylenol
# 3: B324 1990-06-01 adderall-tylenol

Although this also includes id-date combinations where the drug combination is not a tuple.  If you want to only have the lines which have exactly two drugs, then we add a test for this:
dt[, if (.N == 2) paste(drug, collapse = '-'), by = .(id,date)]
#      id       date               V1
# 1: A234 2014-01-02 adderall-tylenol
# 2: B324 1990-06-01 adderall-tylenol

To further subset these results to only those patients where a drug combination was applied more than 25 times on different days, we can chain the result to another test for this:
dt[, if (.N == 2) paste(drug, collapse = '-'), by = .(id,date)][, if (.N>25) .(date,V1), by=id]

If you need, you can write these results to a new file using write.table
The data
dt = fread("id, date, drug
A234,2014-01-01,5FU
A234,2014-01-02,adderall
B324,1990-06-01,adderall
A234,2014-01-02,tylenol
B324,1990-06-01,tylenol")

A: You can use dplyr library to summarize the data table.
library(dplyr)

data = data.frame(id = c("A234","A234", "B324", "A234","B324"),
                  date = strptime(c("2014-01-01","2014-01-02", "1990-06-01", "2014-01-02", "1990-06-01"),
                                  format = "%Y-%m-%d"),
                  drug = c("5FU", "adderall", "adderall", "tylenol", "tylenol"))

data %>%
  group_by(id, date) %>%
  summarise(drug_used = paste(drug,collapse = "-"))

Source: local data frame [3 x 3]
Groups: id [?]

      id       date        drug_used
  <fctr>     <dttm>            <chr>
1   A234 2014-01-01              5FU
2   A234 2014-01-02 adderall-tylenol
3   B324 1990-06-01 adderall-tylenol


Q: Swift - Segmented control - Switch multiple views Until now I still can't figure how to switch multiple views in one view controller. My storyboard is like this one.

Right now I want to embed two views inside my view controller.

My code for segmented control to switch two views in one view controller so far.
import UIKit

class PopularHistoryViewController: UIViewController {

    @IBOutlet weak var segmentedControl: UISegmentedControl!

    @IBAction func indexChanged(sender: UISegmentedControl) {
        switch segmentedControl.selectedSegmentIndex
        {
        case 0:
            NSLog("Popular selected")
            //show popular view
        case 1:
            NSLog("History selected")
            //show history view
        default:
            break;
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

}

Another thing, If I put two views inside my controller, what is best practice to differentiate it?

A: First of all create two outlets and connect hose to the views in your ViewController.
@IBOutlet weak var firstView: UIView!
@IBOutlet weak var secondView: UIView!

And Change the code like:
@IBAction func indexChanged(sender: UISegmentedControl)
{
    switch segmentedControl.selectedSegmentIndex
    {
    case 0:
        firstView.hidden = false
        secondView.hidden = true
    case 1:
        firstView.hidden = true
        secondView.hidden = false
    default:
        break;
    }
}

If you don't want to create Outlets, assign the views individual tags (Say 101 and 102) and you can do it like:
@IBAction func indexChanged(sender: UISegmentedControl)
{
    switch segmentedControl.selectedSegmentIndex
    {
    case 0:
        self.view.viewWithTag(101)?.hidden = false
        self.view.viewWithTag(102)?.hidden = true
    case 1:
        self.view.viewWithTag(101)?.hidden = true
        self.view.viewWithTag(102)?.hidden = false
    default:
        break;
    }
}

A: If you want to do UI layout in Xcode for the two overlapping subviews, a better solution is to use two UIContainerViewController, and use the same way of setting the hidden property as suggested in the above answer.

A: You can use the isHidden property of the UIView to show/hide your required views.
First you have to link both views  to IBOutlets through the Interface builder
@IBOutlet weak var historyView: UIView!
@IBOutlet weak var popularView: UIView!

@IBAction func indexChanged(_ sender: UISegmentedControl) {
    switch segmentedControl.selectedSegmentIndex {
    case 0:
        historyView.isHidden = true
        popularView.isHidden = false
    case 1:
        historyView.isHidden = false
        popularView.isHidden = true
    default:
        break;
    }
}

Note: it was named hidden in Swift 1 and 2.

A: Add both views to the view controller in the story board and set one of them to be hidden = yes or alpha = 0. When your index changed function gets called set the current view on screen to hidden = yes/alpha of 0 and set the previously hidden view to hidden = no/alpha = 1. This should achieve what you want.

A: @IBAction func acSegmentAction(_ sender: Any) {

    switch acSegmentedControl.selectedSegmentIndex {
        case 0:
           // print("addressview selected")
            addressView.isHidden = false
            contactProviderView.isHidden = true
        case 1:
            //print("contact provider selected")
            addressView.isHidden = true
            contactProviderView.isHidden = false
        default:
            break;
    }
}

A: If it is a simple view, not a part of the screen, you can indeed use isHidden property of two subviews of your view controller view. But I don't like this approach because it's hard to understand latter what is going on with your nib when all of the subviews are in one pile.
I would add and remove those two views as child view controllers programmatically. It's the cleanest way there is, in my opinion.
But even if you decided to go with just views, don't put them directly on view controller's view. Use nibs, preferably with owner class. And in many cases consider adding and constraint them programmatically. It's more code, but also cleaner and conserves resources.

A: So what is written above does not work for me, so I figured out myself in Xcode 11 with Swift 5.
(view1 = historyView, view2 = popularView)
@IBOutlet weak var view1: UITableView!
@IBOutlet weak var view2: UITableView!

@IBAction func segmentedControlChanged(_ sender: Any) {

    func showView1() {
        view1.isHidden = false
        view2.isHidden = true
    }

    func showView2() {
        view1.isHidden = true
        view2.isHidden = false
    }

    guard let segmentedControl = sender as?
        UISegmentedControl else { return }
    if segmentedControl.selectedSegmentIndex == 0 {
        showView1()

    }
        else {
            showView2()
        }
    }

Maybe this helps anyone.


Q: How to connect output layers to the input layer of another neural network? The Actor-network has 5 input neurons representing the state values and will produce one output value held by one output neuron.
The Q Network has 6 input neurons: 5 representing the state values and 1 representing the output of Actor-network.
I'll do gradient descent to train the Actor-network seperately, holding Q network's weights as constant.
My question is:
How should I structure to plug the output layer of Actor-Network into the input layer of the Q network, with TensorFlow 2.x?

A: You can just use the ŧf.keras.Model API:
actor_model = tf.keras.Model(inputs=...,outputs=...)
Q_model = tf.keras.Model(inputs=actor_model.outputs, outputs=...)


Q: How to recover deleted files from [formatted] FAT32/NTFS drive in Linux? Is there like EasyRecovery for Linux? Free open source command-line based software strongly preferred.
Expecting something like:
$ fat32_recovery --some-arcane-options dump.img dir/
Recovery in progress...
    ~ILE1.TXT -> dir/XILE1.TXT
    ~IR1 -> dir/XIR1/
    ~IR1/ololo.txt -> dir1/XIR1/ololo.txt
    ~IR1/kekeke.avi -> dir1/XIR/kekeke.avi [damaged 10%]
    goodfile.txt -> dir1/goodfile.txt

Is there special things for jpg photos or documents (like in EasyRecovery)?
There are numerous step-by-step recovery GUI tools for Windows, I'm looking for console-based ones targeted for power users.

A: You can try PhotoRec, which works natively on Linux.  It works with all Windows and Linux filesystems.  If the filesystem itself is damaged beyond what PhotoRec can handle, you can also use TestDisk (from the same company) which can repair and recover an entire filesystem if possible.  Both of these tools are free, open source, and cross platform.  From the website:

PhotoRec ignores the file system and goes after the underlying data,
  so it will still work even if your media's file system has been
  severely damaged or reformatted.

Alternatively, you might have some luck using Recuva under Wine.  From the entry in WineHQ, it appears as though it works with Windows-based filesystems (e.g. NTFS/FAT32), but not Linux-based ones (e.g. Ext3, XFS).


Q: Word 2007 does not update when printing I used the "update fields when printing" option for years; it is a useful feature.
Unfortunately, the update stopped working a few years ago. Our IT guys say it's because of one of the service packs, but that seems odd, especially when I see people asking how to stop the automatic update.


Q: How to get a random CGFloat for a constraint? I'm trying to randomize a leading constraint for a button in swift. To activate this I am selecting a button. When I select the button for the first time, it works well, but all the times after this, it shows a lot of errors in the NSLog. Here's the code:
let button = UIButton()
@IBAction func start(sender: UIButton) {
     let randomNumber = Int(arc4random_uniform(180) + 30)
     let cgfloatrandom = CGFloat(randomNumber)
     button.hidden = false
     button.translatesAutoresizingMaskIntoConstraints = false
     NSLayoutConstraint.activateConstraints([
        button.leadingAnchor.constraintEqualToAnchor(view.leadingAnchor, constant: cgfloatrandom),
        button.topAnchor.constraintEqualToAnchor(view.topAnchor, constant: 390),
        button.widthAnchor.constraintEqualToConstant(75),
        button.heightAnchor.constraintEqualToConstant(75)
        ])
}

Please help. Thank you. Anton

A: The problem is you're adding constraints to a button that already has been properly constrained. While you could remove all the constraints and recreate them, that is really inefficient and would not be recommended.
I would recommend simply keeping a reference to the leading constraint, which will allow you to access it every time the button is tapped to modify the constant.
To do this, implement a property for your leading constraint, like so:
var leadingConstraint: NSLayoutConstraint!

When you create this button, you'll want to properly constrain it as well. Here is where you'll be creating that special leading constraint. This is done outside of the button action function, perhaps in viewDidLoad:
button = UIButton()
button.translatesAutoresizingMaskIntoConstraints = false
//...

leadingConstraint = button.leadingAnchor.constraintEqualToAnchor(view.leadingAnchor, constant: 0)

NSLayoutConstraint.activateConstraints([
    leadingConstraint,
    button.topAnchor.constraintEqualToAnchor(view.topAnchor, constant: 390),
    button.widthAnchor.constraintEqualToConstant(75),
    button.heightAnchor.constraintEqualToConstant(75)
])

Now when the button is tapped, you won't need to set translatesAutoresizingMaskIntoConstraints, and you can simply update the constant of the existing leading constraint.
@IBAction func start(sender: UIButton) {
     button.hidden = false

     let randomNumber = Int(arc4random_uniform(180) + 30)
     leadingConstraint.constant = CGFloat(randomNumber)
}


Q: Pick main color from picture I'm new to Dart/Flutter framework and I'm still exploring their possibilities.
I know in Android it's possible to take a picture and extract the main color value from it programmatically. (Android example)
I wonder, how would this be achieved in pure Dart? I would like it to be compatible with both iOS and Android operating system.

A: Here's a simple function which returns the dominant color given an ImageProvider. This shows the basic usage of Palette Generator without all the boilerplate.
import 'package:palette_generator/palette_generator.dart';

// Calculate dominant color from ImageProvider
Future<Color> getImagePalette (ImageProvider imageProvider) async {
  final PaletteGenerator paletteGenerator = await PaletteGenerator
      .fromImageProvider(imageProvider);
  return paletteGenerator.dominantColor.color;
}

Then use FutureBuilder on the output to build a Widget.

A: I probably think you got a fix but for future searches to this question, I suggest you check Pallete Generator by the flutter team.
I will try and give a simple explanation of how the code works but for a detailed example head over to the plugin's GitHub repo.
The example below is going to take an image then select the dominant colors from it and then display the colors
First, we add the required imports
import 'package:palette_generator/palette_generator.dart';

After that let's create the main application class.
class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      ...
      home: const HomePage(
        title: 'Colors from image',
        image: AssetImage('assets/images/artwork_default.png',),
        imageSize: Size(256.0, 170.0),
      ...

      ),
    );
  }
}

In the image field above, place the image that you want to extract the dominant colors from, i used the image shown here.
Next, we create the HomePage class
@immutable
class HomePage extends StatefulWidget {
  /// Creates the home page.
  const HomePage({
    Key key,
    this.title,
    this.image,
    this.imageSize,
  }) : super(key: key);

  final String title; //App title
  final ImageProvider image; //Image provider to load the colors from
  final Size imageSize; //Image dimensions

  @override
  _HomePageState createState() {
    return _HomePageState();
  }
}

Lets create the _HomePageState too
class _HomePageState extends State<HomePage> {
  Rect region;
  PaletteGenerator paletteGenerator;

  final GlobalKey imageKey = GlobalKey();

  @override
  void initState() {
    super.initState();
    region = Offset.zero & widget.imageSize;
    _updatePaletteGenerator(region);
  }

  Future<void> _updatePaletteGenerator(Rect newRegion) async {
    paletteGenerator = await PaletteGenerator.fromImageProvider(
      widget.image,
      size: widget.imageSize,
      region: newRegion,
      maximumColorCount: 20,
    );
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: _kBackgroundColor,
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Column(
        mainAxisSize: MainAxisSize.max,
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          new AspectRatio(
            aspectRatio: 15 / 15,
            child: Image(
              key: imageKey,
              image: widget.image,
            ),
          ),
          Expanded(child: Swatches(generator: paletteGenerator)),
        ],
      ),
    );
  }
}

The code above just lays out the image and the Swatches which is a class defined below. In initState, we first select a region which the colors will be derived from which in our case is the whole image.
After that we create a class Swatches which receives a PalleteGenerator and draws the swatches for it.
class Swatches extends StatelessWidget {

  const Swatches({Key key, this.generator}) : super(key: key);

  // The PaletteGenerator that contains all of the swatches that we're going
  // to display.
  final PaletteGenerator generator;

  @override
  Widget build(BuildContext context) {
    final List<Widget> swatches = <Widget>[];
    //The generator field can be null, if so, we return an empty container
    if (generator == null || generator.colors.isEmpty) {
      return Container();
    }
    //Loop through the colors in the PaletteGenerator and add them to the list of swatches above
    for (Color color in generator.colors) {
      swatches.add(PaletteSwatch(color: color));
    }
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: <Widget>[
        //All the colors,
        Wrap(
          children: swatches,
        ),
        //The colors with ranking
        Container(height: 30.0),
        PaletteSwatch(label: 'Dominant', color: generator.dominantColor?.color),
        PaletteSwatch(
            label: 'Light Vibrant', color: generator.lightVibrantColor?.color),
        PaletteSwatch(label: 'Vibrant', color: generator.vibrantColor?.color),
        PaletteSwatch(
            label: 'Dark Vibrant', color: generator.darkVibrantColor?.color),
        PaletteSwatch(
            label: 'Light Muted', color: generator.lightMutedColor?.color),
        PaletteSwatch(label: 'Muted', color: generator.mutedColor?.color),
        PaletteSwatch(
            label: 'Dark Muted', color: generator.darkMutedColor?.color),
      ],
    );
  }
}

After that lets create a PaletteSwatch class. A palette swatch is just a square of color with an optional label
@immutable
class PaletteSwatch extends StatelessWidget {
  // Creates a PaletteSwatch.
  //
  // If the [color] argument is omitted, then the swatch will show a
  // placeholder instead, to indicate that there is no color.
  const PaletteSwatch({
    Key key,
    this.color,
    this.label,
  }) : super(key: key);

  // The color of the swatch. May be null.
  final Color color;

  // The optional label to display next to the swatch.
  final String label;

  @override
  Widget build(BuildContext context) {
    // Compute the "distance" of the color swatch and the background color
    // so that we can put a border around those color swatches that are too
    // close to the background's saturation and lightness. We ignore hue for
    // the comparison.
    final HSLColor hslColor = HSLColor.fromColor(color ?? Colors.transparent);
    final HSLColor backgroundAsHsl = HSLColor.fromColor(_kBackgroundColor);
    final double colorDistance = math.sqrt(
        math.pow(hslColor.saturation - backgroundAsHsl.saturation, 2.0) +
            math.pow(hslColor.lightness - backgroundAsHsl.lightness, 2.0));

    Widget swatch = Padding(
      padding: const EdgeInsets.all(2.0),
      child: color == null
          ? const Placeholder(
              fallbackWidth: 34.0,
              fallbackHeight: 20.0,
              color: Color(0xff404040),
              strokeWidth: 2.0,
            )
          : Container(
              decoration: BoxDecoration(
                  color: color,
                  border: Border.all(
                    width: 1.0,
                    color: _kPlaceholderColor,
                    style: colorDistance < 0.2
                        ? BorderStyle.solid
                        : BorderStyle.none,
                  )),
              width: 34.0,
              height: 20.0,
            ),
    );

    if (label != null) {
      swatch = ConstrainedBox(
        constraints: const BoxConstraints(maxWidth: 130.0, minWidth: 130.0),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.start,
          children: <Widget>[
            swatch,
            Container(width: 5.0),
            Text(label),
          ],
        ),
      );
    }
    return swatch;
  }
}

Hope this helps, thank you.

A:     //////////////////////////////
//
// 2019, roipeker.com
// screencast - demo simple image:
// https://youtu.be/EJyRH4_pY8I
//
// screencast - demo snapshot:
// https://youtu.be/-LxPcL7T61E
//
//////////////////////////////

import 'dart:async';
import 'dart:typed_data';
import 'dart:ui' as ui;
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:image/image.dart' as img;
import 'package:flutter/services.dart' show rootBundle;

void main() => runApp(const MaterialApp(home: MyApp()));

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String imagePath = 'assets/5.jpg';
  GlobalKey imageKey = GlobalKey();
  GlobalKey paintKey = GlobalKey();

  // CHANGE THIS FLAG TO TEST BASIC IMAGE, AND SNAPSHOT.
  bool useSnapshot = true;

  // based on useSnapshot=true ? paintKey : imageKey ;
  // this key is used in this example to keep the code shorter.
  late GlobalKey currentKey;

  final StreamController<Color> _stateController = StreamController<Color>();
  //late img.Image photo ;
  img.Image? photo;

  @override
  void initState() {
    currentKey = useSnapshot ? paintKey : imageKey;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    final String title = useSnapshot ? "snapshot" : "basic";
    return SafeArea(
      child: Scaffold(
        appBar: AppBar(title: Text("Color picker $title")),
        body: StreamBuilder(
            initialData: Colors.green[500],
            stream: _stateController.stream,
            builder: (buildContext, snapshot) {
              Color selectedColor = snapshot.data as Color ?? Colors.green;
              return Stack(
                children: <Widget>[
                  RepaintBoundary(
                    key: paintKey,
                    child: GestureDetector(
                      onPanDown: (details) {
                        searchPixel(details.globalPosition);
                      },
                      onPanUpdate: (details) {
                        searchPixel(details.globalPosition);
                      },
                      child: Center(
                        child: Image.asset(
                          imagePath,
                          key: imageKey,
                          //color: Colors.red,
                          //colorBlendMode: BlendMode.hue,
                          //alignment: Alignment.bottomRight,
                          fit: BoxFit.contain,
                          //scale: .8,
                        ),
                      ),
                    ),
                  ),
                  Container(
                    margin: const EdgeInsets.all(70),
                    width: 50,
                    height: 50,
                    decoration: BoxDecoration(
                        shape: BoxShape.circle,
                        color: selectedColor!,
                        border: Border.all(width: 2.0, color: Colors.white),
                        boxShadow: [
                          const BoxShadow(
                              color: Colors.black12,
                              blurRadius: 4,
                              offset: Offset(0, 2))
                        ]),
                  ),
                  Positioned(
                    child: Text('${selectedColor}',
                        style: const TextStyle(
                            color: Colors.white,
                            backgroundColor: Colors.black54)),
                    left: 114,
                    top: 95,
                  ),
                ],
              );
            }),
      ),
    );
  }

  void searchPixel(Offset globalPosition) async {
    if (photo == null) {
      await (useSnapshot ? loadSnapshotBytes() : loadImageBundleBytes());
    }
    _calculatePixel(globalPosition);
  }

  void _calculatePixel(Offset globalPosition) {
    RenderBox box = currentKey.currentContext!.findRenderObject() as RenderBox;
    Offset localPosition = box.globalToLocal(globalPosition);

    double px = localPosition.dx;
    double py = localPosition.dy;

    if (!useSnapshot) {
      double widgetScale = box.size.width / photo!.width;
      print(py);
      px = (px / widgetScale);
      py = (py / widgetScale);
    }

    int pixel32 = photo!.getPixelSafe(px.toInt(), py.toInt());
    int hex = abgrToArgb(pixel32);

    _stateController.add(Color(hex));
  }

  Future<void> loadImageBundleBytes() async {
    ByteData imageBytes = await rootBundle.load(imagePath);
    setImageBytes(imageBytes);
  }

  Future<void> loadSnapshotBytes() async {
    RenderRepaintBoundary boxPaint =
        paintKey.currentContext!.findRenderObject() as RenderRepaintBoundary;
    //RenderObject? boxPaint = paintKey.currentContext.findRenderObject();
    ui.Image capture = await boxPaint.toImage();

    ByteData? imageBytes =
        await capture.toByteData(format: ui.ImageByteFormat.png);
    setImageBytes(imageBytes!);
    capture.dispose();
  }

  void setImageBytes(ByteData imageBytes) {
    List<int> values = imageBytes.buffer.asUint8List();
    photo;
    photo = img.decodeImage(values)!;
  }
}

// image lib uses uses KML color format, convert #AABBGGRR to regular #AARRGGBB
int abgrToArgb(int argbColor) {
  int r = (argbColor >> 16) & 0xFF;
  int b = argbColor & 0xFF;
  return (argbColor & 0xFF00FF00) | (b << 16) | r;
}


Q: How can i return different value from what was in the dropdown in dart? I am working with dropbox, but what i want to do is retrieve value depending on what the user chooses on the dropbox; for example the users picks "apple" on the dropdownbox what i want to return will be "Vitamin C"
Here is what i have so far:
String myFruits;

  List<String> fruits = [
    "APPLE",
    "ORANGE",
    "BANANA",];

        DropdownSearch(
          onChanged: (dynamic value) {
            myFruits = value;
          },
          mode: Mode.DIALOG,
          items: fruits,
        ),

For now when i print myFruits what it shows is the selected value of the dropbox, what I want is that if pick apple it will return "vitamin c" like that. Thanks :) How can i achieve this?

A: you can define a Map from fruits and returnedValue like:
Map<String, String> returnedValue = {
  "APPLE" : "Vitamin A",
  "ORANGE" : "Vitamin C",
  "BANANA" : "Vitamin K",
};

and return from this.

all your code like this :
   Function(String) returnFunction();

   String myFruits;
   String myVitamin;

   List<String> fruits = [
     "APPLE",
     "ORANGE",
     "BANANA",
   ];
   Map<String, String> returnedValue = {
      "APPLE" : "Vitamin A",
      "ORANGE" : "Vitamin C",
      "BANANA" : "Vitamin K",
   };

        DropdownSearch(
          onChanged: (dynamic value) {
            myFruits = value;
            myVitamin = returnedValue[value];
            returenFunction(myVitamin); // if you want return from this class
          },
          mode: Mode.DIALOG,
          items: fruits,
        ),


Q: Java lazy reading of XML file? I am wondering how I can lazily read a large XML file that doesn't fit into memory in Java. Let's assume the file is correctly formatted and we don't have to make a first pass to check this. Does someone know how to do this in Java?
Here is my fake file (real file is a Wikipedia dump which is 50+ Gb):
<pages>
  <page>
    <text> some data ....... </text>
  </page>
  <page>
    <text> MORE DATA ........ </text>
  </page>
</pages>

I was trying this with an XML library that is supposed to be able to do this but it's loading the whole thing into memory >:O
DOMParser domParser = new DOMParser();
//This is supposed to make it lazy-load the file, but it's not working
domParser.setFeature("http://apache.org/xml/features/dom/defer-node-expansion", true);
//Library says this needs to be set to use defer-node-expansion
domParser.setProperty("http://apache.org/xml/properties/dom/document-class-name", "org.apache.xerces.dom.DocumentImpl");

//THIS IS LOADING THE WHOLE FILE
domParser.parse(new InputSource(wikiXMLBufferedReader));

Document doc = domParser.getDocument();
NodeList pages = doc.getElementsByTagName("page");

for(int i = 0; i < pages.getLength(); i++) {
    Node pageNode = pages.item(i);
    //do something with page nodes
}

Do anyone know how to do this? Or what am I doing wrong in my attempt with this particular Java XML library?
Thanks.

A: You should be looking at SAX parsers in Java. DOM parsers are built to read the entire XMLs, load into memory, and create java objects out of them. SAX parsers serially parse XML files and use an event based mechanism to process the data. Look at the differences here.
Here's a link to a SAX tutorial. Hope it helps.

A: If you're prepared to buy a Saxon-EE license, then you can issue the simple query "copy-of(//page)", with execution options set to enable streaming, and it will return you an iterator over a sequence of trees each rooted at a page element; each of the trees will be fetched when you advance the iterator, and will be garbage-collected when you have finished with it. (That's assuming you really want to do the processing in Java; you could also do the processing in XQuery or XSLT, of course, which would probably save you many lines of code.)
If you have more time than money, and want a home-brew solution, then write a SAX filter which accepts parsing events from the XML parser and sends them on to a DocumentBuilder; every time you hit a startElement event for a page element, open a new DocumentBuilder; when the corresponding endElement event is notified, grab the tree that has been built by the DocumentBuilder, and pass it to your Java application for processing.


Q: Distinct character SET of substring in string Suppose a SET is all distinct character in a string.
I need to find out count of such distinct SET  made from substrings in a string.
2 SETS are same when they have same characters in them.
eg:-string=ABBC
answer=6
distinct character sets of substrings are:{A},{B},{C},{A,B},{A,B,C},{B,C}
Note:Substring BBC and BC have same SET {B,C}, ABBC substring is SET {A,B,C}
PS:Seen on hackerearth Augito backend contest.The contest is over on 30-05-2021
Constraint 1<=Stringlen<=10^5 so expected complexity is O(N) or O(NLOGN)

A: You can use a two pointer approach + counting the frequencies.
static int countSub(String str)
{
    int n = (int)str.length();

    // Stores the count of
    // subStrings
    int ans = 0;

    // Stores the frequency
    // of characters
    int []cnt = new int[26];

    // Initialised both pointers
    // to beginning of the String
    int i = 0, j = 0;

    while (i < n)
    {

        // If all characters in
        // subString from index i
        // to j are distinct
        if (j < n &&
        (cnt[str.charAt(j) - 'a'] == 0))
        {

            // Increment count of j-th
            // character
            cnt[str.charAt(j) - 'a']++;

            // Add all subString ending
            // at j and starting at any
            // index between i and j
            // to the answer
            ans += (j - i + 1);

            // Increment 2nd pointer
            j++;
        }

        // If some characters are repeated
        // or j pointer has reached to end
        else
        {

            // Decrement count of j-th
            // character
            cnt[str.charAt(i) - 'a']--;

            // Increment first pointer
            i++;
        }
    }

    // Return the final
    // count of subStrings
    return ans;
}

Here it considered only lower case letters. You can refer here


Q: How to calculate this residue How to calculate this residue $$Res\left(\frac{\ln z}{z(z+1)},0\right).$$ Is it $\infty$? And if this could not be calculated, then how to calculate $$\int_0^\infty \frac{x}{e^x+1}dx$$ by changing variables $y=e^x$.


Q: Issue integrating Node js with dialogflow I have created a Google Dialogflow agent, now I am trying to integrate it with a node js app so that I can create a custom UI for the chatbot.
I have followed the instructions in the document...
Enabled API for the project, generated the JSON key.
Below is my code:
const dialogflow = require('dialogflow');
const uuid = require('uuid');

/**
 * Send a query to the dialogflow agent, and return the query result.
 * @param {string} projectId The project to be used
 */
async function runSample(projectId = 'br-poaqqc') {
  // A unique identifier for the given session
  const sessionId = uuid.v4();

  // Create a new session
  const sessionClient = new dialogflow.SessionsClient({
    keyFilename: "./br-poaqqc-51d2d712d74f.json"
  });
  const sessionPath = sessionClient.sessionPath(projectId, sessionId);
  // The text query request.
  const request = {
    session: sessionPath,
    queryInput: {
      text: {
        // The query to send to the dialogflow agent
        text: 'hi',
        // The language used by the client (en-US)
        languageCode: 'en-US',
      },
    },
  };
  // Send request and log result
  try {
    const responses = await sessionClient.detectIntent(request);
  } catch(err) {
      console.log('Error getting response',err)
  }
  console.log(responses);
  console.log('Detected intent');
  const result = responses[0].queryResult;
  console.log(`  Query: ${result.queryText}`);
  console.log(`  Response: ${result.fulfillmentText}`);
  if (result.intent) {
    console.log(`  Intent: ${result.intent.displayName}`);
  } else {
    console.log(`  No intent matched.`);
  }
}

runSample();

There seems to be some certificate error. Below is the log:
Error getting response Error: SELF_SIGNED_CERT_IN_CHAIN undefined: Getting metadata from plugin failed with error: request to https://www.googleapis.com/oauth2/v4/token failed, reason: self signed certificate in certificate chain
    at Object.callErrorFromStatus (D:\PV\Codebase\chatbot-ui\node_modules\@grpc\grpc-js\build\src\call.js:30:26)
    at Object.onReceiveStatus (D:\PV\Codebase\chatbot-ui\node_modules\@grpc\grpc-js\build\src\client.js:175:52)
    at Object.onReceiveStatus (D:\PV\Codebase\chatbot-ui\node_modules\@grpc\grpc-js\build\src\client-interceptors.js:341:141)
    at Object.onReceiveStatus (D:\PV\Codebase\chatbot-ui\node_modules\@grpc\grpc-js\build\src\client-interceptors.js:304:181)
    at Http2CallStream.outputStatus (D:\PV\Codebase\chatbot-ui\node_modules\@grpc\grpc-js\build\src\call-stream.js:116:74)
    at Http2CallStream.maybeOutputStatus (D:\PV\Codebase\chatbot-ui\node_modules\@grpc\grpc-js\build\src\call-stream.js:155:22)
    at Http2CallStream.endCall (D:\PV\Codebase\chatbot-ui\node_modules\@grpc\grpc-js\build\src\call-stream.js:141:18)
    at Http2CallStream.cancelWithStatus (D:\PV\Codebase\chatbot-ui\node_modules\@grpc\grpc-js\build\src\call-stream.js:457:14)
    at D:\PV\Codebase\chatbot-ui\node_modules\@grpc\grpc-js\build\src\channel.js:225:36
    at processTicksAndRejections (internal/process/task_queues.js:85:5) {
  code: 'SELF_SIGNED_CERT_IN_CHAIN',
  details: 'Getting metadata from plugin failed with error: request to https://www.googleapis.com/oauth2/v4/token failed, reason: self signed certificate in certificate chain',
  metadata: Metadata { internalRepr: Map {}, options: {} }
}
(node:1632) UnhandledPromiseRejectionWarning: ReferenceError: responses is not defined
    at runSample (D:\PV\Codebase\chatbot-ui\app.js:35:15)
(node:1632) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:1632) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

The issue is lies around the sessionClient sending the request object to the dialogflow API. Beating my head over it for the past couple of hours. :/
Any clue where the issue is?
Thanks in advance! :)

A: const dialogflow = require('dialogflow');
const uuid = require('uuid');
const config = require('./config'); // your JSON file

if(!config.private_key) throw new Error('Private key required')
if(!config.client_email)throw new Error('Client email required')
if(!config.project_id) throw new Error('project required')

const credentials = {
    client_email: config.client_email,
    private_key: config.private_key,
};

const sessionClient = new dialogflow.SessionsClient(
    {
        projectId: config.project_id,
        credentials
    }
);

async function runSample(projectId = 'br-poaqqc') {
    // A unique identifier for the given session
    const sessionId = uuid.v4();

    const sessionPath = sessionClient.sessionPath(config.project_id, sessionId);
    // The text query request.
    const request = {
        session: sessionPath,
        queryInput: {
            text: {
                // The query to send to the dialogflow agent
                text: 'hi',
                // The language used by the client (en-US)
                languageCode: 'en-US',
            },
        },
    };
    // Send request and log result
    try {
        const responses = await sessionClient.detectIntent(request);
        console.log(responses);
        console.log('Detected intent');
        const result = responses[0].queryResult;
        console.log(`  Query: ${result.queryText}`);
        console.log(`  Response: ${result.fulfillmentText}`);
        if (result.intent) {
            console.log(`  Intent: ${result.intent.displayName}`);
        } else {
            console.log(`  No intent matched.`);
        }
    } catch (err) {
        console.log('Error getting response', err)
    }

}

 runSample();

Don't seems any issue but i think issue was with try block.
Make sure you are with internet connection if trying from local and your firewall is not blocking googleapis

A: the issue was not to do with the code, the firewall was blocking the 'googleapis.com' domain. I deployed the app in Heroku server and it worked fine. :)
For anyone who ponders around the same issue and ends up here, make sure its not a firewall issue. Cheers!


Q: How to display 4 products in a row on PLP I have a situation where I need to display 4 products in a row on the product listing page whereas by default it's 5 in a row.
I know how to achieve this by overriding simple CSS but there is a condition I do not have the authority to override the existing CSS and so I don't really option as per the CSS is concerned so is there a way I can achieve through .phtml file by some minor customization.

A: If your custom theme is inheriting from Blank or Luma, by default on desktop view there are 4 products in a row.
So if you're viewing 5 in a row, it means that the default css of PLP was already changed.
You are binded in not using css rules, and that might be more than a concern. Grid system of PLP is totally controlled by css. Example:
.product-item {
  margin-left: 2%;
  padding: 5px;
  width: calc((100% - 6%)/4);
}

Yes, you can include a new grid system, like bootstrap for example, and call it's classes in the phtml but at the same time you should remove the original classes as well making sure that only the new grid rules will be loaded. I hope this hint helps you dealing with this problem.


Q: Mutating a slice of an array doesn't work import numpy as np
def solve_eps(eps):
    A = np.array([[eps, 1, 0], [1, 0, 0], [0, 1, 1]])
    b = np.array([1 + eps, 1, 2])

    m_21 = A[1, 0] / A[0, 0]
    m_31 = A[2, 0] / A[0, 0]

    print("What A[1, :] should be:", A[1, :] - A[0, :] * m_21)
    A[1, :] = A[1, :] - A[0, :] * m_21
    print("But it won't assign it to the slice!!!!!", A[1, :])

If we run solve_eps(2), you see that the slice doesn't assign:

What A[1, :] should be: [ 0.  -0.5  0. ]
  But it won't assign it to the slice!!!!! [0 0 0]

But, if you run:
A = np.array([[3, 1, 1], [2, 2, 2]])
A[1, :] = A[1, :] - (A[0, :] * 4)

A[1, :] = [-10, -2, -2]

What's going on here?

A: Set dtype=float when you define A:
A = np.array([[eps, 1, 0], [1, 0, 0], [0, 1, 1]], dtype=float)

The reason you assignment failed was because you were assigning floats to an integer array.
Assigning integers to an integer slice works fine, as you noticed.


Q: Update Stored Procedure - only update certain fields and leave others as is I'm currently making a stored procedure which will update a products details. I want to make it (if possible) so that only the fields entered under 'values' column when being executed are updated and the rest remain the same as before.
ALTER PROCEDURE [dbo].[spUpdateProduct]
@ProductID int, @Brand nvarchar(30), @ModelNo nvarchar(9), @Description
nvarchar(50), @CostPrice decimal(6,2), @Stock int, @SalePrice decimal(6,2)

AS
BEGIN
SET NOCOUNT ON

UPDATE tblProduct
SET
    Brand = @Brand,
    ModelNo = @ModelNo,
    [Description] = @Description,
    CostPrice = @CostPrice,
    Stock = @Stock,
    SalePrice = @SalePrice

WHERE ProductID = @ProductID

END

This is currently what I have. When I go to change a value it errors saying I didn't enter a value for 'Brand' which is the next value after 'ProductID'.
Execute Window
Error when trying to update two fields (ProductID and CostPrice)
EDIT: The fields are all set to 'not null' when I created the table.

A: This is how I would do it. Have null-able parameters
ALTER PROCEDURE [dbo].[spUpdateProduct]
@ProductID int,
@Brand nvarchar(30) = null,
@ModelNo nvarchar(9) = null, ..... (to all the parameters except @ProductID)

AS
BEGIN
SET NOCOUNT ON

UPDATE tblProduct
SET
    Brand = isNull(@Brand, Brand),
    ModelNo = isNull(@ModelNo, ModelNo),
    [Description] = isNull(@Description, Description),...

WHERE ProductID = @ProductID

END

Basically you are only updating the fields if parameters are not null otherwise keeping old values.

A: You have two problems - (a) the parameter to the stored procedure must be provided (the error tells you this) and (b) what to do when the parameter is not provided. For the first problem, check the pass null value or use SQL query to execute stored procedure like so:
exec spUpdateProduct 1, null, null, null, 140.99, null, null
For problem (b), use coalesce to update based on value being passed:
ALTER PROCEDURE [dbo].[spUpdateProduct]
@ProductID int, @Brand nvarchar(30), @ModelNo nvarchar(9), @Description
nvarchar(50), @CostPrice decimal(6,2), @Stock int, @SalePrice decimal(6,2)

AS
BEGIN
SET NOCOUNT ON

UPDATE t
SET
    Brand = coalesce(@Brand, t.Brand),
    ModelNo = coalesce(@ModelNo, t.ModelNo),
    [Description] = coalesce(@Description, t.Description),
    CostPrice = coalesce(@CostPrice, t.CostPrice),
    Stock = coalesce(@Stock, t.Stock),
    SalePrice = coalesce(@SalePrice, t.SalePrice)
FROM tblProduct as t
WHERE ProductID = @ProductID

END

A: After spending some time pondering this, I came up with a solution that doesn't use dynamic sql and also solves issues that coalese and isNull approaches don't solve. Note: minimal testing... looks like it does add a little overhead... but having this ability might allow flexibility on your client side code.
Table Schema:
FirstName NVARCHAR(200)
LastName NVARCHAR(200)
BirthDate DATE NULL
Activated BIT

Xml Param:
DECLARE @param =
N'<FirstName>Foo</FirstName>
<LastName>Bar</LastName>
<BirthDate>1999-1-1</BirthDate>
<Activated>1</Activated>'

UPDATE [dbo].[UserMaster]
[FirstName] = case when @param.exist('/FirstName') = 1 then @param.value('/FirstName[1]','nvarchar(200)') else [FirstName] end,
[LastName] = case when @param.exist('/LastName') = 1 then @param.value('/LastName[1]','nvarchar(200)') else [LastName] end,
[BirthDate] = case when @param.exist('/BirthDate') = 1 then @param.value('/BirthDate[1]','date') else [BirthDate]end,
[Activated] = case when @param.exist('/Activated') = 1 then @param.value('/Activated[1]','bit') else [Activated] end
WHERE [UserMasterKey] = @param.value('/UserMasterKey[1]','bigint')

This will allow you to pass in an XML parameter, with any field you want and Update that field. Note that setting fields equal to themselves in this context, for example [FirstName] = [FirstName], is perfectly fine. The engine will optimize this away.
Now, this is a more complex solution to @Anand and @r.net 's answers, however it does solve the 'setting nullables' problem that some commenters pointed out.
I liked how elegant their solutions were, but wanted to be able to set NULL on nullable columns, while still retaining the ability to use the default field value if I don’t pass in a parameter for that field. The using null checks as the basis for defaults in this case fills the hole and digs another one, so to speak, because they don't allow one to explicitly update a field to null.
Passing an xml parameter allows you to do that, all without taking a dynamic sql approach.
I would also look into using Table-valued parameters, as I believe there could be a similar solution using those.


Q: gpg verify of GNU Emacs download fails - Did I do it correctly? I have downloaded a GNU tar archive (emacs-26.1.tar.xz) and now want to verify it against its signature file. gpg returns with the verify option the following output:
    gpg: no valid OpenPGP data found.
    gpg: the signature could not be verified.

Obviously the download could not be verified. But what does this mean? Is the tar archive probably corrupt? Or had I not imported the correct keys?

Here is step-by-step what I did:

*

*I downloaded the archive file and its .sig file:
$ wget https://ftp.gnu.org/gnu/emacs/emacs-26.1.tar.xz
$ wget https://ftp.gnu.org/gnu/emacs/emacs-26.1.tar.xz.sig

*I downloaded the GNU keyring (the Emacs download page gave me the link):
$ wget https://ftp.gnu.org/gnu/gnu-keyring.gpg

*With gpg I imported the GNU keyring:
$ gpg --import gnu-keyring.gpg

Note that this returned:
.
.
.
gpg: Total number processed: 525
gpg:               imported: 525  (RSA: 187)
gpg: no ultimately trusted keys found

*Finally I verified the tar archive:
gpg --verify emacs-26.1.tar.xz.sig emacs-26.1.tar.xz

This then returned (as stated at the top):
gpg: no valid OpenPGP data found.
gpg: the signature could not be verified.
Please remember that the signature file (.sig or .asc)
should be the first file given on the command line.

So, is the tar archive corrupt or had I not imported the correct keys? If the latter is the case, what are the correct keys for this GNU download?


Q: Null pointer exception to check whether a xml have the element or not My part of code is below see,
NodeList nodes=doc.getElementsByTagName("user");
if(nodes.getLength()==0)
system.exit(1);

Initially, xml dont have user element.
But, I got an null pointer exception.
How to solve this...
And how do I find the no of nodes even if the nodes doesn't exists initially.
It shud return 0 nodes.
Thank you
Also I checked this....
     NodeList nodes=doc.getElementsByTagName("user");
     if(nodes==null)
     system.exit(1);
Then aldo I got null pointer exception.


Q: Optimal solution for non-overlapping maximum scoring sequences While developing part of a simulator I came across the following problem. Consider a string of length N, and M substrings of this string with a non-negative score assigned to each of them. Of particular interest are the sets of substrings that meet the following requirements:

*

*They do not overlap.

*Their total score (by sum, for simplicity) is maximum.

*They span the entire string.

I understand the naive brute-force solution is of O(M*N^2) complexity. While the implementation of this algorithm would probably not impose a lot on the performance of the whole project (nowhere near the critical path, can be precomputed, etc.), it really doesn't sit well with me.
I'd like to know if there are any better solutions to this problem and if so, which are they? Pointers to relevant code are always appreciated, but just algorithm description will do too.

A: This can be thought of as finding the longest path through a DAG. Each position in the string is a node and each substring match is an edge. You can trivially prove through induction that for any node on the optimal path the concatenation of the optimal path from the beginning to that node and from that node to the end is the same as the optimal path. Thanks to that you can just keep track of the optimal paths for each node and make sure you have visited all edges that end in a node before you start to consider paths containing it.
Then you just have the issue to find all edges that start from a node, or all substring that match at a given position. If you already know where the substring matches are, then it's as trivial as building a hash table. If you don't you can still build a hashtable if you use Rabin-Karp.
Note that with this you'll still visit all the edges in the DAG for O(e) complexity. Or in other words, you'll have to consider once each substring match that's possible in a sequence of connected substrings from start to the end. You could get better than this by doing preprocessing the substrings to find ways to rule out some matches. I have my doubts if any general case complexity improvements can come for this and any practical improvements depend heavily on your data distribution.

A: O(N+M) solution:
Set f[1..N]=-1
Set f[0]=0
for a = 0 to N-1
    if f[a] >= 0
        For each substring beginning at a
            Let b be the last index of the substring, and c its score
            If f[a]+c > f[b+1]
                Set f[b+1] = f[a]+c
                Set g[b+1] = [substring number]
Now f[N] contains the answer, or -1 if no set of substrings spans the string.
To get the substrings:
b = N
while b > 0
    Get substring number from g[N]
    Output substring number
    b = b - (length of substring)

A: It is not clear whether M substrings are given as sequences of characters or indeces in the input string, but the problem doesn't change much because of that.
Let us have input string S of length N, and M input strings Tj. Let Lj be the length of Tj, and Pj - score given for string Sj. We say that string
This is called Dynamic Programming, or DP. You keep an array res of ints of length N, where the i-th element represents the score one can get if he has only the substring starting from the i-th element (for example, if input is "abcd", then res[2] will represent the best score you can get of "cd").
Then, you iterate through this array from end to the beginning, and check whether you can start string Sj from the i-th character. If you can, then result of (res[i + Lj] + Pj) is clearly achievable. Iterating over all Sj, res[i] = max(res[i + Lj] + Pj) for all Sj which can be applied to the i-th character.
res[0] will be your final asnwer.

A: inputs:
N, the number of chars in a string
e[0..N-1]: (b,c) an element of set e[a] means [a,b) is a substring with score c.

(If all substrings are possible, then you could just have c(a,b).)
By e.g. [1,2) we mean the substring covering the 2nd letter of the string (half open interval).
(empty substrings are not allowed; if they were, then you could handle them properly only if you allow them to be "taken" at most k times)
Outputs:
s[i] is the score of the best substring covering of [0,i)
a[i]: [a[i],i) is the last substring used to cover [0,i); else NULL

Algorithm - O(N^2) if the intervals e are not sparse; O(N+E) where e is the total number of allowed intervals.  This is effectively finding the best path through an acyclic graph:
for i = 0 to N:
    a[i] <- NULL
    s[i] <- 0
a[0] <- 0
for i = 0 to N-1
    if a[i] != NULL
        for (b,c) in e[i]:
            sib <- s[i]+c
            if sib>s[b]:
                a[b] <- i
                s[b] <- sib

To yield the best covering triples (a,b,c) where cost of [a,b) is c:
i <- N
if (a[i]==NULL):
    error "no covering"
while (a[i]!=0):
    from <- a[i]
    yield (from,i,s[i]-s[from]
    i <- from

Of course, you could store the pair (sib,c) in s[b] and save the subtraction.


Q: SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 99 Current browser version is 105 I am currently new to robot framework. currently using latest version of chrome and ChromeDriver which is 105 but when i try to run the test it gives the message "SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 99" I have tried uninstalling everything and reinstalling it again but nothing works can anyone help me with this. Thank you!
Screenshots below:
enter image description here
SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 99
Current browser version is 105.0.5195.127 with binary path C:\Program Files\Google\Chrome\Application\chrome.exe
enter image description here

A: Chrome driver has a page on how to identify the exact version that you need, but it's a pain, especially if you regularly update chrome, or want to make it part of a build process.
Not sure about robot framework, but chromedriver-autoinstaller sure helped me out when building a pipeline to get a selenium/chrome project going, as it will detect the version of chrome installed and install the correct driver version automatically.


Q: Setting parent window URL from a child window? This is what I am trying to do: Once submit a form on my main JSP/HTML page a new page with some link opens. When I click on any of the link the link should open in the parent Window. I.e the Window I started from. How do i do this?

A: You'll need JavaScript for this. HTML's target can't target the window's parent (opener) window.
The following will open the page in the parent window if JavaScript is enabled, and open it in a new window if it is disabled. Also, it will react gracefully if the current page does not have an opener window.

Click

MDC Docs on window.opener

A: Use parent.location.href if it's on the same page in an iframe. Use opener.location.href if it's another entire tab/window.

A: Use window.opener.location.href in javascript
For example,
Click me!


Q: Deleting a Jtable row from a custom model extending AbstractTableModel I have a JTable that is using a custom model i have designed. This model is extending the AbstractTableModel as shown below. I have a button Delete that I would want when clicked will delete the selected/highlighted row Here is my table model:
public class ProductTableModel extends AbstractTableModel
{

    private final List<String> columnNames;
    private final List<Product> products;

    public ProductTableModel() {
        String[] header = new String[] {
            "Quantity",
            "Description",
            "Unity Price",
            "Total Price"
        };
        this.columnNames = Arrays.asList(header);
        this.products = new ArrayList<>();
    }

    @Override
    public Class<?> getColumnClass(int columnIndex) {
        switch (columnIndex) {
            case 0: return Integer.class;
            case 1: return String.class;
            case 2: return Double.class;
            case 3: return Double.class;
                default: throw new ArrayIndexOutOfBoundsException(columnIndex);
        }
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        Product product = this.getProduct(rowIndex);
        switch (columnIndex) {
           case 0: return product.getProductQuantity();
            case 1: return product.getProductDescription();
            case 2: return product.getProductPrice();
            case 3: return product.getProductTotalAmount();
                default: throw new ArrayIndexOutOfBoundsException(columnIndex);
        }
    }

    @Override
    public boolean isCellEditable(int rowIndex, int columnIndex) {
        return true;
    }

    @Override
    public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
        if (columnIndex < 0 || columnIndex >= getColumnCount()) {
            throw new ArrayIndexOutOfBoundsException(columnIndex);
        } else {
            Product product = this.getProduct(rowIndex);
            switch (columnIndex) {
                case 0: product.setProductQuantity((Integer)aValue); break;
                case 1: product.setProductDescription((String)aValue); break;
                case 2: product.setProductPrice((Double)aValue); break;
                case 3: product.setProductTotalAmount((Double)aValue); break;
            }
            fireTableCellUpdated(rowIndex, columnIndex);
        }
    }

    @Override
    public int getRowCount() {
        return this.products.size();
    }

    @Override
    public int getColumnCount() {
        return this.columnNames.size();
    }

    @Override
    public String getColumnName(int columnIndex) {
        return this.columnNames.get(columnIndex);
    }

    public void setColumnNames(List<String> columnNames) {
        if (columnNames != null) {
            this.columnNames.clear();
            this.columnNames.addAll(columnNames);
            fireTableStructureChanged();
        }
    }

    public List<String> getColumnNames() {
        return Collections.unmodifiableList(this.columnNames);
    }

    public void addProducts(Product product) {
        int rowIndex = this.products.size();
        this.products.add(product);
        fireTableRowsInserted(rowIndex, rowIndex);
    }

    public void addProducts(List<Product> productList) {
        if (!productList.isEmpty()) {
            int firstRow = this.products.size();
            this.products.addAll(productList);
            int lastRow = this.products.size() - 1;
            fireTableRowsInserted(firstRow, lastRow);
        }
    }

    public void addEmptyRow() {
       products.add(new Product());
        this.fireTableRowsInserted(products.size()-1, products.size()-1);
    }

    public void insertProduct(Product product, int rowIndex) {
        this.products.add(rowIndex, product);
        fireTableRowsInserted(rowIndex, rowIndex);
    }

    public void deleteProduct(int rowIndex) {
        if (this.products.remove(this.products.get(rowIndex))) {
            fireTableRowsDeleted(rowIndex, rowIndex);
        }
    }

    public Product getProduct(int rowIndex) {
        return this.products.get(rowIndex);
    }

    public List<Product> getProducts() {
        return Collections.unmodifiableList(this.products);
    }

    public void clearTableModelData() {
        if (!this.products.isEmpty()) {
            int lastRow = products.size() - 1;
            this.products.clear();
            fireTableRowsDeleted(0, lastRow);
        }
    }
}

Here is a method for deleting a product from the model:
public void deleteProduct(int rowIndex) {
    if (this.products.remove(this.products.get(rowIndex))) {
        fireTableRowsDeleted(rowIndex, rowIndex);
    }
}

Here is the code that would be executed when the delete but is clicked:
delete.addActionListener((ActionEvent e) -> {
    if (e.getSource().equals(delete)) {
        int modelRowIndex = table.convertRowIndexToModel(table.getSelectedRow());
        ProductTableModel model=(ProductTableModel)table.getModel();
        model.deleteProduct(modelRowIndex);
    }
}

When I run this program it is showing the table as it is supposed to be. I add some rows in the table at run time using the addEmptyRow()in my ProductTableModel. When I highlight/select one row in the table and click the delete button, its showing me the following error:
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: -1
at java.util.ArrayList.elementData(ArrayList.java:418)
at java.util.ArrayList.get(ArrayList.java:431)
at quotationTable.ProductTableModel.deleteProduct(ProductTableModel.java:119)
at quotationTable.Table$InteractiveTableModelListener.lambda$tableChanged$0(Table.java:152)
at quotationTable.Table$InteractiveTableModelListener$$Lambda$25/930643647.actionPerformed(Unknown Source)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2346)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6525)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
at java.awt.Component.processEvent(Component.java:6290)
at java.awt.Container.processEvent(Container.java:2234)
at java.awt.Component.dispatchEventImpl(Component.java:4881)
at java.awt.Container.dispatchEventImpl(Container.java:2292)
at java.awt.Component.dispatchEvent(Component.java:4703)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4898)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4533)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4462)
at java.awt.Container.dispatchEventImpl(Container.java:2278)
at java.awt.Window.dispatchEventImpl(Window.java:2739)
at java.awt.Component.dispatchEvent(Component.java:4703)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:746)
at java.awt.EventQueue.access$400(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:697)
at java.awt.EventQueue$3.run(EventQueue.java:691)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:86)
at java.awt.EventQueue$4.run(EventQueue.java:719)
at java.awt.EventQueue$4.run(EventQueue.java:717)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:716)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

Sorry for the big stack trace but one man advised me to put it in full.When I print the table.getSelectedRow()and table.convertRowIndexToModel(table.getSelectedRow()); they are giving me -1.
How do we solve this and what could be the possible reasons?

A: probably in this line of code
this.products.remove(this.products.get(rowIndex)

rowIndex return null or zero value because check and debug this line my friend

A: The code I posted if fine and it works. The problem was due to a shadow reference -that is I was having two instances of my table.This answers why I was getting -1 when calling getSelectedRow()-the possible reason to my question why I was having this value yet I was adding rows to my table.In simple terms - I was adding rows to myTable1OnTheScreenand calling deleteSelectedRow()on myTable2ThatHasNoRowsAddedToIt hence, getSelectedRow()would return -1 because it was refering to myTable2ThatHasNoRowsAddedToIt.


Q: Finding out zero frequency values from a column with inner join I have two tables named courses and teachers. I need to find the list of teachers who don't take any courses.

This is the query I wrote for getting the teacher who took the most numbered courses -
SELECT t.name AS teacher_name
     , COUNT(c.teacher_id) AS courses_taken
  FROM courses c
  JOIN teachers t
    ON c.teacher_id = t.id
 GROUP
    BY c.teacher_id
 ORDER
    BY courses_taken DESC
 LIMIT 1;

By reversing this query I am getting the teacher's list who take minimum numbers of courses which is 1 but I need to find the list of teacher who don't take any courses.

A: Left Join and Where condition can help you.
SELECT *
  FROM teachers t
  LEFT
  JOIN  courses c
    ON t.id = c.teacher_id
 WHERE c.teacher_id IS  NULL

A: Teachers don't usually "take" courses.  They "teach" courses.  Students "take" courses.
That said, not exists seems appropriate:
SELECT t.*
FROM teachers t
WHERE NOT EXISTS (SELECT 1
                  FROM courses c
                  WHERE c.teacher_id = t.id
                 );

If you think about this, it is almost a direct translation of your question:  Get teachers where there is no course that the teacher teachers.


Q: Google api 3 returning nothing when WEB APi is published I have made a simple ASP.NET Web API that gets events from a shared google calendar, and serves them to me in json. When i fire it up from localhost i get 104 events returned:  but when I've published it to my IIS server, the array contains no elements. I can't debug on it, but i get an empty array presented:
I have made an app on https://console.developers.google.com/ and added both localhost and http://domainname.dk/oauthcallback to it.
My code:
public void GetFixedEvents()
        {
            const string calendarId = "xxxxxxxxxxxxxxxx@group.calendar.google.com";

            try
            {
                var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    new ClientSecrets
                    {
                        ClientId = clientId,
                        ClientSecret = clientSecret,

                    },
                    new[] { CalendarService.Scope.Calendar },
                    "user",
                    CancellationToken.None).Result;
                var service = new CalendarService(new BaseClientService.Initializer
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "CalendarTest",
                });
                var queryStart = DateTime.Now;
                var queryEnd = queryStart.AddYears(1);

                var query = service.Events.List(calendarId);
                query.TimeMin = queryStart;
                query.TimeMax = queryEnd;
                query.SingleEvents = true;

                var events = query.Execute().Items;

                foreach (var item in events)
                {
                    var tempEvent = new PubEvent
                    {
                        Title = item.Summary,
                        Description = item.Description ?? "None",
                        Start = item.Start.DateTime,
                        End = item.End.DateTime,
                        EventType = item.Summary.Contains("Ladies") ? EventType.LadiesNight : EventType.StudentNight
                    };
                    _pubEvents.Add(tempEvent);
                }

            }
            catch (Exception e)
            {
                Console.WriteLine("Exception encountered: {0}", e.Message);
            }
        }

Can anyone help? Is it a problem with redirect uri? I have tried adding all the ones I can possibly think of. Is there any way to log the call to the google api?


Q: Stripping value in PS and comparing if it is an integer value I am running PS cmdlet get-customcmdlet which is generating following output
Name                         FreeSpaceGB
----                         -----------
ABC-vol001                   1,474.201

I have another variable $var=vol
Now, I want to strip out just 001 and want to check if it is an integer.
I am using but getting null value
$vdetails = get-customcmdlet | split($var)[1]
$vnum = $vdetails -replace '.*?(\d+)$','$1'

My result should be integer 001

A: Assumption: get-customcmdlet is returning a pscustomobject object with a property Name that is of type string.
$var = 'vol'
$null -ne ((get-customcmdlet).Name -split $var)[1] -as [int]

This expression will return $true or $false based on whether the cast is successful.

If your goal is to pad zeroes, you need to do that after-the-fact (in this case, I just captured the original string):
$var = 'vol'
$out = ((get-customcmdlet).Name -split $var)[1]
if ($null -ne $out -as [int])
{
    $out
}
else
{
    throw 'Failed to find appended numbers!'
}


Q: Word VBA Tabstop wrong behaviour I have the following VBA code
Private Sub CreateQuery_Click()

  Dim doc As Document
  Dim i As Integer

  Set doc = ActiveDocument
  i = doc.Paragraphs.Count

  doc.Paragraphs(i).Range.InsertParagraphAfter
  i = i + 1

  For j = 0 To 1000
      doc.Paragraphs(i).Range.InsertParagraphAfter
      i = i + 1
      doc.Paragraphs(i).Range.InsertParagraphAfter
      i = i + 1
      With doc.Paragraphs(i)
          .Range.Font.Italic = True
          .Range.ListFormat.ApplyBulletDefault
          .Indent
          .Indent
          .TabStops.Add Position:=CentimetersToPoints(3.14)
          .TabStops.Add Position:=CentimetersToPoints(10)
          .TabStops.Add Position:=CentimetersToPoints(11)
      End With
      For k = 0 To 10
          With doc.Paragraphs(i)
              .Range.InsertAfter "testState" & vbTab & CStr(doc.Paragraphs(i).Range.ListFormat.CountNumberedItems) & vbTab & CStr(doc.Paragraphs.Count)
              .Range.InsertParagraphAfter
          End With
          i = i + 1
      Next
      i = doc.Paragraphs.Count
      With doc.Paragraphs(i)
          .Range.ListFormat.ApplyBulletDefault
          .TabStops.ClearAll
          .Outdent
          .Outdent
      End With
  Next

  i = doc.Paragraphs.Count

  doc.Paragraphs(i).Range.InsertParagraphAfter
  i = i + 1

End Sub

Basically this code just prints n numbers of lines with the specific format.

*

*Bullet list

*Indented

*and TabStops

(source: lans-msp.de)
The Code works perfectly for an arbitrary number of lines, but then at some point Word just stops applying the TabStops.
I know that if I wouldn't reset the format every 10 lines, the code would work seemingly forever (really?!?). But the every 10 line brake is a must.
The exact line number where everything breaks down is dependent on the amount of RAM. On my work computer with 1GB it only works until about line 800(as you can see). My computer at home with 4GB didn't show this behaviour. But I'm sure it would have shown it as well if I had it let run long enough, because in my production code(which is a bit more complex) my home computer shows the problem as well.
Is this some kind of memory leak or something? What did I do wrong? Is maybe, god-forbid, VBA itself the culprit here?

A: Try to apply the formatting using a defined style. See if that makes a difference.

A: You might try turning automatic pagination off while adding the lines, to see if that helps.
Application.Options.Pagination = False


Q: IntelliJ IDEA: Move line? I really like IntelliJ IDEA's "Move statement" shortcut (Ctrl + Shift + ↑/↓). However -- I am not sure if this is a bug releated to ActionScript editing only -- move statement is not always what I want and sometimes it is not correct when editing AS code.
So I just want to move a block of lines up/down. The Eclipse shortcut is Alt + ↑/↓ and does not move statement-wise. Is there an equivalent in IntelliJ IDEA?

A: As other people have said this is already available as a command.  You can configure the short cut to your liking, but by default (at least in IntelliJ 10) it is bound to ALT + SHIFT + ↑ and ALT + SHIFT + ↓

A: shift + alt + ↑/↓
you can find All short cuts  HERE
https://resources.jetbrains.com/storage/products/intellij-idea/docs/IntelliJIDEA_ReferenceCard.pdf

A: Please find some useful shortcut for IntelliJ:

(1) IntelliJ Debugger
Step over (Go To next Step or line) :  F8
Step into (Go into function) :  F7
Smart step into :  Shift + F7
Step out :  Shift + F8
Run to cursor : Alt + F9
Evaluate expression : Alt + F8
Resume program : F9 [Mac = Cmd + ALT + R]
Toggle breakpoint : Ctrl + F8 [Mac = Cmd + F8]
View breakpoints : Ctrl + Shift + F8 [Mac = Cmd + Shift + F8]

(2) Open Specific File
Ctrl + Shift + N

(3) Open All Methods Implemented in class
Open specific class and press,
Ctrl + F12

(4) Go to Specific Line Number
Ctrl + G

(5) Method Implementation and Declaration
Declaration : Ctrl + B
Implementation : Ctrl + Alt + B
Response Type Declaration : Ctrl + Shift + B
Super class override Method : Ctrl + U

(6) Reformate Code
Ctrl + Alt + L

(7) Import relevant class
Click on relevant class (Red color field) and press,
Alt + Enter
Select valid class as per requirement

(8) Hierarchy of method calls
Select specific method and press,
Ctrl + Alt + H

(9) Comment In Code
Single Line : Select specific line and press,
Ctrl + /
Multiple Line : Select Multiple Line and Press,
Ctrl + Shift + /
(Note : Same operation for uncomment the code)

(10) Display Line Number
Hit Shift twice > write "line" > Show Line Numbers (the line doesn't have the toggle)
View > Active Editor > Show Line Number

(11) Code Selection
Full class selection : Ctrl + A
Method Selection : Select Method Name and press, Ctrl + W

(12) Basic Code Completion
To complete methods, keywords etc press,
Ctrl + Space

(13) Code Copy and Paste
Copy : Ctrl + C
Paste : Ctrl + V

(14) Search Operation
Specific File : Ctrl + F
Full Project : Ctrl + Shift + F

(15) Switcher Popup
Open Switcher Popup : Ctrl + Tab
Continue press Ctrl and use ↑/↓/←/→ for move one place to another

(16) Forward Move & Backward Move
Backward : Ctrl + Alt + ← (Left-Arrow)
Forward : Ctrl + Alt + → (Right-Arrow)

(17) Next/previous highlighted error
F2 or (Shift + F2)

(18) Open Java Doc
Select specific method name and press,
Ctrl + Q

(19) Find All commands
Ctrl + Shift + A

(20) Move Line Up/Down
shift + alt + ↑/↓
Thanks...

A: The LineMover plug-in works very well and is an acceptable solution.

A: Open Settings -> Keymap then search for "move line" via the upper right searchbox.
Under the Code folder you'll see:

*

*Move Statement Down

*Move Statement Up

*Move Line Down

*Move Line Up
The actions you're looking for are (as you may guess) the move line actions.

A: try command+shift+up/down this will auto adjust the indentation

A: You can move several lines together with move statement.  Are you trying to move partial lines?  I don't think there's a way in Idea.


Q: Defining the BinarySearch for a user defined class in Java I have defined a class for storing the GPS data in Java as follows :
class data implements Comparable
{
        float lati;
        float longi;
        int time; // Time in seconds
        public int compareTo(Object obj)
        {
                data t = (data)obj;
                if(this.time == t.time)
                        return 0;
                if(this.time< t.time)
                        return -1;
                else
                        return 1;
        }
}

I have stored all the data in an ArrayList which I have sorted using the Collections.sort(d1) .(here d1 ArrayList of data type objects). But I am facing the problem is how can I use the Collections.binarySearch on this ArrayList to find the index of a specific element. When I try using it, I get the error message that binarySearch can'b be used with this data type. Can someone please help.

A: Comparable needs a parameter. Try with the following class:
class Data implements Comparable<Data> {

    float lati;
    float longi;
    Integer time;

    @Override
    public int compareTo(Data o) {
        // Integer already implements Comparable
        return time.compareTo(o.time);
    }

}

A: Here is one example on how to do it.
import java.util.*;

class Data implements Comparable<Data>
{
    float lati;
    float longi;
    int time; // Time in seconds

    public Data(int time) { this.time = time; }

    public int compareTo(Data obj)
    {
            if(this.time == obj.time)
                    return 0;
            if(this.time< obj.time)
                    return -1;
            else
                    return 1;
    }

    public static void main(String[] args) {
        ArrayList<Data> dataArray = new ArrayList<>();
        dataArray.add(new Data(3));
        dataArray.add(new Data(1));
        dataArray.add(new Data(2));

        Collections.sort(dataArray);
        System.out.println(Collections.binarySearch(dataArray,new Data(1)));
        System.out.println(Collections.binarySearch(dataArray,new Data(3)));
        System.out.println(Collections.binarySearch(dataArray,new Data(2)));
    }
}


Q: SOAPBinding.ParameterStyle.BARE vs SOAPBinding.ParameterStyle.WRAPPED : generated less parameters on request I use SOAPUI and generate java classes with JAX-WS import.
I have an interface like this
@WebService(name = "test", targetNamespace = "http://lang.java")
@SOAPBinding(parameterStyle = SOAPBinding.ParameterStyle.WRAPPED)
@XmlSeeAlso({
    ObjectFactory.class
})
public interface Test{

@WebMethod(action = "https://...action")
@WebResult(name = "getBean", targetNamespace = "http://...getBean", partName = "getBean")
public Bean test(
@WebParam(name = "parameter1", targetNamespace = "http://lang.java", partName = "parameter1")
String parameter1,
@WebParam(name = "parameter2", targetNamespace = "http://lang.java", partName = "parameter2")
String parameter2,
@WebParam(name = "parameter3", targetNamespace = "http://lang.java", partName = "parameter3")
String parameter3,
@WebParam(name = "parameter4", targetNamespace = "http://lang.java", partName = "parameter4")
long parameter4);
}

If I use SOAPBinding.ParameterStyle.WRAPPED the body message generated is
<S:Body>
<ns2:test xmlns:ns2="http://lang.java" xmlns:ns3="http://...getBean">
<ns2:parameter1>1</ns2:parameter1>
<ns2:parameter2>2</ns2:parameter2>
<ns2:parameter3>a</ns2:parameter3>
<ns2:parameter4>1</ns2:parameter4>
</ns2:test>
</S:Body>

If I use SOAPBinding.ParameterStyle.BARE the body message generated is
<S:Body>
<ns2:parameter1 xmlns:ns2="http://lang.java" xmlns:ns3="http://...getBean">1</ns2:parameter1>
</S:Body>

Why is the diference? Why in Bare option it only generates the first parameter? I need that Bare option create all parameters

A: Its ok! I find the answer here http://www.javajee.com/soap-binding-style-encoding-and-wrapping
Bare option only can use one parameter. When we use Bare, the message request must have zero or one element into Body. The solution is make an object with all parameters we want , and send this object to the method.


Q: Production Build Has Error: Uncaught ReferenceError: define is not defined I am basically just trying to serve a new ember created project on my production server. After running,
ember build --env production

And taking the files from dist/assets/ and putting on a page on my server that includes them I get the error.
Uncaught ReferenceError: define is not defined

My app is serving basically a blank HTML file with these assets included. The url I am trying to serve from is MyURL/admin.


Q: nativescript carousel by javascript I want to create a horizontal scroll-view with stack-layout similar to 'olx' app. But the problem i am facing is to achieve endless scroll or carousel like scroll.
in the below link, carousel template was already implemented but it was too complicated to understand.
https://play.nativescript.org/?template=play-js&id=sRSad7&v=6
how to build and achieve endless horizontal scroll of the icons in stack-layout like in 'OLX' app. I am not expecting someone to code but just a flowchart of doing things would be very helpful.


Q: How to extract search keywords from Google search result page URL by Swift? How do you extract search keywords from Google search result page URL by Swift?
I was simply trying to get stings after "&q=" but I found out I needed to consider more complicated cases such as "https://www.google.co.jp/search?hl=ja&q=test#q=speedtest+%E4%BE%A1%E6%A0%BC&hl=ja&prmd=nsiv&tbs=qdr:d"
I would appreciate your advice.
Update:
As per advised by LEO, I put this way.
if let url = NSURL(string: urlStr){

        var extractedQuery = ""
        if let fragment = url.fragment {
            extractedQuery = fragment
        } else if let query = url.query{
            extractedQuery = query
        }

        if let queryRange = extractedQuery.rangeOfString("&q="){
            let queryStartIndex = queryRange.endIndex
            let queryKeyword = extractedQuery.substringFromIndex(queryStartIndex)
            print(queryKeyword)
        }
    }

A: You can convert your string to NSURL and access its query and fragment properties:
if let url = NSURL(string: "https://www.google.co.jp/search?hl=ja&q=test#q=speedtest+%E4%BE%A1%E6%A0%BC&hl=ja&prmd=nsiv&tbs=qdr:d"), query = url.query, fragment = url.fragment {
    print(query)    // "hl=ja&q=test\n"
    print(fragment) // "q=speedtest+%E4%BE%A1%E6%A0%BC&hl=ja&prmd=nsiv&tbs=qdr:d\n"
}


Q: Why is the string 'andy' not printing please enter a new username? current_users = ['Andy', 'Brett', 'Cassie', 'Derek', 'Eric']
new_users = ['eric', 'greg', 'hank', 'ian', 'john', 'andy', 'frank']
new_users.sort()

for current_user in current_users:
    current_user = current_user.lower()

for new_user in new_users:
    if new_user == current_user:
        print(f"\n{new_user}, Please enter a new username!")
    else:
        print(f"\n{new_user}, Username is available.")

Andy is being printed as username is available.
Also please help me simplify as I am just learning python.

A: You can use list comprehension to convert the usernames in current_users to lowercase. Secondly, you've to check whether the new_user is already present in current_users to do that you have to use in keyword.
The in keyword

tests whether or not a sequence contains a certain value.

here is code,
current_users = ['Andy', 'Brett', 'Cassie', 'Derek', 'Eric']
new_users = ['eric', 'greg', 'hank', 'ian', 'john', 'andy', 'frank']
new_users.sort()

current_users = [user.lower() for user in current_users]

for new_user in new_users:
    if new_user in current_users:
        print(f"\n{new_user}, Please enter a new username!")
    else:
        print(f"\n{new_user}, Username is available.")

Hope it helps!

A: You should try using in to the list:
current_users = ['Andy', 'Brett', 'Cassie', 'Derek', 'Eric']
new_users = ['eric', 'greg', 'hank', 'ian', 'john', 'andy', 'frank']
new_users.sort()

current_users = [i.lower() for i in current_users]

for new_user in new_users:
    if new_user in current_users:
        print(f"\n{new_user}, Please enter a new username!")
    else:
        print(f"\n{new_user}, Username is available.")

A: a single equal mark is used to assign a value to a variable, whereas two consecutive equal marks is used to check whether 2 expressions give the same value .
= is an assignment operator
== is an equality operator
current_users = ['Andy', 'Brett', 'Cassie', 'Derek', 'Eric']
new_users = ['eric', 'greg', 'hank', 'ian', 'john', 'andy', 'frank']
new_users.sort()

for current_user in current_users:
    current_user == current_user.lower()

for new_user in new_users:
    if new_user == current_user:
        print(f"\n{new_user}, Please enter a new username!")
    else:
        print(f"\n{new_user}, Username is available.")


Q: Using Thevenin's theorem, how do you find the Thevenin voltage?
The above image shows a circuit.  It is required that we simplify the circuit using Thevenin's theorem to find the Thevenin voltage, current and resistance.
I've done a countless number of problems but only succeed in finding the Thevenin resistance. Having difficulties with finding voltage, in turn, unable to find the Thevenin current.

A:
I've done a countless number of problems but only succeed in finding the Thevenin resistance. Having difficulties with finding voltage, in turn, unable to find the Thevenin current.

The I-V characteristic of a linear 1-port network is a straight line. The Thevenin voltage is where this line crosses the x-axis (the voltage with a 0 A load). The Thevenin resistance is the slope of the line (\$\frac{dV}{dI}\$).
You can use any method you like to find the equation of this straight line. Normally, you will find two points on the line by considering what will be the output of the circuit with two different test loads. For some circuits it might be useful to consider loading the network with a voltage source, for some with a current source, for some with a resistor or two different resistors. It's up to you. Now use the two points you found to get the equation of the line.
There is no "Thevenin current" so there's no point trying to find it. It might be useful to try to find the Norton equivalent source current. That's just the place where the I-V curve crosses the y-axis (the current with a 0 V load).

A: I'll save myself a little time and avoid re-writing your schematic. You have labeled the parts and just need to label the nodes. The bottom node I'll consider "ground" or \$0\:\text{V}\$, labeled on your schematic as B(-). I'll number the remaining nodes from left to right, as \$V_1\$, \$V_2\$, and \$V_3\$ (which is also labeled on your schematic as A(+).)
Four equations in four unknowns (to read how I do nodal, see this section called nodal, done my way):
$$\begin{align*}
\frac{V_1}{R_1}+\frac{V_1}{R_2}&=I_{V_1}+\frac{V_2}{R_1}+\frac{0\:\text{V}}{R_2}\\\\
\frac{V_2}{R_1}+\frac{V_2}{R_3}&=9\:\text{A}+\frac{V_1}{R_1}+\frac{V_3}{R_3}\\\\
\frac{V_3}{R_3}+\frac{V_3}{R_4}+I_{V_1}&=\frac{V_2}{R_3}+\frac{0\:\text{V}}{R_4}\\\\
V_1&=9\:\text{V}+V_3
\end{align*}$$
This solves out as \$V_3=0\:\text{V}\$. So this means that \$V_\text{TH}=0\:\text{V}\$. (The other values are \$V_1=9\:\text{V}\$, \$V_2=63\:\text{V}\$, and \$I_{V_1}=4.5\:\text{A}\$.)
If you don't have it already installed, I recommend getting sympy and sage. They are free and work well. For example, here's the above solved using sympy:
var('v1 v2 v3 r1 r2 r3 r4 iv1')
eq1=Eq( v1/r2+v1/r1, iv1+v2/r1+0/r2 )
eq2=Eq( v2/r1+v2/r3, 9+v1/r1+v3/r3 )
eq3=Eq( v3/r3+v3/r4+iv1, v2/r3+0/r4 )
eq4=Eq( v1, 9+v3 )
ans=solve( [eq1,eq2,eq3,eq4], [v1,v2,v3,iv1] )
ans[v3].subs({ r1:12, r2:1, r3:14, r4:36 })
0

I recommend sympy as it makes this all a piece of cake and its free to use.
Next, inject \$1\:\text{A}\$ by adding a current source straight into node \$V_3\$ (or A(+) if you like) in order to inject that current and see what happens to that node voltage.
The four equations in four unknowns now is:
$$\begin{align*}
\frac{V_1}{R_1}+\frac{V_1}{R_2}&=I_{V_1}+\frac{V_2}{R_1}+\frac{0\:\text{V}}{R_2}\\\\
\frac{V_2}{R_1}+\frac{V_2}{R_3}&=9\:\text{A}+\frac{V_1}{R_1}+\frac{V_3}{R_3}\\\\
\frac{V_3}{R_3}+\frac{V_3}{R_4}+I_{V_1}&=1\:\text{A}+\frac{V_2}{R_3}+\frac{0\:\text{V}}{R_4}\\\\
V_1&=9\:\text{V}+V_3
\end{align*}$$
Note that all I did was add \$1\:\text{A}\$ on the right side of the \$3^\text{rd}\$ equation. This now solves out as \$V_3=\frac{36}{37}\:\text{V}\$. From this, you can infer that \$R_\text{TH}=\frac{36}{37}\:\Omega\$.
Here's sympy, again:
var('v1 v2 v3 r1 r2 r3 r4 iv1')
eq1=Eq( v1/r2+v1/r1, iv1+v2/r1+0/r2 )
eq2=Eq( v2/r1+v2/r3, 9+v1/r1+v3/r3 )
eq3=Eq( v3/r3+v3/r4+iv1, 1+v2/r3+0/r4 )
eq4=Eq( v1, 9+v3 )
ans=solve( [eq1,eq2,eq3,eq4], [v1,v2,v3,iv1] )
ans[v3].subs({ r1:12, r2:1, r3:14, r4:36 })
36/37

There are many other methods you can apply. But this is pretty bullet-proof and I can write out nodal equations all day long almost as fast as I can type. So that's the method of my choice, anyway.

A: The Thevenin voltage is equal to the open circuit voltage of the terminals in question.
If you apply superposition to your circuit, you will find the solution for \$V_{a,b}\$ to be fairly trivial.


Q: How to get the list of duplicated values in a range I tried recording the macros but it's using copying and pasting, but I prefer the codes to be dynamic as the range of my data changes weekly.
I have 2 columns, A & D. Column A is a pivot table, so I think, maybe that's why VBA codes for moving down rows don't work. (error for trying to move pivot table). I want Column D to be a list of unique duplicates that are from column A and condense it so no gaps.
So far I can extract the unique duplicates and condense them but the results are pasted it from D1 instead of D8. So I need help to bring down the values 8 rows. Now I don't want to copy and paste the pivot table as values or trying to get rid of it since I need the pivot table there as I can just refresh it every week for new list.
Any suggestion or advice is appreciated.
    Sub dp()

    AR = Cells(Rows.Count, "A").End(xlUp).Row

    For Each p1 In Range(Cells(8, 1), Cells(AR, 1))
        For Each p2 In Range(Cells(8, 1), Cells(AR, 1))
            If p1 = p2 And Not p1.Row = p2.Row Then
                Cells(p1.Row, 4) = Cells(p1.Row, 1)
                Cells(p2.Row, 4) = Cells(p2.Row, 1)
            End If
        Next p2
    Next p1
    Columns(4).RemoveDuplicates Columns:=Array(1)
        Dim lastrow As Long
        Dim i As Long
        lastrow = Range("D:D").End(xlDown).Row

        For i = lastrow To 1 Step -1

        If IsEmpty(Cells(i, "D").Value2) Then

            Cells(i, "D").Delete shift:=xlShiftUp
        End If
    Next i
End Sub

A: Here is a different approach
Sub dp()

Dim AR As Long, p1 As Range, n As Long

AR = Cells(Rows.Count, "A").End(xlUp).Row
n = 8
With Range(Cells(8, 1), Cells(AR, 1))
    For Each p1 In .Cells
        If WorksheetFunction.CountIf(.Cells, p1) > 1 Then
            If WorksheetFunction.CountIf(Columns(4), p1) = 0 Then
                Cells(n, "D") = p1
                n = n + 1
            End If
        End If
    Next p1
End With

End Sub

A: Here are three different techniques:

*

*ArraysList

*ADODB.Recordset

*Array and CountIf

ArraysList
Sub ListDuplicates()
    Dim v, listValues, listDups
    Set listValues = CreateObject("System.Collections.ArrayList")
    Set listDups = CreateObject("System.Collections.ArrayList")

    For Each v In Range("A8", Cells(Rows.Count, "A").End(xlUp)).Value
        If listValues.Contains(v) And Not listDups.Contains(v) Then listDups.Add v
        listValues.Add v
    Next

    Range("D8").Resize(listDups.Count).Value = Application.Transpose(listDups.ToArray)
End Sub

ADODB.Recordset
Sub QueryDuplicates()
    Dim rs As Object, s As String
    Set rs = CreateObject("ADODB.Recordset")
    s = ActiveSheet.Name & "$" & Range("A7", Cells(Rows.Count, "A").End(xlUp)).Address(False, False)
    rs.Open "SELECT [Pivot Table] FROM [" & s & "] GROUP BY [Pivot Table] HAVING COUNT([Pivot Table]) > 1", _
            "Provider=MSDASQL;DSN=Excel Files;DBQ=" & ThisWorkbook.FullName

    If Not rs.EOF Then Range("D8").CopyFromRecordset rs
    rs.Close
    Set rs = Nothing
End Sub

Array and CountIf (similar to SJR answer but using an array to gather the data)
Sub ListDuplicatesArray()
    Dim v, vDups
    Dim x As Long, y As Long
    ReDim vDups(x)
    With Range("A8", Cells(Rows.Count, "A").End(xlUp))

        For Each v In .Value
            If WorksheetFunction.CountIf(.Cells, v) > 1 Then
                For y = 0 To UBound(vDups)
                    If vDups(y) = v Then Exit For
                Next
                If y = UBound(vDups) + 1 Then
                    ReDim Preserve vDups(x)
                    vDups(x) = v
                    x = x + 1
                End If

            End If
        Next
    End With

    Range("D8").Resize(UBound(vDups) + 1).Value = Application.Transpose(vDups)
End Sub

A: here's another approach:
Option Explicit

Sub main()
    Dim vals As Variant, val As Variant
    Dim strng As String

    With Range(Cells(8, 1), Cells(Rows.count, 1).End(xlUp))
        vals = Application.Transpose(.Value)
        strng = "|" & Join(vals, "|") & "|"
        With .Offset(, 3)
            .Value = Application.Transpose(vals)
            .RemoveDuplicates Columns:=1, Header:=xlNo
            For Each val In .SpecialCells(xlCellTypeConstants)
                strng = Replace(strng, val, "", , 1)
            Next val
            vals = Split(WorksheetFunction.Trim(Replace(strng, "|", " ")), " ")
            With .Resize(UBound(vals) + 1)
                .Value = Application.Transpose(vals)
                .RemoveDuplicates Columns:=1, Header:=xlNo
            End With
        End With
    End With
End Sub

A: another one approach here
Sub dp2()
    Dim n&, c As Range, rng As Range, Dic As Object
    Set Dic = CreateObject("Scripting.Dictionary")
    Dic.comparemode = vbTextCompare
    Set rng = Range("A8:A" & Cells(Rows.Count, "A").End(xlUp).Row)
    n = 8
    For Each c In rng
        If Dic.exists(c.Value2) And Dic(c.Value2) = 0 Then
            Dic(c.Value2) = 1
            Cells(n, "D").Value2 = c.Value2
            n = n + 1
        ElseIf Not Dic.exists(c.Value2) Then
            Dic.Add c.Value2, 0
        End If
    Next c
End Sub

but if you prefer your own variant, then you need to:
1) replace this line of code: Columns(4).RemoveDuplicates Columns:=Array(1)
by this one:
Range("D8:D" & Cells(Rows.Count, "D").End(xlUp).Row).RemoveDuplicates Columns:=1
2) another problem is in this line of code:
lastrow = Range("D:D").End(xlDown).Row
it will return the row #8 instead of last row that you've expected, so you need to replace it by this one: lastrow = Cells(Rows.Count, "D").End(xlUp).Row
3) also, replace to 1 step -1 by to 8 step -1
so, finally your code can looks like this:
Sub dp()
    Dim AR As Long, p1 As Range, p2 As Range, lastrow&, i&
    AR = Cells(Rows.Count, "A").End(xlUp).Row
    For Each p1 In Range(Cells(8, 1), Cells(AR, 1))
        For Each p2 In Range(Cells(8, 1), Cells(AR, 1))
            If p1 = p2 And Not p1.Row = p2.Row Then
                Cells(p1.Row, 4) = Cells(p1.Row, 1)
                Cells(p2.Row, 4) = Cells(p2.Row, 1)
            End If
    Next p2, p1
    Range("D8:D" & Cells(Rows.Count, "D").End(xlUp).Row).RemoveDuplicates Columns:=1
    lastrow = Cells(Rows.Count, "D").End(xlUp).Row
    For i = lastrow To 8 Step -1
        If IsEmpty(Cells(i, "D").Value2) Then
            Cells(i, "D").Delete shift:=xlShiftUp
        End If
    Next i
End Sub


Q: Extracting text after "?" I have a string
x <- "Name of the Student? Michael Sneider"

I want to extract "Michael Sneider" out of it.
I have used:
str_extract_all(x,"[a-z]+")
str_extract_all(data,"\\?[a-z]+")

But can't extract the name.

A: I think this should help
substr(x, str_locate(x, "?")+1, nchar(x))

A: Try this:
sub('.*\\?(.*)','\\1',x)

A: x <- "Name of the Student? Michael Sneider"

sub(pattern = ".+?\\?" , x , replacement = '' )

A: To take advantage of the loose wording of the question, we can go WAY overboard and use natural language processing to extract all names from the string:
library(openNLP)
library(NLP)
# you'll also have to install the models with the next line, if you haven't already
# install.packages('openNLPmodels.en', repos = 'http://datacube.wu.ac.at/', type = 'source')

s <- as.String(x)    # convert x to NLP package's String object

# make annotators
sent_token_annotator <- Maxent_Sent_Token_Annotator()
word_token_annotator <- Maxent_Word_Token_Annotator()
entity_annotator <- Maxent_Entity_Annotator()

# call sentence and word annotators
s_annotated <- annotate(s, list(sent_token_annotator, word_token_annotator))
# call entity annotator (which defaults to "person") and subset the string
s[entity_annotator(s, s_annotated)]
## Michael Sneider

Overkill? Probably. But interesting, and not actually all that hard to implement, really.

A: str_match is more helpful in this situation
str_match(x, ".*\\?\\s(.*)")[, 2]
#[1] "Michael Sneider"