text:
Q: How to store previous selection in drop down menu in this case in html/php I have drop down on change I have set a confirmation, clicking OK the form is submitted this part is working fine but on clicking cancel the selection still changes in drop down how do I prevent that.
How do I store my previous selection and set that when I click cancel to drop down?
<td style="width:auto;text-align:center">
<select class="form-control" name="Ostatus" onchange="if(confirm('Are you sure you want change the status?')){this.form.submit()}">
<option value="Uploaded" <?php if ($dispatchstatus == "Uploaded") echo "selected='selected'";?> >Uploaded</option>
<option value="Processing" <?php if ($dispatchstatus == "Processing") echo "selected='selected'";?> >Processing</option>
<option value="Dispatched" <?php if ($dispatchstatus == "Dispatched") echo "selected='selected'";?> >Dispatched</option>
</select>
</td>

A: If you want to retain the value/the selected option of the after resetting the form you just need to add click event to the reset button and store the selected option before resetting.

document.getElementById("resetbtn").addEventListener("click", function(event){
  event.preventDefault()
  var select = document.getElementById("selection");
  var option = select.options[select.selectedIndex].text;
  document.getElementById("mainform").reset();
  select.value = option;
});
<form id="mainform">
  <select id="selection">
    <option value="1">1</option>
        <option value="2">2</option>
            <option value="3">3</option>
  </select>
  <input type="test">
  <button type="reset" value="Reset" id="resetbtn">Reset</button>
</form>


text:
Q: trying to add agency bootstrap template to Laravel 5.4 I am trying to add the agency Bootstrap theme to a laravel 5.4 project.  The urle for the them is Agency Bootstrap Theme
Now the first problem I am having is having the Navbar overlay the picture. Like this.
What I am getting is this
This is the code I have for the page.
<!DOCTYPE html>

     <meta charset="utf-8">
     <meta http-equiv="X-UA-Compatible" content="IE=edge">
     <meta name="viewport" content="width=device-width, initial-scale=1">
     <meta name="description" content="">
     <meta name="author" content="">
       <title>Agency - Start Bootstrap Theme</title>

       <link href="css/bootstrap.min.css" rel="stylesheet">

      <link href="css/agency.css" rel="stylesheet">

      <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet"  type="text/css">
      <link href="https://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">
      <link href='https://fonts.googleapis.com/css?family=Kaushan+Script' rel='stylesheet' type='text/css'>
      <link href='https://fonts.googleapis.com/css?family=Droid+Serif:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
      <link href='https://fonts.googleapis.com/css?family=Roboto+Slab:400,100,300,700' rel='stylesheet' type='text/css'>

        <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
            Menu
        </button>
        Start Bootstrap

                    Services

                    Portfolio

                    About

                    Team

                    Contact

Welcome To Our Studio!

It's Nice To Meet You

            Tell Me More

I don't know why the image is below the navbar.  Any help would be appreciated.  As you can see in my example the navbar is on the left and in the template it is neatly on the right.

A: On your nav element, you have a class called "fixed-top" and should be "navbar-fixed-top". You have to follow this structure:

            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                Toggle navigation Menu
            </button>
            Start Bootstrap

                    Services

                    Portfolio

                    About

                    Team

                    Contact

A:
If you are using the template in your welcome.blade.php, for example, you need to link your css and js, and those files have to be in your public folder.
substitute:
<link href="css/agency.css" rel="stylesheet">

to:
<link href="{{ asset('css/agency.css') }}" rel="stylesheet">

do the same with js files.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get text "BTC" from tickerid "Binance:BTCUSDT" [Pine Script Trading View] I want to get text "BTC" from tickerid "BINANCE:BTCUSDT". How to split them? Please help me.
TradingView - PineScript

A: Below code will split the tickerid using : as a delimeter. It will then return the first three characters of the pair.
Read this for more string manupilation related functions.
//@version=5
indicator("String Test", overlay=true)

getPair(_str, _n) =>
    string[] _pair = str.split(_str, ":")
    string[] _chars = str.split(array.get(_pair, 1), "")
    int _len = array.size(_chars)
    int _end = math.min(_len, math.max(0, _n))
    string[] _substr = array.new_string(0)
    if _end <= _len
        _substr := array.slice(_chars, 0, _end)
    string _return = array.join(_substr, "")

if barstate.islast
    label.new(bar_index, 0, getPair(syminfo.tickerid, 3), yloc=yloc.abovebar)


text:
Q: react router navigate links from rest api I'm new in react and faced with the problem when tried to accomplish navigate through my api pages. What I've done: http://pastebin.com/hxf9PJ8k
It works perfectly on my opinion, but show only first api page. Links to all user profile works too, it was simple to do just adding an  id to api link. So, my api returned to me objects that is actually users, and overall count of users in database and links to next page if exist or null and previous page or null. Now I cannot understand how to use those link to create 2 buttons — next and prev. How to pass whole link or just part next to page= to Users props and make xhr request.
Api example view:

count:  2302
next:   "http://localhost:8080/instant/api/?page=2"
previous:
results:
    0:  Object
    1:  Object
    2:  Object

Thanks in advance!

A: Basically what suggest to yo to do is to create a currentPage variable which makes your logic very simple.
for previous and next buttons create a separate component to handle paging condition, handle any click event on the parent component to keep it simple.
class PrevBtn extends React.Component {
    constructor(props){
        super(props);
        this.props.clickHandler = this.props.clickHandler.bind(this);
    }

    render() {
        let button = null;
        const {currentPage} = this.props;

        if(currentPage>1){
          button = Prev
        }else{
          button = Prev
        }
        return(
{button}
)
      }
    }

I just did an example for you in codePen, but I just did the prev button logic, you can figure it out how to do the next button component.


text:
Q: Python: How to find path to the script running a python script Lets say i have a python script at homedir/codes/py/run.py
I also have a bash script at homedir/codes/run.sh
This bash script runs run.py by python py/run.py.
The thing is that i need to be able to find out, in run.py, the path to the calling script run.sh. If run.sh is run from its own directory, i can just use os.getcwd(). But run.sh can in principle be run from anywhere, and then os.getcwd() will return the path to where run.sh is run FROM, and not the actual location of run.sh.
ex:

*

*At homedir/codes: ./run.sh -> os.getcwd() returns homedir/codes

*At homedir: ./codes/run.sh -> os.getcwd() returns homedir
But i want homedir/codes no matter how run.sh is called. Is this possible?

A: To get the absolute path of the current script in bash, do:
SCRIPT=$(readlink -f "$0")

Now, pass that variable as the last argument to the python script.  You can get the argument from python as:
sys.argv[-1]

A: you can get the absolute qualified path with:
os.path.join(os.path.abspath(os.curdir))


text:
Q: uwsgi emperor mode - Warning message I use uwsgi running in the emperor mode to serve multiple Django Applications on one server. Therefore for every project  I have a own config file like this one:
<uwsgi>
    <master>true</master>
    <processes>1</processes>
    <vaccum>true</vaccum>
    <chmod-socket>666</chmod-socket>
    <socket>/tmp/%n.sock</socket>
    <uid>www-data</uid>
    <gid>www-data</gid>
    <pythonpath>%d../%n</pythonpath>
    <module>%n</module>
</uwsgi>

Everything works fine, the only thing which concerns me or which I don't completly understand is, when I run uwsgi with "uwsgi --emperor /home/user/apps/vassals/" I get the warning message "* WARNING: you are running uWSGI as root !!! (use the --uid flag) *".
Can I ignore that message or does it mean that uwsgi doesn't consider the uid gid settings in the project config files?
Many thanks.
Mario

A: uWSGI will warns you whenever you run it as root. Independently by the usage (it is perfectly fine to run the emperor as root to allow vassals to be mapped to different uid), you will get the warning. Users must be conscious when they run root processes.

