text:
Q: Download leaflet map from a shiny app hosted on shiny.io I have a shiny app that displays a map from the leaflet package.
I am interested in saving the map from the shiny app as either a PNG file or HTML file. I have managed to save it as PNG file when running locally and opening the shiny app on the browser with the code below :
library(shiny)
library(leaflet)
library( mapview)

ui <- fluidPage(
      leafletOutput(outputId = "eiffelmap")
       , downloadButton(outputId = "savemap")
       )

server <- function(input, output, server){

   name <- 'EIFFEL TOWER'
   longitude <- 2.2945
   latitude <- 48.8583
   location <- data.frame(name,longitude,latitude)

   icon.pop <- awesomeIcons(icon = 'thumb-tack',
                         markerColor = 'blue',
                         library = 'fa',
                         iconColor = 'black')
  map <- reactive({
  name <- 'EIFFEL TOWER'
  longitude <- 2.2945
  latitude <- 48.8583
  location <- data.frame(name,longitude,latitude)

  icon.pop <- awesomeIcons(icon = 'thumb-tack',
                           markerColor = 'blue',
                           library = 'fa',
                           iconColor = 'black')

  leaflet(location) %>%
  addProviderTiles(providers$Stamen.TonerLite,
                   options = providerTileOptions(noWrap = TRUE)
  ) %>%

  addAwesomeMarkers(~longitude, ~latitude, label = ~name, icon=icon.pop)

})

output$eiffelmap <- renderLeaflet({

          map()

       })

output$savemap <- downloadHandler(
    filename = "eiffelmap.png",
    content = function(file){

     mapshot(
      x = map()
      , file = file
    )
  }
)

}

shinyApp(ui, server)

My question is why the download does not work when the app is hosted on shiny.io but works when opened locally on a browser? What is wrong with my code?
Also any insight on how to save the leaflet map as an interactive HTML that can be zoomed in and out?
Any insight or help is highly welcome and appreciated.

A: I am not sure if you were asking this independently or as part of the app but if you want to save the map as an interactive HTML just run this part of your code and select the Export option in the Viewer pane and then Save as Web Page...
library(leaflet)
name <- 'EIFFEL TOWER'
longitude <- 2.2945
latitude <- 48.8583
location <- data.frame(name,longitude,latitude)

icon.pop <- awesomeIcons(icon = 'thumb-tack',
                         markerColor = 'blue',
                         library = 'fa',
                         iconColor = 'black')

leaflet(location) %>%
  addProviderTiles(providers$Stamen.TonerLite,
                   options = providerTileOptions(noWrap = TRUE)
  ) %>%

  addAwesomeMarkers(~longitude, ~latitude, label = ~name, icon=icon.pop)

Update:
Please try this (using htmlwidgets::saveWidget())
library(shiny)
library(leaflet)
library(htmlwidgets)

ui <- fluidPage(
  leafletOutput(outputId = "eiffelmap")
  , downloadButton(outputId = "savemap")
)

server <- function(input, output, server){

  name <- 'EIFFEL TOWER'
  longitude <- 2.2945
  latitude <- 48.8583
  location <- data.frame(name,longitude,latitude)

  icon.pop <- awesomeIcons(icon = 'thumb-tack',
                           markerColor = 'blue',
                           library = 'fa',
                           iconColor = 'black')
  map <- reactive({
    name <- 'EIFFEL TOWER'
    longitude <- 2.2945
    latitude <- 48.8583
    location <- data.frame(name,longitude,latitude)

    icon.pop <- awesomeIcons(icon = 'thumb-tack',
                             markerColor = 'blue',
                             library = 'fa',
                             iconColor = 'black')

    leaflet(location) %>%
      addProviderTiles(providers$Stamen.TonerLite,
                       options = providerTileOptions(noWrap = TRUE)
      ) %>%

      addAwesomeMarkers(~longitude, ~latitude, label = ~name, icon=icon.pop)

  })

  output$eiffelmap <- renderLeaflet({

    map()

  })

  output$savemap <- downloadHandler(
    filename = "eiffelmap.html",
    content = function(file){

      saveWidget(
        widget = map()
        , file = file
      )
    }
  )

}

shinyApp(ui, server)


text:
Q: Can "core data generated code" be moved to a superclass shared by 2 targets with identical data models? I have a multi-targeted app and I want to move identical classes from 2 different targets sources to a common framework on top of them.
However, the two classes I want to move are generated by 2 different Core Data Models (one for each app). They are identical because the entities in both model are identical.
So, for example, they both have the following code:
@property (nonatomic, retain) NSSet* Character;

@interface MyClass (CoreDataGeneratedAccessors)
- (void)addCharacterObject:(Character *)value;
- (void)removeCharacterObject:(Character *)value;
- (void)addCharacter:(NSSet *)value;
- (void)removeCharacter:(NSSet *)value;

And this code is more tricky: SubStage1 and SubStage2 are 2 core data model classes and they both are subclasses of SubStage.
Here the code is different:
@property (nonatomic, retain) SubStage1 * SubStage1;

and
@property (nonatomic, retain) SubStage2 * SubStage2;

Can I change the previous code from both subclasses into:
@property (nonatomic, retain) Stage * Stage;

I'm wondering if the same code is supposed to interact with a different core data model, depending on the compiled target. I'm afraid it is not working anymore because the core data entities SubStage1 and SubStage2 refer to the subclasses SubStage1 and SubStage2...
I hope the question is clear.
thanks

A: If the classes are identical use only one, but include it in both targets. Each target can have its own data model file, but share the same class module.

redpajama_set_name: RedPajamaStackExchange


text:
Q: VirtualBox - Ubuntu installation Have installed VirtualBox  - when istalling ubuntu linux the display is cut off on left and right and I cannot see the continue button on extreame right for any screen.  no way to expand it.

A: You must install guest additons as Arronical says in his comment. If you don't know how to do that, simply do the following:

*

*Lauch the virtual machine

*Put your mouse cursor over the menu bar of the virtual machine viewer. It is a little menu bar in the bottom of the scrren if you are running in full screen mode. Otherwise, look the Devices menu in the top menu bar.

*Search for the "Devices" menu, click it and select "Install Guest Additions"

*If you have gvfs or some volume management package installed, you should see a CD icon in your desktop. Browse it.

*Open a terminal, in the mount point of the Guest Additions CD and run:
sudo sh ./VBoxLinuxAddtions.run
Here is a image for reference:

*If you have installed gcc, make and the linux-headers, the script will run without problems, however, if something fails, the console will tell you what to install or do.


text:
Q: After remove App and reauthorize it, email permission is not asked again I'm using FB.login with {scope:'email'} parameter.
When an user is logging in for the first time to my app, the login dialog ask him "if he authorize to connect to my app" and then ask him for "email permission". Well.
But if the user remove my app from his Facebook account, when he is logging in again to my app, the login dialog ask him for authorization but never ask him for email permission?! Is these permission always stored even the app is removed?
Thank you for answering and sorry for my English: I'm French :)


text:
Q: PUT/POST request throttle Rack attack redirect not working So I have a form that makes XHR to external api on to get token and then submit to url which calls our db at "/update" on our backend. We are trying to limit number of requests a person can make using the form by using a rack attack throttle. So that when a limit is reached for example after two attempts the third should give a 429 error and then redirect to our page /429. I have this so far:
throttle '/update', {
    limit: 2,
    period: 60
  } do |req|
    next nil unless req.path == '/update' && req.put?

    req.ip
  end

Then for our throttle response we are doing:
Rack::Attack.throttled_response = lambda do |env|
headers = {
        'Location' => '/429'
      }
      [302, headers]
  end

The code does work and returns a 429 but the redirect doesn't happen even though we have Location in the headers. Also we have an endpoint where we do a GET and the same response redirects the user to /429 successfully.
So how to redirect the user when making a put or post request with Rack Attack ruby on rails library? Is there another way to redirect the user? Any help would be appreciated.

A: The problem is with the HTTP response status code. If you want the browser to redirect you need to use one of the 3XX status.
# frozen_string_literal: true

module Rack
  class Attack
    throttle('test', limit: 1, period: 60.seconds) do |req|
      true
    end
  end

  # response
  Rack::Attack.throttled_response = lambda do |env|
    headers = {
        'Location' => '/test_redirect'
    }
    [301, headers, []]
  end
end


