text:
Q: What is the difference between -> and :: in Perl What is the exact difference between :: and -> in Perl?
-> sometimes works where :: does not.

A: When the right hand side is a function -> passes its left hand side as the first argument to the function. So the following examples are equivalent if $foo is an object blessed to package Foo and Bar is in package Foo. -> will resolve inherited methods making it cleaner and more useful for objects.
$foo->Bar();

Foo::Bar($foo);

-> can also take a package name
Foo->Bar();

Foo::Bar('Foo');

This means that -> is generally used in instance methods so that the object is passed its self and constructors so the constructors know which package to bless with. This is usually a parameter so it can be inherited.

A: :: has two uses.

*

*It's the namespace separator in package names
use Foo::Bar;    # Load Foo/Bar.pm
$Foo::Bar::var   # $var in namespace Foo::Bar

*Appended to a bareword, it creates a string literal[1].
The following is the same as 'hello' except it warns if the package hello doesn't exist:
hello::

-> has two uses.

*

*It's used to dereference.
$array_ref->[$i]
$hash_ref->{$k}
$code_ref->(@args)

*It's used in method calls to denote the invocant.
CGI->new()        # Static method call
$cgi->param()     # Object method call

You're probably asking what's the difference between
Foo::Bar::mysub()

and
Foo::Bar->mysub()

The former is a function call. The latter is a method call. A method call is like a function call with two differences:

*

*Method calls use inheritance.