A: You could ignore it, however, for best practice you should specify running user.
uwsgi --emperor /path/to/vassels/* --uid www-data --gid www-data

It's complaining that the emperor process is running as root. Now, while this doesn't serve any requests, it could be a potential problem. Each of the vassels will have the configuration you've specified.
It's always advisable if at all possible to run a process isolated.


text:
Q: php foreach loop implode every 3 loop I need to make a gallery. I have images from 01 to 09. I need to divide them on foreach. The first div must have an active class. And we need to repeat the div every 3 image. I need exactly this html:

            ...

But my code doesn't work. I don't know how to complete this...
Here is my PHP code:

            <?php
            $countedimage = 0;
            $counteddiv = 0;
            $count = count($images_bottom);
            for ($x = 0; $x <= $count; $x++) {
                $countedimage++;
                $counteddiv++;
                if($countedimage == '4') {
                    $countedimage = 0;
                ?>
            <div class="item<?php if($counteddiv != '1') { ?> active<?php } ?>">

                                <img src="<?php echo $images_bottom[$x]['popup']; ?>" class="img-responsive" alt="a" />

                <?php } ?>
                <?php } ?>

A: Firstly, lets start with grouping your images into multiples of three.
// An arbitrary list of image file names (used for clarity).
$images = ['image-1.jpg', 'image-2.jpg', 'image-3.jpg', 'image-4.jpg', 'image-5.jpg', 'image-6.jpg', 'image-7.jpg', 'image-8.jpg', 'image-9.jpg'];

// Separate images into groups of three.
$images = array_chunk($images, 3);

Next we need to look at the output. So taking your example HTML:

        <?php // Loop over each group of three images ?>
        <?php foreach ($images as $g => $group): ?>

            <div class="item <?= ($g == 0) ? 'active' : '' ?>">

                    <?php // Loop over each image in group ?>
                    <?php foreach ($group as $i => $image): ?>

                                    <img src="<?= $image ?>" class="img-responsive" alt="a" />

                    <?php endforeach ?>

        <?php endforeach ?>

A: So, you basically want to print this portion for every item:

            <img src="<?php echo $src ?>" class="img-responsive" alt="a"/>

And you only want to print this portion every 3rd time, around groups of 3 of the above chunks:

Instead of trying to keep track of 2 separate counts as you are doing, you can simplify things by using the modulus operator % along with the index of your loop $x.
This is really useful when you want to repeat something at certain intervals.  Essentially, you can repeat something every $z number of times by doing something like:
if($totalCount % $z == 0)

Example:
for ($x = 1; $x < 50; $x++) {
    if ($x % 5 == 0) echo $x . '
';
}

//   results:
//    5
//    10
//    15
//    20
//    25
//    30
//    35
//    40
//    45

In your case, something like this would work:
<?php for ($x = 0; $x < count($images_bottom); $x++) {
    $src = $images_bottom[$x]['popup'];
    $item_active = $x==0 ? 'item active' : 'item'; // only use 'item active' first one

if ($x % 3 == 0) { // only display every 3rd time?>
    <div class="<?php echo $item_active ?>">

<?php } ?>

                        <img src="<?php echo $src ?>" class="img-responsive" alt="a"/>

<?php if ($x % 3 == 2 || $x == count($images_bottom)-1){ // only display after every 3rd time (after items 0, 1, 2) or on last one ?>

<?php } ?>

<?php } ?>


text:
Q: How to transfer the whole element using html5 event.dataTransfer? I want to remember or get data of the current drag element. This is what I did :
$('.source_element').on('dragstart', function(e){
   e.originalEvent.dataTransfer.setData("source", this);
});

$('.destination').on('drop', function(e){
   var source = e.originalEvent.dataTransfer.getData('source');
   console.log(source);
   console.log(source.className);
   console.log($(source));
   $(this).html($(source).html());

   e.preventDefault();
});

The first console.log show [object HTMLDivElement] as a string, not an object, second undefined, third throws an error.
So I suspect that dataTransfer.setData only accept the data as a string, object is not allowed. If that's the case, how do you solve this problem, how can I remember which element is being dragged without knowing its specific ID ?

A: Just use some string to uniquely identify the element, like giving each element an id or a data attribute
$('.source_element').on('dragstart', function(e){
   var id = 'drag-'+(new Date()).getTime();
   this.id = id;
   //$(this).attr('data-drag', id);
   e.originalEvent.dataTransfer.setData("source", id);
});

$('.destination').on('drop', function(e){
   var source = e.originalEvent.dataTransfer.getData('source');
   console.log(source);
   console.log($('#'+source));
   $(this).html($('#'+source).html());
   //console.log($('[data-id="'+source+'"]'));
   //$(this).html($('[data-id="'+source+'"]').html());

   e.preventDefault();
});

A: I'm not a fan of globals, but sometimes they suit the problem.  If you want to be able to move an HTMLElement with some data, try this:
window.dragDepo = {};
const dragID = "unique_dragging_name";
sourceEl.addEventListener("dragstart", (event) => {
  window.dragDepo[dragID] = { el: sourceEl, origin: "where it was before" }
  event.dataTransfer.setData("text/plain", dragID);
});

// clear global data asap
sourceEl.addEventListener("dragend", (event) => window.dragDepo[dragID] = undefined);

.
destinationEl.addEventListener("drop", (event) => {
  const dragID = event.dataTransfer.getData("text/plain");
  dragData = window.dragDepo[dragID];
});

A: You could also do this by inserting a stringified JSON object to the dataTransfer.setData part:
Add the HTML element (use outerHTML so it's a string):
var dragData = {element:originalElement.outerHTML, type:'move-hovered'}
dragData = JSON.stringify(dragData);
event.dataTransfer.setData("text/plain", dragData);

In the above, I create the dragData object with 2 keys - one is the element, and the other, move-hovered, is just a name for the drag event, so you can identify it.
Then JSON parse it when dropped:
var data = e.dataTransfer.getData("text");
var dragData = JSON.parse(data)
var element = dragData.element

Not sure if there's a limit on the length of the text that can be passed, but this is working for me. The main issue though is that there is no reference to the original HTML element, as a new string is used.
And you have to recreate the HTML node when dropped:
var dragDataElement = document.createElement('div')
dragDataElement.innerHTML = dragData.element
originalElement = dragDataElement.firstChild


text:
Q: How to set minimum word count in wordpress post I am planning to create a code filter and set a minimum word count in saving/submitting the wordpress post. I tried this code.
function minWord($content)
{
    global $post;
    $content = $post->post_content;
    if (str_word_count($content) < 300 ) //set this to the minimum number of words
    wp_die( __('Error: your post is below the minimum word count. It needs to be longer than 300 words.') );
}
add_action('publish_post', 'minWord');

but the issue, when I input < 300 words the post still saves it on the database. My question now is what should I do that if the content will have < 300 words it won't save to the database?

A: The wp_insert_post_data hook will be called before the post is saved to the database. We also check the status of the post so this function doesn't run on other admin pages.
function enforceMinWordCount( $data, $post )
{
    if ($data['post_status'] === 'publish' &&
        str_word_count($post['post_content']) < 300 ) {
        wp_die( __('Error: your post is below the minimum word count. It needs to be longer than 300 words.') );

    }
    return $data;
}

add_action( 'wp_insert_post_data', 'enforceMinWordCount', 99, 2 );

This isn't very UX-friendly however, since a user will lose their post and get sent to an error screen. I'd recommended setting the status of the post to pending if it doesn't meet the minimum word count requirements, and notifying the user via the admin_notices hook that it cannot be published until the word count is reached.

A: use 'save_post' hook . Try below code.
 function minWord( $post_id ) {

         $content = get_the_content( $post_id )
        if (str_word_count($content) < 300 ) //set this to the minimum number of words
        wp_die( __('Error: your post is below the minimum word count. It needs to be longer than 300 words.') );
        return;
     }
    add_action( 'save_post', 'minWord' );


text:
Q: trouble about setting value of slider in wpf? I have a slider in wpf and want the user , set the min and max value of it.
in xaml code :
     <Slider x:Name="slider1" Width="34" Minimum="{Binding Path=Minval}" Value="10"    Height="105" Margin="5,5,5,5"  Maximum="{Binding Path=Maxval}"/>

      <TextBox  Height="23" HorizontalAlignment="Left" Margin="5,5,5,5" Name="minvaltxt" VerticalAlignment="Top" Width="120" />

<TextBox  Height="23" HorizontalAlignment="Left" Margin="5,5,5,5" Name="maxvaltxt" VerticalAlignment="Top" Width="120" />

   <Button Content="Apply" Name="btn"  Height="23" HorizontalAlignment="Left" Margin="5,5,5,5" VerticalAlignment="Top" Width="24" Click="btn_Click"  />

in code behind :
    private double maxval = 80;
    public double Maxval
    {

        get { return maxval; }
        set { value = maxval; }
    }

    private double minval = 5;
    public double Minval
    {

        get { return minval; }
        set { value = minval; }
    }

     private void btn_Click(object sender, RoutedEventArgs e)
     {
      minval= double.Parse(minvaltxt.Text);
      maxval= double.Parse(maxvaltxt.Text);
     slider1.Minimum = Minval
     slider1.Maximum = Maxval;

     }

but it does not update the min and max value of silder !
what is the problem ?
thanks for any help.
.
the question now edited.
thanks.

A: *

*Have you set the DataContext for your view?

*In Xaml you have used Maxcamdistance while the property name is Maxval in VM.

*Implement INotifyPropertyChanged on your class and raise propertychanged for your property.

*In button_click() set Properties not variables.

A: The problem is that you don't use dependency properties or INotifyPropertyChanged to inform the UI that the values of Minval and Maxval were changed. Have a look at my answer here: Bind boolean to visualstate

A: Thanks for all of lovely users who try to help .
Finaly I found the solution.
Infact , it did not need  INotifyPropertyChanged or dependency properties !
The problem was about using 2 Windows Form Host in the same windows that causes one of
numericupdown return zero !
I do not khow why this accured but I used UserControl to overcome this problem.
User Control supports multiple Windows Form Host without any problem.
It seems that wpf windows has a limitation for hosting windows form.
Thanks alot.
Be Fresh.


text:
Q: Images not showing on launch by the main, but showed on Scene builder I'm new on coding, especialy in java, and i've tryed to use JavaFx with scene builder.
My issue today is that i've done that menu with scene builder:
https://imgur.com/a/IH0lf
And when I run it the images doesn't show. I've try with other scenes i've made, same issue.
https://imgur.com/a/UuCMi
Here is my Main :
package com.doki;

import java.io.IOException;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;

public class MainRpg extends Application {

    private Stage stage;
    private BorderPane fenetre;

    @Override
    public void start(Stage stage) {
        this.stage = stage;
        this.stage.setTitle("Xar'Saroth");

        initFenetre();

        showMenu();
    }

    /**
     * Initializes the root layout.
     */
    public void initFenetre() {
        try {
            // Load root layout from fxml file.
            FXMLLoader loader = new FXMLLoader();
            loader.setLocation(MainRpg.class.getResource("view/Fenetre.fxml"));
            fenetre = (BorderPane) loader.load();

            // Show the scene containing the root layout.
            Scene scene = new Scene(fenetre);
            stage.setScene(scene);
            stage.show();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * Shows the person overview inside the root layout.
     */
    public void showMenu() {
        try {
            // Load person overview.
            FXMLLoader loader = new FXMLLoader();
            loader.setLocation(MainRpg.class.getResource("view/Menu.fxml"));
            AnchorPane personOverview = (AnchorPane) loader.load();

            // Set person overview into the center of root layout.
            fenetre.setCenter(personOverview);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * Returns the main stage.
     * @return
     */
    public Stage getStage() {
        return stage;
    }

    public static void main(String[] args) {
        launch(args);
    }
}

And my scene code :
<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.Button?>
<?import javafx.scene.control.ButtonBar?>
<?import javafx.scene.image.Image?>
<?import javafx.scene.image.ImageView?>
<?import javafx.scene.layout.AnchorPane?>

<AnchorPane prefHeight="600.0" prefWidth="900.0" xmlns="http://javafx.com/javafx/9.0.1" xmlns:fx="http://javafx.com/fxml/1">
   <children>
      <ImageView fitHeight="600.0" fitWidth="900.0" pickOnBounds="true" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
         <image>
            <Image url="@../menuImage.jpg" />
         </image>
      </ImageView>
      <ImageView fitHeight="186.0" fitWidth="489.0" layoutX="206.0" layoutY="343.0" pickOnBounds="true" preserveRatio="true" AnchorPane.bottomAnchor="150.0">
         <image>
            <Image url="@../xarSaroth.png" />
         </image>
      </ImageView>
      <ButtonBar layoutX="295.0" layoutY="518.0" prefHeight="40.0" prefWidth="281.0" AnchorPane.bottomAnchor="50.0">
        <buttons>
          <Button mnemonicParsing="false" prefHeight="25.0" text="Continuer" />
            <Button mnemonicParsing="false" prefHeight="25.0" prefWidth="134.0" text="Nouvelle Partie" />
        </buttons>
      </ButtonBar>
   </children>
</AnchorPane>

I've read thoses posts :
Why isn't my background image being displayed in FXML
Images imported in scene builder is not getting displayed while executed in netbeans
But the solutions didn't work on me, or i'm just a bit too stupid.
By the way i've gor this error message when I launch, I don't think that is the issue :
WARNING: Loading FXML document with JavaFX API of version 9.0.1 by JavaFX runtime of version 8.0.121
Thanks!
EDIT :
I have done this change : ((Image)loader.getNamespace().get("image1")).getException().printStackTrace(System.err);
and it makes that kind of error. I understand that there is a path issue no?
    java.io.FileNotFoundException: C:\Users\Stagiaire ACI\Desktop\Java\XarSaroth\bin\com\doki\menuImage.jpg (Le fichier spécifié est introuvable)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at sun.net.www.protocol.file.FileURLConnection.connect(Unknown Source)
at sun.net.www.protocol.file.FileURLConnection.getInputStream(Unknown Source)
at java.net.URL.openStream(Unknown Source)
at com.sun.javafx.iio.common.ImageTools.createInputStream(ImageTools.java:486)
at com.sun.javafx.iio.ImageStorage.loadAll(ImageStorage.java:311)
at com.sun.javafx.tk.quantum.PrismImageLoader2.loadAll(PrismImageLoader2.java:127)
at com.sun.javafx.tk.quantum.PrismImageLoader2.<init>(PrismImageLoader2.java:71)
at com.sun.javafx.tk.quantum.QuantumToolkit.loadImage(QuantumToolkit.java:720)
at javafx.scene.image.Image.loadImage(Image.java:1065)
at javafx.scene.image.Image.initialize(Image.java:807)
at javafx.scene.image.Image.<init>(Image.java:695)
at com.sun.javafx.fxml.builder.JavaFXImageBuilder.build(JavaFXImageBuilder.java:47)
at com.sun.javafx.fxml.builder.JavaFXImageBuilder.build(JavaFXImageBuilder.java:37)
at javafx.fxml.FXMLLoader$ValueElement.processEndElement(FXMLLoader.java:763)
at javafx.fxml.FXMLLoader.processEndElement(FXMLLoader.java:2823)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2532)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2441)
at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2409)
at com.doki.MainRpg.showMenu(MainRpg.java:56)
at com.doki.MainRpg.start(MainRpg.java:24)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(LauncherImpl.java:863)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
at java.lang.Thread.run(Unknown Source)