text:
Q: Exception in thread "main" java.lang.ClassNotFoundException, mapreduce I'm new to both java and hadoop. Thank you for any help. I try to do a join operations on two tables. ValueWrapper is a customized type using Writable interface, I also put it in the stdRepartition package.I use command line to run it. The process and result showed below:
Results:
javac StdRepartition.java ValueWrapper.java
jar -cvf StdRepartition.jar ./*.class
added manifest
adding:StdRepartition
adding:StdRepartition$DataMapper.class
adding:StdRepartition$StdReducer.class
adding:ValueWrapper.class

hadoop jar StdRepartition.jar stdRepartition.StdRepartition input output
Exception in thread "main" java.lang.ClassNotFoundException: stdRepartition.StdRepartition
    at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:270)
    at org.apache.hadoop.util.RunJar.main(RunJar.java:205)

Code:
    package stdRepartition;

    import java.io.IOException;
    import java.util.ArrayList;

    import org.apache.hadoop.conf.Configuration;
    import org.apache.hadoop.fs.Path;
    import org.apache.hadoop.io.IntWritable;
    import org.apache.hadoop.io.NullWritable;
    import org.apache.hadoop.io.Text;
    import org.apache.hadoop.mapred.FileSplit;
    import org.apache.hadoop.mapreduce.Job;
    import org.apache.hadoop.mapreduce.Mapper;
    import org.apache.hadoop.mapreduce.Reducer;
    import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
    // import org.apache.hadoop.mapreduce.lib.input.MultipleInputs;
    import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

    public class StdRepartition {

        public static class DataMapper extends Mapper<Object, Text, IntWritable, ValueWrapper> {
            private Text flag = new Text();
            private Text content = new Text();
            private ValueWrapper valueWrapper = new ValueWrapper();
            public void map(Object key, Text value, Context context) throws IOException, InterruptedException{
                FileSplit fileSplit = (FileSplit)context.getInputSplit();
                String filename = fileSplit.getPath().getName();
                int ID;
                if(filename.endsWith("data.txt")) {
                    String[] parts = value.toString().split("s+");
                    ID = Integer.parseInt(parts[0]);
                    flag = new Text("data");
                    content = value;
                }
                else {
                    String[] parts = value.toString().split("\\|");
                    ID = Integer.parseInt(parts[0]);
                    flag = new Text("user");
                    content = new Text(parts[2]);
                }
                valueWrapper.setFlag(flag);
                valueWrapper.setContent(content);
                context.write(new IntWritable(ID), valueWrapper);
            }
        }

        public static class StdReducer extends Reducer<IntWritable, ValueWrapper, NullWritable, Text> {
            private ArrayList<Text> ratings = new ArrayList<Text>();
            private Text age = new Text();
            public void reduce(IntWritable key, Iterable<ValueWrapper> value, Context context) throws IOException, InterruptedException {
                for(ValueWrapper val: value) {
                    Text flag = val.getFlag();
                    if(flag.toString().equals("user")) {
                        age = val.getContent();
                    }
                    else {
                        ratings.add(val.getContent());
                    }
                }

                String curAge = age.toString();
                for(Text r: ratings) {
                    String curR = r.toString();
                    curR = curR + "    " + curAge;
                    context.write(NullWritable.get(), new Text(curR));
                }
            }
        }

        @SuppressWarnings("deprecation")
        public static void main(String[] args) throws Exception {
            Configuration conf = new Configuration();
            Job job = new Job(conf, "StdRepartition");
            job.setJarByClass(StdRepartition.class);

            job.setMapperClass(DataMapper.class);
            job.setMapOutputKeyClass(IntWritable.class);
            job.setMapOutputValueClass(ValueWrapper.class);
            job.setReducerClass(StdReducer.class);
            job.setOutputKeyClass(NullWritable.class);
            job.setOutputValueClass(Text.class);
            // MultipleInputs.addInputPath(job, new Path(args[0]), TextInputFormat.class, DataMapper.class);
            // MultipleInputs.addInputPath(job, new Path(args[1]), TextInputFormat.class, DataMapper.class);

            // Set the input path to be a directory
            FileInputFormat.setInputPaths(job, args[0]);
            FileOutputFormat.setOutputPath(job, new Path(args[1]));

            System.exit(job.waitForCompletion(true)? 0:1);
        }
    }

A: I know the reason. need to package .class files outside the directory to package jar. Thanks for all the help. I also leant how to edit post here.

A: To execute a map reduce program you have to perform the below steps -

*

*Create jar file of your map reduce program(You have already done).

*Place the input file to HDFS/file system.

and finally execute the below command.
hadoop jar [jar file name with fully qualified] [driver class name with fully qualified] /[input path] /[output path]

Here is the very simple and basic Hello World in Map Reduce step by step guide.

A: You must use the full qualified name, but without specifying the extension like '.class' or '.java'


text:
Q: opening HTML links from local HTML UIWebVIew in Safari I have an app that is made of local HTML files.
All the tel: links and mailto: work fine, and open the telephone and mail on iOS, but when I use a simple HTML link to a website, nothing happens,
Here is my code, any input would be appreciated.
Regards
Sam
//
//  ViewController.swift
//  LoadLocalHtml
//
//  Created by Farhad on 9/20/16.
//  Copyright © 2016 WebInDream. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var webView: UIWebView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

    loadHtmlFile()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func loadHtmlFile() {
        let url = Bundle.main.url(forResource: "index", withExtension:"html")
        let request = NSURLRequest(url: url!)
        webView.loadRequest(request as URLRequest)
        webView.scrollView.bounces = false;
        webView.isOpaque = false;
    }

}

here is the HTML code as requested. here is the HTML code as requested. here is the HTML code as requested. here is the HTML code as requested. here is the HTML code as requested. here is the HTML code as requested. here is the HTML code as requested. here is the HTML code as requested. here is the HTML code as requested. here is the HTML code as requested. here is the HTML code as requested. here is the HTML code as requested. here is the HTML code as requested. here is the HTML code as requested. here is the HTML code as requested. here is the HTML code as requested. here is the HTML code as requested. here is the HTML code as requested. here is the HTML code as requested. here is the HTML code as requested. here is the HTML code as requested. here is the HTML code as requested. here is the HTML code as requested.
<!DOCTYPE html>

LOCATIONS

HEAD OFFICE
35 Headlands
Kettering
Northamptonshire
NN15 7ES

T: 01536 513 165

HARROGATE
The Tower Studio
Fourth Avenue, Hornbeam Park
Harrogate
HG2 8QT

T: 01423 815 121

GLOUCESTER
North Warehouse
Gloucester Docks
Gloucester
GL1 2EP

T: 01452 525 019

MILTON KEYNES
Exchange House
494 Midsummer Boulevard
Milton Keynes
MK9 2EA

T: 01908 255 620

NEWCASTLE
Hoults Yard
Walker Road
Newcastle
NE6 2HL

T: 0191 389 8917

CONTACT DETAILS

EMAIL gss@gotch.co.uk

                WEB gssarchitecture.com

                TWITTER @GSSARCHITECTURE

                LINKEDIN COMPANY PROFILE

            Return to Previous Menu

A: Implement UIWebViewDelegate and assign delegate to your webview like  webview.delegate = self to identify clicked link
Try this
class ViewController: UIViewController,UIWebViewDelegate {

    @IBOutlet weak var webView: UIWebView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        webview.delegate = self
        loadHtmlFile()
    }

    func loadHtmlFile() {
        let url = Bundle.main.url(forResource: "index", withExtension:"html")
        let request = NSURLRequest(url: url!)
        webView.loadRequest(request as URLRequest)

        webView.scrollView.bounces = false;
        webView.isOpaque = false;

    }

    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        if navigationType == .linkClicked {
            if let url = request.url {
                UIApplication.shared.openURL(url)
                return false
            }
        }
        return true
    }

}

A: @Sam Manser  Try  to use WKWebView instead of UIWebView. As UIWebView is Dperected from iOS 11. When you tap on your link, It's navigating to safari browser perfect.
Swift 4
     import UIKit
     import WebKit

     class ViewController: UIViewController , WKUIDelegate , WKNavigationDelegate {

        @IBOutlet weak var indeWebView: WKWebView!

        override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view, typically from a nib.
            loadButtonHTMLFile()
        }

        func loadButtonHTMLFile() {
            let url = Bundle.main.url(forResource: "index", withExtension:"html")
            indeWebView.uiDelegate = self
            indeWebView.navigationDelegate = self
            indeWebView.scrollView.bounces = false
            indeWebView.load(URLRequest(url: url!))
        }

        //Open Tapped Link in Safari
        func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Swift.Void) {

            if navigationAction.navigationType == WKNavigationType.linkActivated {
                if let url = navigationAction.request.url {
                    UIApplication.shared.open(url, options: [:], completionHandler: nil)
                }
            }
            // Call this completion handler compulsary
            decisionHandler(WKNavigationActionPolicy.allow)
        }
     }


text:
Q: How to combine missing values from other duplicated row, return a more complete data and remove the duplicates Here's my dataframe:
df1 = structure(list(item = c("HY04SB", "HY04SB", "GSP8Y1", "GSP8Y1",
"9PLM0A", "9PLM0A"), weird = c("w'`tc7>", NA, NA, "($^-yk1%",
"jd(,*'7_", NA), simple = c(NA, 14661746, 58489634, NA, NA, NA
), code = c("WX&}Awx:65Dgn9A3", "WX&}Awx:65Dgn9A3", "$8@g44;T7w'{8e^=",
NA, NA, "(X<f..\\Js9da]CE")), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -6L))

# A tibble: 6 × 4
  item   weird      simple code
  <chr>  <chr>       <dbl> <chr>
1 HY04SB w'`tc7>        NA "WX&}Awx:65Dgn9A3"
2 HY04SB NA       14661746 "WX&}Awx:65Dgn9A3"
3 GSP8Y1 NA       58489634 "$8@g44;T7w'{8e^="
4 GSP8Y1 ($^-yk1%       NA  NA
5 9PLM0A jd(,*'7_       NA  NA
6 9PLM0A NA             NA "(X<f..\\Js9da]CE"

This is what I would like to achieve:
structure(list(item = c("HY04SB", "GSP8Y1", "9PLM0A"), weird = c("w'`tc7>",
"($^-yk1%", "jd(,*'7_"), simple = c(14661746, 58489634, NA),
    code = c("WX&}Awx:65Dgn9A3", "$8@g44;T7w'{8e^=", "(X<f..\\Js9da]CE"
    )), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA,
-3L))

# A tibble: 3 × 4
  item   weird      simple code
  <chr>  <chr>       <dbl> <chr>
1 HY04SB w'`tc7>  14661746 "WX&}Awx:65Dgn9A3"
2 GSP8Y1 ($^-yk1% 58489634 "$8@g44;T7w'{8e^="
3 9PLM0A jd(,*'7_     NA   "(X<f..\\Js9da]CE"

I tried the solution from Filling missing values from other rows in group (including duplicates) but without any success and don't think it's what I want because it's not in the reduced dataframe with incomplete variables removed, and not sure how to retain one of the row with NA as it's more complete than previous duplicates...
new_df <- df1 %>%
  group_by(item) %>%
  mutate(valnew = str_c(weird, simple, code, sep=":")) %>%
  select(-weird, -simple, -code) %>%
  complete(ID, valnew = unique(valnew[!is.na(valnew)])) %>%
  filter(!is.na(valnew)) %>%
  separate(valnew, into = c('weird', 'simple', 'code'), sep=":") %>%
  mutate(rn = row_number()) %>%
  left_join(df1 %>%
              select(ID)) %>%
  filter(!duplicated(rn)) %>%
  select(names(df1))

Can someone assist this, how to produce the result in 3 x 4 as shown above?

A: You can use fil1 after grouping to give rows that share the same item the same information and then slice to select n amount of observations per group
library(dplyr)
library(tidyr)

df1 |>
  group_by(item) |>
  fill(-item, .direction = "updown") |>
  slice(1) |>
  ungroup()

  item   weird      simple code
  <chr>  <chr>       <dbl> <chr>
1 9PLM0A jd(,*'7_       NA "(X<f..\\Js9da]CE"
2 GSP8Y1 ($^-yk1% 58489634 "$8@g44;T7w'{8e^="
3 HY04SB w'`tc7>  14661746 "WX&}Awx:65Dgn9A3"

A: A solution with sapply
  df1 = as_tibble(t(
  sapply(unique(df1$item), function(X) # "loop" over  items
  sapply(colnames(df1), function(COL)  # get unique value of each column else give NA
  ifelse(length((REF = unique(df1[df1$item == X, COL][!is.na(df1[df1$item == X, COL])]))), REF, NA)))
  ))

df1<-readr::type_convert(df1) #auto change column type.


text:
Q: Linking problem when using open-mpi (using the wrappers) At the linking stage, I am getting an error of the form:
Undefined symbols for architecture x86_64:
  "_mpi_allreduce", referenced from:
      _pcnaup2 in libparpack.a(pcnaup2.o)
      _pslamch in libparpack.a(pslamch.o)
      _pcgetv0 in libparpack.a(pcgetv0.o)
      _pcnaitr in libparpack.a(pcnaitr.o)
      _pscnorm2 in libparpack.a(pscnorm2.o)
  "_mpi_comm_rank", referenced from:
      _pcnaupd in libparpack.a(pcnaupd.o)
      _pcmout in libparpack.a(pcmout.o)
      _pcvout in libparpack.a(pcvout.o)
      _pivout in libparpack.a(pivout.o)
      _pcgetv0 in libparpack.a(pcgetv0.o)
      _psvout in libparpack.a(psvout.o)

when I am trying to link with mpifort, so that the command that is being run looks like
mpifort -L(lots of libraries) -l(lots of libraries) -o qlua qlua.o

though I am confused; because I was under the impression that using the wrapper mpifort should handle all the linking to the mpi library for me, so I'm not too sure what steps I should take to debug such an error. For completeness, when I run mpifort -v the output is:
Using built-in specs.
COLLECT_GCC=/usr/local/bin/gfortran
COLLECT_LTO_WRAPPER=/usr/local/Cellar/gcc/10.2.0_2/libexec/gcc/x86_64-apple-darwin19/10.2.0/lto-wrapper
Target: x86_64-apple-darwin19
Configured with: ../configure --build=x86_64-apple-darwin19 --prefix=/usr/local/Cellar/gcc/10.2.0_2 --libdir=/usr/local/Cellar/gcc/10.2.0_2/lib/gcc/10 --disable-nls --enable-checking=release --enable-languages=c,c++,objc,obj-c++,fortran --program-suffix=-10 --with-gmp=/usr/local/opt/gmp --with-mpfr=/usr/local/opt/mpfr --with-mpc=/usr/local/opt/libmpc --with-isl=/usr/local/opt/isl --with-system-zlib --with-pkgversion='Homebrew GCC 10.2.0_2' --with-bugurl=https://github.com/Homebrew/homebrew-core/issues --disable-multilib --with-native-system-header-dir=/usr/include --with-sysroot=/Library/Developer/CommandLineTools/SDKs/MacOSX10.15.sdk SED=/usr/bin/sed
Thread model: posix
Supported LTO compression algorithms: zlib
gcc version 10.2.0 (Homebrew GCC 10.2.0_2)


text:
Q: Higher Than Expected Inherent Latency in OpenAL Playback (Windows, C++) TL/DR: A simple echo program that records and plays back audio immediately is showing higher than expected latency.
I am working on a real-time audio broadcasting application. I have decided to use OpenAL to both capture and playback audio samples. I am planning on sending UDP packets with raw PCM data across a LAN network. My ideal latency between recording on one machine and playing back on another machine is 30ms. (A lofty goal).
As a test, I made a small program that records samples from a microphone and immediately plays them back to the host speakers. I did this to test the baseline latency.
However, I'm seeing an inherent latency of about 65 - 70 ms from simply recording the audio and playing it back.
I have reduced the buffer size that openAL uses to 100 samples at 44100 samples per second. Ideally, this would yield a latency of 2 - 3 ms.
I have yet to try this on another platform (MacOS / Linux) to determine if this is an OpenAL issue or a Windows issue.
Here's the code:
using std::list;

#define FREQ 44100   // Sample rate
#define CAP_SIZE 100 // How much to capture at a time (affects latency)
#define NUM_BUFFERS 10

int main(int argC, char* argV[])
{
    list<ALuint> bufferQueue; // A quick and dirty queue of buffer objects
    ALuint helloBuffer[NUM_BUFFERS], helloSource;
    ALCdevice* audioDevice = alcOpenDevice(NULL); // Request default audio device

    ALCcontext* audioContext = alcCreateContext(audioDevice, NULL); // Create the audio context
    alcMakeContextCurrent(audioContext);

    // Request the default capture device with a ~2ms buffer
    ALCdevice* inputDevice = alcCaptureOpenDevice(NULL, FREQ, AL_FORMAT_MONO16, CAP_SIZE);

    alGenBuffers(NUM_BUFFERS, &helloBuffer[0]); // Create some buffer-objects

    // Queue our buffers onto an STL list
    for (int ii = 0; ii < NUM_BUFFERS; ++ii) {
        bufferQueue.push_back(helloBuffer[ii]);
    }

    alGenSources(1, &helloSource); // Create a sound source

    short* buffer = new short[CAP_SIZE]; // A buffer to hold captured audio
    ALCint samplesIn = 0;  // How many samples are captured
    ALint availBuffers = 0; // Buffers to be recovered
    ALuint myBuff; // The buffer we're using
    ALuint buffHolder[NUM_BUFFERS]; // An array to hold catch the unqueued buffers

    alcCaptureStart(inputDevice); // Begin capturing

    bool done = false;
    while (!done) { // Main loop
        // Poll for recoverable buffers
        alGetSourcei(helloSource, AL_BUFFERS_PROCESSED, &availBuffers);
        if (availBuffers > 0) {
            alSourceUnqueueBuffers(helloSource, availBuffers, buffHolder);
            for (int ii = 0; ii < availBuffers; ++ii) {
                // Push the recovered buffers back on the queue
                bufferQueue.push_back(buffHolder[ii]);
            }
        }
        // Poll for captured audio
        alcGetIntegerv(inputDevice, ALC_CAPTURE_SAMPLES, 1, &samplesIn);
        if (samplesIn > CAP_SIZE) {
            // Grab the sound
            alcCaptureSamples(inputDevice, buffer, samplesIn);

            // Stuff the captured data in a buffer-object
            if (!bufferQueue.empty()) { // We just drop the data if no buffers are available
                myBuff = bufferQueue.front(); bufferQueue.pop_front();
                alBufferData(myBuff, AL_FORMAT_MONO16, buffer, samplesIn * sizeof(short), FREQ);

                // Queue the buffer
                alSourceQueueBuffers(helloSource, 1, &myBuff);

                // Restart the source if needed
                // (if we take too long and the queue dries up,
                //  the source stops playing).
                ALint sState = 0;
                alGetSourcei(helloSource, AL_SOURCE_STATE, &sState);
                if (sState != AL_PLAYING) {
                    alSourcePlay(helloSource);
                }
            }
        }
    }
    // Stop capture
    alcCaptureStop(inputDevice);
    alcCaptureCloseDevice(inputDevice);

    // Stop the sources
    alSourceStopv(1, &helloSource);

    alSourcei(helloSource, AL_BUFFER, 0);

    // Clean-up
    alDeleteSources(1, &helloSource);
    alDeleteBuffers(NUM_BUFFERS, &helloBuffer[0]);
    alcMakeContextCurrent(NULL);
    alcDestroyContext(audioContext);
    alcCloseDevice(audioDevice);

    return 0;
}

Here is an image of the waveform showing the delay in input sound and the resulting echo. This example is shows a latency of about 70ms.
Waveform with 70ms echo delay
System specs:
Intel Core i7-9750H
24 GB Ram
Windows 10 Home: V 2004 - Build 19041.508
Sound driver: Realtek Audio (Driver version 10.0.19041.1)
Input device: Logitech G330 Headset
Issue is reproducible on other Windows Systems.
EDIT:
I tried to use PortAudio to do a similar thing and achieved a similar result. I've determined that this is due to Windows audio drivers.
I rebuilt PortAudio with ASIO audio only and installed ASIO4ALL audio driver. This has achieved an acceptable latency of <10ms.

A: I ultimately resolved this issue by ditching OpenAL in favor of PortAudio and Steinberg ASIO. I installed ASIO4ALL and rebuilt PortAudio to accept only ASIO device drivers. I needed to use the ASIO SDK from Steinberg to do this. (Followed guide here). This has allowed me to achieve a latency of between 5 and 10 ms.
This post helped a lot: input delay with PortAudio callback and ASIO sdk


text:
Q: Is it safe to delete Windows Defender Scans History Files? OS: Windows 10 Pro (used as production server to host websites, and mail functions.)
I've noticed that de-fragmenting my hard drive (using MyDefrag v4.3.1) it's taking for ever to work itself through this C:\ProgramData\Microsoft\Windows Defender\Scans\History\Store folder.
Looking further into it I found that this folder is over 26 GB in size and is holding over 2.3 million files. The file content is encrypted - so of no use to figure out what is stored. They date range is from 2016-04 to 2019-02 (the time I stopped using Defender.)
At the moment I am not using Windows Defender as antivirus software, but G Data Antivirus software. The reason I removed Windows Defender is because it was using 100% of the computers resources for an extended time, just making the system unusable. The server was again responsive after I switched. Checking into the remouval I looked at the Windows features on or off tool - and it looks like Defender is not even listed.
Before running the defrag tool I did a Disk Cleanup System Files and removed all I could (Windows Defender logs are not listed in the list.) I also used the Remove Temporary Files tool offered in Windows 10 (but there too, no mention of Windows Defender log files.)
Doing some research on the subject I found this post, but very little else that sounds useful. Your suggestion is much appreciated.

A: I went ahead and deleted these files, after getting some help from here; and it worked.

A: if you don't know how to clear the Protection history just check out the video
https://youtu.be/vWyoptIYlak


text:
Q: Python request triggers cloudflare unless proxied by fiddler I have ran into a interesting problem. I have a python application in which I scrape multiple websites. One of the websites have cloudflare security implemented, but it's not really strict (I can scrape the website without specifying any means of authentication and it returns the data).
While debugging, I proxy all my python http requests through Fiddler in order to inspect them and see what am I missing and what differs from the request made by browser. I did the same thing here with the code specified below:
response = requests.get(url, headers=headers,
                         proxies={"http": "http://127.0.0.1:8888", "https": "http://127.0.0.1:8888"},
                         verify=r"certificate.pem")

As soon as I got it to work, I wanted to remove the proxy so I wouldn't have to run fiddler when I'm running my service. The only thing I changed was the snippet above. I changed it to:
            response = requests.get(url, headers=headers)

After running my code, I see that it's returning 403 and that my browser is being verified ('Please stand by, while we are checking your browser...').
I don't think that the http request changed, so I'm assuming something is different in non application level. I'm guessing something fails at the transport level, but before snooping around with wireshark, I decided to ask here instead.


text:
Q: How can I remove a stack with serverless greengrass plugin? I am using kepware to collect data and send it to AWS greengrass IoT Core. I deploy my project with serverless and the plugin serverless-plugin-greengrass. Here a part of my serverless file:
[...]
functions:
  opcuaPubSub:
    description: Lambda function for get data from kepware.
    handler: src.opcua_pub_sub.handler
    greengrass:
      subscriptions:
        - target: cloud
          subject: topic/opcua

custom:
  output:
    file: stack.json
  pythonRequirements:
    usePipenv: true
  greengrass:
    autoDeploy: true
    groupId: ${env:GROUP_ID}
    defaults:
      pinned: true
      memorySize: 262144
      encodingType: json

plugins:
  - serverless-python-requirements
  - serverless-stack-output
  - serverless-pseudo-parameters
  - serverless-plugin-greengrass

But I cann't remove the stack with serverless. When I run: serverless remove --stage xxx I have the following error :
Greengrass: Execute reset for group id xxxxx-xxxx-xxxx-xxxx...

  Serverless Error ---------------------------------------

  That deployment type is not valid.  Please specify one of the following types: {NewDeployment,Redeployment}.

I don't understand because 'serverless' is expecting NewDeployment or Redeployment, but what I would like is to remove the stack. I tried to reset deployement of the greengrass group before run: 'serverless remove...', with the command aws greengrass reset-deployments --group-id $GROUP_ID but I obtain the same error. If I delete manually the stack in cloudformation console, it's work my group greengrass will be deleted.
(I run serverless remove --stage xxx when I want to change branch in gitlab-ci).
Someone knows why I can not remove this stack with serverless ?

A: Let's divide your problem into three parts.

*

*Deploy Lambdas

*Associate Lambdas to one or multiple Greengrass groups

*Deploy the updated Greengrass group to its target devices

I have a similar setup running for last 6-9 months. I did not use serverless alone to achieve all of these.
Rather, I used

*

*serverless for #1

*serverless & cloudformation for #2

*ci/cd pipelines with aws cli for #3
I prefer this approach due to the fact it allowed me to maintain 'static unchanging' resources and 'dynamically changing' resources next to each other in a mono-repo, yet handle them with care. E.g. you create Greengrass Group once, but you will end up adding/removing Subscriptions to various Topics at a later point in time (multiple times).
TL; DR
#1 serverless Limit it to deploying / re-deploying Lambdas with source code packages and dependency injection etc.
#2 serverless & cloudformation is where I define AWS::Greengrass::FunctionDefinition and AWS::Greengrass::SubscriptionDefinition resources and grab these resources as a part of when I want to create a new Greengrass group definition.
#3 ci/cd pipelines with aws cli is where i call it as 'Flash Greengrass Device' (involves 2 steps, see below). They almost everytime works.
# Retrieve Service Role Arn & grant exclusive permissions to Greengrass to use this role.
echo "Associating Greengrass Service Role to AWS Account.."
export GGG_ROLE_NAME=`aws2 cloudformation list-stack-resources --stack-name XXX | jq ".StackResourceSummaries[].PhysicalResourceId" --raw-output | grep YYY`
export GGG_ROLE_ARN=`aws2 iam get-role --role-name $GGG_ROLE_NAME | jq ".Role.Arn" --raw-output`
aws2 greengrass associate-service-role-to-account --role-arn $GGG_ROLE_ARN --region $AWS_DEFAULT_REGION

# Get Group ID, Group Version & Flash it!
export GGG_ID=`aws2 greengrass list-groups --query  "Groups[?Name=='XXX']" | jq ".[0].Id" --raw-output`
export GGG_VERSION_ID=`aws2 greengrass list-groups --query  "Groups[?Name=='XXX']" | jq ".[0].LatestVersion" --raw-output`
export GGG_DEPL_ID=`aws2 greengrass create-deployment --group-id $GGG_ID --group-version-id $GGG_VERSION_ID --deployment-type NewDeployment | jq ".DeploymentId"  --raw-output`
export GGG_DEPL_STATUS=`aws2 greengrass get-deployment-status --deployment-id $GGG_DEPL_ID --group-id GGG_ID | jq ".DeploymentStatus" --raw-output`

Cheers!


text:
Q: convert numeric string values into a single integer (not ascii values) I'm trying to convert string like "1234" into a single integer like, n = 1234;
I'm using for loop for this but its saving the ASCII values instead of the actual values
below is the code
#include<stdio.h>

main()
{
    char lc[] = "12345";
    int i,n;
    p = lc;

    for(i=0;i<5;i++)
    {
        n = lc[i];
        printf("%d\n",n);
    }
}

what am I missing ??

A: If by "conversion" you mean printing then you should substract the ascii value of zero from the character , then the ascii of zero wil print as zero , the ascii of one as one ans so on,
char lc[] = "12345";
int i,n;

for(i=0;i<5;i++)
{
    n = lc[i]-'0';
    printf("%d\n",n);
}

A: In your case you only assign in each iteration the current ASCII values to n, as you mentioned you want to convert the Stringinto an int.
A simple and powerful function to achieve that is alternative to your way: atoi(string)
In your case:
 char lc[] = "12345";
 int n = atoi(lc);

A: Because we use ascii 48 represent digit 0, so a simply way to reach that is covert it by mod it, because the ascii define with increment, so 49 should be 1, and so on.
#include<stdio.h>

main()
{

    char lc[] = "12345";
    int i,n;
    //p = &lc;
    int ascii_base=48;
    for(i=0;i<5;i++)
    {
        n = lc[i];
        printf("%d\n",n - ascii_base);
    }
    return 0;
}

And if you want to save it back, and you can do it like:
#include<stdio.h>

main()
{

    char lc[] = "12345";
    int ln = sizeof lc;
    int i,n;
    //p = &lc;
    int ascii_base=48;
    for(i=0;i<5;i++)
    {
        n = lc[i];
        ln[i]=n - ascii_base;

    }
    printf("%s\n", ln);
    return 0;
}

A: An alternative to atoi is to use sscanf which is useful if you want to convert multiple numbers that are in one string, especially if they are of different types such as a float and an integer. You will need to include stdio
char one_int[] = "12345";
char one_float = "3.14";
char a_float_and_an_int = "1024  6.28";

int first_int;
float first_float;
int second_int;
float second_float;

sscanf(one_int,"%d", &first_int);
sscanf(one_float, "%f", &first_float);
sscanf(a_float_and_an_int, "%d %f", &second_int, &second_float");


text:
Q: How to prevent onInput from firing during dynamic component initialization? I have a table that has been created dynamically, and am attempting to put full CRUD capabilities onto it. For business reasons I am unable to use external libraries for this, and so have resulted in using basic HTML with react. I am currently trying to detect changes within the data. My problem is in regards to the onInput event with the div inside the  tag. When the components are first initialized with the data, the onInput event fires for each one rather than waiting for an actual user input. To a degree I understand why this is happening, but I am in need of a workaround for it or an alternative. I have created a small demo below to show a mock of the current code:
Parent class:
import React, {Component} from 'react';

class FormContainer extends Component{
    constructor(props){
        super(props)
        this.state={
            rowData : myData
        }
        this.onInput = this.onInput.bind(this)
    }

    onInput = (rowKey) => {
        console.log(rowKey)
    }

    render() {
        return(
           <Grid
           data={this.state.rowData}
           onInput={this.onInput}
           />
        )
    }
}

Grid class:
import React, {Component} from 'react';

class Grid extends Component{
    constructor(props){
        super(props)
    }

    render(){
        let columns = [];
        let rows = [];
        if(this.props.data != null){
            columns = this.props.data.slice(0, 1).map((row, i) => {
                return(
                  Object.keys(row).map((column, key) => {
                    return(
                      {column}
                    )
                  })
                )
                })

            rows = this.props.data.map((row, rowKey) => {
              return(

                {Object.keys(row).map((data, cellKey) => {
                  return(
                  {row[data]}
                  )
                })}

              )
            })
        }
        return(

{columns}

{rows}

        )
    }
}

export default Grid;

A: The issue is that when your component is rendered any time, you are calling your onInputmethod:
 onChange={this.props.onInput(rowKey)}>{row[data]}

Instead of calling it you have to pass the a function, in this case you can pass an anonymous function or an arrow function:
 onChange={ () => { this.props.onInput(rowKey); } }>{row[data]}


text:
Q: Can't get Eclipse to build C++ - Program g++/gcc not found in path Windows I have read all of the links I could find on stackoverflow but none of them actually contained a solution.
I am using Eclipse CDT and I have installed both cygwin64 and MinGW in trying to figure this out.
My paths seem to be correct, and I seem to be using the correct toolchains, but I still can't seem to fix it.
MINGW_HOME Variable:
C:\MinGW

MSYS_HOME Variable:
C:\MinGW\msys\1.0

PATH Variable:
${MINGW_HOME}\bin;${MSYS_HOME}\bin;C:\ProgramData\Oracle\Java\javapath;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\ATI Technologies\ATI.ACE\Core-Static;C:\Program Files (x86)\QuickTime\QTSystem\;C:\Program Files (x86)\Windows Live\Shared;C:\Program Files (x86)\Windows Kits\8.1\Windows Performance Toolkit\;C:\Program Files (x86)\Microsoft SDKs\TypeScript\1.0\

Thanks for your help!

A: I had similar issues that Eclipse CDT does not find MinGW gcc. Almost always the problem is that eclipse is 32-bit, MinGW is 64-bit or vice versa.
A solution that worked for me is to make sure that eclipse (include Java) and MinGW are both 32-bit (or both 64-bit).


text:
Q: Javascript function only executes every other time I'm working on a letter guessing game and I have a scoreboard at the bottom that shows how many lives the player has left before they lose the game. I have an onscreen keyboard that the user clicks to choose which letter they want to guess.
Everything works fine, except for removing the player's 'lives'.  I have the lives as images that are in an ordered list. On each button click, a function checks to see if that button press matches a letter in the phrase. If it doesn't, it needs to remove a life from the ordered list, and add 1 to the missed count.
Adding 1 to the missed counts works on every wrong button press, but removing the heart only works on every other one, and I'm not sure why. Any help would be greatly appreciated.

function checkLetter(clickedButton) {
  const letters = document.getElementsByClassName('letter');
  let letterFound = null;
  for (let i = 0; i < letters.length; i += 1) {
    if (clickedButton === letters[i].textContent) {
      letters[i].classList.add('show');
      letterFound = true;
    }
  }
  return letterFound;
}

function changeScore() {
  let scoreboardList = document.querySelector('ol');
  scoreboardList.removeChild(scoreboardList.childNodes[0]);
}

qwerty.addEventListener('click', (e) => {
  const button = e.target;
  const buttonText = button.textContent;
  checkLetter(buttonText);
  if (checkLetter(buttonText) == null) {
    missed += 1;
    changeScore();
    console.log(missed);
  } else {
    button.classList.add('chosen');
  }
});

 <!DOCTYPE html>

    <meta charset="utf-8">
    <title>Wheel of Success!</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="css/styles.css" rel="stylesheet">

Wheel of Success

        Start Game

Wheel of Success

          <button>q</button><button>w</button><button>e</button><button>r</button><button>t</button><button>y</button><button>u</button><button>i</button><button>o</button><button>p</button>

          <button>a</button><button>s</button><button>d</button><button>f</button><button>g</button><button>h</button><button>j</button><button>k</button><button>l</button>

          <button>z</button><button>x</button><button>c</button><button>v</button><button>b</button><button>n</button><button>m</button>

A: From what I can tell, your call to scoreboardList.removeChild(scoreboardList.childNodes[0]); will remove the first node. In your case, this is not necessarily an element, but can also be a text node containing only white space. This is probably the reason, why only every second call looks like it is doing something. The other one is removing white space. I have changed the code to explicitly remove the first "heart" node instead. And, of course, what Lewis mentioned in his comment: Don't call checkLetter twice. Just use it in the if directly.

let missed = 0;

function changeScore() {
  let scoreboardList = document.querySelector('ol');

  // !!!!!! These two lines are the important changes:
  let heart = scoreboardList.querySelector('li:first-child'); // find first heart item
  scoreboardList.removeChild(heart); // remove the heart
}

document.addEventListener('click', (e) => {
  //const button = e.target;
  //const buttonText = button.textContent;
  //if (checkLetter(buttonText) == null) {
    missed += 1;
    changeScore();
    console.log(missed);
  //} else {
  //  button.classList.add('chosen');
  //}
});

A: Just update your changeScore() method like this:
function changeScore() {
  let scoreboardList = document.querySelector('ol');

  // Replace this
  // scoreboardList.removeChild(scoreboardList.childNodes[0]);

  // By this 'EDIT'
  scoreboardList.removeChild(scoreboardList.querySelector('li:first-child'));
}

That will remove a heart each time the answer is false.


text:
Q: SailsJS MongoDB Database connection error I am new for SailsJS. I am trying to create database connection with mongo but it shows error like this
A hook (`orm`) failed to load!
error: Error: Consistency violation: A model (`sleep`) references a datastore which cannot be found (`mongo`).
If this model definition has an explicit `connection` property, check that it is spelled correctly.
If not, check your default `connection` (usually located in `config/models.js`).
Finally, check that this connection (`mongo`) is valid as per http://sailsjs.org/documentation/reference/configuration/sails-config-connections.

A: Your model is connecting to an invalid connection 'mongo'.
Check the connection either in you model 'Sleep' or in config/models.js


text:
Q: How Do I deploy an application to IIS while that web application is running Where I work, we release bug fixes in to the system every night when we know our clients are not using the system.
Trying to take a step towards better service I'd like to deploy to IIS while the application is running.
A solution that comes to mind is to setup two different IIS applications and switch them over after deploy using a script. But I'm not going to try this out as I don't want any complications during our busy hours.
Does anyone have experience in this area of deployment?
Thanks

A: Regardless of whether you're using PHP, ASP, ASP.NET etc there is no native support for  transactional deployment on IIS.
The simplest approach would be to have two physical folders and (optionally two web sites - one production, one test) on your web server, for example:

c:\websites\myapp\dep1
c:\websites\myapp\dep2

Initially your site would have its physical path pointing to c:\websites\myapp\dep1.
When you deploy your latest build you'd deploy into c:\websites\myapp\dep2. Once you're done just switch the physical path of the production site over to this folder. This means you still have the original site and can fall back to it if the new code fails for whatever reason.
The next time you do a deployment you'd deploy into c:\websites\myapp\dep1 and once you're done switch the production site to that folder.
You could optionally have a test site that points to the folder you're deploying to so you can make sure the site works before switching your production site over.
This could all be scripted.
Here's some related reading that may be of interest:

Publishing/uploading new DLL to IIS: website goes down whilst uploading
Is smooth deployment possible with componentized ASP.NET MVC apps?

Rob Conery also had an excellent blog post about the lack of a decent deployment story for ASP.NET application. You should take a trawl through the comments some of which are quite insightful:

ASP.NET Deployment Needs To Be Fixed
Getting Constructive On ASP.NET Deployment


text:
Q: Assign a pattern to the whole page but reveal it only on some shapes, the rest should be black I would like to create a web page where the background is flat black but I need to add also a background pattern that should be visible only inside some shapes (circles in this simple example, but they will be a complicated path, different for each section).
I know I could assign the pattern to the shapes, but I need also to animate the shapes and is not possible to animate the pattern.
Here my starting code
I applied a texture in CSS to the entire page and I add some circles.
Now I need to "hide" the texture everywhere except inside the shapes. And the page background should be black.
How can I do that?

A: Is this the sort of thing you are after?

/* hide the SVG */
svg#pattern {
  position: absolute;
  left: -9999px;
}