*Method calls pass the invocant (what's left of the ->) to the sub as its first argument.

{
   package Foo::Baz;
   sub new {
      my ($class, $arg) = @_;
      my $self = bless({}, $class);
      $self->{arg} = $arg;
      return $self;
   }

   sub mysub1 {
      my ($self) = @_;
      print($self->{arg}, "\n");
   }
}

{
   package Foo::Bar;
   our @ISA = 'Foo::Baz';
   sub mysub2 {
      my ($self) = @_;
      print(uc($self->{arg}), "\n");
   }
}

my $o = Foo::Bar->new('hi');  # Same as: my $o = Foo::Baz::new('Foo::Bar', 'hi');
$o->mysub1();                 # Same as: Foo::Baz::mysub1($o);
$o->mysub2();                 # Same as: Foo::Bar::mysub2($o);

Notes

*

*Foo->method deceptively calls the sub named Foo if it exists (using its the value it returns as the invocant). Foo::->method, meaning 'Foo'->method, doesn't.

A: Lots of explanations here, but here is the very simplistic answer for new developers:
FOO::BAR();  # is calling the class's (aka. package's) default object
$FOO->BAR(); # is calling an initiated object

An object typically has properties that are often set, where as an uninitiated object uses the default object properties only.
Say FOO has a property called 'Age' that has a default value of 1 that we can change via a set command earlier in our program. Then we decide to call the package again both ways for fun we could see:
use FOO;
$FOO = new FOO(); #new instance of foo
$FOO->SetAge(21);

# more code here

print $FOO->GetAge(); # prints 21
print FOO::GetAge(); # prints 1

What about packages without any stored variables? In many cases there may be no difference at all, but this ultimately depends on how the class is written. In the end it is more complex than that.. and this isn't truly the exact answer, but it is what I believe you are looking for based on your question.
Just to prevent confusion generally I do not use the classes/packages name when creating an object. If for some reason I don't know what to call it I prefix it with an 'o' so it is clear it is an object and not a class, which is a good practice for any programing language.
i.e. use
$oFOO = new FOO(); // new object instance of foo

Hope that helps.


text:
Q: Onclick functions in a while loop I have x amount of elements with id "accordion_toggle__1" -> "accordion_toggle__x". I wanted to try to put an onclick function on each of them that would toggle the class "accordion__hidden" in the corresponding elements with ids "accordion__1" -> "accordion__x".
Here is the code that i tried to use:
let x=1;

while(!!document.getElementById("accordion_toggle__"+x)){
        document.getElementById("accordion_toggle__"+x).onclick = function(){
            document.getElementById("accordion__"+x).classList.toggle("accordion__hidden");
        }
        x++;
}

It doesn't seem to work. I think when e.g. I have 4 accordion_toggles, they all try to toggle the classlist of the unexisting "accordion__5". How can I solve this?

A: The x will always point to last(5) because that is global var.
For this case, just change to:
let x = 1;

while (!!document.getElementById("accordion_toggle__" + x)) {
    const n = x;
    document.getElementById("accordion_toggle__" + x).onclick =

    function() {
        document.getElementById("accordion__" + n).classList.toggle("accordion__hidden");
    }
    x++;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: tbselenium tor browser unable to get url on ubuntu I am trying to use Tor browser with selenium and python on ubuntu. Browser is opening but showing proxy error.
Here is code I am trying:
from time import sleep
from tbselenium.tbdriver import TorBrowserDriver

driver = TorBrowserDriver("/tor/tor-browser-linux32-8.0.3_en-US/tor-browser_en-US/")
driver.get('https://www.whatismyip.com/')

Exception got in the terminal is-
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: Reached error page: about:neterror?e=proxyConnectFailure&u=https%3A//www.whatismyip.com/&c=UTF-8&f=regular&d=Firefox%20is%20configured%20to%20use%20a%20proxy%20server%20that%20is%20refusing%20connections.

Message shown on tor browser is:
https://pasteboard.co/HKYjivJ.png


text:
Q: Disable background transparency in (neo)vim I'm running Neovim 0.2.1 in Konsole with i3 and Compton in the back. I'm using a little bit of transparency in Konsole for a more dapper experience, but given that I use vim as my primary editor I'd prefer to not have transparency there as it's a little bit distracting. My colour scheme is vim-monokai.
What's really got me scratching my head is that I have two computers, both running virtually the same setup (Intel integrated graphics, i3, Compton, Konsole, zsh, same neovim version and plugins). One does not have transparency in its terminal, while the other does.

A: For vim:
highlight Normal ctermbg=Black
highlight NonText ctermbg=Black

Your colorschema most likely does not set ctermbg. Replace "Black" with the desired background color.


text:
Q: Can't define a div outside parent div The project I have been working on has an HTML file that looks like this:

                <input type="search" ng-model="spsearch" id="spsearch" placeholder="Search Providers" name="spsearch">

I want to move spnsearch independently of the parent div, hence, wrote it outside the parent div, as:

            <input type="search" ng-model="spsearch" id="spsearch" placeholder="Search Providers" name="spsearch">

   .............
   ............

When I inspect the page in the browser, no change takes places. That is, spn-service-provider-list still contains the search box. Can someone please explain to me why is this happening? I am a beginner with UI development, so please bear with me if the question is elementary. Thanks!


text:
Q: Decide Trustworthiness Of Statements About Probabilities This is maybe a trivial question, but I don't know the answer right now.  Assume you have $n$ coins, each with probability $P_i$ of landing on head.  You don't know the probabilities, but there are $m$ agents $A^j$ who claim that the $i$th coin lands on head with probability $P^j_i$.  You are only allowed to toss each coin exactly once.  Assume you want to somehow decide how trustworthy the agents are.  Which scoring function $s:2^n\times[0,1]^n\to\mathbf{R}$ (input tossing result and claimed probabilities, output score) would you use?
Some properties I imagine the scoring function should have:

*

*$E(s(-,(P'_i)_i))<E(s(-,(P_i)_i))$ for $(P'_i)_i\neq (P_i)_i$

*$P(s(-,(P'_i)_i)<s(-,(P_i)_i))>0.5$ for $(P'_i)_i\neq (P_i)_i$
First thing which comes to mind is computing the probability that the observed tosses occur under the given probability distribution.


text:
Q: jQuery clone() an element with children and saving to data() as backup? There is something wrong in my jQuery plugin. I can't post the whole script because it would be too big, this is a little and modified excerpt. Basically it works this way:

*

*An ajax call, if result set is empty then backup the element and it's content (if there is no already backup defined) and the override it's content

*If result set contains data look for certain elements inside it and use .html() to display the data

But there is somehting wrong in the above. When the call is executed 3 consecutive times children of the backup is sadly empty!
Any help is much appreciated. Here is a simplified version of the control flow:
var backup = function() { this.data('backup', this.clone(true)); }

var onObjectProperty = function(obj) {

   // This is where my script fail!!! 3 consecutive times of empty data,
   // and children() contains no data!
   if($.type(this.data('backup')) !== 'undefined')
      console.log(this.data('backup').children());

    };

if(!val.error && !val.count) // Not an error, but data is empty
{
   // Keyword "this" is the current element in selection loop (on which
   // the plugin was invoked)
   if($.type(context.data('backup')) === 'undefined')
      backup.call(this); // Backup if not already defined

   opt.onEmpty.call(context); // Call the function to handle empty data
   return true; // Skip the current iteration in the loop
}

// Here we have no errors and result set contains data
onObjectProperty.call(this, obj); // Pass the context and the data

EDIT: found the error, was not cloning the backup before adding it to the DOM!

A: What's with the parentheses on the second if-$.type line? =)
Ok got it. Not sure how to read all these "obj", "context" and "val", how they fit in, but for what it's worth I managed to get backups to/fro data going, see below.
Cool idea anyway!

helu

        there
        <input></input>

    <button onclick="doit($('#xxx'));">do</button>
    <button onclick="dumpit($('#xxx'));">see</button>
    <button onclick="addit($('#xxx'));">add</button>


text:
Q: How to implement Oracle's "func(...) keep (dense_rank ...)" In Hive I have a table abcd in Oracle DB
  +-------------+----------+
  | abcd.speed  | abcd.ab  |
  +-------------+----------+
  | 4.0         | 2        |
  | 4.0         | 2        |
  | 7.0         | 2        |
  | 7.0         | 2        |
  | 8.0         | 1        |
  +-------------+----------+

And I'm using a query like this:
select min(speed) keep (dense_rank last order by abcd.ab NULLS FIRST) MOD from abcd;

I'm trying to convert the code to Hive, but it looks like keep is not available in Hive.
Could you suggest an equivalent statement?

A: select  -max(struct(ab,-speed)).col2 as mod
from    abcd
;

+------+
| mod  |
+------+
| 4.0  |
+------+

Let start by explaining min(speed) keep (dense_rank last order by abcd.ab NULLS FIRST):
Find the row(s) with the max value of ab.
For this/those row(s), find the min value of speed.
We are using 2 tricks here.
The 1st is based on the ability to get the max value of a struct.
max(struct(c1,c2,c3,...)) returns the same result as if you have sorted the structs by c1, then by c2, then by c3 etc. and then chose the last element.
The 2nd trick is to use -speed (which is the same of -1*speed).
Finding the max of -speed and then taking the minus of that value (which gives us speed), is the same of finding the min of speed.
If we would have ordered the structs, it would have looked like this (since 2 is bigger than 1 and -4 is bigger than -7):
+----+-------+
| ab | speed |
+----+-------+
|  1 |  -8.0 |
|  2 |  -7.0 |
|  2 |  -7.0 |
|  2 |  -4.0 |
|  2 |  -4.0 |
+----+-------+

The last struct in this case in struct(2,-4.0), therefore this is the result of the max function.
The fields names for a struct are col1, col2, col3 etc., so
struct(2,-4.0).col2 is -4.0. and preceding it with minus (which is the same as multiple it by -1) as in -struct(2,-4.0).col2 is 4.0.


text:
Q: Creating enum from variadic arguments? In some other langauges you can specify enums along with states, eg.:
public enum Planet {
    MERCURY (3.303e+23, 2.4397e6),
    VENUS   (4.869e+24, 6.0518e6),
    EARTH   (5.976e+24, 6.37814e6),
    MARS    (6.421e+23, 3.3972e6),
    JUPITER (1.9e+27,   7.1492e7),
    SATURN  (5.688e+26, 6.0268e7),
    URANUS  (8.686e+25, 2.5559e7),
    NEPTUNE (1.024e+26, 2.4746e7);
   ...

This isn't hard to emulate in c++ - but only it easily becomes somewhat verbose.
I know this has been asked before and similar questions exists, e.g. in Build an enum using variadic template parameters, but I wanted to ask this again and have slightly different perspective.
Consider the following 'hand-written' approach:
#pragma warning(error : 4062)

enum tvtype {
    black_and_white,
    color
};

struct TvType {
    tvtype tvtype_;
    constexpr TvType(tvtype type) : tvtype_{type} {

    }
    constexpr operator tvtype() const {
        return tvtype_;
    }
};

constexpr TvType BlackAndWhite(black_and_white);
constexpr TvType Color(color);

bool hasColor(TvType tv) {
    switch (tv) {
        case BlackAndWhite:
        return false;
        //case Color:
        //return true;
    };

    return false;
}

Try it yourself (comment in the two lines in the switch to make it compile)
This method is working well - only it is somewhat verbose.
Using this method it should now be possible to store some extra information along with the enum value, like a string representation, perhaps adding functions as well, etc.
Also because it's actually an enum underneath, it's possible for the compiler to check that all cases have been checked in the switch (the example above should generates a compile error due that the 'color' case is outcommented).
I'm interested in a generic / templated way of getting the enum generated or something similar that fulfills the requirement of compiler checked switch and extensibility.
But in order to templatize the above, it seems the enum should be generated in a (compile-time) programatical way, which leads to the question:
Is it possible to create an enum from a fold expression for instance or failing that from some kind of recursive template ?

A:
Is it possible to create an enum from a fold expression for instance or failing that from some kind of recursive template ?

Not with variadic templates. Template arguments can be types, or constant values. You can't substitute a symbol to stick it inside an enum block.
However, you can do that with macros. Only trouble is, while C++11 has something called "variadic macros", it's very limited.
#define MY_MACRO(...) enum { __VA_ARGS__ }

You can't do any kind of transformation on variadic arguments like you can with templates, it literally just replaces __VA_ARGS___ with all the tokens the ... represents.
But, using the technique from this great answer: https://stackoverflow.com/a/11763277/1863938 , you can support "up to N" variadic solutions. Using that, you can create a macro that templates your boilerplate class for up to N values. Below is for up to 4 symbols:
#define _JENUM_GET_MACRO(_1,_2,_3,_4,NAME,...) NAME

#define _JENUM_VALUE_DEF1(_1) _##_1##_v_
#define _JENUM_VALUE_DEF2(_1,_2) _JENUM_VALUE_DEF1(_1), _JENUM_VALUE_DEF1(_2)
#define _JENUM_VALUE_DEF3(_1,_2,_3) _JENUM_VALUE_DEF1(_1), _JENUM_VALUE_DEF1(_2), _JENUM_VALUE_DEF1(3)
#define _JENUM_VALUE_DEF4(_1,_2,_3,_4) _JENUM_VALUE_DEF1(_1), _JENUM_VALUE_DEF1(_2), _JENUM_VALUE_DEF1(3), _JENUM_VALUE_DEF1(_4)
#define _JENUM_VALUE_DEF(...) _JENUM_GET_MACRO(__VA_ARGS__, _JENUM_VALUE_DEF4, _JENUM_VALUE_DEF3, _JENUM_VALUE_DEF2, _JENUM_VALUE_DEF1)(__VA_ARGS__)
#define _JENUM_ENUM_DEF(name, ...) enum _##name##_e_ { _JENUM_VALUE_DEF(__VA_ARGS__) };

#define _JENUM_CLASS_DEF(name) struct name {\
    _##name##_e_ _value;\
    constexpr name(const name& that) : _value(that._value) { }\
    constexpr name(_##name##_e_ _value) : _value(_value) { }\
    constexpr operator _##name##_e_() const { return _value; }\
};\

#define _JENUM_CONST_DEF1(name, _1) constexpr name _1(_JENUM_VALUE_DEF1(_1));
#define _JENUM_CONST_DEF2(name, _1,_2) _JENUM_CONST_DEF1(name, _1) _JENUM_CONST_DEF1(name, _2)
#define _JENUM_CONST_DEF3(name, _1,_2,_3) _JENUM_CONST_DEF1(name, _1) _JENUM_CONST_DEF1(name, _2) _JENUM_CONST_DEF1(name, _3)
#define _JENUM_CONST_DEF4(name, _1,_2,_3,_4) _JENUM_CONST_DEF1(name, _1) _JENUM_CONST_DEF1(name, _2) _JENUM_CONST_DEF1(name, _3) _JENUM_CONST_DEF1(name, _4)
#define _JENUM_CONST_DEF(name, ...) _JENUM_GET_MACRO(__VA_ARGS__, _JENUM_CONST_DEF4, _JENUM_CONST_DEF3, _JENUM_CONST_DEF2, _JENUM_CONST_DEF1)(name, __VA_ARGS__)

#define JENUM(name, ...)\
    _JENUM_ENUM_DEF(name, __VA_ARGS__)\
    _JENUM_CLASS_DEF(name)\
    _JENUM_CONST_DEF(name, __VA_ARGS__)

... just follow the pattern to add more overloads
Then, to use:
JENUM(TvType, BlackAndWhite, Color);

Now, if you want to add methods and whatnot, it's easier to just inherit than to try and work anything into the macro:
struct TvTypeEx : public TvType {
    using TvType::TvType;
    TvTypeEx(TvType that) : TvType(that) { }
    bool hasColor() const { return *this == Color; }
};

Now you can do stuff like:
TvTypeEx tv = Color;
return tv.hasColor() ? GetColorContent() : GetBlackAndWhiteContent();

Demo: https://godbolt.org/z/rdqS65


text:
Q: Facebook scheduled page post changes ID when published I have a private website, in which I've been putting links to my Facebook page posts, in the form of:
https: // www . facebook . com / <page id> _ <post id>
However, since a few days ago, it seems like the "post id" of scheduled posts change when they become published. Hence, I cannot prepare links to my scheduled posts and put them in my website in advance.
Any help? How can I know in advance the post id (or the post link) a scheduled post will have AFTER being published in the future?


text:
Q: Not able see error or ouput when running perl script? perl output screen closed quickly that's why i'm unable to see any error msg at all. but by opening perl through cmd only can see. Is there any method to pause output screen like in batch ?..
How can I pause the console window in .pl and .bat file?

A: If you want your script to wait for user input before exiting, you can add this in anywhere in the script:
END { <STDIN> }

Using the END block will handle multiple exit points (for example dying from an error).

A: You don't state it, but I suspect you're running the script from a GUI. Open a shell window (bash or command.com) and run the script from the command line. That will keep the output around long enough to examine.

A: If you're on Windows, open CMD window first ("Start"->"Run"->"cmd.exe")
Also, you can pipe the command output to "|more" command on both Windows and Unix
If you're on some other environment, you need to explain WHERE and HOW you're executing your Perl script


text:
Q: Safari only showing one option in select element I'm creating a web site to add statistics from multiple games. The first part reads json files which contain the stats (multiple files per game) and populates an HTML select element for the user to select which games to include in the stats (allowing user to select multiple games). It's working in Chrome and Edge on my computers, but in Safari (iPhone) only one of the games shows as an option (the 4th of 5 games). Below is the function to read the files.
Why would this not be working in Safari? I'm not sure if it has to do with the await / async or something else.
jsonFiles = ['file1.json', 'file2.json', 'file3.json'];

async function readGames() {
    let games = {};
    for (let file of jsonFiles) {
        let playlist;
        let gameDate;
        let response = await fetch(file);
        let data = await response.json();
        playlist = data.playlist;
        gameDate = (new Date(playlist.slice(playlist.indexOf('(')+1, playlist.indexOf(')'))).getTime())/10000;
        if (!(gameDate in games)) games[gameDate] = playlist;
    }
    //Remove previous options in the select element
    while(gamesSelect.firstChild) {
        gamesSelect.removeChild(gamesSelect.firstChild);
    }
    const gameValues = Object.values(games);
    for (let game of gameValues) {
        let option = document.createElement('option');
        option.setAttribute("value", game);
        option.innerHTML = game;
        gamesSelect.append(option);
    }
}


text:
Q: Is there away to send Json Data from a form with Angular 8 I want to send Json data from my model variable that has all my form bindings. When I use postman the requests go through but when I do it in angular it doesn't work. I have no idea what I am doing so that it doesn't send my post request properly but I can't get it to format correctly.I keep on getting a observable when I console.log my request. I tried everything but it's not working.I think angular is adding the keyword "new" to my response body.This is a link to my live code: live
 I get this error with my spring boot application:
This application has no explicit mapping for /error, so you are seeing this as a fallback.

Sun Oct 06 12:26:12 EDT 2019
There was an unexpected error (type=Bad Request, status=400).
Failed to convert value of type 'java.lang.String' to required type 'java.lang.Integer'; nested exception is java.lang.NumberFormatException: For input string: "new"
org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'java.lang.Integer'; nested exception is java.lang.NumberFormatException: For input string: "new"
    at org.springframework.web.method.annotation.AbstractNamedValueMethodArgumentResolver.resolveArgument(AbstractNamedValueMethodArgumentResolver.java:132)
    at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:127)
    at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:167)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:134)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:892)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:797)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1039)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:897)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:118)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:92)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:118)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:118)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:118)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:526)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:860)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1587)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: java.lang.NumberFormatException: For input string: "new"
    at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.base/java.lang.Integer.parseInt(Integer.java:652)
    at java.base/java.lang.Integer.valueOf(Integer.java:983)
    at org.springframework.util.NumberUtils.parseNumber(NumberUtils.java:211)
    at org.springframework.beans.propertyeditors.CustomNumberEditor.setAsText(CustomNumberEditor.java:115)
    at org.springframework.beans.TypeConverterDelegate.doConvertTextValue(TypeConverterDelegate.java:429)
    at org.springframework.beans.TypeConverterDelegate.doConvertValue(TypeConverterDelegate.java:402)
    at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:155)
    at org.springframework.beans.TypeConverterSupport.convertIfNecessary(TypeConverterSupport.java:73)
    at org.springframework.beans.TypeConverterSupport.convertIfNecessary(TypeConverterSupport.java:53)
    at org.springframework.validation.DataBinder.convertIfNecessary(DataBinder.java:693)
    at org.springframework.web.method.annotation.AbstractNamedValueMethodArgumentResolver.resolveArgument(AbstractNamedValueMethodArgumentResolver.java:124)
    ... 51 more