A: OK, I think that when you write code for the url path of the image in imageView, you should not refer to the file tree structure of the IDE, but should refer to the file tree structure of the compiled directory.
For example, here is the wrong code. I have marked the "image" folder as Resource Folder in IDEA. The picture will show when you preview in the scene builder, but it does not show when you run the program.
the wrong example
According to the picture, the url path is absolutely correct but it fails to show. Why? I think you should refer to the file tree structure of the compiled directory "out" and you will understand.
the correct example
So in this case, you can change the code as:
<image>
    <Image url="@../desk.jpg" />
</image>

It will work although it fails to preview in scene builder.
And the following code also works, because the "BallGame" is the root directory:
<image>
    <Image url="@/desk.jpg" />
</image>

Another way, to keep in the same form before and after compiling. You can place the image folder in the src folder. For example;
another way
It also works.


text:
Q: How can I have different HOST_ID() for different sessions in my Webservice? I have an Asp .Net Webservice. In its method I call HOST_ID() function of SQL Server to get unique ID of each session or connection but I get one ID for each session. How can I make it Unique for each http session?

A: From Books Online:

Returns the workstation identification number. The workstation identification number is the process id (PID) of the application on the client computer that is connecting to SQL Server.

This is unlikely to be unique.


text:
Q: what pattern or process to notify multiple systems about changes in another system Imagine a system X with an http api with a lot of data from a (mysql) database.
Imagine multiple systems being dependent on this data but doing very different tasks. Some work on one data-set others work on a huge bunch of data-sets.
The data changes to an unknown number of sets in system X do not have a periodic rhythm. There can be a large number of changes in a very short time.
The other systems must somehow be aware of those data changes and react accordingly.
What pattern or process is advisable to keep bottlenecks in all system at the lowest level.
So that you prevent that either system X won't be able to handle to notify all other systems or handle all other systems trying to fetch changes.
And prevent other systems to slow down because they need to fetch large datasets or wait for system X being overloaded.
Also ideally all systems should not need to know about the other systems. Especially system X shouldn't need to implement specific notification methods for each system.
Would the observer pattern be applicable in this situation?

A: Going by your requirement that no systems should not need to know about the other systems, I think you should go for pub-sub pattern. To understand how it is different from Observer pattern, please refer my other response:
Is Observer pattern and pub-sub same when a database is used in the implementation?
Observer pattern would have work if you didn't had this requirement of systems being unaware of each other. Although if it's ok to know the Subject system but all other systems (i.e. Observer systems) being unaware of each other, in that case even Observer pattern should be good enough as well


text:
Q: Controlling max voltage (power supply) when Vin varies? Is there a way to regulate max DC voltage on a circuit when the input voltage CAN exceed the desired voltage?
I'm trying to figure out power supply/regulation for a fan where the datasheet specs for 10.8v to 13.2v input at up to 4.6A.  I have bench tested the fan up to 14.1v and it didn't fail, so there is some margin of error above 13.2v.
However, my input voltage can vary from ~11.5v to 15.2v.  Normal operating range is ~12-14v.  Total draw for the fans is ~9.2 amps (2 fans).
I have looked at the following:
1) LDO regulators - generally can't supply enough power (even if divided into two circuits, one for each fan), plus I'd have to set for a low voltage to begin with (~11v) which would wind up wasting a fair amount of power most of the time.
2) Avalanche diodes - This could sink significant amounts of current, which would be bad..  not just for the PCB but also because of the battery chemistry it is drawing from as it would pose a fire risk.
3) Switch mode regulators - generally speaking you need some margin above your target output voltage, which isn't always the case here..
4) Using a power diode in series to drop the voltage some arbitrary amount and just heat sink away the wasted power.  Inefficient but may work.  The problem is I would need it to sink ~1v at the top end of the voltage range and less than that at the bottom (preferably closer to 0.5v) which doesn't really seem possible in the datasheets I've been looking at.
So far #4 looks like the best of the "not good" options..   But are there any options I'm missing here?

A: Switching regulators can go both ways
Switching regulators can not only step down the voltage (as in a buck converter), but can step up the voltage (a boost converter), or even regulate a voltage that may be above or below the output (you'd use either a four-switch buck-boost or a SEPIC converter for this).  (They can also invert the polarity of an input, but that's neither here nor there.)
Unfortunately, 9.2A is rather outside the range of a SEPIC as the SEPIC topology is capacitively coupled and you can't really get capacitors that can handle 9.2A of high frequency ripple current without heating up a bunch and causing other problems.  This leaves the four-switch topology as your primary option.  Furthermore, you'll need to use a controller and external power FETs at such high currents, as in the LTC3789 circuit depicted below:

A: You missed PWM (pulse-width modulation). Use a big transistor / MOSFET to pulse the motor at a duty cycle appropriate to give the required average current to the motor. e.g. Give 100% on-time up to 12 V falling to 80% at 15 V.
Pay attention to adequate fly-back protection diodes. These need to be capable of handling the full rated current of the fan.

A: ThreePhaseEel has the correct answer, as already noted, but I'd like to redraw the schematic for my own understanding and to highlight the important parts.  Maybe it'll help someone else too.

simulate this circuit – Schematic created using CircuitLab
So a Four-Switch Buck-Boost really is one followed by the other, at least as drawn in TPE's example.  The rest of the components are for current and voltage feedback in various places or to adjust the controller's logic.
To simplify the control at the expense of some efficiency, M2 and M3 could be replaced with diodes.  (both "pointing up")  These are actually included parasitically in all the FETs (M1-M4), meaning that a manufacturer can't get rid of them even if they wanted to, so every symbol like that should be imagined with an "ordinary" silicon PN diode across it.  The app note puts a couple of schottky diodes there anyway because their lower voltage drop results in less power loss if they ever were to conduct.  (but still not nearly as good as their respective FETs being on)

A: One other possibility would be a crude linear regulator such as:

The output voltage varies with input voltage something like:

A: The buck-boost converter is valid, but it looks like it wil more than double the price of the cooling fan assembly and slash the MTBF (mean time between failures) to a small fraction of the fan motor life.
The most obvious first step is to stop solving a problem the customer may not need you to solve. I don't recognize your particular power bus specs, but they look like someone is adding safety margins to a typical vehicle 12v lead acid battery power bus. 11v represents engine off or alternator failed with depleted battery and some copper loss and a polysilicon fuse at full load. The 15.2v represents engine-on, failed voltage regulator, overcharged and sulfated battery, lightly loaded power bus. If some of this range can be pushed into a survive for 100 hours instead of normal operating conditions, you may all save some money, but sometimes the path to the system or platform's chief engineer is too long and the specs can't be sanitized.
The second most obvious solution is to contact some fan vendors. You aren't the first person to need a bigger voltage range. Military platforms are typically much larger ranges. The fan vendors have a lot more fan motor design variations and blade/wheel designs available than they catalog. Keeping the number of variations down improves volumes and pricing, and distributor shelf space so expect to pay more for an uncommon motor and or blade/wheel, but at least it won't tank your MTBF at the same time. The best part about this solution is that at most companies the purchasing department will want to take the lead and will take care of finding vendors and stirring up options and only involve you to confirm details and a final list of acceptable choices. They'll handle all the phone calls and the boilerplate and keep the tree of options being explored for management and do the cost/volume haggling and all the vendor salesmen will still invite you along for the free lunch at the nice restaurant. Minimum extra work, someone else has to put together the status and explain it to management, and free lunches. Think about it.
Only increase system complexity and cost when there's no other option. In this case there are at least 3 choices for increasing fan voltage range using off the shelf fan motors with a narrow voltage range.
1) Use a PWM chopper to cut the peak RMS voltage, let it go to 100% except when necessary. PLUS: minimum complexity and design effort, uses motor magnetics for reactive smoothing. MINUS: no low voltage boost, large airflow variation Vmin to Vmax, need to qualify motors for compatibility with chosen PWM scheme, unknown EMI mitigation cost risk.
2) Use a boost regulator and change to a higher voltage motor. PLUS: constant motor voltage minimizes airflow variation, limited EMI mitigation cost risk. MINUS: higher cost, needs cooling, needs stalled (stuck) motor protection, adds significant FITs (failures in thousand hours), have to change fan motor selection.
3) Use a buck regulator and change to a lower voltage motor. The PWM input to the 12v motor could be considered a variation on this scheme. A full-up isolated buck converter isn't needed and isn't cost effective. Cost effective versions will use a chopper and the motor reactance and as little else as possible, which suggests a nominal motor voltage near Vmin. PLUS: Low cost, minimum added complexity, low airflow variation MINUS: adds FITS and $, changes motor, must qualify motors compatible with PWM scheme chosen, unknown EMI mitigation cost risk.
Note that all of the motor control schemes have to be roust enough to support the stalled stalled rotor current to start the motor, not just the average running current, but you can make complexity trade offs about the short term start load versus the stuck rotor overheat and burn issues.
If the voltage range has to be supported, a motor that will accomodate it with appropriate overheat protection is certain to be the high MTBF choice and lowest NRE (nonrecurring engineering cost) and its extremely likely to be lowest unit cost as well.