body {
  background-color: black;
  height: 2000px;
  color: white;
}

section {
  height: 400px;
}

circle {
  animation: throb 1s infinite;
}

@keyframes throb {
  0% { r: 48px; }
  50% { r: 30px; }
  100% { r: 48px; }
}
<svg id="pattern">
  <defs>
    <pattern id="check" width="10" height="10" patternUnits="userSpaceOnUse">
      <rect width="10" height="10" fill="linen"/>
      <rect width="5" height="5" fill="black"/>
      <rect x="5" y="5" width="5" height="5" fill="black"/>
    </pattern>
  </defs>
</svg>

Test page

    <svg width="400" height="100">
      <circle cx="50" cy="50" r="48" fill="url(#check)"/>
    </svg>

    <svg width="400" height="100">
      <circle cx="50" cy="50" r="48" fill="url(#check)"/>
    </svg>

    <svg width="400" height="100">
      <circle cx="50" cy="50" r="48" fill="url(#check)"/>
    </svg>

A:

body {
    background-color: black;
}
.container {
    opacity: 0.8;
        background-image: linear-gradient(135deg, black 25%, transparent 25%), linear-gradient(225deg, black 25%, transparent 25%), linear-gradient(45deg, black 25%, transparent 25%), linear-gradient(315deg, black 25%, #e5e5f7 25%);
        background-position: 10px 0, 10px 0, 0 0, 0 0;
        background-size: 10px 10px;
        background-repeat: repeat;
        width:200px;
        height:200px;
}

<svg x="0" y="0" width="0" height="0">
    <clipPath id="test">
    <circle cx="100" cy="100" r="20" fill="red"></circle>
    </clipPath>
</svg>


text:
Q: Let $I$ be an inversion and let $C$ be a circle such that $I(C)$ is also a circle. When do $C$ and $I(C)$ have equal radii? Let $I$ be an inversion and let $C$ be a circle such that $I(C)$ is also a circle. When do $C$
and $I(C)$ have equal radii?
When it comes to inversion in a circle, I only know two cases:

*

*a circle that does not pass through the origin maps onto a circle

*a circle punctured at the origin maps onto a line that does not pass through the origin.
However, none of these cases mention anything about the radius. Does anyone have an idea?


text:
Q: IF/Else/CASE Statement in WHERE clauses I am selecting records from has a column called [tagged], and it's defaulted to Zero.
My problem is when the @tagged variable is NULL, then I want to select both 0,1 values.  This makes me think I should be doing an IF/ELSE, but my attempts are failing.
--- simple example:
declare @tagged int = NULL

SELECT *
FROM [TableName]
WHERE datecreated > '2016-01-01'
AND tagged = @tagged

Many DBAs are recommending the CASE clause.
But I need help knowing where to add it.
Do I add it inside the Query?
My feeble attempt was this:

SELECT *
FROM [TableName]
WHERE datecreated > '2016-01-01'
AND (
    CASE @tagged
    WHEN 0 THEN (tagged = 0)
    WHEN 1 THEN (tagged = 1)
    ELSE (tagged IN(0,1)
    END
)

A: Use OR condition rather than chunky CASE statement.
SELECT *
FROM   [TableName]
WHERE  datecreated > '2016-01-01'
       AND ( tagged = @tagged
              OR @tagged IS NULL )

In case you are looking to solve it using CASE then (considering there are no NULL values in tagged column)
WHERE  datecreated > '2016-01-01'
       AND tagged = CASE
                      WHEN @tagged IS NOT NULL THEN @tagged
                      ELSE tagged
                    END


text:
Q: Fragment Communication - selecting tabs and running methods in other tabs (Fragments) I have implemented a tabbed Action bar using android fragments (not from the support package).  I have a button on one of the tabs which when pressed calls a method in the parent activity using a interface.
The method in the parent activity function is to change the selected tab (fragment) and call a method in that tab.
I have an interface which allows one of the fragments to call this method in the parent activity
@Override
public void onChangeTabButtonSelected(String billingID)
{
    int position = 1;  // Selects 2nd Tab
    getActionBar().setSelectedNavigationItem(position);
        ((fragmentTabSearchClients) searchClientsTab).getClients(billingID);

}

This works fine and the tab is changed and the method is called but it appears the fragment lifecycle has not been initiated correctly has the method called getClients uses `getView()' which always returns null.
In the parent class is there a way to initialise the tab before calling a method on the tab?


text:
Q: Как получить дочерний(-ие) элемент(-ы) определенного блока?

let image=document.querySelector(".parent").children; //понятно что children возвращает NodeList[img, img, img, img].
image.addEventListener("click", function(){

alert("You clicked on image"); //Что-то неправильно, поэтому не выводится содержимое alert
});

P.S. Здесь простая ошибка думаю, просто когда изучаю сложные вещи забываются простые -_-

A:

//With using for() {}
let images = document.querySelectorAll(".parent img");
let func=function(){
alert("You clicked on image");
}
for(let i=0; i<images.length; i++){
 images[i].addEventListener("click", func);
  }

A:

// With using for of

let images = document.querySelectorAll(".parent img");
let func=function(){
alert("You clicked on image");
    }
for (let image of images)
image.addEventListener("click", func);


text:
Q: PHP nusoap how to remove array wrapper element from response I am using PHP nusoap library to create a webservice. The service returns 2 fields and an array of users and soap body is formatted as below:
<company></company>
<noOfUsers></noOfUsers>
<users>
    <user>
      .......
    </user>
    <user>
      .......
    </user>
    <user>
      .......
    </user>
</users>

How can i change this response to remove the users wrapper so that the response looks like:
<company></company>
<noOfUsers></noOfUsers>
<user>
.......
</user>
<user>
.......
</user>
<user>
.......
</user>

A: TL;DR: you can't
This is impossible because valid XML document can not have top-level nodes with same names. I bet there should be kinda hack/workaround, but I woul suggest you not to enter this territory and deal with what's being generated by default.


text:
Q: 'for' limit must be a number LUA Error So, I'm getting an error that looks like: [ERROR] addons/itemstore/lua/itemstore/lua/itemsure/vgui/container.lua:43 'for' limit must be a number
Here is container.lua
local PANEL = {}

AccessorFunc( PANEL, "ContainerID", "ContainerID" )
AccessorFunc( PANEL, "Rows", "Rows" )
AccessorFunc( PANEL, "Columns", "Columns" )

function PANEL:Init()
    self.Items = {}

    table.insert( itemstore.containers.Panels, self )
end

function PANEL:Refresh()
    local container = itemstore.containers.Get( self:GetContainerID() )
    if ( container ) then
        for i = 1, container.Size do
            if ( not self.Items[ i ] ) then
                self.Items[ i ] = self:Add( "ItemStoreSlot" )
            end

            local panel = self.Items[ i ]
            panel:SetItem( container:GetItem( i ) )
            panel:SetContainerID( self:GetContainerID() )
            panel:SetSlot( i )
            panel:InvalidateLayout()
        end

        self:InvalidateLayout()
    end
end

function PANEL:SetContainerID( containerid )
    self.ContainerID = containerid
    self:Refresh()
end

function PANEL:PerformLayout()
    self:SetSpaceX( 1 )
    self:SetSpaceY( 1 )

    local container = itemstore.containers.Get( self:GetContainerID() )
    if ( container ) then
        for i = 1, container.Size do
            local panel = self.Items[ i ]

            if ( panel ) then
                panel:SetSize( unpack( itemstore.config.SlotSize ) )
            end
        end
    end

    self.BaseClass.PerformLayout( self )
end

vgui.Register( "ItemStoreContainer", PANEL, "DIconLayout" )

Any solutions anybody can think of? I can't think of anything because to me, it should be working fine?

A: The error is pretty clear. In line 43 you have a for statement that uses container.Size as its limit, which in your case is not a number.
Solution:
use a number as the for limit. If you have to use container.Size and it comes from "outside", find out why it is not a number and what you can do about it. If you cannot make sure its a number then you cannot use it as your for limit.
So put your for loop inside an if type(container.Size) == "number" then  statement or similar.


text:
Q: PHP readdir while loop don't work cleanly I wrote a short php code that displays an image and the titke to every file in a directory. The problem is that if i run the code many files get the a  instead of an image. So for example a .zip file is in front of a .txt file. Now it will display the  of the txt file instead of the .zip image.
The code:
$file_dir = "upload/demofiles";
if ($handle = opendir($file_dir)) {
    $i = 1;
    while (false !== ($entry = readdir($handle))) {
    $format = pathinfo($entry, PATHINFO_EXTENSION);
    $file_path = $file_dir.'/'.$entry;

    if($format == "txt"){
        $myfile = fopen($file_path, "r") or die("Unable to open file!");
        $file_element = '';
    }

    if($format == "png"){
        $myfile = fopen($file_path, "r") or die("Unable to open file!");
        $file_element = '';
    }

    if($format == "zip"){
        $myfile = fopen($file_path, "r") or die("Unable to open file!");
        $file_element = '';
        fclose($myfile);
    }

    if($format == "pdf"){
        $file_element = '<embed src="'.$file_path.'" width="80px" scrolling="no" style="height:80px">';
    }

    if(!isset($file_element)){
        $file_element = '';
    }

    if ($entry != "." && $entry != "..") {
        echo '

'.$file_element.'

'.$entry.'

        ';
    }
    $i++;
    }
}

why does this happend? I think the variables should be cleared after on loop run.
Thank you!

A: Try this code:
$file_dir = "upload/demofiles";
if ($handle = opendir($file_dir)) {
    $i = 1;
    while (false !== ($entry = readdir($handle))) {
    $format = pathinfo($entry, PATHINFO_EXTENSION);
    $file_path = $file_dir.'/'.$entry;

    switch($format){
        case "txt":
            $myfile = fopen($file_path, "r") or die("Unable to open file!");
            $file_element = '';
        break;

        case "png":
            $myfile = fopen($file_path, "r") or die("Unable to open file!");
            $file_element = '';
        break;

        case "zip":
            $myfile = fopen($file_path, "r") or die("Unable to open file!");
            $file_element = '';
            fclose($myfile);
        break;

        case "pdf":
            $file_element = '<embed src="'.$file_path.'" width="80px" scrolling="no" style="height:80px">';
        break;

        default:
            $file_element = '';
        break;
    }

    if ($entry != "." && $entry != "..") {
        echo '

'.$file_element.'

'.$entry.'

        ';
    }
    $i++;
    }
}


text:
Q: PHP - Using bootstrap modal as a confirmation to delete multiple selected checkboxes I have data retrieved from database and populated inside a table. For each rows there is a checkbox where the user will be able to select multiple rows and delete it. How can I make it in such a way that when the user click the delete button after checking the checkbox on the table, a bootstrap modal will appear as a confirmation to delete those selected rows. The user will then click the confirm button on the bootstrap modal to delete the record from the database. Currently when I click the confirm button on the bootstrap modal it does not delete the record on the database.
index.php (PHP)
<?php
include_once 'configuration.php';

session_start();

$message = "";

if((isset($_SESSION['username']) == ""))
{
    header("Location: index.php");
}

$sql = "SELECT id, title FROM books";
$query = mysqli_query($db, $sql);
?>

index.php (HTML)

            <form id="booksForm" action="" method="POST">

                                <input type="checkbox" class="chkAll" value="" />
                                #
                                Title
                                Action

                            <?php
                                while($result = mysqli_fetch_array($query))
                                {
                                    $html = '

                                                    <input type="checkbox" name="chkDelete[]" value="' . $result['id'] . '">

                                                ' . $result['id'] . '
                                                ' . $result['title'] . '

                                                    Edit

';

                                    echo $html;
                                }
                            ?>

                <input type="button" id="btnDelete" value="Delete" data-toggle="modal" data-target="#confirmDelete"/>

<?php echo $message;?>

            </form>

                            <button type="button" class="close" data-dismiss="modal">×</button>
                            Delete selected data?

                            Click confirm to delete data permanently.

                            <button class="btn btn-success" id="btnConfirm">Confirm</button>
                            <button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>

deleteBooks.php (PHP)
<?php
include_once 'configuration.php';

if(isset($_POST['btnConfirm']))
{
    $checkbox = isset($_POST['chkDelete']) ? $_POST['chkDelete'] : array();

    $id = 0;

    for($i=0;$i<count($checkbox);$i++)
    {
        $id = $checkbox[$i];

        $deleteQuery = "DELETE FROM books WHERE id='$id'";
        $DeleteQueryExec = mysqli_query($db, $deleteQuery);
    }
}
?>

A: Your code is wrong here:-data: $('confirmDelete').serialize(),. It should be $("#formid").serialize(); See you do one thing first find out the checkbox array clicked values like this:-
var matches = [];
$(".className:checked").each(function() {
    matches.push(this.value);
});

As per request
Then add data: {'selChkbxs' : matches, 'btnConfirm': 1} in the place of data: $('confirmDelete').serialize(),
The ajax code:-

Then in the ajax deleteBooks.php page add this
<?php

if(empty($_POST)){

    $msg = 1;

} else {

    include_once 'configuration.php';

    if(isset($_POST['btnConfirm']))
    {
        $checkbox = isset($_POST['selChkbxs']) ? $db->real_escape_string($_POST['selChkbxs']) : null;

        $deleteQuery = "DELETE FROM books WHERE id IN ($checkbox)";
        if($DeleteQueryExec = mysqli_query($db, $deleteQuery))
        $msg = 2;
        else
        $msg = 3;

    }

}

die($msg);

?>

Post back if you find trouble


text:
Q: Knockout JS foreach data-binding with computed fields I am trying to bind a grid with 3 fields in each row using Knockout.js: net price (textbox), tax amount (label), total price (textbox).
All fields are autocaltulated as  soon as  either net or total price changes. The calc is simple: net price = total price - tax amount; total price = net price + tax amount; tax amount = taxrate (const) * net price
These bindings for a single entity is demonstrated in this fiddle: http://jsfiddle.net/ruslans/yEDRT/
But how would I do it for a whole list in anobservable array i have no idea?
TaxRate is constant for each row but can be different (it comes from source data).
Plus. all numeric fields must be formatted to 2 decimal places, hence the function. this is what I've got so far:

            Net Price
            Tax Band
            Tax Amount
            Total Price

                    <input type="checkbox" class="optionCheck" />

                <input type="hidden" class="optionTaxRate" data-bind="value: TaxRate" />

                <input type="number" min="0" max="99999999.99" step="0.01" data-bind="value: $root.formatNumber(NetPrice)" />

                <input type="number" min="0" max="99999999.99" step="0.01" data-bind="value: $root.getTotalDealerFitOptionPrice($data)" />

http://jsfiddle.net/ruslans/k7tK3/2/
have you done anything like it before? If so, could you give me pointers on how this could be achieved, please?

A: Your issue is that you are using an observable array of objects - this will get recomputed only when the size of the array changes, not the contents of the array!
What you want is an array of ko.observable.  Then your ko.computed function will be revaluated when the individual values change.  If you have a dynamic list of items to sum, then use an observable array of observables.
Hope that helps!


text:
Q: How to put ownCloud behind Nginx with Docker? I want to access an ownCloud instance trough Nginx both set up inside separate Docker containers. So I've made docker-compose.yml:

nginx:
  image: nginx
  ports:
    - 80:80
  volumes:
    - ./nginx.conf:/etc/nginx/nginx.conf
  links:
    - owncloud
owncloud:
  image: owncloud
  ports:
    - 6789:80
  volumes:
    - ~/ownCloud:/var/www/html/data

And nginx.conf to proxify requests with following contents:

http {
  server {
    listen 80 default;
    server_name docker.dev;

    location / {
      proxy_pass http://127.0.0.1:6789;
      proxy_buffering off;
      proxy_set_header Host $host;
      proxy_set_header X-Real-IP $remote_addr;
    }
  }
}
events {}

Seems right to me, but Nginx logs out such message:
[error] 6#6: *8 connect() failed (111: Connection refused) while connecting to upstream, client: 192.168.99.1, server: docker.dev
What am I doing wrong?

A: The problem is that inside the nginx container, 127.0.0.1:6789 will not map to owncloud. This is because, docker is only mapping port 80 on owncloud port 6789 on the host machine.
Imagine each container as well as the docker host is a completely separate machine. In this case the nginx machine sends a request to 127.0.0.1 which is just itself, not the host machine, not the owncloud machine.
There are many ways to communicate between docker containers and you are already using one of them, docker compose's built in linking system.
In your docker-compose.yml you have already linked owncloud to nginx, which is correct. What this does is edit the nginx containers /etc/hosts file to map owncloud the owncloud container's ip address. (You can check it out by running docker exec name_of_nginx_container cat /etc/hosts). What this means is, inside the nginx container http://owncloud maps to port 80 on the owncloud comtainer.
With that in mind, this is a full configuration that works with docker compose's linking system.
docker-compose.yml
nginx:
  image: nginx
  ports:
    - 80:80
  volumes:
    - ./nginx.conf:/etc/nginx/nginx.conf
  links:
    - owncloud
owncloud:
  image: owncloud
  expose:
    - 80
  volumes:
    - ~/ownCloud:/var/www/html/data

nginx.conf
http {
  server {
    listen 80 default;
    server_name docker.dev;

    location / {
      proxy_pass http://owncloud;
      proxy_buffering off;
      proxy_set_header Host $host;
      proxy_set_header X-Real-IP $remote_addr;
    }
  }
}
events {}

The only differences are that you only need to expose port 80 on the owncloud image, not map it to the host and the proxy_pass line in nginx.conf.
Hope that helps.


text:
Q: Best way to join and handle multiple attributes related to the same feature this is not going to be a question, I'm just trying to find some advice.
Suppose I have a point shapefile (for example just two points, actually I have many more points) representing water control stations. The attribute table looks like:
ID    X        Y          Cl       Na
A    3480240   5887204   125.70   60.30
B    3480450   5887280   230.30   120.80

Now, how can I join another table that contains repeated measures of Cl and Na for each ID? This could be the example of the other table (measures in different years) I want to join:
ID    Cl       Na      Year
A    100.30   210.20   2010
A    120.40   200.30   2011
A    130.40   198.20   2012
B    101.00   199.20   2009
B    130.40   210.40   2010
B    140.60   210.00   2011
B    166.90   240.20   2012

I have tried both the QGIS standard join option and the mmqgis plugin (join from csv file) but the results are not as expected.
QGIS join option adds some columns to each ID, but many fields have "NULL" attributes while mmqgis increased the number of rows for each ID and each field contains the same value (e.g. Cl values are always 120.20 for each year).
So I would just like to know if anybody has worked with this kind of data in order to understand the best way to handle multi-attribute field related to one single feature?

A: SQL approach
Following the comment by Alexandre Neto, a combined table can be obtained using DB Manager:
SELECT ID, Na, Cl, Year_1  FROM my_table
UNION ALL
SELECT ID, Na, Cl, null AS Year_1 FROM my_points

*

*my_table: table without XY

*my_points: XY points shapefile

(Note) I changed field "Year" of my_table to "Year_1" just to avoid any unforeseen troubles. "Year" could be ok.

To link the above table with the XY locations, above query is modified like:
SELECT combined.ID, combined.Na, combined.Cl, combined.Year_1, my_points.geometry
FROM(
    SELECT ID, Na, Cl, Year_1  FROM my_table
    UNION ALL
    SELECT ID, Na, Cl, null AS Year_1 FROM my_points
    ) AS combined
CROSS JOIN my_points
ON combined.ID = my_points.ID

When we use identify features tool at the Point A or B, it will return these records from the combined table.


text:
Q: Why is this android app crashing on the emulator? I have been attempting to run this application from this repository
https://github.com/tekinarslan/AndroidMaterialDesignToolbar
But each time it crashes with the following message
    07-26 11:36:39.864    4405-4405/com.tekinarslan.material.sample E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.tekinarslan.material.sample/com.tekinarslan.material.sample.SampleActivity}: java.lang.IllegalArgumentException: AppCompat does not support the current theme features
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
        at android.app.ActivityThread.access$600(ActivityThread.java:130)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:137)
        at android.app.ActivityThread.main(ActivityThread.java:4745)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
        at dalvik.system.NativeStart.main(Native Method)
 Caused by: java.lang.IllegalArgumentException: AppCompat does not support the current theme features
        at android.support.v7.app.AppCompatDelegateImplV7.ensureSubDecor(AppCompatDelegateImplV7.java:360)
        at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:246)
        at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:106)
        at com.tekinarslan.material.sample.SampleActivity.onCreate(SampleActivity.java:36)
        at android.app.Activity.performCreate(Activity.java:5008)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
        at android.app.ActivityThread.access$600(ActivityThread.java:130)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:137)
        at android.app.ActivityThread.main(ActivityThread.java:4745)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
        at dalvik.system.NativeStart.main(Native Method)

The following is the build.gradle file
apply plugin: 'com.android.application'

android {
compileSdkVersion 22
buildToolsVersion "22.0.1"

defaultConfig {
    applicationId "com.tekinarslan.material.sample"
    minSdkVersion 16
    targetSdkVersion 22
    versionCode 1
    versionName "1.2"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:support-v4:22.1.1'
compile 'com.android.support:appcompat-v7:22.1.1'

}

And this is the styles.xml file
<resources>

<style name="AppTheme" parent="AppTheme.Base"/>

<style name="AppTheme.Base" parent="Theme.AppCompat">
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="android:windowNoTitle">true</item>
    <item name="windowActionBar">false</item>
    <item name="drawerArrowStyle">@style/DrawerArrowStyle</item>

</style>

<style name="DrawerArrowStyle" parent="Widget.AppCompat.DrawerArrowToggle">
    <item name="spinBars">true</item>
    <item name="color">@android:color/white</item>
</style>
</resources>

It shows the same message even after I replace ActionBarActivity with AppCompatActivity in the SampleActivity.java file..Please help

A: Replacing android:windowNoTitle with just windowNoTitle fixes the issue.
Had similar problem and
https://blog.xamarin.com/android-tips-hello-material-design-v7-appcompat/
fixed using suggestion given in this link.
<!--If you are using revision 22.1 please use just windowNoTitle. Without android:-->
    <item name="windowNoTitle">true</item>

If your intention is to not use actionbar at all and use only toolbar, you can use Theme.AppCompat.NoActionBar as parent. (This I have tried on your git code and it works).


text:
Q: What push service do browsers use when sending push notifications between the request and the client? When using service workers to send push notifications to a user device from the Edge browser, does Edge use an Azure service as the push service to relay the message payload to the client?
I am interested in using push notifications inside a closed environment and confused on the security concerns I may need to be aware of.
Resources: Push Service Fundamentals

A: From the doc you provide, it says

Each browser can use any push service they want, it's something developers have no control over. This isn't a problem because every push service expects the same API call. Meaning you don't have to care who the push service is. You just need to make sure that your API call is valid.

So I think you don't need to care about the push services browsers using and don't need to worry about the security concerns.
But to answer your question: For the push service Edge using, I think it's Windows Push Notification Service (WNS). For other browsers, you can also refer to this article.


text:
Q: Delphi: Custom hints for Tree View Is there a fast way to create 5 custom hints for 5 SubItems of Item of Tree View?
I have TreeView, 1 Item and 5 SubItems. I need a special hint for each SubItem (for first one - "F1", second one -"F2" and so on).
I can not apply this to my purpose: http://delphi.about.com/od/vclusing/a/treenode_hint.htm?

A: It sounds like you just want the OnHint event:
procedure TMyForm.TreeView1Hint(Sender: TObject; const Node: TTreeNode; var Hint: string);
begin
  Hint := Node.Text;
end;

Sometimes this method can be a bit crude and offer up a Node that you aren't obviously hovering over.  If you want more control you can use GetNodeAt and GetHitTestInfoAt:
procedure TMyForm.TreeView1Hint(Sender: TObject; const Node: TTreeNode; var Hint: string);
var
  P: TPoint;
  MyNode: TTreeNode;
  HitTestInfo: THitTests;
begin
  P := TreeView1.ScreenToClient(Mouse.CursorPos);
  MyNode := TreeView1.GetNodeAt(P.X, P.Y);
  HitTestInfo := TreeView1.GetHitTestInfoAt(P.X, P.Y) ;
  if htOnItem in HitTestInfo then begin
    Hint := MyNode.Text;
  end else begin
    Hint := '';
  end;
end;

The definition of THitTests is as follows:
type
  THitTest = (htAbove, htBelow, htNowhere, htOnItem, htOnButton, htOnIcon,
    htOnIndent, htOnLabel, htOnRight, htOnStateIcon, htToLeft, htToRight);
  THitTests = set of THitTest;

As you can see this gives you a lot of fine grained control over when and what you show as a hint.

A: I would set the hint of the component in response to OnMouseMove (or that other event that gives you mouse coordinates, from which you can get the item the mouse is over - I might have mistaken the name and at the moment I have no Delphi with me).


text:
Q: SSE implementation in Spring REST Can anybody provide an example for SSE ( Server sent events) using Spring Rest ?  Basically i have a request and the response for it would be sent by the server in multiple chunks.  I would like to have the server and client implementation in Spring REST Api without third party rest api like jersey.

A: There isn't any direct support for SSE in Spring currently but it looks like it will be available in 4.2 which is in RC2 right now
You can see the details here
https://jira.spring.io/browse/SPR-12212
This works via returning an SseEmitter or a ResponseBodyEmitter from the controller methods.
@RequestMapping(value="/stream", method=RequestMethod.GET)
public ResponseBodyEmitter handle() {
        ResponseBodyEmitter emitter = new ResponseBodyEmitter();
        // Pass the emitter to another component...
        return emitter;
}

// in another thread
emitter.send(foo1);

// and again
emitter.send(foo2);

// and done
emitter.complete();

You can see the Reference documentation here
http://docs.spring.io/spring/docs/4.2.0.RC2/spring-framework-reference/htmlsingle/#mvc-ann-async-http-streaming


text:
Q: My django admin page gives Page not found (404) my project was running ok I used my admin page at it was all all right today I tried to open it and it gives a Page not found (404)
No Product matches the given query.
Request Method: GET
Request URL:    http://127.0.0.1:8000/admin
Raised by:  store.views.product_detail
No Product matches the given query.
Request Method: GET
Request URL:    http://127.0.0.1:8000/admin
Raised by:  store.views.product_detail
I havent touched the store app or project files at all at it was waking just fine yesterday now i cannot access admin page
project urls
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('admin/', admin.site.urls),

    path('', include('store.urls', namespace='store')),
    path('basket/', include('basket.urls', namespace='basket')),
    path('account/', include('account.urls', namespace = 'account')),
]

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

store urls
from django.urls import path

from . import views

app_name = 'store'

urlpatterns = [
    path('', views.product_all, name='product_all'),
    path('<slug:slug>', views.product_detail, name='product_detail'),
    path('shop/<slug:category_slug>/', views.category_list, name='category_list'),
]

store views
from urllib import request
from django.shortcuts import get_object_or_404, render

from store.context_processors import categories

from .models import Category, Product

def product_all(request):
    products = Product.products.all()
    return render(request, 'store/home.html', {'products': products})

def category_list(request, category_slug=None):
    category = get_object_or_404(Category, slug=category_slug)
    products = Product.objects.filter(category=category)
    return render(request, 'store/products/category.html', {'category': category, 'products': products})

def product_detail(request, slug):
    product = get_object_or_404(Product, slug=slug, in_stock=True)
    return render(request, 'store/products/single.html', {'product': product})  ```

context_processors.py wicht i have includet in my project settings
from .models import Category

def categories(request):
return {
'categories': Category.objects.all()
}

A: This is the code that causes the error
path('<slug:slug>', views.product_detail, name='product_detail'),

Change it to
path('detail/<slug:slug>/', views.product_detail, name='product_detail'),

The product_detail just overwrites the admin URL


text:
Q: How to extract the output of model? I have to submit my predictions (each of them is one of 2289 classes!). But, I don't know how to do this. Help me!!
Model looks like this
:
model = Sequential()
model.add(Conv2D(32, kernel_size = (3, 3), input_shape=(32,64,1), activation = 'relu'))
model.add(Conv2D(64, (3,3), activation='relu'))
model.add(MaxPooling2D(pool_size=2))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(2000, activation = 'relu'))
model.add(Dropout(0.6))
model.add(Dense(2289, activation='softmax'))
model.summary()
model.compile(loss = 'sparse_categorical_crossentropy', optimizer = 'adam', metrics = ['accuracy'])

and i used fit function
history = model.fit(trainimage,trainlabel, validation_data=(validimage,validlabel), epochs=10, batch_size=200)

What I wanna know is how to extract the predictions of given test images
# Indexing of predictions
argpreds = np.argmax(history)

# Load label dictionary
with open('./drive/My Drive/Colab Notebooks/CoE202_KakaoArena/y_vocab.pickle', 'rb') as f:
    y_dict = pickle.load(f)

# Inverse label dictionary
inv_y_dict = dict((y,x) for x,y in y_dict.items())
submissions = [inv_y_dict[argpred] for argpred in argpreds]

# Write the results to 'submissions.csv'
f = open('./drive/My Drive/Colab Notebooks/CoE202_KakaoArena/submissions.csv', 'w')
for i, j in zip(pids, submissions):
    line = '{},{}\n'.format(i,j)
    f.write(line)
f.close()

This is a modification of my TA's code. But I got an error "TypeError: 'numpy.int64' object is not iterable"
Thanks for helping me

A: Generally the error object is not iterable occurs when you are using a variable like a list. So its only single dimensional data type like an int mot a list.


text:
Q: Java 6 applications are prevented from being deployed to Google App Engine from any version of the SDK When i tried to deploy the Java 6 application in App engine. I got error like
Java 6 applications are prevented from being deployed to Google App Engine from any
version of the SDK, including older ones. If you need to continue to deploy Java 6
applications for compatibility reasons, you can request that your application be
whitelisted for Java 6 deployment by visiting link.

Then i changed java version 1.7 in project settings. Even after, app engine deployment throw same error.
How to fix this issue.

A: I finally fix this issue by installing Eclipse 4.3 Kepler and App Engine SDK 1.9.2.
Install Latest Eclipse 4.3
https://www.eclipse.org/downloads/
Install Latest Google Eclipse Plugin
https://developers.google.com/eclipse/docs/getting_started

A: Create a new small Java 7 project that deploys and runs successfully.  Copy your existing application content into the new project.  Rename the old project to use it as an archive.  Rename the new project to use the original project name and application id.

A: If you use Eclipse, check at Preferences>Java>Compiler. The JDK Compliance is (on my laptop) not updated to the version 1.7


text:
Q: Git persistent branch with all but one commit Normally, if I had done some work on a feature but will not be able to deploy it to master until some indefinite future time, I'd just put it in a branch and occasionally rebase that branch to the latest changes to master.
Today, I have a situation that does not quite match that common case:
I made a change to master a while back, now deep in the history. I've now decided that this change is not appropriate, so I will undo it at in master. However, I do want to save this code in a branch, because it may be relevant someday.

A: As I wrote this question, the answer became obvious.  (Stack Overflow as the ultimate rubber duck debugger?)
I just need to:

*

*Undo the feature in a new commit in master

*Create the new branch

*In the new branch, git revert the commit that undid the feature

*In the future, rebase the branch on to master as needed


text:
Q: I am having trouble with running a jar file I try to run a java program with the following script:
#!/usr/bin/env bash

java -cp dl.jar Elevator

Elevator is the main class. But I get an error every time.
Error: Could not find or load main class Elevator
Caused by: java.lang.ClassNotFoundException: Elevator

My classes are all in the .jar file under the directory src/hw4. I have tried adding src/hw4 to the classpath, but to no avail.

A: You should not use direct class name. You have to use the full package.
If in your IDE you wrote for exammple: package hw4; and you want to run the class Elevator, use this :
java -cp dl.jar hw4.Elevator

It seems to correspond to your jar file.
The src folder is not on the class path. It's just a directory in your IDE to order all files as project files and project content.


text:
Q: I can not get ipython notebook working. Ubuntu 12.04 I installed ipython notebook using their instructions. That didn't work. So i tried other instructions. I seemed to get closer to getting it working. currently this is the output i get when i try to run ipnotebook.
    Traceback (most recent call last):
  File "/usr/local/bin/ipython", line 9, in <module>
    load_entry_point('ipython==1.1.0', 'console_scripts', 'ipython')()
  File "/usr/local/lib/python2.7/dist-packages/ipython-1.1.0-py2.7.egg/IPython/__init__.py", line 118, in start_ipython
    return launch_new_instance(argv=argv, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/ipython-1.1.0-py2.7.egg/IPython/config/application.py", line 544, in launch_instance
    app.initialize(argv)
  File "<string>", line 2, in initialize
  File "/usr/local/lib/python2.7/dist-packages/ipython-1.1.0-py2.7.egg/IPython/config/application.py", line 89, in catch_config_error
    return method(app, *args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/ipython-1.1.0-py2.7.egg/IPython/terminal/ipapp.py", line 312, in initialize
    super(TerminalIPythonApp, self).initialize(argv)
  File "<string>", line 2, in initialize
  File "/usr/local/lib/python2.7/dist-packages/ipython-1.1.0-py2.7.egg/IPython/config/application.py", line 89, in catch_config_error
    return method(app, *args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/ipython-1.1.0-py2.7.egg/IPython/core/application.py", line 362, in initialize
    self.parse_command_line(argv)
  File "/usr/local/lib/python2.7/dist-packages/ipython-1.1.0-py2.7.egg/IPython/terminal/ipapp.py", line 307, in parse_command_line
    return super(TerminalIPythonApp, self).parse_command_line(argv)
  File "<string>", line 2, in parse_command_line
  File "/usr/local/lib/python2.7/dist-packages/ipython-1.1.0-py2.7.egg/IPython/config/application.py", line 89, in catch_config_error
    return method(app, *args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/ipython-1.1.0-py2.7.egg/IPython/config/application.py", line 474, in parse_command_line
    return self.initialize_subcommand(subc, subargv)
  File "<string>", line 2, in initialize_subcommand
  File "/usr/local/lib/python2.7/dist-packages/ipython-1.1.0-py2.7.egg/IPython/config/application.py", line 89, in catch_config_error
    return method(app, *args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/ipython-1.1.0-py2.7.egg/IPython/config/application.py", line 405, in initialize_subcommand
    subapp = import_item(subapp)
  File "/usr/local/lib/python2.7/dist-packages/ipython-1.1.0-py2.7.egg/IPython/utils/importstring.py", line 42, in import_item
    module = __import__(package, fromlist=[obj])
  File "/usr/local/lib/python2.7/dist-packages/ipython-1.1.0-py2.7.egg/IPython/html/notebookapp.py", line 38, in <module>
    from jinja2 import Environment, FileSystemLoader
ImportError: No module named jinja2

A: In order to load Jinja locally you also have to have it installed locally
easy_install Jinja2

or
pip install Jinja2

or
sudo apt-get install python-jinja2