home.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Newproduct } from '../model/Newproduct';
import { catchError, retry } from 'rxjs/operators';
import { HttpHeaders } from '@angular/common/http';
import { FormGroup } from '@angular/forms';
const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type':  'application/json;charset=UTF-8',
    'Transfer-Encoding':'chunked',

  })
};
@Injectable({
  providedIn: 'root'
})
// @ts-ignore
export class HomeService {

  constructor(private http: HttpClient) {
  }

  getAll(): Observable<any> {
    return this.http.get('http://localhost:8080/api/product');
  }
  getByPriceAsc():Observable<any>{
    return this.http.get('http://localhost:8080/api/product/price/up');
  }
  getByPriceDesc():Observable<any>{
    return this.http.get('http://localhost:8080/api/product/price/down');
  }
  getBySaleAsc():Observable<any>{
    return this.http.get('http://localhost:8080/api/product/sale/up');
  }
  getBySaleDesc():Observable<any>{
    return this.http.get('http://localhost:8080/api/product/sale/down');
  }

  getByDiscountAsc():Observable<any>{
    return this.http.get('http://localhost:8080/api/product/discount/up');
  }
  getByDiscountDesc():Observable<any>{
    return this.http.get('http://localhost:8080/api/product/discount/down');
  }

  getByParm(availability,category):Observable<any>{

    return this.http.get( 'http://localhost:8080/api/'+'product/category/'+ availability +'/'+ category);

  }

  addProduct(model:any):Observable<any>{
    console.log( this.http.post<any>('http://localhost:8080/api/product/new',model,httpOptions));
    return this.http.post<any>('http://localhost:8080/api/product/new',model,httpOptions);
  }

}

product-form.ts

import { Component, OnInit } from '@angular/core';
import { Product } from '../model/Product';
import { Category } from '../model/Category';
import { Supplier } from '../model/Supplier';
import { SupplierService } from '../service/Supplier.service';
import { CategoryService } from '../service/Category.service';
import { Newproduct } from '../model/Newproduct';
import { Injectable } from '@angular/core';
import { Home } from '../model/Home';
import { HomeService } from '../service/Home.service';
import { NgForm } from '@angular/forms';
import { HttpHeaders } from '@angular/common/http';

@Component({
  selector: 'app-product-form',
  templateUrl: './product-form.component.html',
  styleUrls: ['./product-form.component.css']
})
export class ProductFormComponent implements OnInit {

suppliers: Supplier[];
categories: Category[];
value: number;
model = { productName: '', category: {category: null, categoryName: null}, fullPrice: '', salePrice:'', availability: false, supplier: {supplier:null,supplierName:null},
discount:null };

json = JSON.stringify(this.model);

// model = new Newproduct(null,new Category( this.value,"name"),null,null,false,new Supplier(null,null),null);
GetSelectedValue(change){
  console.log(change);
}
GetSelectedValue1(change){
  console.log(change);
}
submitted = false;
get diagnostic() { return JSON.stringify(this.model)};

onSubmit() {
  console.log(JSON.stringify(this.model));
  this.homeService.addProduct(this.model);
 }

  constructor(private supplierService: SupplierService,private categoryService: CategoryService,private homeService: HomeService) { }

  ngOnInit() {

    this.supplierService.getAll().subscribe(data => {
      this.suppliers = data;
    });

    this.categoryService.getAll().subscribe(data => {
      this.categories = data;
    });
  }
}

I tried everything I possibly could think of switching forms structure. json.strinify to get my code to json format.  it works perfectly in postman so I think that it's a problem with my httpclient and how I am structuring the post request.


text:
Q: Laravel Octane Event Listener not firing I'm using laravel sail to run laravel octane on swoole.
I made a change to my EventServiceProvider:
<?php

namespace App\Providers;

use App\Events\SubscriptionCreated;
use App\Listeners\CreateUserTeam;
use App\Listeners\SendSubscriptionReceipt;
use App\Listeners\UpdateTeamFeatures;
use Illuminate\Auth\Events\Registered;
use Illuminate\Auth\Listeners\SendEmailVerificationNotification;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;

class EventServiceProvider extends ServiceProvider
{
    /**
     * The event listener mappings for the application.
     *
     * @var array
     */
    protected $listen = [
        Registered::class => [
            SendEmailVerificationNotification::class,
            CreateUserTeam::class
        ],
        SubscriptionCreated::class => [
            SendSubscriptionReceipt::class,
            UpdateTeamFeatures::class
        ]
    ];

    /**
     * Register any events for your application.
     *
     * @return void
     */
    public function boot()
    {
        \Log::debug("HERE", $this->listen);
    }
}

Here is my listener:
<?php

namespace App\Listeners;

use App\Models\Team;
use Illuminate\Auth\Events\Registered;

class CreateUserTeam
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        \Log::debug("HIT");
    }

    /**
     * Handle the event.
     *
     * @param  Registered  $event
     * @return void
     */
    public function handle(Registered $event)
    {
        $user = $event->user;
        $team = Team::create([
            'manager_id' => $user->id,
        ]);
        $team->createAsStripeCustomer();
        $user->update(['team_id' => $team->id]);
    }
}

No matter what I try this event listener is not being fired. I've tried clearing the cache, composer dump-autoload, php artisan optimize, reloading octane, stopping octane and starting it again. Even stopping the docker containers and starting them again. Nothing works.
It logs the list of listeners (including the CreateUserTeam listener) and it will fire the Email notification but not the other listener.
If anyone has any insight... please. I am at wits-end

A: I created same situation with you,
Added my listener like you did:
    protected $listen = [
    Registered::class => [
        SendEmailVerificationNotification::class,
        TestListener::class,
    ],
];

Used Laravel's registration test for it:
<?php

namespace Tests\Feature\Auth;

use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class RegistrationTest extends TestCase
{
    use RefreshDatabase;

    public function test_registration_screen_can_be_rendered()
    {
        $response = $this->get('/register');

        $response->assertStatus(200);
    }

    public function test_new_users_can_register()
    {
        $response = $this->post('/register', [
            'name' => 'Test User',
            'email' => 'test@example.com',
            'password' => 'password',
            'password_confirmation' => 'password',
        ]);

        $this->assertAuthenticated();
        $response->assertRedirect(RouteServiceProvider::HOME);
    }
}

Here is my test listener
<?php

namespace App\Listeners;

use Illuminate\Auth\Events\Registered;

class TestListener
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        \Log::debug("HIT");
        dump("test");
    }

    /**
     * Handle the event.
     *
     * @param  object  $event
     * @return void
     */
    public function handle(Registered $event)
    {
        $user = $event->user;

        dump($user->id);
    }
}

And run my test inside the sail:

As you can see it runs handle function inside TestListener.php
Can you remove you other code parts inside handle function and try like this? I think you may have some error in your code


text:
Q: How to calculate $\int^{\pi/4}_0 \frac{\tan^2x}{1+x^2}dx$ How do I even begin calculating: $$\int^{\pi/4}_0 \frac{\tan^2x}{1+x^2}dx\text{ ?}$$I substituted $\tan^2x=\sec^2x-1$ but that did nothing. Then I did integration by parts to get $$\frac{\tan x-x}{1+x^2}+2\int_0^{\pi/4}\frac{x^2{\tan x-x}}{1+x^2}dx$$ which is harder than the original problem. Then I found this that seems to have some potential: $$\int_0^{\pi/4}\frac{\sec^2x-\tan^2x}{1+x^2}dx=\arctan\frac{\pi}{4}$$I have a feeling that this is the key, but I don't know what to do next. Also I tried to put the integral into a calculator which failed to calculate the exact answer (it approximated it to be $0.15$).
P.S. The problem can be found in page $4$ that has two infinite series on the top and bottom.


text:
Q: How can I read from stdin with this specific command? I'm very new to C and I like to know what my program needs so it is able to read from a given test.stdin file, when this command is written to the console:
cat test.stdin | ./myprogram | tee myoutput.stdout

?
So I guess the test.stdin is some file on the computer which feeds my program with data/input, then my program is doing something with that data and writes the result into the file myoutput.stdout which is also somewhere on my computer.
What do I need in my program so the command above is working? I need to do some calculations with the data in stdin, but I don't know how to begin, how to read like that and make the command work for my program.

A: In C, reading from "standard input", or stdin, is the default.  It's the easiest thing there is.  You don't have to explicitly open anything; stdin is always opened for you (along with stdout and stderr) before your main function even gets called.
You can read from stdin with a variety of standard library functions.  The most common are getchar and scanf.  And, to repeat: you can just start calling them, on the first line of main, if you like.  They work right away; there are no setup steps required.
getchar reads one character.
scanf reads "formatted input", although this function is full of problems and gotchas, to the point that it's almost not worth using.
To read one line from stdin, the function used to be gets, although it had a fatal problem and has been removed from the language.  Today, to read one line from stdin, one way to do it is with the fgets function, which can actually read lines from any stream, so you have to explicitly pass it stdin as its fp argument.

A: stdout(Standard output) is a place to which a program can send
information (e.g., text). The program never knows where the information
it sends to standard output is going. The information can go to a
printer, an ordinary file, or the terminal(screen). By default the shell
directs standard output from a command to terminal(screen) and describes
how you can cause the shell to redirect this output to another file.
stdin(Standard input) is a place a program gets information from; by
default, the shell directs standard input from the keyboard.
As with standard output, the program never "knows" where the information
comes from. The following sections explain how to redirect standard input
to a command so it comes from an ordinary file instead of from the
keyboard.
You can cause the shell to redirect standard input or standard output of
any command by associating the input or output with a command or file
other than the device file representing the keyboard or the
terminal(screen).
The cat utility provides a good example of the way the keyboard and
terminal(screen) function as standard input and standard output,
respectively. When you run cat, it copies a file to standard output.
Because the shell directs standard output to the screen, cat displays the
file on the screen.
cat writes to the standard output, which is not necessarily a
terminal,
even if cat was typed as part of a command to an interactive shell. If
you really need something to write to the terminal even when the standard
output is redirected, that is not so easy (you need to specify which
terminal, and there might not even be one if the command is executed from
a script)

A: You can just read from stdin, as @MikeCAT says, but as a beginner you may not know how to do that. You can use getchar, fgets, and scanf, to name a few. There is no need to "open" stdin, because it is opened by default for any C program, as are stdout and stderr. If you are running on Linux, you can learn about the usage of the various input functions by using man... i.e., man getchar. If you're not on Linux, you can just do a google search.


text:
Q: How to make width of datagrid autofit to parent control width Having a DataGrid inside a grid, I would like to make the datagrid width and datagrid columns auto fit inside the parent control.
So that if user decide to increase window width, how do I make the grid width and its columns also increase?
<Window x:Class="AME.WpfBidouille.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <DataGrid>
            <DataGrid.Columns>
                <DataGridTextColumn Header="Publication date"/>
                <DataGridTextColumn Header="A very large field to be displayed"/>
                <DataGridTextColumn Header="N° Omega" />
                <DataGridTextColumn Header="Crée le" />
                <DataGridTextColumn Header="Login" />
                <DataGridTextColumn Header="Demandeur" />
                <DataGridTextColumn Header="Type" />
                <DataGridTextColumn Header="Status" />
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
</Window>