A: Didn't see the mini-note where the OP mentions it's a thermal control fan. There's no inherent reason for the built-in brushless motor control to be limited to a tiny voltage range, but Vmax does set peak transient voltages and a lower value lets them buy lower voltage parts. If the vendor can't offer improved specs ask another vendor. A simple fan and a separate thermal control PWM will be more trouble and cost more than buying a fan with what you want, but if you can't find what you want it's an option. Pasting on a complex voltage regulator to overcome an ill suited thermal feedback motor control shouldn't be necessary.


text:
Q: Real group transparency in three.js Like this question, I want to change opacity of a group. But the accepted answer in that question is not completely correct. Changing opacity of a group is not equal to changing opacity of it's parts. I can show this with this small svg example:
Group opacity (Good):

<svg width="200" viewBox="0 0 50 50" version="1.1" xmlns="http://www.w3.org/2000/svg">
    <g opacity="0.5">
        <g>
            <rect x="20" y="30" width="10" height="50" fill="brown"/>
            <g style="fill: #0b0">
                <circle cx="20" cy="30" r="10"/>
                <circle cx="30" cy="30" r="10"/>
                <circle cx="25" cy="20" r="10"/>
            </g>
        </g>
    </g>
</svg>

Individual opacity (Bad):

<svg width="200" viewBox="0 0 50 50" version="1.1" xmlns="http://www.w3.org/2000/svg">
    <g>
        <g>
            <rect x="20" y="30" width="10" height="50" fill="brown" opacity="0.5"/>
            <g style="fill: #0b0">
                <circle cx="20" cy="30" r="10" opacity="0.5"/>
                <circle cx="30" cy="30" r="10" opacity="0.5"/>
                <circle cx="25" cy="20" r="10" opacity="0.5"/>
            </g>
        </g>
    </g>
</svg>

How to do something like this in three.js?


text:
Q: Garage door impulse generator volt free I have a NovoPort (PDF) garage door opener and I want to control the door with an ESP32. One of the issues I am having is the warning for "Do not connect any current-carrying cables". In the photo below I have a emergency stop sensor connected which connects to I (24V) and has an input to H.

*

*If the input has to be volt-free how is this emergency sensor working?

*I want to provide a second impulse generator (12F, illustration 12b) but I'm unsure how to provide a volt-free input
Note: There is a few versions of this opener, but they all appear to have the same requirements.
Note: The connections on the left (K) go to the motor.

A: That's just an odd way of specifying that you should only connect a bare contact closure to the input — in other words, the device you connect can either pass current between the two terminals or not, and it doesn't supply any voltage or current of its own. In normal use, you'd simply connect a pushbutton switch between the two terminals.
For automated operation, since this is AC, you could use either a relay or an AC-rated optoisolator.

A: To add remote control to this, you would use a relay, and connect it to either NC (normal closed) or NO(normal open) depending on what it is looking for. then you would activate the relay with your ESP32.


text:
Q: How can I trash a "windows.old" folder in Mac OS X? I deleted the windows.old folder when I am in Mac OS X and it is now in the trash. However, I found neither can I empty the trash nor put the folder back to the drive with Windows installed.
If I choose empty trash, my Mac OS X will crash, if I choose secure empty trash, there will be a window pop-up saying that some files in the windows.old folder are read-only and then stops the deleting process. Now how can I delete the windows.old, because it's size is large and I want my storage back.

A: Just open up a Terminal window in Mac OS X and run a command like this:
rm -rf /Users/cwang/.Trash/windows.old

I'm assuming your user's name is clang but just change that to match whatever user name that's dealing with this issue and just run that command.
If somehow that still doesn't work, I would then recommend rebooting your Mac in "Recovery Mode." And then once you are fully booted into the "Recovery Mode" volume, open up the Terminal and do the following:
ls /Volumes/

That will list all connected volumes associated with your machine. Remember, when you are in "Recovery Mode" you are booting from a different volume than your main disk, so you need to figure out the full path to your main disk to fix things like this. Now note your system's true volume name which might be something like Hard Disk/. With that noted, you can then run the rm -rf command like this:
rm -rf /Volumes/Hard\ Disk/Users/cwang/.Trash/windows.old

And that should get rid of the windows.old directory as well. Now just reboot into your main Mac OS X volume and you should be good to go.


text:
Q: What exactly does R CMD Sweave --pdf do? I noticed this in the changes of R 2.14:

R CMD Sweave now has a --pdf option to produce a PDF version of the processed Sweave document.

Trying it out, I noticed that it not only ran pdfLaTeX on the resulting tex but also correctly included bibTeX references and cleaned up afterwards. Seems like a very very nice way of using Sweave now (not to mention how easy it now is to implement the whole routine in editors).
But what exactly is this now running? I couldn't find any more details on it. It seems Sweave -> pdflatex -> bibtex -> pdflatex -> pdflatex at least?

A: Thanks for the question. I had wondered myself about the code behind that 'automagical' process.
R CMD Sweave --pdf ultimately calls tools::texi2dvi, which:

Run[s] latex and bibtex until all cross-references are resolved and
  create[s] either a dvi or PDF file.

(See here for more texi2dvi details).
Here is the chain of events set into motion by an R CMD Sweave --pdf call:

*

*The source file rcmdfn.c has code that instructs R CMD Sweave to run utils:::.Sweave() --args" through Rterm.exe.

*If --pdf is set, utils:::.Sweave() calls tools::texi2pdf() to process the Sweave file.

*texi2pdf() in turn calls tools::texi2dvi().

*Finally, texi2dvi() looks at the environment to learn which tools are available to it, and does the work described in the help file linked above.

A: You could try to perform the conversion from Rnw to pdf manually en see how many times the respective steps are needed to get the same result as R CMD Sweave.

A: I don't know much about the interior workings, but I know the development version of RStudio will let you select between knitr and Sweave as well as between pdflatex and xelatex, and gives bibtex as an option.


text:
Q: get method with javascript <script>
$(document).ready(function(){
var oMain = new CMain({
                       win_occurrence:40,
                       slot_cash: 200,
                       bonus_occurrence:15,
                       min_reel_loop:1,
                       reel_delay: 0,
                       time_show_win:2000,
                       time_show_all_wins: 2000,
                       money:500,
                       min_bet:0.05,
                       max_bet: 0.5,
                       max_hold:3,
                       perc_win_prize_1: 50,
                       perc_win_prize_2: 35,
                       perc_win_prize_3: 15,
                       num_symbol_bonus:3,
                       num_spin_ads_showing:10 });

            $(oMain).on("start_session", function (evt) {
                if(getParamValue('ctl-arcade') === "true"){
                    parent.__ctlArcadeStartSession();
                }
            });
            $(oMain).on("end_session", function (evt) {
                if(getParamValue('ctl-arcade') === "true"){
                    parent.__ctlArcadeEndSession();
                }
            });
            $(oMain).on("save_score", function (evt, iMoney) {
                if(getParamValue('ctl-arcade') === "true"){
                    parent.__ctlArcadeSaveScore({score:iMoney});
                }
            });
            $(oMain).on("show_interlevel_ad", function (evt) {
                if(getParamValue('ctl-arcade') === "true"){
                    parent.__ctlArcadeShowInterlevelAD();
                }
            });
            $(oMain).on("share_event", function (evt, oData) {
                if(getParamValue('ctl-arcade') === "true"){
                    parent.__ctlArcadeShareEvent(oData);
                }
            });

            if(isIOS()){
                setTimeout(function(){sizeHandler();},200);
            }else{
                sizeHandler();
            }
       });
    </script>

here is my codes. there is variable(money) inside js codes. i wanna get that variable from my mysql db how can i do it?
if it helps i can share my php file from here.
that whole online betting script i wanna add user balance in my slot game


text:
Q: Get country from tweet with certain keywords I am using TwitterSource for Flume from Cloudera. I want to get tweets by country with certain keywords. I'm not sure what to compare to when I want to get tweets from The Netherlands. I have the following which results in nothing being processed:
public void onStatus(Status status) {
    if(status.getPlace().getCountry().equalsIgnoreCase("netherlands")) {
        headers.put("timestamp", String.valueOf(status.getCreatedAt().getTime()));
        Event event = EventBuilder.withBody(DataObjectFactory.getRawJSON(status).getBytes(), headers);
        channel.processEvent(event);
    }
}

The reason I don't use FilterQuery for this is because I want to use this for keywords. If I combine this it would be logical OR and not AND.
FilterQuery query = new FilterQuery().track(keywords);

A: On analysis you'll find that most of the tweets don't have location attached to it. Also, even if location is attached, the city, state or country may not be available or be correct. Also I've found tweets  where such country names literally don't exist.
So, you'll have to map city names(or state names) to country names and then check to see if the country matched to the Netherlands. Use Google Maps to achieve this.
Also you may find my answer here helpful.


text:
Q: Install libraries in Google Coral TPU I tried to install the following libraries without success on Google Coral TPU. These libraries I want to cooperate with tensorflow lite:
pandas
numpy
scikit-learn
scikit-image
click tqdm

In Google Coral TPU, in order to work with tensorflow lite, and I am getting these errors:
File "numpy/core/setup.py", line 422, in generate_config_h
          moredefs, ignored = c6wfs --no-warn-script-location --no-binary :none: --only-binary :none: -i https://pypi.org/simple -- setuptools wheel Cython>=0.29.13 "numpy==1.13.3; python_version=='3.6' and platform_system!='AIX'" "numpy==1.14.5; python_version=='3.7' and platform_system!='AIX'" "numpy==1.17.3; python_version>='3.8' and platform_system!='AIX'" "numpy==1.16.0; python_version=='3.6' and platform_system=='AIX'" "numpy==1.16.0; python_version=='3.7' and platform_system=='AIX'" "numpy==1.17.3; python_version>='3.8' and platform_system=='AIX'"" failed with error code 1 in None

I am searching all day to find something on google without any success. What should I do?

A: numpy should already be installed, right?
Any other libraries should be install-able using apt-get:
$ sudo apt install python3-sklearn python3-skimage python3-pandas
$ sudo pip3 install tqdm


text:
Q: Log execution time of each method of the request using Spring AOP Suppose I have a basic Spring boot application with a simple architecture (Controller, Service, Repository). I'm trying to log the execution time of each layer in the application (and different things from each layer), I'm trying to do this using Spring AOP with an @Around Aspect. The thing is that the application is a concurrent application and multiple requests can come at the same time, so if i do something like this:
 @Around("controller() || restController() ")
 public Object logAround(final ProceedingJoinPoint joinPoint) throws Throwable {
    log.info("time elapsed" + timeElapsed)
    //Log some other Controller useful info
 }

 @Around("service() ")
 public Object logAround(final ProceedingJoinPoint joinPoint) throws Throwable {
    log.info("time elapsed" + timeElapsed)
    //Log some other Service useful info
 }

 @Around("repository() ")
 public Object logAround(final ProceedingJoinPoint joinPoint) throws Throwable {
    log.info("time elapsed" + timeElapsed)
    //Log some other Repository useful info
 }

I won't be able to follow the logs of each request because multiple concurrent requests can happen at a time.
I'm using SLF4J with lombok implementation, but I think I can switch to any other implementation of SLF4J such as log4j if it makes any difference for what I want.
I'd love to have a one-line log for each request.

A: To track timing for each request.

*

*Add Thread id as part of logging by changing log format as below
Thread id will be unique for each request
%d %-5level [%thread] [%logger{36}] : %msg%n%rEx

*As you are logging time performance of each layer, redirect performance logging to separate file.


text:
Q: how I can show the sum of in a datagridview column in asp.net i have a datagridview which are used to display a transaction record. And one of the columns in datagridview is "amount"
girdview codeenter code here
<asp:GridView ID="gvGrossDetails" runat="server" AllowPaging="true" AutoGenerateColumns="false"
              CellPadding="0" CellSpacing="1" CssClass="grid_bg" GridLines="None" DataKeyNames="Code"
              OnRowEditing="gvPayeeGross_RowEditing" OnRowDeleting="gvGrossDetails_RowDeleting"
              OnRowUpdating="gvGrossDetails_RowUpdating" OnRowCancelingEdit="gvGrossDetails_RowCancelingEdit"
              PagerStyle-Width="0px" PageSize="10" ShowFooter="true" Width="112%" Style="margin-top: 0px">
    <PagerStyle CssClass="hide" />
    <SelectedRowStyle CssClass="tble_hdr_not_sltd" />
    <HeaderStyle CssClass="tble_hdr_not_sltd" />
    <EmptyDataRowStyle CssClass="row_odd" HorizontalAlign="Center" />
    <FooterStyle CssClass="hide" />
    <RowStyle CssClass="row_even" />
    <EmptyDataTemplate>

                    <asp:Label Text="Records not found" ID="lblEmpty" runat="server"></asp:Label>

    </EmptyDataTemplate>
    <AlternatingRowStyle CssClass="row_odd" />
        <Columns>
            <asp:TemplateField Visible="false">
                <HeaderTemplate>
                </HeaderTemplate>
                <ItemTemplate>
                    <asp:Label ID="lblPayeeID1" runat="server" Text='<%#Bind("Code") %>'></asp:Label>
                </ItemTemplate>
                <ItemStyle Width="0%" />
                <HeaderStyle />
            </asp:TemplateField>

            <asp:TemplateField Visible="false">
                <HeaderTemplate>
                </HeaderTemplate>
                <ItemTemplate>
                    <asp:Label ID="lblPayeeCode" runat="server" Text='<%#Bind("Code") %>'></asp:Label>
                </ItemTemplate>
                <ItemStyle Width="0%" />
                <HeaderStyle />
            </asp:TemplateField>

            <asp:TemplateField ItemStyle-Width="20%" HeaderStyle-HorizontalAlign="Left">
                <HeaderTemplate>
                    Account head
                </HeaderTemplate>
                <ItemTemplate>
                    <asp:Label ID="lblGrossType" runat="server" Text='<%# Bind("Accounthead") %>' Wrap="true"></asp:Label>
                </ItemTemplate>
                <ItemStyle CssClass="item_Style1" />
                <EditItemTemplate>

                                <asp:Label ID="txtGrossType" runat="server" Text='<%# Bind("Accounthead")%>'
                                    CssClass="black_normal"   Width="110px"></asp:Label>

                </EditItemTemplate>
                <ItemStyle Width="20%" />
            </asp:TemplateField>
            <asp:TemplateField ItemStyle-Width="13%" HeaderStyle-HorizontalAlign="Left">
                <HeaderTemplate>
                    Payee Amount
                </HeaderTemplate>
                <ItemTemplate>
                    <asp:Label ID="lblPresentedAmount" runat="server" Text=' <%# Eval("PayeeAmount")%>' Wrap="true"></asp:Label>
                </ItemTemplate>
                <ItemStyle CssClass="item_Style1" />
                    <EditItemTemplate>

                                    <asp:Label ID="txtPresentedAmount" runat="server" Text='<%# Bind("PayeeAmount")%>'
                                        CssClass="black_normal" onblur="requiredCheck(this);" MaxLength="5" Width="110px"></asp:Label>

                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:Label Text="total" ID="lbltotal" runat="server"></asp:Label>

                    </FooterTemplate>
                    <ItemStyle Width="13%" />
                </asp:TemplateField>
                <asp:TemplateField ItemStyle-Width="13%" HeaderStyle-HorizontalAlign="Left">
                    <HeaderTemplate>
                        Approved Amount
                    </HeaderTemplate>
                    <ItemTemplate>
                        <asp:Label ID="lblApproveAmount" runat="server" Text='<%# Eval("ApprovedAmount")%>'
                            Wrap="true"></asp:Label>
                    </ItemTemplate>
                    <ItemStyle CssClass="item_Style1" />
                    <EditItemTemplate>

                                    <asp:TextBox ID="txtApproveAmount" runat="server" Text='<%# Bind("ApprovedAmount")%>'
                                        CssClass="black_normal" onblur="requiredCheck(this);" MaxLength="5" Width="110px"></asp:TextBox>
                                    <ajaxToolkit:FilteredTextBoxExtender ID="fltrApprove" runat="server" FilterType="Custom"
                                        FilterMode="InvalidChars" InvalidChars="'abcdefghijklmnopqrstuvwxyz@!#$%^&*%<> ,"
                                        TargetControlID="txtApproveAmount">
                                    </ajaxToolkit:FilteredTextBoxExtender>

                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="approrve" runat="server"></asp:TextBox>
                    </FooterTemplate>
                    <ItemStyle Width="13%" />
                </asp:TemplateField>

                <asp:TemplateField ItemStyle-Width="6%">
                    <HeaderTemplate>

                                                Delete

                                                Delete

                    </HeaderTemplate>
                    <ItemTemplate>

                                    <asp:Button ID="btnSEdit" CssClass="btnEdit" runat="server" CommandName="Edit" UseSubmitBehavior="false"
                                        CausesValidation="false" />

                                    <asp:Button ID="btnSDelete" CssClass="btnDelete" runat="server" CommandName="delete"
                                        UseSubmitBehavior="false" CausesValidation="false" />

                    </ItemTemplate>
                    <EditItemTemplate>

                                    <asp:Button ID="btnSUpdate" CssClass="btnUpdate" runat="server" CommandName="Update"
                                        UseSubmitBehavior="false" ValidationGroup="GSave" CausesValidation="false" />
                                    <asp:Button ID="btnSCancel" CssClass="btnCancel" runat="server" CommandName="Cancel"
                                        UseSubmitBehavior="false" CausesValidation="false" />

                    </EditItemTemplate>
                    <ItemStyle Width="6%" />
                </asp:TemplateField>
            </Columns>
        </asp:GridView>

My question is, how do i gonna make "GrandTotal" by sum all "amount" in gridview into textbox in asp.net?
when i am trying below code:
<FooterTemplate>
    <asp:Label Text="total" ID="lbltotal" runat="server"> </asp:Label>

</FooterTemplate>

Cannot identity the id of label(error:does not exists "lbltotal")
Please tell where i am doing wrong?
int sum = 0;
for (int i = 0; i < dataGridView1.Rows.Count; ++i)
{
    sum += Convert.ToInt32(dataGridView1.Rows[i].Cells[2].Value);
}
lbltotal.text = sum.ToString();

How to solve this issue?

A: use table.Compute function
   private void ComputeBySalesSalesID(DataSet dataSet)
{
    // Presumes a DataTable named "Orders" that has a column named "Total."
    DataTable table;
    table = dataSet.Tables["Orders"];

    // Declare an object variable.
    object sumObject;
    sumObject = table.Compute("Sum(Total)", "EmpID = 5");

    //Find label
     GridViewRow footer = dgOpenBal.FooterRow;
     var lblTotal = (Label)footer.FindControl("lblTotal");
     lblTotal.Text = sumObject.ToString();
}

Another approach use stored procedure to get calculated amount from Sproc
private void ComputeBySalesSalesID(DataSet ds)
{
         if (ds.Tables[0].Rows.Count > 0)
                {
                    DataRow drSum = ds.Tables[0].Rows[0];
                    GridViewRow footer = dgOpenBal.FooterRow;
                    var lblTotal = (Label)footer.FindControl("lblTotal");
                    lblTotal.Text = drSum["sum"].ToString();
                }
}

A: try this...
 int sum = 0;
 for (int i = 0; i < dataGridView1.Rows.Count; ++i)
 {
     sum += Convert.ToInt32(dataGridView1.Rows[i].Cells[2].Value);
 }
GridViewRow row = GridView1.FooterRow;
((Label)row.FindControl("lbltotal")).Text=sum.ToString();


text:
Q: Performance issue with AWS EMR S3DistCp I am using S3DistCp on an EMR cluster in order to aggregate around 200K small files (for a total of 3.4GB) from a S3 bucket to another path in the same bucket. It is working but it is extremely slow (around 600MB transferred after more than 20 minutes).
Here is my EMR configuration:
1 master m5.xlarge
3 cores m5.xlarge
release label 5.29.0

The command:
s3-dist-cp --s3Endpoint=s3-eu-central-1.amazonaws.com --src=s3://my-bucket/input/ --dest=s3://my-bucket/output/ --groupBy=.*input/(entry).*(.json.gz) --targetSize=128

Am I missing something ? I have read that S3DistCp can transfer a lot of files in a blink but I can't figure how. Both EMR and bucket are in the same region by the way.
Thank you.

A: Here are the recomendations

*

*use R type instance. It will provide more memory compared to M type instances

*use coalesce to merge the files in source as you have many small files

*Check the number of mapper tasks. The more the task, the lesser the performance


text:
Q: Prove a partial derivative equation where only parametric equations are given. I have my calculus 2 exam tomorrow and I have been struggling with this question. I am not sure where to even start, since they haven't actually provided the function g(x, y).
$$$$
$$Let \space z=g(x, y)$$
$$$$
$$x=s+t$$ $$y = s*t$$ Now show that
$$ \frac{\partial^2{z}}{\partial{s}\partial{t}} = \frac{\partial^2{g}}{\partial{x^2}} +x \frac{\partial^2{g}}{\partial{x}\partial{y}} + y\frac{\partial^2{g}}{\partial{y^2}} + \frac{\partial{g}}{\partial{y}} $$.