A: Set the Width on each of your columns to "*"
    <DataGrid>
        <DataGrid.Columns>
            <DataGridTextColumn Width="*" Header="Publication date"/>
            <DataGridTextColumn Width="*" Header="A very large field to be displayed"/>
            <DataGridTextColumn Width="*" Header="N° Omega" />
            <DataGridTextColumn Width="*" Header="Crée le" />
            <DataGridTextColumn Width="*" Header="Login" />
            <DataGridTextColumn Width="*" Header="Demandeur" />
            <DataGridTextColumn Width="*" Header="Type" />
            <DataGridTextColumn Width="*" Header="Status" />
        </DataGrid.Columns>
    </DataGrid>

A: Another way you could do this is to create a Style and use that to apply it to the DataGrid
    <Style x:Key="DynamicGridColumns" TargetType="DataGrid">
        <Setter Property="ColumnWidth" Value="*" />
    </Style>

    <DataGrid Style="{StaticResource DynamicGridColumns}">
        <DataGrid.Columns>
            <DataGridTextColumn Header="Publication date"/>
            <DataGridTextColumn Header="A very large field to be displayed"/>
            <DataGridTextColumn Header="N° Omega" />
            <DataGridTextColumn Header="Crée le" />
            <DataGridTextColumn Header="Login" />
            <DataGridTextColumn Header="Demandeur" />
            <DataGridTextColumn Header="Type" />
            <DataGridTextColumn Header="Status" />
        </DataGrid.Columns>
    </DataGrid>


text:
Q: Trigger an event that blocks the execution of the default code I'm working on a auth based application where the user must be logged to access to a certain routes of the website. I haven't found documentation on how to accomplish this so I worked on a idea on how to solve it.
This is my function to know if a user is logged or not:
App.filterAuth = function(navigateTo) {
    navigateTo = typeof navigateTo !== 'undefined' ? navigateTo : '#';

    if (App.logged == false) {
        App.vent.trigger('navigate', navigateTo);
    }
};

My idea is that when a user is logged sets the App.logged = true. Then, when my router tries to execute a concrete router I can just call App.filterAuth(). This actually works and doing some debugging I see that everything is triggered corrected.
The problem? For example I execute this on a protected route that loads a feed of images for a user. When App.filterAuth() is executed I see that it tries to navigate to # but the execution of this feed view isn't stopped and also the view associated to my # route is not triggered.
Any idea on how I can improve this function that makes it work correctly?
Thanks in advance!

A: This might not be an answer to question directly, but there is a backbone plugin which can help you with what you try to do: https://github.com/boazsender/backbone.routefilter
You can specify additional methods, which will be triggered before / after route code is processed. If you return false from before callback, router code won't be evaluated: https://github.com/boazsender/backbone.routefilter#returning-false-from-within-a-before-filter
So, you could create before filter, which could check, if route should be secured. If it is secured and user is not authenticated, you just return false and router code is not used.


text:
Q: Python non-blocking socket shutdown: can it raise BlockingIOError? If you shutdown a non-blocking socket:
sock.setblocking(False)
...
sock.shutdown(SHUT_RDWR)

is it possible that the call to shutdown will raise a BlockingIOError, and if so, under what conditions? I've not experienced it happening, but this (of course) doesn't mean it can't happen.

A: According to POSIX and Linux documentation, shutdown cannot return EWOULDBLOCK or equivalent error. The asyncio library consequently makes no provisions to handle such a result.
Although shutdown() transmits (meta-)data to the peer, you can think of shutdown as exiting immediately with the actual work being done by the OS behind the scenes. close() works in much the same way.


text:
Q: SQL Count each time row equal to column So I have the carriesOut table:
+------------+------------+
| theatreNo |   doctor   |
+------------+------------+
|          1 | DD0094CYY  |
|          1 | DD234CD1X  |
|          2 | DD1199XYZ  |
|          2 | DD1199XYZ  |
|          4 | AB2323CYA  |
|          4 | AB2323CYA  |
+------------+------------+

And the doctor table:
+-------------+---------+
|  NINumber   |  lname  |
+-------------+---------+
| AB2323CYA   | Falk    |
| DD0094CYY   | Gibbson |
| DD1199XYZ   | Smith   |
| DD234CD1X   | Hammer  |
+-------------+---------+

I'm trying to find how many times every doctor has been in an operation, for example, I should get the output:
    +------------+---------+------------+
    |   doctor   |  lname  | operations |
    +------------+---------+------------+
    | DD0094CYY  | Gibbson |          1 |
    | AB2323CYA  | Falk    |          2 |
    | DD1199XYZ  | Smith   |          2 |
    | DD234CD1X  | Hammer  |          1 |
    +------------+---------+------------+

And here is what I've tried so far:
SELECT o.doctor
     , d.lname
     , COUNT(theatreNo) operations
  FROM Hospital_CarriesOut o
  JOIN Hospital_Doctor d
    ON d.NINumber = o.doctor
 WHERE theatreNo IN (1,2,4)
 GROUP
    BY statement DESC

I only get the the following output:
+------------+---------+------------+
|   doctor   |  lname  | operations |
+------------+---------+------------+
| DD0094CYY  | Gibbson |          1 |
| AB2323CYA  | Falk    |          1 |
| AB2323CYA  | Falk    |          3 |
| DD234CD1X  | Hammer  |          1 |
+------------+---------+------------+

A: it should be group by Hospital_CarriesOut.doctor, Hospital_Doctor.lname
   SELECT Hospital_CarriesOut.doctor, Hospital_Doctor.lname,
     COUNT(theatreNo) AS operations
    FROM Hospital_CarriesOut JOIN Hospital_Doctor ON Hospital_CarriesOut.doctor=Hospital_Doctor.NINumber WHERE theatreNo IN (1,2,4)
    GROUP BY Hospital_CarriesOut.doctor, Hospital_Doctor.lname