A: It shouldn't be too troubling that they don't give you $g$ since the answer is in terms of $g$. There's nothing to work out and they don't expect you to do so.
I'll compute one derivative and leave the rest to you:
$$
\frac{\partial z}{\partial t} = \frac{\partial z}{\partial x} \frac{\partial x}{\partial t} + \frac{\partial z}{\partial y}\frac{\partial y}{\partial t}
$$
Now observe that:
$$
\frac{\partial z}{\partial x} = \frac{\partial g}{\partial x}
$$
$$\frac{\partial z}{\partial y} = \frac{\partial g}{\partial y}$$
$$\frac{\partial x}{\partial t} = 1$$
$$\frac{\partial y}{\partial t} = s$$
The last two were obtained from the relationship between $x, y$ and $t, s$. Now take the derivative with respect to $s$:
$$
\frac{\partial z}{\partial t} = \frac{\partial g}{\partial x} + s\frac{\partial g}{\partial y}
$$


text:
Q: Predict the byte size of a base64 encoded byte[] I'm trying to predict the size string representation of a base64 encoded byte array.
I've come up with the formula below, however the length of the actual encodedString is 4 larger than the base64EncodedSize.
The whole idea here is to calculate/predict what the encoded string size would be for a given byte[]. I would prefer not to convert the byte[] to a base 64 string just to determine it's length.
FileInfo pdfFile = new FileInfo(@"C:\TEMP\1.pdf");

long originalSizeInBytes = pdfFile.Length;

String encodedString = Convert.ToBase64String(File.ReadAllBytes(pdfFile.FullName));

long base64EncodedSize = (originalSizeInBytes / 3) * 4;

----------------------------------------------------------------------------------
- Results -
-----------------------------------------------------------------------------------
  originalSizeInBytes                           913663  long
  base64EncodedSize                             1218216 long
  encodedString.Length                          1218220 int
  base64EncodedSize                             1218216 long
  encodedString.Length - base64EncodedSize      4       long

A: That will be
long base64EncodedSize = 4 * (int)Math.Ceiling(originalSizeInBytes / 3.0);


text:
Q: Plotting multiple patches from list of patches matplotlib python I am trying to plot multiple centered circle sets on a single figure. I have a function for creating patches of circles. I use this to create a list of total patches. However when I try to add these to my figure I can only see the last set of circles.
This is the current outcome:

Something like this is the desired outcome:

This is my code:
"""
def add_circles(center, radius_gt, area_pred, area_db):
    # fig, ax = plt.subplots()#figsize = (10,10)) # note we must use plt.subplots, not plt.subplot

    circle = plt.Circle(center, (radius_gt/2), facecolor='None', alpha=1, linewidth=1.5, linestyle='--', edgecolor='g')
    circle_pred = plt.Circle(center, gen_diameter(area_pred)/2, color='blue')
    circle_db = plt.Circle(center, gen_diameter(area_db)/2, color='r')

    patches = [circle_db, circle_pred, circle]

    return center, patches

total_patches = []

center = [5,0]
center, patches = add_circles(center, 3, average_3_pred, average_3_db)
[total_patches.append(patch) for patch in patches]
print(center)
# [ax.add_patch(patch) for patch in patches]

center[0] = center[0] + (5 + gen_diameter(average_3_db)/2 + gen_diameter(average_4_db)/2)
center, patches = add_circles(center, 4, average_4_pred, average_4_db)
[total_patches.append(patch) for patch in patches]
print(center)
# [ax.add_patch(patch) for patch in patches]

center[0] = center[0] + (5 + gen_diameter(average_4_db)/2 + gen_diameter(average_6_db)/2)
center, patches = add_circles(center, 6, average_6_pred, average_6_db)
[total_patches.append(patch) for patch in patches]
print(center)
# [ax.add_patch(patch) for patch in patches]

center[0] = center[0] + (5 + gen_diameter(average_6_db)/2 + gen_diameter(average_7_db)/2)
center, patches = add_circles(center, 7, average_7_pred, average_7_db)
[total_patches.append(patch) for patch in patches]
print(center)
# [ax.add_patch(patch) for patch in patches]

center[0] = center[0] + (5 + gen_diameter(average_7_db)/2 + gen_diameter(average_9_db)/2)
center, patches = add_circles(center, 9, average_9_pred, average_9_db)
[total_patches.append(patch) for patch in patches]

fig, ax = plt.subplots()#figsize = (10,10)) # note we must use plt.subplots, not plt.subplot

[ax.add_patch(patch) for patch in total_patches]

ax.set_aspect('equal')
ax.set_xlim(0,80)
ax.set_ylim(-10,10)

"""


text:
Q: WiX - Modify existing product - remove a file after a feature is deselected My installer adds a windows service and DLLs which the service uses. Those DLLs are features which can be added or removed using the installer.
When once installed feature is removed using the change dialog, a corresponding DLL is not removed, and is still present in the system. This is not the expected behavior - I would like for the DLL to be removed after a feature is deselected.
Here's how features are defined
  <Feature Id="Modules" Title="Modules" Level="1" ConfigurableDirectory="WIXUI_INSTALLDIR"
       Display="expand" AllowAdvertise='no' InstallDefault='local' Absent='disallow'>
<ComponentRef Id="MyModules" />
<Feature Id="Feature1" Title="F1" Level="0" ConfigurableDirectory="WIXUI_INSTALLDIR">
  <Condition Level="1">Some condition</Condition>
  <ComponentRef Id="Module1" />
</Feature>

<Component Id="Module1" Guid="GUID">
<File Id="File.Module1" Source="$(var.BuildDestination)/$(var.NameSpacePrefix).Module1.dll">
</File>

A: It turned out that that the issue was caused by the feature conditions which were not met during the Change process.
After removing the
<Condition Level="1">Some condition</Condition>

Installer removed obsolete DLLs without issues.


text:
Q: Do I need buffer inverter for a Crystal Oscillator? I want to be able to select between two clock signals, 16MHz and 1MHz, using an analog SPDT switch. Do I proceed correctly, by buffering these oscillators? Or is there a better way to do this?
The clock goes to the MCLK input of an AD5934, whose input capacitance I do not know, but I'm assuming it drives multiple circuitry inside the IC.
The analog switch has an input capacitance of 17.5pF, while the oscillators specify a maximum load of 15pF, that's why I assume a buffer is needed.
Is this the correct way to do such a clock switching?

A: You can use what you have shown but personally I'd make a 2:1 logic multiplexer from 4 NAND gates: -

There are plenty of other options courtesy of google images.


text:
Q: Is $\forall I: I(f)=1$ where $f$ stands for a formula the meaning / definition of a tautology? I have a question about the following formula. Is $\forall I: I(f)=1$ where $f$ stands for a formula and I for an interpretation the meaning / valid definition of tautology?

A: There are two notions kicking around here, one syntactic and the other semantic.

*

*Syntactic tautologies: $f$ is a theorem of the empty theory, with respect to whatever proof system is being used.