text:
Q: Can't stop rails server with CTRL-C I'm new to Ruby and Rails. I start the WEBrick Server from scripts/server (via ./scripts/server from the directory created by rails) on Debian. The Server starts and is reachable, but if I press CTRL + C then appears
ERROR SystemExit: exit
    [rails dir]/vendor/rails/railties/lib/commands/server.rb:106:in `exit'

and the Server won't stop. What goes wrong?

A: *nix
First step, lookup the process ID (PID) of rails server; you'll need the port it's running on.
Second step, manually kill the process using the PID obtained in step one.
sudo lsof -i tcp:<PORT> # e.g. 3000

kill -9 <PID> # e.g. 14319

A: For any latecomers, Rails 2.3.8 doesn't like Rack 1.2.1
Add gem 'rack', '1.1.0' to your gemfile, run bundle update rack and your server should exit correctly.

A: Try to find the process with ps aux in your terminal.
Then, kill -9 it.


text:
Q: Average of Two Strings C++ I have two String Max and Min that where obtained using a list of Strings by simple comparison operation.
Now, I want to use these two Strings to find like the average of this two Strings. Meaning I want to have like the middle String between these two Strings.
For example if I enter "a" and "z" the average should be "m"

A: Are you doing these operations on strings of same size? In this case, you can use average of the ascii of each character.
in c it will be
(char)((int)c1 + int(c2))/2.

Make sure the strings have the same case (both uppercase or both lowercase.)

A: returns the ASCII code of "a" and "z", averages and displays this symbol
string a="a";
string b="z";
int first=Convert.Toint16(a);
int second=Convert.ToInt16(b);
int average=(first+second)/2;
char c=Convert.ToChar(average);


text:
Q: Sum time in SQL Stored procedure How sum time in SQL my procedure return:
START   --    FINISH   ---   TOTAL
18:14:47    20:32:54    02:18:06
12:35:45    15:06:06    02:30:21
18:08:26    21:25:39    03:17:12

I need sum column TOTAL (08:05:40)
My stored procedure:
Alter PROCEDURE [dbo].[timeTotal]
@userName nvarchar(50)
AS
BEGIN

    SELECT

            CONVERT(VARCHAR(8),dateadd(HH,7,workStart),108) AS workStart,
            CONVERT(VARCHAR(8),dateadd(HH,7,workFinish),108) AS workFinish,
            CONVERT(VARCHAR(8),workFinish - workStart,108) AS total

    FROM workTime
    WHERE userName = userName

END

I need get 08:05:40

A: To sum time difference in hours, use the following:
SELECT
   (RIGHT('00' + CONVERT(VARCHAR(10), SUM(DATEDIFF(MINUTE, FromTime, ToTime)) / 60), 2)
  + ':' +
    RIGHT('00' + CONVERT(VARCHAR(2), SUM(DATEDIFF(Minute, FromTime, ToTime)) % 60), 2)
  + ':' +
    RIGHT('00' + CONVERT(VARCHAR(2), SUM(DATEDIFF(SECOND, FromTime, ToTime)) % 60), 2))
AS TotalTime FROM AllocateRoom

Use the above in the stored procedure and it returns sum of time difference as follows:
01:20:20

Finally your expected data as follows:
;WITH DEMO(ID, FromTime, ToTime) AS
(
    SELECT TOP 1
        ID
       ,CONVERT(DATETIME,FromTime,120) AS FromTime
       ,CONVERT(DATETIME,ToTime,120) AS ToTime
    FROM (VALUES (1,'2016-09-03 18:14:47.000','2016-09-03 20:32:54.000')
                ,(2,'2016-09-03 12:35:45.000','2016-09-03 15:06:06.000')
    ) AS X(ID,FromTime,ToTime)
)
SELECT
    k.ID,
    k.FromTime,
    k.ToTime,
    DATEADD(SECOND,DATEDIFF(SECOND, k.FromTime, k.ToTime),CONVERT(TIME(0),'00:00:00',0)) AS TIME_DIFF,
    DATEADD(SECOND,SUM(DATEDIFF(SECOND, k.FromTime, k.ToTime)) OVER
        (
            PARTITION BY (SELECT NULL)
        ),CONVERT(TIME(0),'00:00:00',0)) AS TIME_SUM
FROM DEMO k;

A: use DATEDIFF() instead of subtraction to find the time different between 2 dates
DATEDIFF(SECOND, workStart, workFinish) AS total

to display it in HH:MM:SS,
CONVERT(VARCHAR(8), DATEADD(SECOND, 0, DATEDIFF(SECOND, workStart, workFinish)),108) AS total


text:
Q: Error in using templates in C++ I want to implement an AVL Tree using templates in C++. The header file, C++ file and the main file are as below :
AVLTree.h
#include <iostream>

using namespace std;

namespace MYTree
{
    template <class T>
    class AVLTree
    {
        public:
            struct AVLNode
            {
                struct AVLNode *left;
                struct AVLNode *right;
                struct AVLNode *parent;
                int balanceFactor;
            };

            //Constructor
            AVLTree();
            //Variables
            AVLNode *root;
            //Methods
            AVLNode<T> *lookup(const T &key);
            AVLNode<T> *insert(const T &key);
            void remove(const T &key);
    };
}

AVLTree.cpp
#include "AVLTree.h"

#include <iostream>

using namespace std;

template <class T>
AVLTree<T>::AVLTree()
{
    cout <<"HI\n";
}

template <class T>
AVLNode<T>* AVLTree<T>::lookup(const T &key)
{
}

template <class T>
AVLNode<T>* AVLTree<T>::insert(const T &key)
{
}

template <class T>
void AVLTree<T>::remove(const T &key)
{
}

main.cpp
#include "AVLTree.h"

#include <iostream>

using namespace std;

int main()
{
    AVLTree<int> tree();

    return 0;
}

When I compile the main.cpp, I get the following errors :
In file included from main.cpp:1:
AVLTree.h:27: error: `MyTree::Node' is not a template
AVLTree.h:28: error: `MyTree::Node' is not a template
AVLTree.h:30: confused by earlier errors, bailing out

Edit :
main.cpp:9: error: `AVLTree' undeclared (first use this function)
main.cpp:9: error: (Each undeclared identifier is reported only once for each function it appears in.)
main.cpp:9: error: expected primary-expression before "int"
main.cpp:9: error: expected `;' before "int"

I am using templates for the very first time. Can someone help me ?

A: AVLNode isn't a template; it's a regular class nested within a template. So within the template, just use the class name:
AVLNode *lookup(const T &key);

and outside the template, qualify it with the template's scope:
template <class T>
AVLTree<T>::AVLNode* AVLTree<T>::lookup(const T &key)
{
}

You'll also need to fix the definition of AVLNode; you're currently declaring Node to be a data member of AVLTree (which you don't want), and attempt to define a type AVLNode to be an alias for Node (which won't compile since Node isn't a type). Just define a class type, with no data members or typedefs:
struct AVLNode
{
    AVLNode *left;
    AVLNode *right;
    AVLNode *parent;
    int balanceFactor;
};

As noted in the comments, templates (including member functions of class templates) usually need to be defined in a header, as the definition must be available wherever it's used.
You'll also need to make sure the definitions are in the correct namespace, and qualify the template name appropriately (MYTree::AVLNode) when you're not in that namespace.
AVLTree<int> tree(); declares a function; remove the () to create a default-initialised object.
Finally, don't do using namespace std; in the global namespace, as it can lead to confusing name conflicts.

A: This typedef
       typedef struct Node AVLNode;

is invalid. First of all you have no defined structure Node and secondly this typedef hides declaration of name struct AVLnode
It shall be removed. The error messages are results of this typedef because in this declarations
        AVLNode<T> *lookup(const T &key);
        AVLNode<T> *insert(const T &key);

you specified  name AVLNode as a template name.
Nevertheless your code contains other errors. Template member functions have to be placed in the same header file where the template class is defined. Otherwise you will get linker errors that references are undefined.
This statement in main
AVLTree<int> tree();

is not a definition of an object. It is a function declaration that has return type AVLTree<int> and has no parameters.

A: you use AVLNode<T> but AVLNode is not a template, as the message say.

A: With this:
struct AVLnode
{
    ...
}Node;

you declare a member variable named Node.
When you later do
typedef struct Node AVLNode;

you try to use the member variable as a structure.
Remember that you are programming C++, where structure names can be used as types just the same as class names.
You also try to use AVLNode as a template in e.g.
AVLNode<T> *lookup(const T &key);

But just as the error messages says, the AVLNode structure is not a templated structure.


text:
Q: Bound for number of distinct prime divisors (don't understand the proof) The task is to determine a bound for the number of distinct prime divisors. The proof can be found here:

The smallest number with $k$ distinct prime divisors is the $k^\text{th}$ primorial. So the most distinct prime divisors for any number up to $x$ will be the the number of divisors of the largest primorial less than or equal to $x$. We know from the primorial asymptotic that this is $\ln(x)\#$. And we know from the Prime Number Theorem that the number of primes less than $\ln(x)$ is $\ln(x)/\ln(\ln(x))$.

Since the upper bound is given by the primorial, we have $\omega(x)\le\omega(x\#)$. By definition, $\omega(x\#)=\pi(x)$. Finally, by the prime number theorem, $\pi(x)\sim x/\ln(x)$. I don't understand how one can conclude that the bound is given by $\ln(x)/\ln(\ln(x))$.

A: Not $\omega(x)\le\omega(x\#)$, that's an extremely loose bound. The text talks about the largest primorial $\le x$, which isn't $x\#$, but apparently is $\ln(x)\#$. Then $\omega(x)\le\omega(\ln(x)\#)=\pi(\ln(x))\sim \ln(x)/\ln(\ln(x))$.


text:
Q: Feature branch got change after merging it to Master I had a feature branch and that I needed to merge into master so I created a pull request through github and merge it.
I was expecting that all changes in feature brach that were different from master will overwrite that particular file in master but after the merge I noticed the opposite that feature branch got updated with the code (the one which was different in master) and master file remained same.
Please correct my understanding if I am wrong. When we merge brach A into branch B, branch A should not get changed. isn't it ?
Thanks,

A:
I was expecting that all changes in feature branch that were different from master will overwrite that particular file in master ...

This expectation is wrong.
Merge does not mean make same.  Merge means combine work.
This is a bit complicated by one thing: Git doesn't store the work you did.  Git stores, instead, full snapshots of every file.  That is:

*

*Each commit is numbered, with a big, ugly, unique hash ID.  This number is how Git actually retrieves the commit from Git's main database.  (This database contains commits and other supporting objects, all of which have these big ugly hash IDs.)

*Each commit stores two things:

*

*A commit has a full snapshot of every file.  The files inside each commit are stored in a special, read-only, Git-only, compressed and de-duplicated format.  If you have a repository with lots of commits, and you check out one commit that has some really big files and some really small ones and you change just one of the small ones and add-and-commit, Git has to store all the files all over again, but it can re-use all but the one changed file.  So only the changed file actually takes any space.  But each commit still has every file!

*A commit also stores some metadata, or information about the commit itself.  This includes the stuff you see in git log output: who made the commit, when, and why (their log message), for instance.  For Git's own purposes, every commit stores a list of previous commit hash IDs in this metadata, too.
This list-of-previous-commit-hash-IDs usually has exactly one entry.  We call that one entry the commit's parent.  It means that each child commit "points to" its parent:
... <-F <-G <-H

Here H stands for the hash ID of the latest commit.  This commit is a commit, so it has a snapshot—all of the files as of the form they had when you made H—and metadata.  The metadata says that you made it last August, or whatever.  It also says that the parent of commit H is earlier commit G (whatever the real, random-looking, hash ID really is: git log will show it).
Commit G, though, is a commit, so it has a full snapshot of every file, and some metadata.  Git can extract both commits (to a temporary area in memory) and compare the files.  When the files exactly match—and are therefore de-duplicated—that's pretty boring, and Git generally will say nothing at all.  When the files don't match, Git can come up with a recipe—a set of changes to apply to the older file—that will make it match the newer file.  That's what you see in git log -p.
Having shown commit H as a change from earlier commit G, git log now steps back one hop.  Now its job is to show commit G.  For this, it needs commit F, G's parent, to get the snapshot to figure out what changed, if you want to see that, but that's easy because G holds F's hash ID.
So Git can show you the author and message and so forth for G, and then a diff from F to G to see what changed, and now Git can move back one hop yet again and show you F.  That's a commit, so it has a snapshot and a parent, and ... well, the idea should be obvious now.
That's all well and good for simple cases, but we have one problem: we have to somehow give the hash ID for commit H to Git.  We could scribble it onto a whiteboard, or jot it down on paper.  But why should we do that, when we have a computer?  Let's have Git store this hash ID for us, in—say—a branch name.  And that's just what we do.
Now, if we have a simple chain of commits like this:
...--F--G--H   <-- master (HEAD)

and we create a new branch name feature, we get:
...--F--G--H   <-- feature, master (HEAD)

We're currently using commit H, via the name master.  If we switch to feature, with git checkout feature or git switch feature, we switch to using commit H via the name feature:
...--F--G--H   <-- feature (HEAD), master

Nothing else has to change, so Git takes a shortcut and changes nothing else: we're still using commit H, just through another name.
If we now make new commits, these new commits get:

*

*a new snapshot, from what we tell Git to use;

*new metadata: your name as author/committer and "now" as the date and time, with the parent commit being the current commit.

By writing out the new commit, Git acquires a new hash ID—there's some fairly deep magic here, using cryptographic hashes, which also explains why nothing about any commit can ever change once you've made it—but we'll just call our new commit I.  New commit I will point back to existing commit H:
             I
            /
...--F--G--H

and now Git pulls its clever little trick: it writes I's hash ID into the current branch name, i.e., feature:
             I   <-- feature (HEAD)
            /
...--F--G--H   <-- master

If we make yet another new commit before we do anything else, we get:
             I--J   <-- feature (HEAD)
            /
...--F--G--H   <-- master

If we now switch back to the name master, here's what happens:
             I--J   <-- feature
            /
...--F--G--H   <-- master (HEAD)

We've now had Git attach the special name HEAD to the name master, which points to commit H, not commit J.  Since we're changing commits, Git will now remove, from our working tree, all the files from J and put in all the files from H instead (using the snapshots).1
If we were to run git merge feature now, you'd get the thing you expected.  But before we do, let's make more commits.  We'll modify some file that also got modified in I and/or J, as we make two new commits K and L:
             I--J   <-- feature
            /
...--F--G--H
            \
             K--L   <-- master (HEAD)

If we compare the files in J vs the files in L (in either order), we'll get a recipe that would change what's in one of those two commits to match what's in the other.  But if we run git merge feature, we don't want to lose the good stuff we did in commits K-L.  So that's not what git merge does.
Instead, git merge:

*

*locates the current commit: that's easy, it's whatever HEAD is attached to, and we already have that commit checked out too, as --ours;

*locates the other commit, in this case commit J, from the name we supply: we can actually give a raw hash ID as Git just needs the commit; this becomes the --theirs commit;

*and, last, uses the graph we've been drawing to find the best shared starting-point commit.

That last commit is obvious from the drawing here: it's commit H.  Commit H is on both branches.  Commits I-J are only on feature, and commits K-L are only on master, but all commits up to and including H are on both branches.  So all those commits are shared, and H is obviously the best one.2
Now, to do the merge, Git will:

*

*compare the snapshot in H to that in L: that shows what you did, on branch master, to get to the --ours commit;

*compare the snapshot in H to that in J: that shows that they did, on branch feature, to get to the --theirs commit;

*combine the two sets of changes.

The combined changes then get applied to the snapshot from H.  That keeps our changes and adds theirs, or, equivalently, keeps their changes and adds ours.  Either way, what ends up in the files doesn't necessarily match either commit J or commit L, because we took two sets of changes.
If all goes well, Git makes a new merge commit.  A merge commit is exactly the same as any other commit: it has a snapshot, and a list of parent hash IDs.  What makes it a merge commit is that the list of parent hash IDs has not just one hash ID, but two:3
             I--J   <-- feature
            /    \₂
...--F--G--H      M
            \    /¹
             K--L   <-- master (HEAD)

There's still just the one snapshot.  The first parent, marked with a tiny 1 here, leads back to the commit we were on when we started the git merge.  The second parent leads back to the commit we told Git to merge.
Note that in the much simpler case of:
             I--J   <-- feature
            /
...--F--G--H   <-- master (HEAD)

Git still does all the fancy merge-base calculation.  This time, however, our commit is H, theirs is J, and the merge base is ... H again.  If Git were to compare the snapshot in H vs the snapshot in H, the list of changes it would find would be empty.
We can force Git to do that anyway, with git merge --no-ff.  The result is a new merge commit, with two parents as usual:
             I--J   <-- feature
            /    \
...--F--G--H------M   <-- master (HEAD)

but now the snapshot in M really does match the snapshot in J.  That's because Git compared H to J to see what they changed, then applied those changes to H, and used no changes from our side, to make the snapshot.  Algebraically,4 H + (J - H) is just J again.
If we don't force a real merge, Git will do a sort of fake not-actually-a-merge, called a fast forward.  But GitHub won't let you do a fast-forward, if you use their clicky buttons: they have MERGE, REBASE AND MERGE, and SQUASH AND MERGE and none of those is Git's internal fast-forward.  (The REBASE AND MERGE option comes close, but isn't the same.)

1This explanation deliberately skips a lot of weird corner cases that Git allows.
2Proof by vigorous hand waving, number 8 on the list.  More seriously, see Lowest Common Ancestor of a DAG.
3Technically, a Git merge can have more than two parents, but that's rare (and mainly used for showing off ).
4Some version control systems do attempt to define an algebra of changes, and hence do this sort of computation.  It ... gets messy.

A: I'm guessing you ran git merge master. This merged master into the current branch.
To merge the feature branch into master, you need to switch to the master branch, and then run git merge feature. That being said, you can create a PR without merging feature into master.


text:
Q: jquery uncaught TypeError: Object [object Object] has no method 'slider' Hi I want jQuery to be able to read the URL that is inserted and if it is a value that is defined I want it to load in different content:
I've used the below code:
 <script type="text/javascript">
      $(document).ready(function () {
    var slider = $('#year_range');

          if(window.location.href.indexOf("#digitl2004")) {
       // hide elements
        $('#year_range').slider('value', 2004);
      }
      });
 </script>

But I keep getting this error:
Uncaught TypeError: Object [object Object] has no method 'slider'
Not sure why this is occurring, any ideas?
Thanks in advance.

A: it's because you are trying to call the "slider" method on a jquery object. but jquery itself does not contain a definition for this method. maybe you are missing a plugin?


text:
Q: TSQL BINARY_CHECKSUM as a default value There is a column in a table, which should store Checksum for list of columns, but I'd like to create it as a default value for this table:
CREATE TABLE tblVitalyTest (id BIGINT IDENTITY(1,1), startTime DATETIME, value1 INT, value2 INT, value3 INT, value4 DATETIME, BinCheckSum BIGINT)
GO
ALTER TABLE tblVitalyTest ADD  DEFAULT (BINARY_CHECKSUM(value1, value2, value3, value4)) FOR [BinCheckSum]
GO

So, it should be used like that:
INSERT INTO tblVitalyTest (startTime,value1,value2,value3,value4) VALUES ('2015-05-25',1,1,1,'2015-11-11')

As a result it should be something like that:

id, startTime, value1, value2, value3, value4, BinCheckSum
1, "2015-05-25", 1, 1, 1, "2015-11-11", 46173

But table "default" table creation fails unfortunately.
There is a query to play around:
DECLARE @a TABLE (id BIGINT IDENTITY(1,1), startTime DATETIME, value1 INT, value2 INT, value3 INT, value4 DATETIME)

INSERT INTO @a (startTime,value1,value2,value3,value4)
    VALUES ('2015-05-25 08:00',1,1,1,'2015-11-11'),('2015-05-25 09:00',1,2,1,'2015-11-11')
          ,('2015-05-25 10:00',null,null,null,'2015-11-11'),('2015-05-25 11:00',2,1,1,'2015-11-11'),('2015-05-25 11:00',null,null,null,'2015-11-12')

SELECT a.*,BINARY_CHECKSUM(a.value1,a.value2,a.value3,a.value4) [BinCheckSum]
FROM @a a

Please let me know is there any way to create a Binary_Checksum as a default value for the column?

A: You can create the column as a computed column. Try this
CREATE TABLE tblVitalyTest
 (id BIGINT IDENTITY(1,1),
     startTime DATETIME,
     value1 INT,
     value2 INT,
     value3 INT,
     value4 DATETIME,
     cksum AS BINARY_CHECKSUM(value1,value2, value3, value4 ))
    GO

Or you can ALTER and existing table as such
ALTER TABLE tblVitalyTest
ADD cksum AS BINARY_CHECKSUM(value1, value2, value3, value4);
GO

Results of this query (based on your INSERT example):
      select id, cksum
      from tblVitalyTest

would be:
   id   cksum
    1   46173
    2   46941
    3   -44486
    4   33885
    5   -44487

A: Basically you can't. But you can do something similar with a trigger. See below
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE TRIGGER dbo.tblVitalyTestUpdateInsertTrigger ON dbo.tblVitalyTest
  AFTER INSERT, UPDATE
AS
  BEGIN

    SET NOCOUNT ON;
    UPDATE
      vt
    SET
      vt.BinCheckSum = BINARY_CHECKSUM(vt.value1, vt.value2, vt.value3,
                                       vt.value4)
    FROM
      dbo.tblVitalyTest vt
      INNER JOIN INSERTED i
        ON vt.id = i.id

  END
GO


text:
Q: Using java, how do count the occurrences of a character in a string, and then format an output with text listing the locations using loops I understand how to count the occurrences of specific characters in a string. What I am struggling is printing "The specific character is at location x, y, z". If I place the text within the loop that tests for location, the text is printed multiple times. I do not want that to happen.
There are other constraints as well. I must keep the program basic, and I am limited to using the charAt() and string.lenghth() functions. The program should only exit when the user enters "-1". When the user enters the string, the program should read through the characters, output the location of the specific characters, and then prompt the user to enter a new string. I am also struggling with allowing the user to enter a new string and running the loop again.
Here is the code I have so far
import java.util.Scanner;

public class GimmeAW {
public static void main(String[] args) {

    Scanner input = new Scanner(System.in);
    System.out.println("Enter the Line\nEntering -1 exits the program")
    String aLine;

    aLine = input.nextLine();
    char one = aLine.charAt(0);
    char two = aLine.charAt(1);

    if (one == '-' && two == '1') {
        System.out.println("System Exit");
        System.exit(1);
    }

    for (int i = 0; i < aLine.length(); i++) {

        if (aLine.charAt(i) == 'w' || aLine.charAt(i) == 't') {
            int location = i;
            System.out.print(" " + i);
        }
    }
}

A: To avoid printing the msg multiple times, just keep the msg outside of the counting loop and print it once for each character ...
char[] ch = {'w', 't'}; // characters to count
int l = aLine.length();

for(int i = 0; i < ch.length; i++) {

    System.out.print("The character " + ch[i] + " is at locations ");
    // searching
    for(int j = 0; j < l; j++) {
        if(aLine.charAt(j) == ch[i]) {
            System.out.print(j + " ");
        }
    }
    System.out.println();
}

And you can put all the code you want to repeat inside a do-while loop and run it until the user wants to.
String choice = "yes";
do {
    // code

    // want to repeat ??
    choice  = in.nextLine();

} while(choice.equals("yes"));


text:
Q: Inductively constructing a homeomorphism between CW complex and polyhedron This is 5-18b of J. Lee's "Introduction to Topological Manifolds".
Suppose $X$ is a regular CW complex. Then let $\mathcal{E}$ be the set of open cells of $X$, $\mathcal{K}$ the collection of all nonempty finite subsets $\{e_0,...,e_k\}\subseteq\mathcal{E}$ with the property that the dimensions of the elements are all distinct, and $e_{i-1}\subseteq\partial e_i$. I have shown that $\mathcal{K}$ is an abstract simplicial complex in part a) of the question. Part b) proceeds as follows:
Suppose $K$ is a Euclidean simplicial complex whose vertex scheme is isomorphic to $\mathcal{K}$. Show that $X$ is homeomorphic to $|K|$ (the polyhedron of $K$) via a homeomorphism that sends the closure of each cell of $X$ onto the polyhedron of a subcomplex of $K$.
The reader is given the following hint: begin by choosing $v_e$ in each simplex $e\in\mathcal{E}$. Then define a homeomorphism inductively, one skeleton at a time, in such a way that it sends each point $v_e$ to the vertex of $K$ corresponding to $e$.
In previous exercises, I proved that any homeomorphism $f:\partial D\to\partial D'$ can be extended to a homeomorphism $F:D\to D'$, for two closed cells $D$ and $D'$. I understand that this fact should help me construct the homeomorphism in some inductive fashion, but I am not sure how to realise this construction. For the $0$-skeletons, it seems clear that the map should take every $e_0$ to $\{e_0
\}$. Then, assume the homeomorphism has been constructed for the $(n-1)$-skeleton. Denoting by $|K|_i$ the $i$-skeleton of the polyhedron $|K|$, we have a homeomorphism $F_{n-1}:X_{n-1}\to |K|_{n-1}$. From this, how would I create the homeomorphism for the $n$-skeleton?

A: That earlier exercise is not going to be sufficient, because your description of the induction has a flaw.
As you say, the homeomorphism between $X$ and $|K|$ is being constructed inductively on the skeleta $X_0 \subset X_1 \subset X_2 \subset \cdots$. However, your induction hypothesis is incorrect, because the image $f(X_n)$ is not going to be equal to the entire $n$-skeleton of $|K|$; instead it is only going to be a subcomplex of the $n$-skeleton of $|K|$.
For example, $f(X_0)$ is not the entire $0$-skeleton of $|K|$, it is only the subcomplex of the $0$-skeleton corresponding to singleton sets $\{e_0\}$ such that the dimension of $e_0$ is equal to $0$.
More generally, given a cell $e \subset X$ of dimension $d \ge 1$ corresponding to a $0$-simplex $\{e\}$ of $|K|$, the point of $X$ which is mapped to that $0$-simplex by $f$ is going to be the chosen point $v_e$ in the interior of $e$. Thus the $0$-simplex $\{e\}$ is not contained in $f(X_{d-1})$, but it is contained in $f(X_d)$.
With that said, let me strengthen the hint from Lee's book somewhat. The description of $f$, and the induction hypothesis of the construction of $f$, should both state with more precision what is the image under $f$ of each closed cell in $X$:

*

*Given an open cell $e \subset X$, what will $f(\overline e) \subset |K|$ be?

If you can answer that question, you should be able to reformulate your induction and then proceed with the construction.


text:
Q: Not able to display the ModelMap object data in jquery HighCharts '    In My Controller method:
              This below code will return the data with a set of records which contains 3 fields
                   1    Fruits      30
                   2    Vegetables  40
                  .... and so on
               Here I want to display second and third column in HighCharts graph '
   List<Object[]> vendingTypesCount = svService.getVendingTypeWiseVendorsCount();
       Map<String,Object> mp = new LinkedHashMap<String,Object>();   // mp is LinkedHashMap object
       for (Object[] objects : vendingTypesCount) {
          mp.put(objects[1].toString(), objects[2]);
       }

      // checked in Java, data is getting accessed perfectly

      map.addAttribute("vendingTypesData",mp);   // here map is the ModelMap object

// In my Jsp:


text:
Q: How can I make integers on a join SHP file stay as INT and not as qlonglong? So I've been trying to join a CSV file with a polygon SHP file and everytime I try to save the joint SHP into a new file it transforms the type from int to qlonglong and prevents me from using some other plugins.

Is there a way to prevent that conversion from happening or do I have to use the field calculator and convert each column to int?


text:
Q: Printing a class item of integer type in flutter Is there a specific method to show integer value in flutter.
I have a code snippet similar to :
class with integer value:
class item{
  item({
    this.int_number
  });
  int int_number=1;
}

To print an int value in flutter, we usually use Text("$number")
but when trying similar method to print the class value :
Text("$item.int_number")

The number isn't printed correctly. but only data about $item
Is there a direct solution to this problem ?? to print int values that is a class item.
Thanks

A: Use toString to converting int variable into String
For Example  :
  int intValue = 1;

I will use this in Text like this
Text("Value is:" + intValue.toString)

For more info try this link

A: use Text("${item.int_number}")
to print the values of instances like obj.value you need to wrap it in {}
thus you can use print("${obj.value}");
EDIT:
Tested this code on dartpad
void main() {
  var item = Item(intNumber: 5);
  print("${item.intNumber}");
  print(item);
}

class Item {
  Item({this.intNumber});
  int intNumber = 1;

  toString() => "Item (int_number = $intNumber)";
}

So you should be able to use
Text('${item.intNumber}')

or
Text('$item')


text:
Q: How to determine number of voices in one recorded file in cocoa? I want to extract the information such as how many voices as per person in one recorded file.
I know the NSSpeechRecognizer class to recognise the speech, but not able to get to know the number of voices in one recorded file.
Please provide some suggestion.
Thanks,
Yogesh Arora

A: Counting the number of voices requires segmenting the audio file and diarising the speakers, which is by no means a simple task. Cocoa doesn't provide an API for that, at least yet. There are some open-source libraries that might help. You might want to check the ALIZE toolkit, for example.


text:
Q: How do I prove my claim? Claim -
Let $u$ be any line. Let points $A , B$ not belonging to the line be in the same half plane. Let $P$ be any arbitrary point line $u$. Then $PA+PB=$ minimum $\iff$ $PA=PB$.
This claim in my mind randomly. Can someone please tell if this is true? If yes can you please guide my how to prove this claim? My aim was to get a contradiction to triangle inequalities by assuming another Point $P'$ on line u and prove that $P\equiv P'$ but I am stuck and not reaching anywhere nor am I able to disprove this. Can someone give atleast a hint? I am not asking for a full solution.

A: As a counterexample, consider $u$ as the $y$-axis, $A=(1,0),$ $B=(2,0),$ and $P=(0,y).$ Clearly, the sum of the lengths is minimized when $y=0,$ but the lengths cannot be equal.


text:
Q: How to overwrite a core file for certain form when its used on multiple form? Is there anyway for overwrite a core file for certain page ? what i mean is i want to customize below given core file for certain form but it will be applied everywhere wherever its use.
i.e its used on billing, shipping, registration etc. i want to customize its & remove its validation for billing section on checkout. but now validation is removed from all these forms.
app\design\frontend\base\default\template\customer\widget\name.phtml

A: you can create name1.phtml file.
and change into the file that you want.
and change in layout file to call your custom file. for certain event only.
so that for certain event your custom phtml file will call and for all other event call default file.


text:
Q: How do I set the ItemsSource of a DataGrid in XAML? I'm trying to set the ItemsSource property of a DataGrid named dgIssueSummary to be an ObservableCollection named IssueSummaryList.  Currently, everything is working when I set the ItemsSource property in my code-behind:
public partial class MainPage : UserControl
{
    private ObservableCollection<IssueSummary> IssueSummaryList = new ObservableCollection<IssueSummary>

    public MainPage()
    {
        InitializeComponent();
        dgIssueSummary.ItemsSource = IssueSummaryList
    }
}

However, I'd rather set the ItemsSource property in XAML, but I can't get it to work.  Here's the XAML code I have:
<sdk:DataGrid x:Name="dgIssueSummary" AutoGenerateColumns="False"
                ItemsSource="{Binding IssueSummaryList}" >
    <sdk:DataGrid.Columns>
        <sdk:DataGridTextColumn Binding="{Binding ProblemType}" Header="Problem Type"/>
        <sdk:DataGridTextColumn Binding="{Binding Count}" Header="Count"/>
    </sdk:DataGrid.Columns>
</sdk:DataGrid>

What do I need to do to set the ItemsSource property to be the IssueSummaryList in XAML rather than C#?

A: You need to make "IssueSummaryList" a property.  If you do this, you can bind to it directly.  You can't bind via Xaml to a private field.
You'll also need to set the DataContext to "this" (or use another method to get it to find the appropriate instance).

A: Your IssueSummaryList is private. You need to make it a Property with get and set
public ObservableCollection<IssueSummary> IssueSummaryList
{
     get
     {
        // ...
     }
}

A: The XAML is correct, so the problem must be in the Binding.

*

*Is the ObservableCollection exposed as a property?

*How have you set the Binding? In the most simple case you use code like:
this.DataContext=this;
in the Window_Load eventhandler


text:
Q: Как оптимизировать программу по памяти? Решаю задачу для контеста Яндекса, вылетает на одном тесте, пишет Memory Limited. Пытался делать решение через списки, но так получается что программа тратит еще больше памяти.

conf_num = int(input())

conf_dict = {}
conf_list = []
m = 1

for i in range(conf_num):
    conf = input()
    conf_list.append(conf)

    for s in range(len(conf) - 2):
        if conf[s:s + 3] not in conf_dict:
            conf_dict[conf[s:s + 3]] = m
            m += 1

conf_table = [[0] * len(conf_dict) for i in range(len(conf_dict))]

pairs_list = []
edge_num = 0

for i in conf_list:
    for s in range(len(i) - 3):
        conf_table[conf_dict[i[s:s + 3]] - 1][conf_dict[i[s + 1:s + 4]] - 1] += 1

        if [i[s:s + 3], i[s + 1:s + 4]] not in pairs_list:
            pairs_list.append([i[s:s + 3], i[s + 1:s + 4]])

        if conf_table[conf_dict[i[s:s + 3]] - 1][conf_dict[i[s + 1:s + 4]] - 1] == 1:
            edge_num += 1

# ВЫВОД

print(len(conf_dict)) # Кол-во вершин графа

print(edge_num) # Кол-во ребер графа

for i in pairs_list:
    print(f'{i[0]} {i[1]} {conf_table[conf_dict[i[0]] - 1][conf_dict[i[1]] - 1]}')

A: Заметьте, что существует максимум 456976=26^4 рёбер, поскольку каждое ребро соответствует комбинации S[i]S[i+1]S[i+2]S[i+3] четырех латинских символов, и при использовании ребра в качестве ключа, памяти требуется всего несколько мегабайт (можно ещё уменьшить, сопоставив последовательности символов число в указанном диапазоне, но и так пройти должно)
Можно сделать всего один проход по строкам, беря 4 символа за раз
from collections import Counter

s = 'abcdcdcdabcd'

e = Counter()
for i in range(len(s) - 3):
    t = s[i:i+4]
    e[t] += 1

for item in e:
    print(item[:3], item[1:], e[item])

abc bcd 2
bcd cdc 1
cdc dcd 2
dcd cdc 1
dcd cda 1
cda dab 1
dab abc 1


text:
Q: Ktor with Kmongo and kotlinx.serialization I have a setup where I use KTor with KMongo and Kotlinx.Serialization.
The Kmongo part works, I can get and put my Class
@Serializable
data class Task(@ContextualSerialization @SerialName("_id") val _id : Id<Task> = newId(),
                val title : String = "",
                val description : String = ""
)

Into the database and retrieve it. That all works flawlessly.
But when I try to send that object through a rest call to the frontend, again with Kotlinx.Serialization.
get<Tasks>{ task ->
        val dao by di().instance<Dao>();
        val task = Task( title = "task1", description = "task1description");
        val foundTask = dao.read(task);
        if(foundTask != null){
            call.respond(foundTask)
        } else {
            call.respond("didn't find anything")
        }
    }

It throws this expection:
kotlinx.serialization.SerializationException: Can't locate argument-less serializer for class WrappedObjectId. For generic classes, such as lists, please provide serializer explicitly.
    at kotlinx.serialization.PlatformUtilsKt.serializer(PlatformUtils.kt:21)
    at kotlinx.serialization.modules.SerialModuleExtensionsKt.getContextualOrDefault(SerialModuleExtensions.kt:29)
    at kotlinx.serialization.ContextSerializer.serialize(ContextSerializer.kt:29)
    at kotlinx.serialization.json.internal.StreamingJsonOutput.encodeSerializableValue(StreamingJsonOutput.kt:227)
    at kotlinx.serialization.builtins.AbstractEncoder.encodeSerializableElement(AbstractEncoder.kt:72)

Now I figured out that this is because there are 2 instances of the kotlin.serialization json. and the one on KMongo does not share it's serializers with the other one.
so I added the serializers from KMongo to the other instance from Ktor
install(ContentNegotiation) {
        json(
            json = Json(DefaultJsonConfiguration.copy(prettyPrint = true), context = kmongoSerializationModule),
            contentType = ContentType.Application.Json
        )
    }

and now I get
java.lang.ClassCastException: class kotlinx.serialization.json.internal.StreamingJsonOutput cannot be cast to class com.github.jershell.kbson.BsonEncoder (kotlinx.serialization.json.internal.StreamingJsonOutput and com.github.jershell.kbson.BsonEncoder are in unnamed module of loader 'app')

So my question is why is it happening and how to fix it?

A: Edit: This issue has been fixed.
I also posted this question on the KMongo github and basically got an instant response that this was fixed for Jackson but not yet for Kotlinx.serialization.
Someone is going to fix this.
Edit: It has been fixed


text:
Q: COM - return an array of object interfaces I want to return from IDL an array of interfaces.
I try this:
interface ISecurityPolicy : IDispatch{
[id(6)]          HRESULT GetPolicyList([out, ref, retval] SAFEARRAY(IEntityPolicy*)* result);
}

I get this warning(in VS 2010):
Warning 1   warning MIDL2456: SAFEARRAY(interface pointer) doesn't work using midl generated proxy : [ Parameter 'result' of Procedure 'GetPolicyList' ( Interface 'ISecurityPolicy' ) ]
Is this a bogus warning as http://social.msdn.microsoft.com/Forums/en-US/vcmfcatl/thread/84a632a9-4e29-4a95-8da7-f7aedb650339 might suggest ?

A: Declaring this as:
interface ISecurityPolicy : IDispatch{
[id(6)]          HRESULT GetPolicyList([out, ref, retval] SAFEARRAY(IUnknown*)* result);
}

simplifies things a little for implementation of the interface.
It could still be a better idea though instead of returning an array of interfaces to the caller to return it an iterator over the "collection".


text:
Q: How to resolve this error with github actions ssh-agent: Error loading key "(stdin)": error in libcrypto I am trying to deploy to aptible with github actions. This is my .yml file
name: Cartwheel Staging CI
run-name: ${{ github.actor }} activated these GitHub Actions

on:
  pull_request:
    branches: [ staging ]

env:
  APTIBLE_ENVIRONMENT: ${{ secrets.APTIBLE_ENVIRONMENT }}
  APTIBLE_APP: ${{ secrets.APTIBLE_STAGING_APP }}

 jobs:

 deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
        with:
          fetch-depth: 0
      - uses: webfactory/ssh-agent@v0.5.4
        with:
          ssh-private-key: ${{ secrets.APTIBLE_GIT_SSH_KEY }}
      - name: Deploy to Aptible
        run: |
          ssh-keyscan beta.aptible.com >> ~/.ssh/known_hosts
          git remote add staging git@beta.aptible.com:${APTIBLE_ENVIRONMENT}/${APTIBLE_STAGING_APP}.git
          git push staging ${GITHUB_SHA}:main

I have saved the APTIBLE_GIT_SSH_KEY as described in webfactory/ssh-agent README.
This is the actual error I receive in my github actions:
Run webfactory/ssh-agent@v0.5.4
  with:
    ssh-private-key: ***
  env:
    APTIBLE_ENVIRONMENT: ***
    APTIBLE_APP: ***
Adding GitHub.com keys to /home/runner/.ssh/known_hosts
Starting ssh-agent
SSH_AUTH_SOCK=/tmp/ssh-XXXXXXRcccK6/agent.1720
SSH_AGENT_PID=1721
Adding private key(s) to agent
Error loading key "(stdin)": error in libcrypto
Error: Command failed: ssh-add -
Error loading key "(stdin)": error in libcrypto

A: The error wasn't constructive so it took me a while to figure out what I did wrong.
I saved my public key in GitHub secrets.
I changed it to my private key and the error is gone.


text:
Q: How do you run chkdsk on every reboot? There was a question a short while ago, Run Program Before Login Screen Appears, where I thought he meant specifically he wanted to run chkdsk on boot based on the picture, but he really wanted to run a different program.
Well, I answered specifically for chkdsk, and I thought some might find my solution to "How do you run chkdsk on every reboot?" interesting.

A: Basically if you just want to run chkdsk /f or maybe chkdsk /r on bootup every time, you can set it to run when you shut down rather than trying to make it work in HKLM\SYSTEM\CurrentControlSet\Control\Session Manager.
Here is how:
Create a file C:\WINDOWS\system32\confirm.txt with JUST y in it.
Then create C:\WINDOWS\system32\Chkdsk_Reboot.bat with this code in it:
echo y > confirm.txt
chkdsk c: /f /x < confirm.txt

Now if you have XP Pro, or other Pro-level OS'es, open gpedit.msc>Computer Configuration>Windows Settings>Scripts>Shutdown, and add that Chkdsk_Reboot.bat as a shutdown script.
Next reboot you will run your chkdsk command.
I am not sure if this will work for XP home since it does not have gpedit.msc. You may be able to create this directory structure and add the batch file there but I am not sure if it will work since Home does not use Group Policy: C:\WINDOWS\System32\GroupPolicy\Machine\Scripts\Shutdown

A: chkdsk is already set to run on every boot.
Take a look at HKLM\SYSTEM\CurrentControlSet\Control\Session Manager and locate a multi-string (REG_MULTI_SZ) entry called BootExecute. The value "autocheck autochk *" says that chkdsk will run on boot, however you will not see it because it runs on background, searching for disk errors.
If chkdsk detects some disk problem, then you will see the blue screen with full disk scan.
Edit:
Autocheck option samples, according to here (section: "The Dirty bit vs the Registy "Autochk" entry"):
Sample command              Resulting registry entry
==============              ========================
Chkdsk C: /F                Autocheck autochk /p \??\C:
Chkdsk C:\mountpoint /F     Autocheck autochk /p \??\VOLUME{GUID}
Chkntfs D: E: /X            Autocheck autochk /k:D /k:E *
Chkntfs G: /C               Autocheck autochk /m \??\G:


text:
Q: Where should I ask questions about software industry practices? I'm a junior developer trying to find my way. As a part of this I have many questions regarding what other developers have done and what the standard for certain situations is. Unfortunately these kinds of questions aren't always technical with a specific and direct answer, resulting in my questions being closed on StackOverflow.
With this in mind - where can and should I ask these questions?

A: How about programmers.stackexchange.com?
See the faq for programmers. Some of your questions should fit there.
Programmers FAQ


text:
Q: How to run an action/command based on a result of a previous command I have a deployment that installs a driver and I want to provide the ability to uninstall.
Im leveraging the PNPUTIL.exe tool.
I know the syntax to delete and uninstall the driver, ex:
pnputil.exe /delete-driver oem103.inf /uninstall /force

But my issue, is the oem*.inf number designation is random on each machine, so I can't hard code the .inf into the command and call it a day.
pnputil has /enum-driver switch that will give you details of all the drivers in the DriverStore. Among the line items is the original name of .inf (something I can work with) and the oem# associated with it.
So what I need help with is scripting something that will enumerate the drivers pipe the results to the command to be able the run /delete-drive and /uninstall switches
I tried messing with the Find and FindSTR commands, but it only returned the one line which was the name of the original .inf. I need the OEM# associated with original name of the .inf to be piped to the command.

A: In the output of pnputil, the desired oemXX.inf is one line above the Original Name.
So numerate the output, look for the original name and subtract one from the line number. This is the line number where you find the oemXX.inf.
Then find that line and extract the oemXX string. (the for %%b is to get rid of the leading spaces)
@echo off
setlocal
set "Orig=rt640x64.inf"
pnputil /enum-drivers |findstr /n "^" > pnputil.txt
for /f "delims=:" %%a in ('findstr /c:" %Orig%" pnputil.txt') do set /a line=%%a-1
for /f "tokens=3 delims=:" %%a in ('findstr /b "%line%:" pnputil.txt') do for %%b in (%%a) do set "oem=%%b"
echo "%oem%"

Note: the output of pnputil is language-dependent, but this code doesn't look for words (except the "Original name" of course) but for line numbers, so it should work on all languages.


text:
Q: C# Windows Explorer File Preview How can I use the file preview of the explorer for files or generate a preview with a library?
I have tried the Windows Codepack API, but when trying to get the preview for all kind of office docs, I only get the Icon of the office doc, although the windows explorer shows the preview of the file correctly (windows 10)
Heres my code:
            MemoryStream m = new MemoryStream();
            ShellFile shellFile = ShellFile.FromFilePath(absolutePath);
            shellFile.Thumbnail.FormatOption = ShellThumbnailFormatOption.ThumbnailOnly;
            Bitmap shellThumb = shellFile.Thumbnail.ExtraLargeBitmap;
            shellThumb.Save(m, ImageFormat.Png);

Corresponding to this post I tried to fix the issue, but the approaches that were shown there didnt work Windows API Code Pack - ShellFile not generating PDF bitmap


text:
Q: Using atoi to convert string index to array index I'm doing a code which calculates the sum of the digits of a factorial, my solution was to convert the number to a string then put that string on an array.
I tried using atoi to convert a string index to the array index, but it doesn't work, giving me the error "passing argument 1 of 'atoi' makes pointer from integer without a cast"
#include <string.h>
#include <stdlib.h>
int fat(int x)
{
    if (x == 0 || x == 1)
    {
        return 1;
    }
    else
    {
        return x * fat(x-1);
    }
}

int main()
{
    int n, i, f=0, arr[30];
    char str[30];
    printf("Type the value of N: ");
    scanf("%d",&n);
    for (i=1;i<=n;i++)
    {
        f = fat(i);
    }
    printf("%d \n", f);
    sprintf(str, "%d", f);
    n=0;
    for (i=0;i<strlen(str);i++)
    {
        arr[i]=atoi(str[i]);
        n=n+arr[i];
    }
    printf("%d", n);
}

A: If you just want to convert a single digit character to a number, you don't need to use atoi(). Use str[i] - '0'.
        arr[i] = str[i] - '0';

There also doesn't seem to be much point to the array. You can just do:
        n += str[i] - '0';

without saving all the numbers in an array that you never use again.


text:
Q: Crop geographical boundaries in a heatmap in r ggplot I'm trying to crop a heat map (or "geom_tile") within a geographical boundary.
I define a random data frame for a heat-map along longitude and latitude coordinates.
set.seed(20)
lon = seq(from = 3.4, to = 6.3, by = 0.1)
lat = seq(from = 13.3, to = 10.1, by = -0.1)

lati <- c()
long <- c()
for (i in 1:length(lat)) {
  for (j in 1:length(lon)) {
    lati <- c(lati,lat[i])
    long <- c(long,lon[j])
  }
}

vals = rnorm(length(lati))

df <- data.frame(
longitude=long,
latitude=lati,
value=vals)

Then I make geographical boundary, specifically for Kebbi state in Nigeria.
library(raster)
library(sf)
nga <- getData('GADM', country='NGA', level=1)
keb <- subset(nga,NAME_1 %in% "Kebbi")
keb2 <- st_as_sf(keb)

Then I combine the heat map and geographical boundaries:
library(ggplot2)
tilekeb <- ggplot() + geom_tile(data=df,aes(x=longitude,y=latitude,fill=vals),alpha=1/2,color="black",size=0) +
  geom_sf(data = keb2, inherit.aes = FALSE, fill = NA)

This yields:

My aim is cut-out (crop) the part that is outside the boundary, leaving the heatmap only within the confined geographical boundary. Does anybody have ideas on how to do that in R/ggplot?
Thank you

A: I actually used raster to do the job
# create spatial points data frame from your df
spg <- df
coordinates(spg) <- ~ longitude + latitude
# coerce to SpatialPixelsDataFrame
gridded(spg) <- TRUE
# coerce to raster
rasterDF <- raster(spg)
# then I crop
plot(rasterDF)
rasterDF_crop <- crop(rasterDF, extent(keb2))
plot(rasterDF_crop)
rasterDF_masked <- mask(rasterDF_crop, keb2)
plot(rasterDF_masked)

then I convert it back to a dataframe :
df_masked <- raster::as.data.frame(rasterDF_masked,xy=TRUE)
colnames(df_masked) <- colnames(df)

and use your code to plot it again
library(ggplot2)
tilekeb <- ggplot() + geom_tile(data=df_masked,aes(x=longitude,y=latitude,fill=value),alpha=1/2,color="black",size=0) +
  geom_sf(data = keb2, inherit.aes = FALSE, fill = NA)

tilekeb