*Semantic tautologies: $f$ is true in every structure in the language of $f$ (or, every interpretation).
In my experience, "tautology" refers primarily to the former notion, while sentences with the latter property are called "validities." You will need to look at whatever text you're using to tell whether the definition of tautology you've given is appropriate.
However, by the completeness theorem, these two notions are in fact the same (as long as we're using a reasonable proof system). This is one reason that it's not a big deal that texts sometimes define "tautology" in different ways.

... At least, in the context of first-order logic (or propositional logic, for that matter). The notions above make sense in much more general contexts: "syntactic tautology" makes sense in the context of any proof system, and "semantic tautology" makes sense in the context of any satisfaction notion (even if the structures involved are quite different from what we're used to!). In general these notions may not line up; e.g. second-order logic (with the standard semantics) has no complete proof system.


text:
Q: ylab and xlab title not showing up in a panel plot 5 rows 2column I have a panel plot shown below. The main problem is ylab and xlab titles are not showing up.
How can I set it or reduce the graphics to have all within the window?

Below the command used to make the plot:
par(mar=rep(2,4))
par(mfrow=c(4,2))

 plot(me.ts,las=1,
  main=" ",     # Main title for t`enter code here`he plot
 xlab="Time",                 # Label for the x-axis
 ylab="rainfall (mm/day)",   # Label for the y-axis
 font.lab=1,                  # Font to use for the axis labels: 1=plain
 ylim=c(0, 4), # Range for the y-axis; "x
 xaxp=c(2071,2095,4), # X-axis min, max and
 bty="l", lwd=2)
 me.time = time(me.ts)
 abline(reg=lm(me.ts ~ me.time),col="blue", lwd=2, asp=1)
  m=lm(me.ts ~ me.time)


text:
Q: How to find the distance between two points given longitude and latitude without do loop? I have two locations with longitude and latitude given and I would like to get the distance between these points in python. My data set looks like below:
 df_TEST = pd.DataFrame({'Location': ['X1','X2'],
                     'Long': [ 28.63615701706,76],
                     'Lat': [ 41.0693487044612,54],
                     'Location1': ['Y1','Y2'],
                     'Long1': [30.7158891385255,65],
                     'Lat1': [36.963486025471,45]})

I would like to add a new column to this dataframe with below code but it works only for one row. I have a huge data set and I would like to add this column  without do loop. Solution suggested from
How to find the distance between two points given longitude and latitude in python-error?
How can I do this?
 df_TEST['distance']=geopy.distance.geodesic(float(df_TEST['Long'] .
[0]), float(df_TEST['Lat'][0]),(float(df_TEST['Long1'] .
[0]),float(df_TEST['Lat1'][0]))).km

A: You can use the apply() function on your DataFrame, to apply a function to each row of the DataFrame.
Here is the code:
def distance(row):
    return (geopy.distance.geodesic((row['Long'], row['Lat']),
                                     row['Long1'], row['Lat1']).km)

df_TEST['distance']=df_TEST.apply(distance, axis=1)

A: I may have missed something but what about
>>> df_TEST['distance_km'] = df_TEST.apply(
        lambda r: geopy.distance.geodesic(
            r.Long, r.Lat,  r.Long1, r.Lat1
        ).km,
        axis=1
    )
>>> df_TEST
  Location       Long        Lat Location1      Long1       Lat1  distance_km
0       X1  28.636157  41.069349        Y1  30.715889  36.963486  3221.113126
1       X2  76.000000  54.000000        Y2  65.000000  45.000000  5904.462593


text:
Q: Need help logging into website and retrieving information I have read through many similar questions, but I am still stuck with logging in to my school gradebook (https://parents.mtsd.k12.nj.us/genesis/parents) to retrieve data. My networking class is shown below:
public class WebLogin {

    public String login(String username, String password, String url) throws IOException {
        URL address = new URL(url);

        HttpURLConnection connection = (HttpURLConnection) address.openConnection();
        connection.setDoOutput(true);
        connection.setRequestProperty("j_username", username);
        connection.setRequestProperty("j_password", password);
        connection.setRequestProperty("__submit1__","Login");

        InputStream response = connection.getInputStream();
        Document document = Jsoup.parse(response, null, "");

        //don't know what to do here!

        return null;
    }
 }

I am not sure what to do with the InputStream or if I am going about logging in correctly, and once again, I have gone through and read several online resources to try to understand this concept  but I am still confused. Any help is appreciated!
UPDATE: So now I understand the basic process and I know what I have to do. When using Jsoup to handle the connection, I know you can do something like this:
    Connection.Response res = Jsoup.connect("---website---")
                .data("j_username", username, "j_password", password)
                .followRedirects(true)
                .method(Method.POST)
                .execute();

However, I am still a little confused as to how to actually send the data (such as a user's username/password to the website with HttpURLConnection, and how to actually store the obtained cookie...otherwise, the help has been really useful and I am fine with everything else

A: One way to do this is using Apache Http Client.
Maybe something like below could work.
Request.Post("https://parents.mtsd.k12.nj.us/genesis/j_security_check")
    .bodyForm(
        Form.form()
        .add("j_username",  username)
        .add("j_password",  password).build()
    )
.execute().returnContent();

You'll have figure out what information are necessary for logging in (URL, request method, name and value of parameters etc.).
Here is an example I found for logging into Gmail.

A: EXAMPLE HOW-TO:
(explanation on the origin in edit part)

*

*connect to website (login page) with user creditentials [with HttpUrlConnection]

*grab cookies

*reconnect to page with user data

*parse data [with JSoup]

*present

(with use of value/key pair with http url connection):
1-2 . assuming we got some URL adress (login page "http://blabla/login.php") & we wanna login so what we do:
// create  & open connection
HttpUrlConnection connection = (HttpURLConnection) new URL(adress).openConnection();

// set do output ...
connection.setDoOutput(true);

/** variable charset for encoding */
String CHARSET = "UTF-8";

// Construct the POST value/key pair  data.
String data = "login=" + URLEncoder.encode(login, CHARSET)
        + "&password=" + URLEncoder.encode(password, CHARSET)
        + "&remember_me=on";

byte[] dataBytes = data.getBytes(CHARSET);

// create output stram to write our creditentials
OutputStream outputStream = new BufferedOutputStream(connection.getOutputStream());

// write value/key data to output stream
outputStream.write(dataBytes);
outputStream.flush();

// connect to url
connection.connect();

// now we are connected and we can do other stuff get input strem header response code etc....
int responseCode = connection.getResponseCode();

 /**
 *     here we grab cookies (how?  - in other story)
 */

connection.disconnect();

3 . THEN WE GOT SECOND PAGE WITH USER DATA ( http://blabla/userdata.php )
(*if we allready were not redirected, ** we also can reuse connection or do request as next step to above)
//we are creating & oppening another connection to new adres as at beginning
HttpUrlConnection connection = (HttpURLConnection) new URL(adressToUserData).openConnection();

// but we do not construct user value/kay data & don't create output stream
// we just add obtained cookies as request property
connection.addRequestProperty("Cookie", _cookie);

//connecting
connection.connect();

//getting input stram
InputStrem is = connection.getInputStream();

//parse data for example with jsoup
Document doc = JSoup.parse(is,null"");

//show parsed result example in grid view

*to parse data you need to know the structure of web page after login (the part with user grades)
to examine a page u can use simple tool built in chrome web browser (right click with mouse & examine element)

then u got the "page" as document from point 3 & u select what u need
Elements tableWithGrades = doc.select("table>grades");

u cant select single element as table row(tr), cell(td), span, div by id or class, name etc from HTML - what u like to. You just need to learn 'syntax' of JSoup & got 'simple' knowledge of html:)

EDIT:
"I am not sure what to do with the InputStream or if I am going about logging in correctly, and once again, I have gone through and read several online resources to try to understand this concept but I am still confused."

to be clear:

*

*you need to made yourself clear objective(goals) - what you want to achieve

*then the way how.

You want to (--goals--):

*

*present data from school server which are avaliable for logged in user

so u need to ACT & "THINK" like a WEB BROWSER:(--way--):

*

*make request with user creditentials (login)

*grab data for logged in user

*parse data (get what u want from the data)

*show results

u know now how to do 1,2 from my previous answers
u need now think how-to 3,4 - there are many ways - many roads to one place :P it's your choice which one will u take - but still you need to be aware of those roads :)
so what part of gathered data & in what kind of way u want to present it ?
EDIT2:

"However, I am still a little confused as to how to actually send the data (such as a user's username/password to the website with HttpURLConnection"

*

*by implementing a login form (activity) which will gather user data

*providing data from any other source (as u desired)

before u call:
// change post string "?login=xxxx&password=zzz" to byte array *
byte[] dataBytes = data.getBytes(CHARSET);

which is bound with:
//write value/key data to output stream
outputStream.write(dataBytes);
outputStream.flush();

or before u call as in yr jsoup example:
res.execute();

u need to set String login="...";, passwod="...."  why???
because your code is called sequential(excluding parareel parts) & java use references

"and how to actually store the obtained cookie..."

*

*use persisten storage like: shared preferences, file,  database

*or for session(per app 'pid=vm' lifecycle) singleton instance(example Application class or any other singleton) or some helper class / variable which will not be consumed by GC during your session

"and does writing to the outputStream do the same thing as what my Jsoup example would do? "

in your statment jsoup uses so known builder pattern which makes the same as code i wrote in point 1-4 but it's something like: "the details on how you do it are not irrelevant to me as far it is working" as you can dig a hole with an ax or a shovel - you get the expected result.

"when you are posting login information, why would that be an encoded param?"

imagine your password looks like this $$$s-_xxx.php?xxaasfs??dfsdfśś%%___////**"* - try to do browser request with that kinnd of url
http://server.com/home.php&action=login&username=xxx&password=$$$s-_xxx.php?xxaasfs??dfsdfśś :)))
URLEncoder.encode(password, CHARSET)

/**
* This class is used to encode a string using the format required by
* {@code application/x-www-form-urlencoded} MIME content type.
*
* <p>All characters except letters ('a'..'z', 'A'..'Z') and numbers ('0'..'9')
* and characters '.', '-', '*', '_' are converted into their hexadecimal value
* prepended by '%'. For example: '#' -> %23. In addition, spaces are
* substituted by '+'.
*/

SOME OTHER HINTS:

*

*when u open a stream you should close it when u're done

*to close stream 'best way' (not always) is to use finally block of  try/catch

*befor you poceed with stram check if it is not null it will save your time

*if u use jsoup check for elements.size()>0 or element!=null before u perform any strings/element involving actions

ps. for youre case you should look also at
Using Form-Based Login in JavaServer Faces Web Applications

I hope that this will give you an overview of one of the possible paths & sorry for typos i dont know english language ;p at all


text:
Q: Is it possible to have multiple parent/root nodes in a D3 Icicle plot? I am new to d3 and currently working on the Icicle layout example. I have 2 questions:

*

*Is it possible to have multiple top-level nodes in this example? In other words, instead of a single top-level node of "flare", can we have 3 top-level nodes ("flare1", "flare 2" and "flare 3"), which can then have their respective children nodes? I have tried importing the json data as an array of objects but that did not work.

If it is not possible to have multiple top-level nodes, how can I hide the root node ("flare") so that the 2nd level nodes ("vis", "util", "animate") appear to be top-level nodes?

*How can we sort the nodes (on a particular level) based on their position in the json file, rather than their size? In other words, how can we sort the second level nodes in the above example so that they appear (from left to right) in the order of "analytics", "cluster", "graph" and so on (their order in json file); instead of their current order ("vis", "util", "animate", etc.).

A: Multiple parent/nodes is probably not possible with a single partition layout, since it's a hierarchical layout that assumes single-parent relationship. But it should be achievable using two partition layouts backed by two different hierarchical jsons. You can generate the two jsons out of a single flat array (i.e. unlike flare.json), by using d3.nest().
The rendering code will likely need to get more sophisticated too, so that it can negotiate between the 2 layouts.
For #2, you can use partition.sort() to order them however you'd like. In your case, you'd want to sort by their index in the input array.
UPDATE
You can achieve what you describe rather simply — if each node truly has exactly one parent. So if you want 3 nodes at the top, they still need to be "wrapped" in a single common parent, which you pass to the partition layout. Then you'll need to take care of NOT rendering the parent node, by either filtering it out before binding and appending DOM nodes, or by setting it to display none. In either case, you can check if d.depth == 0 to identify the root node. And you'll also need to translate all the nodes up to account for the gap left by the missing root node, since the layout will set all the x and y coords as if the root node is in the layout. (Maybe there's a way to have the layout "realize" the root node is gone when assigning x and y positions if you use the .size() function to return 0 for the root node).


text:
Q: .exe file (specifically Wireshark) will not launch anymore on Windows 8.1 I use Wireshark x64 daily in my work. Suddenly today, it refuses to open.

*

*When I doubleclick a pcap (or pcapng) file, Windows tells me the file I tried to click was not found.

*When I try to start Wireshark through the start screen, nothing happens.

*When I try to start Wireshark through Launchy, nothing happens.

*When I try to double click the Wireshark.exe in the Program Files\Wireshark folder, it claims that the file can not be found...(!)

*When I open a cmd prompt, go to the same folder and type in wireshark or Wireshark.exe, I get this:

D:\Program Files\Wireshark>wireshark
      The system cannot find the file D:\Program Files\Wireshark\Wireshark.exe.

I have tried to run process monitor to see if anything related happens, but I have not been able to see anything. At least nothing that contains the path of Wireshark, the process name etc.
I have checked the registry according to several KB articles - there is nothing non-default handling .exe files.
The other .exe-files in the same folder work as expected.
I have tried uninstalling and reinstalling Wireshark (latest version) on the system - this changed nothing.
I have tried "running as admin" - same results as before.
This freaks me out and I start worrying about viruses etc. I did an update of Windows Defender and then a full scan. It found nothing, so in theory I am clean.
Does anyone have any ideas how to troubleshoot this? I use Wireshark quite a bit so it would be great to figure it out - it worked perfectly for the past year or so before this started happening suddenly today.
EDIT: After tons of installing and uninstalling (to same place, to different places), I have made a simple yet strange discovery:
If I rename or make a copy of Wireshark.exe, called anything but Wireshark, it runs!
So there is no reason to think there is anything wrong with Wireshark itself.
So is something sitting in mah' Windows looking at the file names of executables that are to be run, and causing an error? I like that I can start Wireshark, but I am horrified at what this might actually mean.
EDIT 2: As per Ramhound's suggestion, I tried running in safe mode. Same thing happens then - when I try starting the .exe file by double clicking it, it claims it can't be found. If I copy it to another name and run it, it works.
Also, I have gotten updated versions of both SpyBot and Kaspersky online to do full scans on the system, and they have discovered nothing.

A: I have found the concrete reason why Wireshark.exe would not run, while for instance Wireshark2.exe (a copy I made in the same folder) ran just fine. There must be some malware installed somehow, that the mentioned killers did not find.
My detective work eventually led me to a tool called RogueKiller. It discovered several interesting things, such as a registry key like this:
HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\wireshark.exe
Specifically, under this key there was a Debugger setting, referring to "nqij.exe" - not a file I have on my system. When Wireshark tried to run, Windows apparently tried to "debug" it with nqij.exe, which it couldn't find, and the process stopped.
So this solves my problem. Of course now I have to find out how this got on my PC and get rid of it.
By the way, this was an obvious attempt from something to avoid detection - there were bunches of these keys, not just for Wireshark, but for other .exe files that makes me think they were antivirus/antimalvware programs. A non-exhaustive list of examples:
spybotsd.exe
zlclient.exe
hijackthis.exe
keyscrambler.exe
SDFiles.exe
SDMain.exe
SDWinSec.exe
avscan.exe
avp.exe
avgwdsvc.exe
AvastSvc.exe
AvastUI.exe
avcenter.exe
etc., etc., etc.
So today I learned of these registry keys that can stop an .exe file from running. This was the core of my question. Hope this can help someone else as well.


text:
Q: Self Hosted signalR in windows service; Minimum permissions for base url = http://*:1111 I have built a windows service which runs a self hosted SignalR service.
I start the webApp thus: WebApp.Start("http://*:1111")
to get this to start I have to provide my service with an Admin logOn.  But that seems a bit too much of a privilege.
I Tried using NETWORK SERVICE  but that got access denied error.
What is the minimum privilege required to start my WebApp for the URL provided.  Or Must I run my service with Admin privileges?

A: You probably want to use netsh.exe (found in c:\Windows\System32) to allow a specified non-admin user to listen for http requests on port 1111.
The syntax for the command is as follows:
netsh http add urlacl url=http://*:1111/ user=DOMAIN\user

http://msdn.microsoft.com/en-us/library/windows/desktop/cc307223(v=vs.85).aspx


text:
Q: ocaml polymorphic variant type inferred type too general I have this code
let my_fun: [`X | `Y | `Z] -> [`Z | `Y] = function
  | `X -> `Y
  | x -> x

It won't compile with message
11 |   | x -> x
          ^
Error: This expression has type [ `X | `Y | `Z ]
       but an expression was expected of type [ `Y | `Z ]
       The second variant type does not allow tag(s) `X

Why can't the complire infer the type [Z |Y] if it is clear that `X can be never returned from the function?

A: If the type of x was inferred to be [`Y | `Z], then it couldn't be used at type [`X | `Y | `Z] which would be strange since it is bound to an argument of that type.
You can use as patterns to get a binding with a refined type, like this:
let my_fun: [`X | `Y | `Z] -> [`Y | `Z] = function
  | `X -> `Y
  | (`Y | `Z) as yz -> yz

The #type_name patterns can be very useful if you want to do this for polymorphic variants with many cases.

A:
Why can't the compiler infer the type [Z |Y] if it is clear that `X can be never returned from the function?

A simpler example is:
if false then 0 else "hello"

The compiler has to reject it because typing in ML languages requires that both branches have the same type 1, and types int and string cannot be unified; this is true even though you could say that there is no chance the expression could ever evaluate to 0 (keep in mind however that formally speaking, it makes no sense to say we evaluate an expression that is not part of the language as defined).
In a match expression, the types of the left part of all clauses must unify to the type of the expression being matched. So x in the last clause has the same type as the implicit argument in function, which is the input type declared in the signature. This is true whether or not `X is a valid value in that context.
You need to enumerate all the cases that are valid; if you need this often in your code then you'd better write a dedicated function for that:
let f : ([> `Y | `Z ] -> [`Y | `Z ] option) = function
  | (`Y|`Z) as u -> (Some u)
  | _ -> None;

For example:
# f `O;;
- : [ `Y | `Z ] option = None
# f `Y;;
- : [ `Y | `Z ] option = Some `Y

See also Set-Theoretic Types for Polymorphic Variants (pdf)

[1] For comparison, in Common Lisp, which is dynamically typed, the equivalent expression is valid; a static analysis as done by SBCL's compiler can infer its type, i.e. a string of length 5:
> (describe (lambda () (if nil 0 "hello")))
....
Derived type: (FUNCTION NIL
               (VALUES (SIMPLE-ARRAY CHARACTER (5)) &OPTIONAL))


text:
Q: SQL Server - Return rows based on user role We are developing an Access application with a SQL Server backend. We have a table that has records that belong to division A, B or C. The users also belong to role A, B or C. We want each user to see only their corresponding division records, as well as only certain columns.
I've thought of two ways, one making different queries for each role and then, based on the user's role, change the source object of the form. However I don't know if it is possible to retrieve it from SQL SERVER with VBA (all VBA documentation I've found so far is quite lacking).
The other solution I thought was to implement this on the server, however I don't know how a T-SQL query or view could fetch only the information needed based on the user's role
Any ideas?
PS: I can't use functions or stored procedures. For some reason the SQL Server we have been provided has them disabled and IT Ops won't enable them (Don't know the logic behind that).

A: Okay, it's been a while since I posted this but I'll post the solution I came up with in the end. VBA is not quite necessary in this case. It can be done perfectly with views.
To retrieve the users roles, (inner) join the table database_role_members twice with the database_principals one. Join by Id (from database_principals) on both fields. With this, you get a list of all roles and their corresponding users. To get the roles of the user querying the database simply add a where clause that checks that the user name corresponds with the function USER_NAME.
Then, don't give permission to those roles to access the table we want to restrict access to. Instead, make a view that fetches info from that table and add a where clause that looks up the value from a column against the query that retrieves the user roles.
With this you can make a link in access to the view and will allow you to see only the records that correspond to the user roles.
While this approach is easy, it doesn't allow for more complicated row level security. For a more powerful approach it might be useful to check the following link.
https://msdn.microsoft.com/en-us/library/dn765131.aspx

A: You could create the same tables with different schemas and assign user rights to different schemas. For example, instead of using dbo.Users you could have Accounting.Users and Warehouse.Users. Assign users in an accounting group to the Accouting schema. Or as suggested above those could be views within a schema that select data from underlying tables.


text:
Q: yahoo pipes regex extract hyperlink I am using Yahoo pipes to take an RSS feed from Reddit to later combine with other feeds.
The link for the item redirects back to Reddit. I would like it to redirect to the actual content.
In order for me to do so, I need to extract a hyperlink from item.description and replace item.link with it.
http://i.stack.imgur.com/kYJZf.png
I know that I need to use the Regex module to do this.
I've tried different variations of regex commands I've found elsewhere on Stack Overflow, but I can't get them to do what I need.
Would anyone know how I can replace item.link with the URL from item.description?

A: For anyone else struggling with the Yahoo pipes, this is how you do it
Start with the module for "Fetch Xpath"
Enter the URL, in this case https://www.reddit.com/r/unitedkingdom
Go to the URL and click "view source" in your browser (F12 in Chrome)
Select the path to the "frame" that holds all the Reddit posts. In this case it is: //*[@id="siteTable"]/div
Next module - "Create RSS"
Title: item.div.1.p.0.a.content
Link: item.div.1.p.0.a.href
By default, the Reddit link was "item.div.1.ul.li.0.a.href" which will direct you to the Reddit comments section, but the link to the content that I wanted was under "item.div.1.p.0.a.href".
This will then create an RSS feed with Title and then a link directly to the content, not the Reddit comments section.


text:
Q: Why does an each closure over an empty collection run at least once? I have a function that downloads files from a web server that is sometimes fed an empty collection. In the function I call each on that collection and what I would expect to happen is that the function just exits with the each closure not being run at all. The problem is that it does get run with an empty filename parameter and the creation of the FileOutputStream goes boom when it is fed a directory instead of a file.
def get(String baseUrl, List files, String targetDir) {
    files.each { filename ->
    // Goes BOOM on next line
    def fos = new FileOutputStream(targetDir + File.separator + filename)
    ...
}

Why does Groovy behave like this and what should I do instead?

A: It doesn't, so I assume files contains something (like null?)
[].each {
  println "boom"  // This doesn't appear
}

[null].each {
  println "pow!"  // this does
}

Assuming it is nulls in your files List that is causing the issue, you can get rid of them by:
files.findAll().each { filename ->
  def fos = new FileOutputStream( new File( targetDir, filename ) )
  ...

Or of course, make the thing that generates the List not add nulls in the first place
Edit
Actually, it sounds like you have a List with empty strings in it...
The findAll fix should still work, as empty strings evaluate to false under Groovy Truth
Edit 2
As a quick note, you can probably change:
def fos = new FileOutputStream( new File( targetDir, filename ) )
...

to:
new File( targetDir, filename ).withOutputStream { fos ->
  ...

And it will ensure the stream is closed for you :-)


text:
Q: How and Where to use failOnUndocumentedParams in Spring Auto REST Docs? I am working with Spring Auto REST Docs, and want to know the use of failOnUndocumentedParams, and how to use it. I want that documentation should not be generated if I miss a field from the POJO. I believe using failOnUndocumentedParams is my solution. However, I don't know how and where to use it.
@Before
public void setUp() throws IOException {

    mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext)
                .alwaysDo(JacksonResultHandlers.prepareJackson(objectMapper))
                .alwaysDo(MockMvcRestDocumentation.document("{class-name}/{method-name}",

                        Preprocessors.preprocessRequest(),
                        Preprocessors.preprocessResponse(
                                ResponseModifyingPreprocessors.replaceBinaryContent(),
                                ResponseModifyingPreprocessors.limitJsonArrayLength(objectMapper),
                                Preprocessors.prettyPrint())))
                .apply(MockMvcRestDocumentation.documentationConfiguration(this.restDocumentation)
                        .uris()
                        .withScheme("http")
                        .withHost("localhost")
                        .withPort(8080)
                        .and().snippets()

                        .withDefaults(CliDocumentation.curlRequest(),
                                HttpDocumentation.httpRequest(),
                                HttpDocumentation.httpResponse(),
                                AutoDocumentation.requestFields(),
                                AutoDocumentation.responseFields(),
                                AutoDocumentation.pathParameters(),
                                AutoDocumentation.requestParameters(),
                                AutoDocumentation.description(),
                                AutoDocumentation.methodAndPath(),
                                AutoDocumentation.section()))
                .build();
}

Here's how my mockMvc looks.

A: You can configure the feature when creating the request or response field snippets. In your case you want to enable the feature for all tests and thus when setting up Mock MVC:
.withDefaults(
    ...
    AutoDocumentation.requestFields().failOnUndocumentedFields(true),
    AutoDocumentation.responseFields().failOnUndocumentedFields(true),
    ...)

Alternatively one can enable the feature for a single test:
document("some-path",
    AutoDocumentation.requestFields().failOnUndocumentedFields(true),
    AutoDocumentation.responseFields().failOnUndocumentedFields(true))