text:
Q: data contract is already present and the contracts are not equivalent I have an interface contract, and I'm developing a WCF with this contract.
But, there is something wrong because I'm getting this error:
The DataContract element of type ' Contract. Xyt. ObjectWithValXyt'1
[[Contract.Xyt.LayoutXyt, Contract, Version = 2. 5. 0. 0, Culture = neutral, PublicKeyToken = null]]'
You can add to DataContractSet, since the type ' Contract. Xyt. ObjectWithValXyt'1
[[Contract.Xyt.UnitTypeXyt, Contract, Version = 2. 5. 0. 0, Culture = neutral, PublicKeyToken = null]]'
with the same data contract 'ObjectWithVal' in the namespace 'http://myhost.com/Service/2013/09' is already present and the contracts are not equivalent.

And this is a piece of the implementation:
public class Service2 : IAutomationServiceWs
{
    public List<Contract.Xyt.UnitTypeInfoXyt> GetUnitTypeInfos()
    {
        return null;
    }

    public Contract.Xyt.ObjectWithValXyt<Contract.Xyt.UnitTypeXyt> GetUnitTypeAndValidate(Contract.Xyt.UnitTypeRefXyt unitTypeRef)
    {
        return null;
    }

    public List<Contract.Xyt.LayoutInfoXyt> GetLayoutInfos()
    {
        return null;
    }

Why am I getting this error when I run this service on Internet Explorer?

A: Try to do a 'Clean' before a 'Build' or debug.

A: As far as I can tell from the error message, you have 2 different contracts with the same name (ObjectWithVal). You might try to merge them or change the name of one of them.


text:
Q: Spring Why session get expired before session-timeout? I am using Spring security authentication and after successful logis is session set. I have configured session-timeout on 10 minutes, but session is removed after few minutes. I don't know why.
Here is debug output:
2013-09-13 12:34:29 DEBUG HttpSessionEventPublisher:83 - Publishing event: org.springframework.security.web.session.HttpSessionDestroyedEvent[source=org.apache.catalina.session.StandardSessionFacade@5d67c24a]
2013-09-13 12:34:29 DEBUG SessionRegistryImpl:156 - Removing session CA174F1B4B889FFDBF47E22C7C4D5A0B from principal's set of registered sessions
2013-09-13 12:34:29 DEBUG SessionRegistryImpl:164 - Removing principal org.springframework.security.core.userdetails.User@d50fea1e: Username: tester; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_MANAGER,ROLE_USER from registry

web.xml
<session-config>
    <session-timeout>10</session-timeout>
</session-config>

A: Session timeout can be overridden by various means.
See http://docs.oracle.com/javaee/1.3/api/javax/servlet/http/HttpSession.html#setMaxInactiveInterval(int).
Make sure there isn't anything else that is overriding it (Web/App server, framework, ...).

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I send a dice/casino/darts sticker as animated in telethon? I tried to send game stickers in telethon, but I could only send football and basketball stickers as games. Other stickers was static.

A: Those are not 'sticker' they're emoji. You send them as MediaDice file objects
import telethon
await client.send_file(chat,
telethon.types.InputMediaDice(''))


text:
Q: iPhone like Spinner for Android I Need a custom behavior for android as it is in iPhone.

Currently I need an arrangement for selecting the numbers as given in the above picture.
I tried http://code.google.com/p/customspinner/  , but there is no API to set the current value, we can get only the current value set. I should be able to keep set the current value to lets say 70 and this should work for different resolution android devices.


text:
Q: Apache Rewrite Rule gives 404 Paypal IPN Redirection I have been trying to get a rewrite rule working to redirect my old paypal IPN URL to my new one, I have tried the following in the .htaccess file and cant seem to get it to work, any help would be greatly appreciated!!
   # BEGIN PayPal Fix
   <IfModule mod_rewrite.c>
   RewriteEngine On
   RewriteRule ^/wc-api/WC_Gateway_Paypal/
   ^/hosting/modules/gateways/callback/paypal.php [R=307,L]
   </IfModule>
   END PayPal Fix

Another thread on stackoverflow about a similar issue: Change the IPN url on existing subscription
See jon G's post about his rewrite, that is exactly what im trying to accomplish!
Thank you for any and all guidance!

A: There seem to be some problems with your rewrite rule.
The minor problem is that it is unusual to write such a rule in two lines. In fact, I am not sure if this is allowed in the form you use; I would expect that there would have to be at least a line continuation character. So I would put the rule into a single line first.
But the main problem is in the target of your rewrite rule. While the first part of a rewrite rule is a search pattern (regular expression), the second part (target) isn't, so you should leave away the leading ^.
Your rule then should look like this:
RewriteRule ^/wc-api/WC_Gateway_Paypal/ /hosting/modules/gateways/callback/paypal.php [R=307,L]

But I am wondering why there is no script name in your search pattern. Do you really want to map a directory to a script? Or does WC_Gateway_Paypal just appear as directory, but in fact already is mapped to a script by a rewrite rule which is evaluated before?


text:
Q: Where to put the comma on the following sentence? Where do I put the comma in:

It would be pretty implausible to make a claim of your distributed patch
  that while directly intended to modify GPL source it wouldn't itself
  be GPL when that's precisely the requirement.

In there?:

It would be pretty implausible to make a claim of your distributed patch
  that while directly intended to modify GPL source it wouldn't itself
  be GPL, when that's precisely the requirement.

Or nowhere?
I require assistance.

A: Without commas, your sentence is difficult to follow. If you use commas to mark out the adverbial clauses, you'd make it much easier for the reader to follow your meaning. Like this:

It would be pretty implausible to claim that your distributed patch, while directly intended to modify GPL source, would not itself be GPL, when that's precisely the requirement.


text:
Q: jquery flot graph in dialog Problem: Display jquery flot graph in dialog box
I have a page which displays a horizontal bar graph using flot and this is interactive.
When i click on any of the bars, it executes getJSON and with the variables passed, plots another graph in an external php page.
I'm trying to get the graph drawn in the external php page displayed in the jquery dialog box.
Ive been looking everywhere but i'm unable to figure out a solution. Any help is appreciated.
    $.getJSON("page2.php?"+data, function(mdata) {
        $('

').html(result).dialog({
        autoOpen: false,
        modal: true,
        title: 'Page Hits - Monthly',
        width: 450, height: 300
    }).dialog('open');

page 2 is where the graph is drawn and i want to display the graph in the current page inside a dialog box.

A: maybe try $.get instead of $.getJSON
$.get('page2.php?'+data, function(response){
  $('

').html(response).dialog({
    autoOpen: true,
    modal: true,
    title: 'Page Hits - Monthly',
    width: 450, height: 300
  });
});

A: you could just create a PHP class to contain your data, store your graph data in an instance of the class and then pass the object as a post data to your dialog or popup window.
Then could create a method to process the custom data and draw the graph accordingly.


text:
Q: Wordpress deleted file info "UPDATE wp_options SET option_value" I am working on a forensics course, with which I have been looking into an attack on a blog server. I have found a number of deleted Wordpress files, and I have managed to figure out which ones contained blog posts.
The one file I cannot figure out contains information beginning with the following:
wordpress#UPDATE wp_options SET option_value = 'O:9:\"MagpieRSS\":19:{s:6:\"parser\";i:0;s:12:\"current_item\";a:0:{}s:5:\"items\";a:10:{i:0;a:9:{s:5:\"title\";s:37:\"India Vs Pakistan: Now Cyber Terror? \";s:6:\"author\";s:8:\"chinchak\";s:4:\"link\";s:59:\"http://feeds09.technorati.com/~r/trarticles/~3/sxlCqi2M9aE/\";s:4:\"guid\";s:74:\"http://technorati.com/politics/article/india-vs-pakistan-now-cyber-terror/\";s:11:\"description\";s:182:\"The India-Pakistan relations could very well be termed the greatest mystery ever of mankind.\";s:7:\"pubdate\";s:31:\"Tue, 21 Aug 2012 00:03:41 +0000\";s:8:\"category\";s:51:\"PoliticsAssam ViolenceCyber TerrorIndia Vs Pakistan\";s:10:\"feedburner\";a:1:{s:8:\"origlink\";s:74:\"http://technorati.com/politics/article/india-vs-pakistan-now-cyber-terror/\";}
It continues in this way for a while, but I haven't had too much luck trying to use Google to tell me what the "wp_options" means. It looks like someone was trying to spam the blog with commments but I can't be sure without a source which can confirm my view is correct. Can anybody help please?

A: The wp_option table stores key-value information in the columns option_name and option_value. When storing arrays they get serialized, to decode them you can use PHP's unserialize function. It looks like you're dealing with an SQL injection that tries to mess with Wordpress' user options. The purpose is not obvious, because they are rarely displayed. Just used internally. If there's a where clause somewhere in that SQL statement that tells you which option name it's trying to edit you could perhaps match it using this list:
http://codex.wordpress.org/Option_Reference


text:
Q: Consider defining a bean of type 'org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder' in your configuration I'm trying connect jwt token to my project and during the work I've some problems. I've followed instruction mentioned here, but i have errors. I was trying fix it with the same problem from these guys, but it didn't work for me. I guess, i'm missing something.
Could anyone please help me, thanks.
Error:
***************************
APPLICATION FAILED TO START
***************************

Description:

Parameter 1 of constructor in com.example.demo.security.WebSecurity required a bean of type 'org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder' that could not be found.

Action:

Consider defining a bean of type 'org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder' in your configuration.

WebSecurity.java
@EnableWebSecurity
public class WebSecurity extends WebSecurityConfigurerAdapter {
    private AppUserDetailsService appUserDetailsService;
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    public WebSecurity(AppUserDetailsService appUserDetailsService, BCryptPasswordEncoder bCryptPasswordEncoder) {
        this.appUserDetailsService = appUserDetailsService;
        this.bCryptPasswordEncoder = bCryptPasswordEncoder;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable().authorizeRequests()
                .antMatchers(HttpMethod.POST).permitAll()
                .anyRequest().authenticated()
                .and()
                .addFilter(new JWTAuthenticationFilter(authenticationManager()))
                .addFilter(new JWTAuthorizationFilter(authenticationManager()))
                // this disables session creation on Spring Security
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        http.csrf().disable();
    }

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(appUserDetailsService).passwordEncoder(bCryptPasswordEncoder);
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
        return source;
    }
}

AppUserDetailsService.java
@Service
public class AppUserDetailsService implements UserDetailsService {
    private UserRepository userRepository;

    public AppUserDetailsService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Users user = userRepository.findByUsername(username);

        if (user == null)
            throw new UsernameNotFoundException(username);

        return new User(user.getUsername(), user.getPassword(), emptyList());
    }
}

JWTAuthenticationFilter.java
public class JWTAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
    @Autowired
    private AuthenticationManager authenticationManager;

    public JWTAuthenticationFilter (AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
    }

    @Override
    public Authentication attemptAuthentication (HttpServletRequest req, HttpServletResponse res) {
        try {
            Users creds = new ObjectMapper().readValue(req.getInputStream(), Users.class);

            return authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(
                            creds.getUsername(),
                            creds.getPassword(),
                            new ArrayList<>())
            );
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    protected void successfulAuthentication(HttpServletRequest req,
                                            HttpServletResponse res,
                                            FilterChain chain,
                                            Authentication auth) throws IOException, ServletException {

        String token = JWT.create()
                .withSubject(((User) auth.getPrincipal()).getUsername())
                .withExpiresAt(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
                .sign(HMAC512(SECRET.getBytes()));
        res.addHeader(HEADER_STRING, TOKEN_PREFIX + token);
    }
}

A: add this to security package
   @Configuration
public class Encoder {
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

it`s work for me

A: Add this @Bean to your WebSecurity config:
@Bean
public BCryptPasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
}

Also, remove the BCryptPasswordEncoder from your constructor, including the field.

A: As stated above, you can of course use @Configuration and @EnableWebSecurity at the same time.
Before if you have @EnableWebSecurity it is working fine. Now I notice that on my latest Spring Boot application, I should add also Configuration to make it working.
@EnableWebSecurity
@Configuration
public class WebSecurityConfig {
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder(11);
    }
}


text:
Q: BIML Parameterized query on Ole db source I'm building multiple SSIS packages with BIML and i have to retrieve data from an OLE DB Source between a date interval. Here's the xml that is going to generate the packages:
<Dataflow Name="DFT Insert into <#=TableName#>">
    <Transformations>
        <OleDbSource Name="Retreive from Source (<#=TableName#>)" ConnectionName="AS400">
            <DirectInput>
                SELECT s.*
                FROM <#=TableSchema#>.<#=TableName#> s
                WHERE s.date > ? AND s.date <= ?
            </DirectInput>
            <Parameters>
                <Parameter Name="0" VariableName="User.StartDate"/>
                <Parameter Name="1" VariableName="User.MiddleDate"/>
            </Parameters>
        </OleDbSource>

        <OleDbDestination Name="Insert into Destination (<#=TableName#>)" ConnectionName="DB2Mirror" KeepNulls="true" CheckConstraints="false">
            <ExternalTableOutput Table="[<#=TableSchema#>].[<#=TableName#>]" />
        </OleDbDestination>
    </Transformations>
</Dataflow>

This structure would normally work, because i have already tried it but with IDs (int) instead of dates (string). The error that i'm receiving when trying to generate the package is the following:
Could not execute Query on Connection AS400
OleDbCommand.Prepare method requires all variable length parameters to have an explicitly set non-zero Size.

I know that i could create a ssis variable and concatenate the dates in the query as an expression, but i would like to stick with the <DirectInput> instead of the <VariableInput>
Additional information
The datetime (sorry I forgot to mention it was datetime, but i don't think it changes much) format in the variable is correct: yyyy-mm-dd hh:mm:ss. I'm pretty sure that there's nothing wrong with the format because i tried to create a variable as an expression, concatenating the dates like this: <Variable Name="Query" DataType="String" EvaluateAsExpression="true">"SELECT * FROM table WHERE col > '" + @[User::StartDate] + "'"</Variable> and it works. One thing i forgot to mention and it might be important is that the source dbms is a db2

A: Given the following table definition
CREATE TABLE dbo.so_42623962
(
    RowSk int NOT NULL
,   [Date] date
);

This was my minimum, viable Biml that uses parameters with OLE DB Sources
<Biml xmlns="http://schemas.varigence.com/biml.xsd">
<Connections>
    <OleDbConnection Name="tempdb" ConnectionString="Data Source=localhost\dev2016;Initial Catalog=tempdb;Provider=SQLNCLI11.0;Integrated Security=SSPI;"/>
</Connections>
<Packages>
    <Package Name="so_42623962" >
        <Variables>
            <Variable Name="StartDate" DataType="String">2017-01-01</Variable>
            <Variable Name="MiddleDate" DataType="String">2017-01-01</Variable>
        </Variables>
        <Tasks>
            <Dataflow Name="DFT Demo">
                <Transformations>
                    <OleDbSource Name="SRC Query" ConnectionName="tempdb">
                        <DirectInput><![CDATA[SELECT *
                        FROM dbo.so_42623962 AS X
                        WHERE X.[Date] > ? AND X.[Date] <= ? ;]]></DirectInput>
                        <Parameters>
                            <Parameter Name="0" VariableName="User.StartDate" />
                            <Parameter Name="1" VariableName="User.MiddleDate" />
                        </Parameters>
                    </OleDbSource>
                    <DerivedColumns Name="DER Placeholder" />
                </Transformations>
            </Dataflow>
        </Tasks>
    </Package>
</Packages>
</Biml>

That'll build a package just fine. If I take out the CDATA, which requires putting escaping the greater than/less than characters, it still works
        <Dataflow Name="DFT Escaped">
            <Transformations>
                <OleDbSource Name="SRC Query" ConnectionName="tempdb">
                    <DirectInput>SELECT *
                    FROM dbo.so_42623962 AS X
                    WHERE X.[Date] > ? AND X.[Date] <= ?;</DirectInput>
                    <Parameters>
                        <Parameter Name="0" VariableName="User.StartDate" />
                        <Parameter Name="1" VariableName="User.MiddleDate" />
                    </Parameters>
                </OleDbSource>
                <DerivedColumns Name="DER Placeholder" />
            </Transformations>
        </Dataflow>

If I don't wrap the Date column with braces, it still works
        <Dataflow Name="DFT Escapedx2">
            <Transformations>
                <OleDbSource Name="SRC Query" ConnectionName="tempdb">
                    <DirectInput>SELECT *
                    FROM dbo.so_42623962 AS X
                    WHERE X.Date > ? AND X.Date <= ?;</DirectInput>
                    <Parameters>
                        <Parameter Name="0" VariableName="User.StartDate" />
                        <Parameter Name="1" VariableName="User.MiddleDate" />
                    </Parameters>
                </OleDbSource>
                <DerivedColumns Name="DER Placeholder" />
            </Transformations>
        </Dataflow>

So what's left between my working Demo and yours? The easier thing to tackle is the value of your dates (Start/Middle Date). I used yyyy-mm-dd aka ccyy-mm-dd tends to be more universally understood by the systems I work with but you might try the ISO standard of yyyymmdd.
The harder piece to work with will be the fact that your connection manager was named AS400.  In fact, that rings a bell because I had to deal with a "weird" date on another question they used Julian dates but I see AS400 uses a CYMD format which is similarly "odd" and you'd have to write your own expression with a Derived Column to convert yyyy-mm-dd date to a CYMD. Shouldn't be hard but I won't hazard a guess given the richness of possible date formats.


text:
Q: How to Configure login UI for IdentityServer4? Examples I find for IdentityServer4 use MVC for login UI. When a OpenIdConnect implicit client hits the 'authorization_endpoint' (example 'http://localhost:5000/connect/authorize') it gets redirected to the AccountController Login action. How would you configure IdentityServer4 to use a different controller or UI for as the login page?

A: Under the ConfigureServices method (in Startup) add in a SetupIdentityServer options method:
services.AddIdentityServer(*SetupIdentityServer*)
        .AddSigningCredential(...)
        .AddValidationKeys()
        .AddConfigurationStore(builder => builder.UseSqlServer(""))
        .AddOperationalStore(builder => builder.UseSqlServer(""))
        .AddAspNetIdentity<ApplicationUser>();

...where SetupIdentityServer is the name of a method where you can set the login url:
private static void SetupIdentityServer(IdentityServerOptions identityServerOptions)
{
    identityServerOptions.UserInteraction.LoginUrl = "/Controller/Action";
}


text:
Q: How to configure bird OSPF for ipip link? I have a simple ipip tunnel between 192.168.56.254/31 and 192.168.56.255/31.
My simple test config on 192.168.56.254/31 looks like:
protocol ospf test
{
        import none;
        export none;

        area 0.0.0.0 {
                interface "ipip-tun" {
                        cost 5;
                        type ptp;
                        authentication none;
                        neighbors {
                                192.168.56.255;
                        };
                };
        };
}

192.168.56.255/31 is a Mikrotik router. Both instances can't see themselves.
In tcpdump on 192.168.56.254/31, I see:
08:26:11.634115 IP 192.168.56.254 > 224.0.0.5: OSPFv2, Hello, length 44
08:26:11.990261 IP 192.168.56.255 > 224.0.0.5: OSPFv2, Hello, length 44

In the packet sniffer on the Mikrotik device I can see the transmitted packages (also to the multicast address) but no received one.
It confuses me that even the ptp mode uses multicast. Is this normal? If yes, are any configurations for the ipip tunnel required to make multicast work?

A: IPIP tunnel supports unicast only while OSPF ptp runs on mcast, that's why you're not getting the packet on the other side. If you need multicast, use GRE tunnel.


text:
Q: Does AND work in Excel spreadsheet formulae using Ctrl-Shift-Enter? I have an Excel (2010) cell with this formula:
{=SUM(IF('Tasks'!$I:$I=$C4,'Tasks'!$F$2:$F$2000,0))}

which works (the correct total is given). But when I enter another item to search for:
{=SUM(IF(AND('Tasks'!$H:$H=B4,'Tasks'!$I:$I=$C4),'Tasks'!$F$2:$F$2000,0))}

it does not work (total is zero). Does AND not work in this case? Or have I made an error?
Explanation of code: I have two sheets, a Total sheet (where this code is placed) and a Tasks sheet. The Tasks sheet contains work priority (in H column), people (in I column) and estimated time (in F column). So I want to find out, per person and per tasks priority, how much work is estimated. The first line of code is just estimated time per person which, as I wrote, works fine. On the Total sheet, B4 contains the priority of the current item and C4 the name of the current person.

A: In short, No, AND doesn't do what you need here because it returns a single result (only TRUE if all conditions for all cells are TRUE) rather than an "array" of TRUE/FALSE values for each cell in the range.
You need to use * (to multiply and simulate AND) or use multiple IFs
Also you should keep the ranges the same size, in which case you can use this "array formula"
=SUM(IF(('Tasks'!$H$2:$H$2000=B4)*('Tasks'!$I$2:$I$2000=$C4),'Tasks'!$F$2:$F$2000))
confirmed with CTRL+SHIFT+ENTER
....but in Excel 2010 SUMIFS would be preferable (with sum range at the start), i.e.
=SUMIFS('Tasks'!F:F,'Tasks'!H:H,B4,'Tasks'!I:I,C4)

A: You can use a nested IF like so:
{=SUM(IF('Tasks'!$H:$H=B4, if('Tasks'!$I:$I=$C4, 'Tasks'!$F$2:$F$2000,0), 0))}


text:
Q: Drools decision table - one column - two fields Let's suppose we have some class which is related to one or more codes: main and secondary. Every object of this class has at least main code and can have unlimited number of secondary codes:
class Something {

  private String mainCode;
  private List<String> secondaryCodes;
}

I want to make a rule in Drools decision table which allows me to check if value given in column is equal to mainCode or is contained by secondaryCodes.
So I need one column for two rules related to two different fields.
Is it even possible?

A: The constraint can be written as a compound Boolean expression:
mainCode == $param || secondaryCodes contains $param

There's no restriction as to the fields you refer to in such an expression.

A: You can do this in Guvnor using @{param} in a Condition BRL fragment like:
  $s : Something (maincode == "@{codes}" || secondaryCodes contains "@{codes}"

That gives you one column.
-J


text:
Q: What makes a PC able to be a web server and what makes it unable? I have a question about using a computer as a web server. Why can a certain computer be a web server? What features make it able to be a web server? Is there any case where a computer is unable to act as a web server?

A: Pretty much any computer can be used as a [web] server, provided it can connect to a network, and can run web server software. As a web server can be quite simple, and there are free and open source web servers, in practice, any device can act as a web server.
The bigger problem is the networking side.  In order for a system to act as a server, other machines need to be able to access it.  If it's just for use in a LAN, there are no concerns; however, if it's for use from the wider Internet, then data needs to be routed to it.   This requires either a static IP address associated with the server (or port forwarded through a router), or an external service which can map a domain name/subdomain to a changing dynamic IP address.
(FWIW, you can buy $10 computers which can act as a basic web server.)
Of course, while any device can act as a web server, functionality of web sites can vary hugely, and a cheap device (or slow connection) may not be able to keep up with demands depending on what the specific website is.
I note that everything above talks about web servers - but the same can be said for pretty much any type of server.

A: Programming/Software perspective:
A program that is able to listen to Port 80 on Network adapter. That runs on the OS you have. And can process the requests according to HTTP definitions.
A program that listens to any port is reachable from every computer in the same network. Ideally, it should be a known standard port (80 and 8080 for HTML servers; pick beyond 1024 for custom applications). It is even common practice to run development of a network reachable program on the same computer you are doing the development on.
If you can reach it via localhost, you can reach it from anywhere within the same network, and from anywhere else there is a path to this machine and its network adapter.
Caveat: A lot of all-in-one development environments in default installations limit access to Localhost. You do not want your admin tools reachable from the Internet, after all.
Hardware:
The hardware begins somewhere at "that 10-year-old computer that runs XP or Linux" and ends somewhere around "128 core, with 2 TiB RAM and 256 TiB of SSDs in a raid", with the DB running on a different server too. Web applications tend to be pleasingly parallelizable, so you can/have to up it even more with clusters of those servers. And Geocast. And distributed design. And a lot of other stuff. It entirely depends on what scale we are talking about.
The simplest web server you are likely to meet is the router you are using, btw. They all run a Web server for configuration purposes, hosted on a Linux (that is doing all the DHCP and NAT work).
Networking:
Having a path from other networks – including anywhere on the Internet – now that is a totally different story and a part even harder than programming the application. Between the NAT of your Router and carrier grade NAT, this stuff became really hard.

*

*You always have the option to buy a fixed IP address from your ISP, even as private person. As it indicates, that will likely cost extra. A DNS entry would be a quality of life thing.

*Back before Carrier Grade NAT, you could work with your Dynamic IP address and a DynDNS service. But with carrier grade NAT, you now have another uncontrollable NAT to overcome - maybe. Depends on your provider.

*The ultimate solution to traverse a kind of NAT, any number of layers is TCP/IP hole punching. All VPN solutions use it. As do Skype, TeamViewer and all the others. The problem is: In order to do TCP/IP hole punching, you need a server already reachable on the Internet.

*If it is about small scales (1 to 10 endpoints), usually, the simplest way is to just make a VPN connection into the network having the servers. Most Routers have support for it.

A: If you have on hand any kind of computer (PC, laptop, smartphone, raspberryPI...) with Python installed, just type:
$ python -m SimpleHTTPServer

Or if you have Node.js installed:
$ npm install http-server -g
$ http-server

Congratulation, you have a web server!

A: It's not tricky at all. It merely depends on your definition of "web server".
It's entirely possible to run a "web server" on devices as simple as a microcontroller.
Let is consider what the bare minimal web server would need to do. It would need to output some text - not necessarily even in HTML to a client. It would need to know a request is a request, and respond appropriately. You wouldn't even need network connectivity if your "client" was local. It would be an entirely pointless web server.
It would be the web server equivalent of one of these.

Adding network connectivity for a client (Ethernet is nice, but there's no technical reason you can't connect to a web server running on wifi) and being able to route from a client would be better.
A $5 ESP8266 – a cheap, minimal microcontroller with wifi can handle much of that, and maybe even basic dynamic content
I use something like that for quick file sharing using Python. It's still entirely possible to write something like this on a microcontroller or even run it on a phone.
Static content is boring. Add dynamic languages and you'd need to start thinking of heavier weight systems. Stuff that runs Linux or Windows are nice.
At this point, you're talking consumer routers, small applications using web pages at UI and all that.
A web server isn't even a complex problem and can be written in five lines of bash and run on Linux. Now doom... But any system that can run doom can run a web server.
A good web server setup capable of handling a given load is somewhat trickier.

A: Bare minimum
Literally, any computer can become a web server if it has the following:

*

*A network connection

*A very simple web server app, like this.

But would it suffice? Now, that's the tricky question.
Serving an Intranet
For a computer to become a web server that serves modern web pages or web apps to a whole community (e.g. school, company, museum):

*

*Hardware capable of responding several computers at once. Maybe an old computer running Linux or Windows XP would do.

*A high-speed network connection with enough bandwidth, say 1 Gbit/sec Ethernet or 802.11g Wi-Fi.

*A good web server app, like IIS, Apache, Nginx or others. (Surprisingly, these three are free.)

But that was just a minimum for small operations. When your operation gets bigger (i.e. you get a heavier traffic and serve complex web apps instead of static pages), your needs grow. You will eventually need:

*

*Server-class hardware like rack-mounted servers with several Xeon CPUs and hundreds of gigabytes of RAM

*Fiber-optic networks

Serving the world outside
To exploit the Internet infrastructure to serve the whole world, you will need:

*

*A public IP address

*A public DNS server

*Digital certificates issued by reputable certificate authorities for establishing a secure connection

Without these, all you have is a potential web server.


text:
Q: How can I read Gradle metadata in a Jenkinsfile Within my Jenkinsfile I would like to read some metadata from a Gradle buildscript, e.g. group, baseNameand version. With Maven, I can do something like this:
def pom = readMavenPom file: 'pom.xml'
env.POM_VERSION         = pom.version
env.POM_ARTIFACT_ID     = pom.artifactId
env.POM_GROUP_ID        = pom.groupId

Question is: how can I do the same thing with Gradle, given I have a build.gradle that looks like this:
ext {
    group = 'my.group.com'
    baseName = 'myapplication'
    version = '0.5.2-SNAPSHOT'
}

Maybe there is a "trick" to read Gradle build information in a Jenkinsfile since both is Groovy, but I am a Groovy newb :)


text:
Q: How to sum the data in specific level after groupby or pivot_table with multi-index dataframe Here are my schematic diagram for my question.
After I ran "groupby" or "pivot_table" for my dataframe as below, I got an dataframe ② with "A","B" index.  However, I doesn't need much more data. So I would like to aggregate the data in specific index level.
Then I can get the last one dataframe ③.  b should summarise e\f index data, 1+1 = 2
This function just like the fold behavior in Excel. I checked the document(pivot_table), but "margins" this parameter is unfit for this requirement.
Thanks!!

A: I don't know such a function, but here is a workaround:
df
     C
A B
a p  1
  q  1
d r  2
  s  2
b t  3
  v  3
  w  3
c x  4
  y  4

fld=["d","b","c"]
nfidx=df.index.levels[0].difference(fld)

   Index(['a'], dtype='object', name='A')

df2= df.loc[fld].groupby("A").sum()

       C
    A
    b  9
    c  8
    d  4

mi= pd.MultiIndex.from_product([df2.index,[np.nan]],names=["A","B"])

    MultiIndex([('b', nan),
                ('c', nan),
                ('d', nan)],
               names=['A', 'B'])

df2.index=mi

           C
    A B
    b NaN  9
    c NaN  8
    d NaN  4

pd.concat([ df.loc[nfidx],df2])

           C
    A B
    a p    1
      q    1
    b NaN  9
    c NaN  8
    d NaN  4


text:
Q: Adding NPM javascript library to Laravel 8 I'm using the mobiscroll javascript component library with a new Laravel 8 app I'm building. I've used the trial scripts by simply copying the minified css / js to the public/css and public/js directories of my laravel app, and then pushing the script / css files into the layout's stack.
I'd like to be able to require these more "natively" by installing the module via npm and referencing the module. In a react app I'd have no problem with this-- but how is it done in laravel?
I've tried adding window.mobiscroll = require('@mobiscroll/javascript'); to the bootstrap.js file, since that seems to be how the axios and _ libraries are being made available, but I still am getting Uncaught ReferenceError: mobiscroll is not defined errors when I try to initialize a component.
I also tried adding it to the app.js file like this:
require('alpinejs');
require('@mobiscroll/javascript');

with the same error as before. I am running npm run watch so the mix process is happening and succeeding with each attempt, so I don't think it's simply a problem with caching or compilation.
I didn't see anything that seemed to address this on SO or the laravel docs.
EDIT: having the same issue with dayjs, added via npm i dayjs, added to bootstrap.js using window.dayjs = require('dayjs');, compiled via mix, cleared all caches, and still getting error dayjs is not defined.

A: First, install Mobiscroll in your root Laravel folder.
npm install @mobiscroll/javascript-lite --save-dev

Then you want to reference the JS and CSS in the appropriate spots.
In resources/js/bootstrap.js.
try {
    window.mobiscroll = require('@mobiscroll/javascript-lite');

    require('bootstrap');
} catch (e) {
}

In resources/css/app.css.
@import '~@mobiscroll/javascript-lite/dist/css/mobiscroll.css';

If your webpack.mix.js is something like this...
const mix = require('laravel-mix');

mix.js('resources/js/app.js', 'public/js')
    .postCss('resources/css/app.css', 'public/css', [
        //
    ]);

Do an npm run prod.
Make sure you reference your generated CSS file in your Blade template/layout.
<link type="text/css" rel="stylesheet" href="{{ mix('css/app.css') }}">

Also, for JS.
<script src="{{ mix('js/app.js') }}" defer></script>


text:
Q: Dotnet Core project ran into error after upgrading Angular CLI and Core to the latest version I am new to Open source technologies so I am still trying to understand how npm, node and everything works.

*

*Dotnet version : 2.2.102

*Node version : v11.14.0

*NPM version : 6.5.0

I had created a Single Page Angular project with ASP.NET Core using dotnet CLI. Today I decided to upgrade the Angular Core and Angular CLI.
Upgrade details:

*

*Angular core : from 6.1.10 to 7.2.15

*Angular CLI : from 6.0.0 to 7.3.9

After successful upgrade, I also ran npm audit fix as a habit but it returned with 0 dependencies fixed and I didn't care much about it.
Then I executed the command "dotnet build" which said Build Succeeded.
So I moved on to run "dotnet run" command and that's when it started showing errors :

info:
  Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[0]
        User profile is available. Using 'C:\Users\RecursionParameter\AppData\Local\ASP.NET\DataProtection-Keys'
  as key repository and Windows DPAPI to encrypt keys at rest. info:
  Microsoft.AspNetCore.SpaServices[0]
        Starting @angular/cli on port 4777... Hosting environment: Development Content root path: F:\Daily Usage\Projects\dotnet
  core\checklist Now listening on: https://localhost:5001 Now listening
  on: http://localhost:5000 Application started. Press Ctrl+C to shut
  down. info: Microsoft.AspNetCore.SpaServices[0]

checklist@0.0.0 start F:\Daily Usage\Projects\dotnet core\checklist\ClientApp
    ng serve "--port" "4777"

** Angular Live Development Server is listening on localhost:4777, open your browser on http://localhost:4777/ **
info: Microsoft.AspNetCore.SpaServices[0]
        Date: 2019-05-20T12:14:01.608Z Hash: 0c8a551fd7e094fbe22d Time: 4701ms chunk {main} main.js, main.js.map (main) 1.96 kB [initial]
  [rendered] chunk {polyfills} polyfills.js, polyfills.js.map
  (polyfills) 92.4 kB [initial] [rendered] chunk {runtime} runtime.js,
  runtime.js.map (runtime) 6.08 kB [entry] [rendered] chunk {styles}
  styles.css, styles.css.map (styles) 126 kB [initial] [rendered] chunk
  {vendor} vendor.js, vendor.js.map (vendor) 327 kB [initial] [rendered]
fail: Microsoft.AspNetCore.SpaServices[0]
fail: Microsoft.AspNetCore.SpaServices[0]
        ERROR in node_modules/@angular/core/src/di/injector.d.ts(68,70): error TS1005: ',' expected.
        node_modules/@angular/core/src/render3/definition.d.ts(317,32): error TS1005: ')' expected.
        node_modules/@angular/core/src/render3/definition.d.ts(317,33): error TS1003: Identifier expected.
        node_modules/@angular/core/src/render3/definition.d.ts(317,83): error TS1005: ';' expected.
        node_modules/@angular/core/src/render3/definition.d.ts(317,84): error TS1131: Property or signature expected.
        node_modules/@angular/core/src/render3/definition.d.ts(317,98): error TS1005: '=>' expected.
        node_modules/@angular/core/src/render3/definition.d.ts(328,16): error TS1109: Expression expected.
        node_modules/@angular/core/src/render3/definition.d.ts(372,12): error TS1109: Expression expected.
        node_modules/@angular/core/src/render3/definition.d.ts(372,28): error TS1005: ']' expected.
        node_modules/@angular/core/src/render3/definition.d.ts(372,29): error TS1005: ',' expected.
        node_modules/@angular/core/src/render3/definition.d.ts(372,30): error TS1136: Property assignment expected.
        node_modules/@angular/core/src/render3/definition.d.ts(372,31): error TS1136: Property assignment expected.
        node_modules/@angular/core/src/render3/definition.d.ts(372,40): error TS1005: ':' expected.
        node_modules/@angular/core/src/render3/definition.d.ts(372,70): error TS1005: ',' expected.
        node_modules/@angular/core/src/render3/definition.d.ts(383,13): error TS1109: Expression expected.
        node_modules/@angular/core/src/render3/definition.d.ts(383,29): error TS1005: ']' expected.
        node_modules/@angular/core/src/render3/definition.d.ts(383,30): error TS1005: ',' expected.
        node_modules/@angular/core/src/render3/definition.d.ts(383,31): error TS1136: Property assignment expected.
        node_modules/@angular/core/src/render3/definition.d.ts(383,32): error TS1136: Property assignment expected.
        node_modules/@angular/core/src/render3/definition.d.ts(383,41): error TS1005: ':' expected.
        node_modules/@angular/core/src/render3/definition.d.ts(383,52): error TS1005: ',' expected.
info: Microsoft.AspNetCore.SpaServices[0]
        i 「wdm」: Failed to compile.

I have no idea what happened here.


text:
Q: Kähler classes for surfaces of general type with $c_1^2=3c_2$ Given a smooth, compact complex surface with ample canonical bundle satisfying $c_1^2=3c_2$, is it true that every Kahler class is a multiple of $c_1$? This seems to be the case for fake projective planes, because $b_2=1$.

A: The answer is no.
A counterexample is provided by the so-called Cartwright-Steger surface $X$, namely a surface of general type  with $p_g(X)=q(X)=1$ and $K_X^2=9$.
Such a surface has Picard rank $3$, and moreover $\mathrm{NS}(X)=H^{1, 1}(X)$, in other words all Hodge classes in $X$ are algebraic. In particular, the vector space $$H^{1, 1}_{\mathbb{R}}(X):=H^{1,1}(X) \cap H^1(X, \, \mathbb{R})$$ has real dimension $3$, because its complexification is $H^{1, 1}(X).$
On the other hand, by general facts the Kähler cone $\mathcal{K}_X$ of $X$ is an open, convex cone in $H^{1,1}_{\mathbb{R}}(X)$, hence it cannot be of dimension $1$.


text:
Q: Cannot access IP on local network but can internet I am facing a peculiar problem . I have a http server running on one computer (say computer A) . I can access this server from one computer(say computer B) but not from another (OS Ubuntu )(say computer C) in same network (Local network).
The computer C has no problems accessing Internet but cannot access http server on computer A in same network . Computer A and computer C have no problem pinging each other . Please Help.

A: Can computer C ping computers A or B?
What is the netmask set for on all of the computers? Does the netmask of the router match that on the computers?


text:
Q: JS RegExp finding word that is not in tag and replace string I need to write a second RegExp to find variable d inside sentence that is not in tags. So variable in tags should be skipped.
Regex '(?:^|\\b)('+d+')(?=\\b|$)' will find d variable but i need to exclude  tag with class="description".
New sentence is wrapped in a new tag.
sentence = "This is some word. word in tag should be skipped"
d = 'word'
re = new RegExp('(?:^|\\b)('+d+')(?=\\b|$)', 'gi')
sentence = sentence.replace(re, "$1")

Result I'm trying to achieve is:
"This is some word. word in tag should be skipped"

I'm using coffeescript, thanks for the help.

A: Try this one: (word)(?![^<>]*<\/)
Full code:

var sentence = "This is some word. word in tag should be skipped"
var d = 'word'
var re = new RegExp('('+d+')(?![^<>]*<\/)', 'gi')
sentence = sentence.replace(re, "$1")

I based this answer on this snippet: https://regex101.com/library/gN4vI6

A: Trying to manipulate HTML with regular expressions is not a good idea: sooner or later you'll bump into some boundary condition where it fails. Maybe some < or > occur inside attribute values, or even inside text nodes, while the searched term may also occur at unexpected places, like in HTML comments, attribute values, or script tags, ...  The list of boundary cases is long.
Furthermore, your search term may contain characters that have a special meaning in regular expression syntax, so you should at least escape those.
Here is a solution that interprets the string as HTML, using the DOM capabilities, and only replaces text in text nodes:

function escapeRegExp(str) {
    return str.replace(/[\[\]\/{}()*+?.\\^$|-]/g, "\\$&");
}

function wrapText(sentence, word) {
    const re = new RegExp("\\b(" + escapeRegExp(word) + ")\\b", "gi"),
        span = document.createElement('span');
    span.innerHTML = sentence;
    Array.from(span.childNodes, function (node) {
        if (node.nodeType !== 3) return;
        node.nodeValue.split(re).forEach(function (part, i) {
            let add;
            if (i%2) {
                add = document.createElement('span');
                add.textContent = part;
                add.className = 'someClass';
            } else {
                add = document.createTextNode(part);
            }
            span.insertBefore(add, node);
        });
        span.removeChild(node);
    });
    return span.innerHTML;
}

const html = 'This is some word. word should stay',
    result = wrapText(html, 'word');

console.log(result);

Recursing into elements
In comments you mentioned that you would now also like to have the replacements happening within some tags, like p.
I'll assume that you want this to happen for all elements, except those that have a certain class, e.g. the class that you use for the wrapping span elements, but you can of course customise the condition to your needs (like only recursing into p, or ...).
The code needs only a few modifications:

function escapeRegExp(str) {
    return str.replace(/[\[\]\/{}()*+?.\\^$|-]/g, "\\$&");
}

function wrapText(sentence, word) {
    const re = new RegExp("\\b(" + escapeRegExp(word) + ")\\b", "gi"),
        doc = document.createElement('span');
    doc.innerHTML = sentence;

    (function recurse(elem) {
        Array.from(elem.childNodes, function (node) {
            // Customise this condition as needed:
            if (node.classList && !node.classList.contains('someClass')) recurse(node);
            if (node.nodeType !== 3) return;
            node.nodeValue.split(re).forEach(function (part, i) {
                let add;
                if (i%2) {
                    add = document.createElement('span');
                    add.textContent = part;
                    add.className = 'someClass';
                } else {
                    add = document.createTextNode(part);
                }
                elem.insertBefore(add, node);
            });
            elem.removeChild(node);
        });
    })(doc);
    return doc.innerHTML;
}
const html = '
Some word
. word should stay',
    result = wrapText(html, 'word');
console.log(result);


text:
Q: C#: IComparable implementation private I'm new to C# so this might be a really dump question: I implemented IComparable in my class and want to test it with NUnit. But the CompareTo-Method is marked as private and thus not accessible from the test.
What's the reason for this and how can I fix this?

The IComparable:

public class PersonHistoryItem : DateEntity,IComparable
    {
     ...
        int IComparable.CompareTo(object obj)
        {
            PersonHistoryItem phi = (PersonHistoryItem)obj;
            return this.StartDate.CompareTo(phi.StartDate);
        }
    }

The test:

        [TestMethod]
        public void TestPersonHistoryItem() {
            DateTime startDate = new DateTime(2001, 2, 2);
            DateTime endDate = new DateTime(2010, 2, 2);
            PersonHistoryItem phi1 = new PersonHistoryItem(startDate,endDate);

        PersonHistoryItem phi2 = new PersonHistoryItem(startDate, endDate);

        Assert.IsTrue(phi1.CompareTo(phi2)==0);
    }

A: They are not private, they are just explicitly implemented. Declaring your variables as IComparable should solve the problem:
[TestMethod]
public void TestPersonHistoryItem() {
    DateTime startDate = new DateTime(2001, 2, 2);
    DateTime endDate = new DateTime(2010, 2, 2);
    IComparable phi1 = new PersonHistoryItem(startDate,endDate);

    IComparable phi2 = new PersonHistoryItem(startDate, endDate);

    Assert.IsTrue(phi1.CompareTo(phi2)==0);
}

A: var p1 = (IComparable)phi1;
var p2 = (IComparable)phi2;

Assert.IsTrue(p1.CompareTo(p2) == 0);

A: I think the easiest way would be to use implicit interface implementation:
public class PersonHistoryItem : DateEntity, IComparable
{
    ...
    public int CompareTo(object obj)
    {
        PersonHistoryItem phi = (PersonHistoryItem)obj;
        return this.StartDate.CompareTo(phi.StartDate);
    }
}

A: In C# an interface does not define accessors, so you can make your CompareTo method public and change the explicit interface implementation from:
int IComparable.CompareTo(object obj)

To:
public int CompareTo(object obj)

A: Your approach uses explicit interface implementation. That means that the interface methods will not show up on your class unless a cast is done.
Do this:((IComparable)phi1).CompareTo(phi2)

A: The main problem here is that you explicitly implements the CompareTo method, which only allows you to use it when you use your object as a IComparable object.
To correct the problem, specify the visibility as public and implement the CompareTo method not "explicitly" :
public class PersonHistoryItem : DateEntity,IComparable
{
    ...

    public int CompareTo(object obj)
    {
        PersonHistoryItem phi = (PersonHistoryItem)obj;
        return this.StartDate.CompareTo(phi.StartDate);
    }
}


text:
Q: How to use enable if with template arguments and parameter pack? I was working around with c++ templates and came across this piece of code which is using SFINAE using std::enable_if. I am facing two issues with this code.
#include <string>
#include <iostream>

enum class Type : int { First = 1, Second, Third };

template <Type T>
struct Symbol : public std::true_type {
  using Parent = std::true_type;
  using type = Parent::value_type;
  static constexpr type value = Parent::value;
  static constexpr type GetValue() {
        if constexpr (T == Type::First) return value;
    else return !value;
  }
};

template <bool b>
using EnableIf = typename std::enable_if<b, int>::type;

template <Type T> static constexpr bool IsTradingSymbol() {
  return Symbol<T>::GetValue();
}

template <Type T, EnableIf<IsTradingSymbol<T>()>...>
bool GetErrorForUi(Type A) {
  return true;
}
template <Type T, EnableIf<!IsTradingSymbol<T>()>...>
bool GetErrorForUi(Type A) {
  return false;
}

int main () {
  std::cout << GetErrorForUi<Type::First>(Type::First) << std::endl;
  std::cout << GetErrorForUi<Type::Second>(Type::Second) << std::endl;
  return 0;
}

1) Why parameter pack used in EnableIf<IsTradingSymbol<T>()>.... If I remove the ... then the code fails in the compilation. I am unable to deduce the exact error from the trace and why this ... is needed at all there? (compiled with GCC 7.4.0).
enableif.cpp: In function 'int main()':
enableif.cpp:43:54: error: no matching function for call to 'GetErrorForUi<First>(Type)'
   std::cout << GetErrorForUi<Type::First>(Type::First) << std::endl;
                                                      ^
enableif.cpp:26:6: note: candidate: template<Type T, typename std::enable_if<IsTradingSymbol<T>(), int>::type <anonymous> > bool GetErrorForUi(Type)
 bool GetErrorForUi(Type A) {
      ^~~~~~~~~~~~~
enableif.cpp:26:6: note:   template argument deduction/substitution failed:
enableif.cpp:43:54: note:   couldn't deduce template parameter '<anonymous>'
   std::cout << GetErrorForUi<Type::First>(Type::First) << std::endl;
                                                      ^
enableif.cpp:30:6: note: candidate: template<Type T, typename std::enable_if<(! IsTradingSymbol<T>()), int>::type <anonymous> > bool GetErrorForUi(Type)
 bool GetErrorForUi(Type A) {
      ^~~~~~~~~~~~~
enableif.cpp:30:6: note:   template argument deduction/substitution failed:
enableif.cpp:43:54: note:   couldn't deduce template parameter '<anonymous>'
   std::cout << GetErrorForUi<Type::First>(Type::First) << std::endl;
                                                      ^
enableif.cpp:44:56: error: no matching function for call to 'GetErrorForUi<Second>(Type)'
   std::cout << GetErrorForUi<Type::Second>(Type::Second) << std::endl;
                                                        ^
enableif.cpp:26:6: note: candidate: template<Type T, typename std::enable_if<IsTradingSymbol<T>(), int>::type <anonymous> > bool GetErrorForUi(Type)
 bool GetErrorForUi(Type A) {
      ^~~~~~~~~~~~~
enableif.cpp:26:6: note:   template argument deduction/substitution failed:
enableif.cpp:44:56: note:   couldn't deduce template parameter '<anonymous>'
   std::cout << GetErrorForUi<Type::Second>(Type::Second) << std::endl;
                                                        ^
enableif.cpp:30:6: note: candidate: template<Type T, typename std::enable_if<(! IsTradingSymbol<T>()), int>::type <anonymous> > bool GetErrorForUi(Type)
 bool GetErrorForUi(Type A) {
      ^~~~~~~~~~~~~
enableif.cpp:30:6: note:   template argument deduction/substitution failed:
enableif.cpp:44:56: note:   couldn't deduce template parameter '<anonymous>'
   std::cout << GetErrorForUi<Type::Second>(Type::Second) << std::endl;

2) The code is not compiling with icc X86-64 (intel compiler 19.0.1). Does the compiler not support std::enable_ifsfinae or is it a bug with the intel compiler itself?

A:
1) Why parameter pack used in EnableIf()>.... If I remove the ... then the code fails in the compilation. I am unable to deduce the exact error from the trace and why this ... is needed at all there? (compiled with GCC 7.4.0).

Look at EnableIf<IsTradingSymbol<T>()>.
It is
template <bool b>
using EnableIf = typename std::enable_if<b, int>::type;

So is int when the condition is true, nothing otherwise.
Suppose the condition IsTradingSymbol<T>() is true; so
template <Type T, EnableIf<IsTradingSymbol<T>()>...>
bool GetErrorForUi(Type A) {
  return true;
}

become
template <Type T, int ...>
bool GetErrorForUi(Type A) {
  return true;
}

Now you have a template function. It requires some, non deducible from the arguments, parameters: a Type (T), that is mandatory, and a list of integers, zero or more.
You call the function as follows
GetErrorForUi<Type::First>(Type::First);

So you pass to the function, as template parameter, only a Type. Non integers.
This works because the function expect zero or more integers.
But when you remove the ellipsis (...), the function become
template <Type T, int>
bool GetErrorForUi(Type A) {
  return true;
}

Now GetErrorForUi() expect two template parameter: a Type and a int. Exactly one int, no more zero or more.
Now one integer is mandatory and only one is acceptable.
So now the call
GetErrorForUi<Type::First>(Type::First);

doesn't works (gives compilation error) because you don't pass the mandatory template int parameter.
And also
GetErrorForUi<Type::First, 0, 1>(Type::First);

doesn't works (after the ellipsis removing; before should compile) because the functions expects exactly one integer and you pass two ints.
This should answer also to your second point.

A: Traditional way is:
template <Type T, std::enable_if_t<condition_v<T>, int> = 0>
bool GetErrorForUi(Type A);

And not
template <Type T, std::enable_if_t<condition_v<T>, int>...>
bool GetErrorForUi(Type A);

So after Substitution, it is
template <Type T, int /*unnammed*/ = 0>
bool GetErrorForUi(Type A);

template <Type T, int /*unnammed*/...>
bool GetErrorForUi(Type A);

If Substitution Failure happens, it is Not An Error (SFINAE), and those overload are discarded


text:
Q: PHP Class and MySQL I am creating a class and I want to use a MySQL query in most of the classes, its a generic query that checks a certain row in the 'project' table when the customer logs in.
mysql_query("SELECT `id`,`username`,`email` FROM `project` WHERE `id`='{$_COOKIE['id']}'");

That was just an example query I know it isn't secure.
How could I do that without having to define it in every function in an optimized manner?
Sorry just having a brain fart since I haven't done PHP in a few months and have been using other languages.

A: when user logs in use sessions
$_session['username'] = $row['username'] ;// this row is when you fetch query when user log in

then use
$_session['username']

every where in your pages.
 dont forget to start at top of pages
 session_start();

A: Please note that the function you are using to do a query is unsafe and deprecated.
My advise would be to use PDO instead.
If you are using classes you could extend your classes with the class doing the database query. If the result of your query is static (as in : it will always be the same for that user) , I'd set a session instead.


text:
Q: understanding python twisted asynchronicity in terms of operating system I'm new to the twisted library and I'm trying to understand how it is done that operations in python/twisted are performed asynchronously. So far I thought that only GUI-alike (Qt or javascript) platforms use event-driven architecture extensively.
facts:

*

*Twisted programs are run in one thread = no multithreading

*reactor and deferred patterns are used: callbacks/errbacks are declared and the execution of everything is controlled by reactor main loop

*a single CPU can never do anything truly parallelly, because it shares its resources between processes, etc. By parallel code execution I mean that the programming platform (python, javascript, whatever) executes more than one sequence of operations (which can be done, for example, using multithreading)

question 1
Python could be seen as a high-level wrapper for the operating system. What are the OS functions (or C functions) that provide asynchronous operation handling? Are there any?
question 2
Q1 leads me to an idea, that twisted's asynchronicity is not a true asynchronicity, like we have in Javascript. In JavaScript, for example, if we provide 3 different buttons, attach callback functions to them and we click all three buttons - then the 3 callbacks will be executed parallelly. Truly parallelly.
In Twisted - as far as I understand - it's not true asynchronicity - it's, let's say, approximated asynchronicity instead, since no operations would be performed parallelly (in terms of code, as I mentioned in fact3). In Twisted the first n line of code (defining protocols, factories, connections, etc.) are the declarations of what is going to happen when entire system starts. Nothing runs so far. Real execution starts then the reactor.run() is fired. I understand that the reactor runtime is based on a single while True loop which iterates through events. The reactor checks any awaiting tasks to do, processes them, send their result back to the queue (either to callbacks or errbacks). In the next loop execution they'll be processed one step further. So the deferred execution is linear in fact (though, from outside it looks like it was executed parallelly). Is my interpretation correct?
I'd appreciate if someone could answer my questions and/or explain how asynchronicity works in twisted/python platform and how is it related to operating system. Thanks in advance for good explanations!
edit: links to articles explaining asynchronicity are very welcome!

A: It's hard to talk about this without defining a lot of terms more precisely and taking issue with your facts, but here's my attempt:
Question 1:
Try man select, which is approximately how Twisted is implemented - it's a way to ask the operating system to monitor several things at once and let the application know when any one of them fires (block on multiple things).
Question 2:
Yeah, pretty much - but you're wrong about Javascript, it's just like Twisted.

A: Thomas has already answered your first question but I'll like to add something extra to question 2.
From the way you phrased the (second) question, it seems you many misunderstand asynchronicity.
Asynchronous should not be confused with multiprocessing.
Here's an example of asynchronicity.
Lets say you have two tasks to complete.
1) Read a file from disk
2) Sum a couple of integers in memory
In a synchronous system, these task are done one at a time and we wait for the result of the operation before moving on to the next.
In an asynchronous system we start each operation and then periodically check for the completion of each. (This is where that nifty select operation comes in)
See this wiki page for more info: http://en.wikipedia.org/wiki/Asynchronous_I/O
So even on a single core system where in reality only 1 thread is running at a particular point in time, we can still have an asynchronous system so that tasks that take long (reading a file in the above example) don't throw a spanner in the works for tasks that can complete their work quickly (summing some integers in memory)
(As a side note, Twisted does have support for spawning a new threads.
http://twistedmatrix.com/documents/11.0.0/core/howto/threading.html )

A: I gave a half-hour talk on this exact topic at PyCon 2012.  You can watch it online here.


text:
Q: How can I optimize the code to always use the same reference to a String without increasing the memory usage? I am working on an application that has a lot of duplicate Strings and my task is to eliminate them to decrease memory usage. My first thought was to use String.intern to guarantee that only one reference of a String would exist. It worked to decrease the heap memory, but it increased the PermGen way too much; in fact, because there are many strings that are declared only once, the total amount of memory used by the application increased, actually.
After searching for another ideas, I found this approach: https://stackoverflow.com/a/725822/1384913.
It happened the same thing as String.intern: The String usage decreased, but the memory that I saved is being used in the WeakHashMap and WeakHashMap$Entry classes.
Is there an effective way to maintain only one reference for each String that doesn't spend the same amount of memory that I'm recovering doing it?

A: I found an alternative to WeakHashMap: the WeakHashSet provided by Eclipse JDT library. It has the same behaviour that WeakHashMap, but it uses less memory. Also, you only need to call the method add and it will add the String in the set if it doesn't exist yet, or returning the existing one otherwise.
The only thing that I didn't like was the fact that it doesn't use generics, forcing the developer to cast the objects. My intern method turned out to be pretty simple, as you can see bellow:
Declaration of the WeakHashSet:
private static WeakHashSet stringPool = new WeakHashSet(30000); //30 thousand is the average number of Strings that the application keeps.

and the intern method:
public static String intern(String value) {
    if(value == null) {
        return null;
    }
    return (String) stringPool.add(value);
}

A: Why dont you use StringBuilder/StringBuffer class instead of String. Using instance of this class, you can always use same instance with different values. - Ankur

A: In a similar case, wherever possible, I refactored the string constants to enums. That way, you get two benefits:

*

*enum instances are singletons, so you won't have memory problems

*no typos when using Strings.

Cons:

*

*a lot of work, with endless possibilities to make mistakes, if you don't have enough test cases

*sometimes this is not trivial, for example when you have to interact with third party libraries you can't just edit...

*simply a no-go if these are runtime determined, and not compile time...


text:
Q: Android : how to access the access token from spring secuity Oauth server using post request I have developed a oauth spring security project in myserver.When a client request for authentication the server check the client credentials and user credentials and issue a access token if the request is valid.The request should contain client credentials (that is, client_id & client_secret),user credentials (that is, username and password) and the grant type as password.Now i want to setup an oauth consumer in my android application which request to this oauth server with the specified data for access token.How can i do that in android? If anyone knows that please help me to do that.Below is my spring security oauth configuration.
spring-security.xml :
    <?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:oauth="http://www.springframework.org/schema/security/oauth2"
xmlns:sec="http://www.springframework.org/schema/security"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/security/oauth2
http://www.springframework.org/schema/security/spring-security-oauth2-2.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.2.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd ">
<http pattern="/oauth/token" create-session="stateless"  authentication-manager-ref="authenticationManager"
    xmlns="http://www.springframework.org/schema/security" >

    <intercept-url pattern="/oauth/token" access="IS_AUTHENTICATED_FULLY" method="GET" />
    <anonymous enabled="false" />
    <http-basic entry-point-ref="clientAuthenticationEntryPoint" />
    <custom-filter ref="clientCredentialsTokenEndpointFilter" before="BASIC_AUTH_FILTER" />
    <access-denied-handler ref="oauthAccessDeniedHandler" />
</http>

<http pattern="/resources/**" create-session="never" entry-point-ref="oauthAuthenticationEntryPoint"
    xmlns="http://www.springframework.org/schema/security">
    <anonymous enabled="false" />
    <intercept-url pattern="/resources/**" method="GET" />
    <!-- <intercept-url pattern="/resources/**" access="IS_AUTHENTICATED_FULLY" /> -->
    <custom-filter ref="resourceServerFilter" before="PRE_AUTH_FILTER" />
    <access-denied-handler ref="oauthAccessDeniedHandler" />
</http>

<http pattern="/logout" create-session="never"
    entry-point-ref="oauthAuthenticationEntryPoint"
    xmlns="http://www.springframework.org/schema/security">
    <anonymous enabled="false" />
    <intercept-url pattern="/logout" method="GET" />
    <sec:logout invalidate-session="true" logout-url="/logout" success-handler-ref="logoutSuccessHandler"   />
    <custom-filter ref="resourceServerFilter" before="PRE_AUTH_FILTER" />
    <access-denied-handler ref="oauthAccessDeniedHandler" />
</http>

<bean id="logoutSuccessHandler" class="com.example.myproject.oauth.LogoutImpl" >
    <property name="tokenstore" ref="tokenStore"></property>
</bean>

<bean id="oauthAuthenticationEntryPoint"
    class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint">
</bean>

<bean id="clientAuthenticationEntryPoint"
    class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint">
    <property name="realmName" value="springsec/client" />
    <property name="typeName" value="Basic" />
</bean>

<bean id="oauthAccessDeniedHandler"
    class="org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler">
</bean>

<bean id="clientCredentialsTokenEndpointFilter"
    class="org.springframework.security.oauth2.provider.client.ClientCredentialsTokenEndpointFilter">
    <property name="authenticationManager" ref="authenticationManager" />
</bean>

<authentication-manager alias="authenticationManager"
    xmlns="http://www.springframework.org/schema/security">
    <authentication-provider user-service-ref="clientDetailsUserService" />
</authentication-manager>

<bean id="clientDetailsUserService"
    class="org.springframework.security.oauth2.provider.client.ClientDetailsUserDetailsService">
    <constructor-arg ref="clientDetails" />
</bean>

<bean id="clientDetails" class="com.example.myproject.oauth.ClientDetailsServiceImpl"/>

<authentication-manager id="userAuthenticationManager"
    xmlns="http://www.springframework.org/schema/security">
    <authentication-provider  ref="customUserAuthenticationProvider">
    </authentication-provider>
</authentication-manager>

<bean id="customUserAuthenticationProvider"
    class="com.example.myproject.oauth.CustomUserAuthenticationProvider">
</bean>

<oauth:authorization-server
    client-details-service-ref="clientDetails" token-services-ref="tokenServices">
    <oauth:authorization-code />
    <oauth:implicit/>
    <oauth:refresh-token/>
    <oauth:client-credentials />
    <oauth:password authentication-manager-ref="userAuthenticationManager"/>
</oauth:authorization-server>

<oauth:resource-server id="resourceServerFilter"
    resource-id="springsec" token-services-ref="tokenServices" />

<bean id="tokenStore"
    class="org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore" />

<bean id="tokenServices"
    class="org.springframework.security.oauth2.provider.token.DefaultTokenServices">
    <property name="tokenStore" ref="tokenStore" />
    <property name="supportRefreshToken" value="true" />
    <property name="accessTokenValiditySeconds" value="300000"></property>
    <property name="clientDetailsService" ref="clientDetails" />
</bean>

<mvc:annotation-driven />   <!-- Declares explicit support for annotation-driven MVC controllers  @RequestMapping, @Controller -->

<mvc:default-servlet-handler />

<bean id="MyResource" class="com.example.myproject.oauth.MyResource"></bean>

</beans>


text:
Q: Sorting a list with objects? In the contacts class (implements actionListener) I have a JList that contains objects (elements from a file). There are sorting buttons, each button has an actionListener
by firstname by last name by city  The sorting is done by the elements of objects.
the user should give the first and last name and city for a contact. How to do the sorting ??
And to put those into the list I used this code:
Map<String, contacts> ma = readFromFile();
for (Map.Entry<String, contacts> entry : ma.entrySet()) {
    contacts c = (contacts) entry.getValue();
    d.addElement(c.getLastName() + "" + c.getFirstName() + "" + c.getCity());
}

How to do the sorting ?? plz help

A: Instead of JList<String>, create a JList<contacts>
Implement class ContactsRenderer extends JLabel implements ListCellRenderer.
See java doc for more details: http://docs.oracle.com/javase/7/docs/api/javax/swing/JList.html
Implement your custom list data model:
public class ContactsModel extends AbstractListModel<contacts>() {

    private final List<contacts> backingList = ArrayList<contacts>;

    public ContactsModel(Map<String, contacts> ma) {
        //populate backing list here from your map
    }

    public int getSize() {
        return backingList.size();
    }

    public contacts getElementAt(int index) {
        return backingList.get(index);
    }
};

Add a sort method to your model:
public void sort(Comparator<contacts> comparator) {
    Collections.sort(backingList, comparator);
    fireContentsChanged(this, 0, backingList.size());
}

Implement comparators for every sort use case:
public class LastNameAscendingComparator implements Comparator<contacts> {

    @Override
    public int compare(contacts c1, contacts c2){
        return c1.getLastName().compareTo(c2.getLastName());
    }
}

Finally call your model.sort() with a corresponding comparator

A: In java you can sort a list like so:
Collections.sort(yourListOfContacts, new Comparator<Contacts>(){

    @Override
    public int compare(Contacts obj1, Contacts obj2){
       obj1.getFirstName().compareTo(obj2.getFirstName());
    }

});

Notice that the return type of the compare function is an integer. This integer tells the sorting algorithm which one of the two should come first. Note that a -1 means the first element is "less" than the second, a 0 means that they are the same, and a 1 means that the first element is "greater" than the second. So, to reverse the order, you would use: obj2.getFirstName().compareTo(obj1.getFirstName()); or, you could just multiply by -1.
The other fields you want to sort by will follow the same sort of pattern, this is just an example.

A: In Java8 you can sort a list like this:
Collections.sort(contactList, (contact1, contact2)
    -> contact1.getName().compareTo(contact2.getName()));


text:
Q: MPI error from very simple example fortran code I have compiled this code:
 program mpisimple

  implicit none

  integer ierr

  include 'mpif.h'

  call mpi_init(ierr)

  write(6,*) 'Hello World!'

  call mpi_finalize(ierr)

  end

using the command: mpif90 -o helloworld simplempi.f90
When I run with this command:
    $ mpiexec -np 1 ./helloworld
    Hello World!

it works fine as you can see.  But when I run with any other number of processors (here 4) I get the errors and I basically have to ctrl+C to kill it.
Fatal error in MPI_Init: Other MPI error, error stack:
MPIR_Init_thread(805).....: fail failed
MPID_Init(1859)...........: channel initialization failed
MPIDI_CH3_Init(126).......: fail failed
MPID_nem_init_ckpt(858)...: fail failed
MPIDI_CH3I_Seg_commit(427): PMI_KVS_Get returned 4
In: PMI_Abort(69777679, Fatal error in MPI_Init: Other MPI error, error stack:
MPIR_Init_thread(805).....: fail failed
MPID_Init(1859)...........: channel initialization failed
MPIDI_CH3_Init(126).......: fail failed
MPID_nem_init_ckpt(858)...: fail failed
MPIDI_CH3I_Seg_commit(427): PMI_KVS_Get returned 4)
forrtl: severe (174): SIGSEGV, segmentation fault occurred

What could be the problem?  I am doing this on a Linux hpc system.

A: I figured out why this happened. The system I am using does not require users to submit single-core jobs through the scheduler, but does require it for multi-core jobs. Once the mpiexec command was submitted through a PBS bash script, the errors went away and output was as expected.


text:
Q: Javascript array of objects sort by property isn't working I have an array of person objects, each with a name and a score property. I want to sort the array by the person object's score property and then display the array.
I have a function to display the rankings and I've added the sort code to the top of that function, but it is not sorting the array and no errors are being thrown. Any ideas what's wrong?
The javascript code:
var rankings = [];

/* Player object constructor */

function Player(pname, score) {
        this.pname = pname;
        this.score = score;
    }

/* function to add new players removed for clarity, it works */

/* sort and display the player objects by score */

function displayRankings () {

        rankings.sort( function(a, b) {
            return a[1] - b[1];
        });

        for (var i = 0; i < rankings.length; i++) {
            var li = document.createElement("li");
            var node = document.createTextNode(rankings[i].pname + ", " + rankings[i].score);
            li.appendChild(node);

            var element = document.getElementById("rankings");
            element.appendChild(li);
        }
    }

A: Assuming rankings is an array of Person objects, then you need to be accessing the score property, not [1].
rankings.sort( function(a, b) {
    return a.score - b.score;
});


text:
Q: How to check whether a Button is clicked by using JavaScript Is there a simple way to do something along these lines:
JavaScript:
if(document.getElementById('button').clicked == true)
{
   alert("button was clicked");
}

HTML:
<input id="button" type="submit" name="button" value="enter"/>

A: This will do it
<input id="button" type="submit" name="button" onclick="myFunction();" value="enter"/>

<script>
function myFunction(){
    alert("The button was pressed");
};
</script>

A: All the answers here discuss about onclick method, however you can also use addEventListener().
Syntax of addEventListener()
document.getElementById('button').addEventListener("click",{function defination});

The function defination above is known as anonymous function.
If you don't want to use anonymous functions you can also use function refrence.
function functionName(){
//function defination
}

document.getElementById('button').addEventListener("click",functionName);

You can check the detail differences between onclick() and addEventListener() in this answer here.

A: Just hook up the onclick event:
<input id="button" type="submit" name="button" value="enter" onclick="myFunction();"/>

A: Try adding an event listener for clicks:
document.getElementById('button').addEventListener("click", function() {
   alert("You clicked me");
});

Using addEventListener is probably a better idea then setting onclick - onclick can easily be overwritten by another piece of code.
You can use a variable to store whether or not the button has been clicked before:
var clicked = false
document.getElementById('button').addEventListener("click", function() {
   clicked = true
});

addEventListener on MDN

A: You can add a click event handler for this:
document.getElementById('button').onclick = function() {
   alert("button was clicked");
};

This will alert when it's clicked, if you want to track it for later, just set a variable to true in that function instead of alerting, or variable++ if you want to count the number of clicks, whatever your ultimate use is.  You can see an example here.

A: $("#button").on('click',function(){
//do something
});

A: function check() {
    console.log("Button Clicked");
};

var button= document.querySelector("button"); // Accessing The Button //
button.addEventListener("click", check); // Adding event to call function when clicked //

A: you can do something like  this:
<button onClick="funtion()">Button Goes Here</button

function alert(){
console.log('Alert Showed');
alert('You clicked me!');
}
<button onClick="alert()">Click me to get alerted</button>

A: document.querySelector("#button").addEventListener("click", () => {
    console.log("button was clicked");
})

A: // this event listener will help you detect clicks on the document
document.addEventListener('click', function(e){
// <event>.<target>.<id> check that the id is 'button'
if(e.target.id === 'button'){
    // do something here
    console.log(e.target.id);
}

}


text:
Q: What is the correct way to save data that will be sent from server to client via socket after client reestablish its lost connection I have .net core written api and android mobile client. There is signalr socket connection between two of them. When user opens an event on mobile app, i save this event data to db on server and send it to other users that listens the event creator via socket.
I periodically control the socket connection on mobile app and i can reconnect them if they have lost their connection. I have no problem so far.. But i have problem keeping the data for lost connection user
Let me explain with example :

There are Users : Producer1, Consumer1, Consumer2

If Producer1 opens an event via mobile app. It sends data to the server via httprequest and i save it to db.

After saving the data to db, i send this data to Consumer1 and Consumer2 via socket connection.
Lets say Consumer2 dont have network connection while sending the event data.

Consumer1 that have network connection, gets the data successfully and i have no problem for Consumer1.

But, Consumer2 couldn't get the data because it lost their socket connection and we did not reconnect yet.
The sent event data already gone. So Consumer2 will not get the event data.

My question is, how can i keep the data and send it for Consumer2 when just Consumer2 reestablish its connection. What is the efficient and correct way to doing this.
Server Side Code Example :
    public async Task AddEvent(GetEventOutput getEventOutput)
    {
        if(getEventOutput.Active)
        {
            await _hubContext.Clients.Group(SignalR_EVENT + QUESTION_MARK + EVENT_WITH_USER + EQUAL_DASH + getEventOutput.UserID).SendAsync(CREATE_EVENT_ON_MOBILE, JsonConvert.SerializeObject(getEventOutput));
            sendEventCreateNotification(getEventOutput);
        }
    }

Client Side Code Example :
    hubConnection.on(CREATE_EVENT_ON_MOBILE, (getEventOutput) -> {
        System.out.println("CREATE_EVENT_ON_MOBILE : ");
        setUiAfterSignalrHandler.post(new Runnable() {
            @Override
            public void run() {
                if (!isNullOrEmpty(getEventOutput)) {
                    Event event = gson.fromJson(getEventOutput, Event.class);
                    eventsWithTimerRecyclerViewAdapter.insertItem(0, event);
                    setUiAfterSignalrHandler.removeCallbacks(this);
                    leftAndRightTextWithTimerRecyclerView.removeEmptyPlaceHolder(eventsWithTimerRecyclerViewAdapter);
                }
            }
        });
        restartSocket();
    }, String.class);

A: We had similar situation but with notifications. To avoid your problem, I would recommend to use cache or volatile storage to store those events.
For example, when you send your event to the clients, they should invoke a callback method registering that they received the event, then you register your event as completed when all the subscribers responded the event successfully and you can dispose the event.
But the perform this you should have:

*

*List of all connected clients that wants to receive the event.

*Storage for those events (we use Cosmos Db but cache will work well).

So you will not dispose the event until it is completed. But then how you resend the event to the user that was not connected on that time?
Just create a hub method to be invoked by the client just after the connection is establish to send pending events (events that this user has not registered as received, so they did not invoked the callback method).


text:
Q: webRequest api: does not handle requests to favicon.ico I have a Google Chrome extension that I wrote when webRequest Extensions API was at experimental stage.
Currently I am rewriting it and I have noticed, that it does not handle requests to /favicon.ico.
UPD it handles this request only when Dev Tools panel is opened.
It handles all other requests (that I tested) except this.
I use:
chrome.webRequest.onBeforeRequest.addListener(handler, filter)
to listen to all requests going from my browser. Filter value is set to handle all requests:
var filter = { urls: [ "*://*/*" ] };
Is this a known bug?
It may be caused by the way Chrome optimizes it's storage of sites favicons (I mean by loading favicons from it's cache like so: chrome://favicon/http://yandex.ru)

References
webRequest API http://code.google.com/chrome/extensions/webRequest.html


text:
Q: Android ListView first element different color I'm working on a project having two list views used to select different regions and cities. The thing is, I have an option that is "All Region" and "All Cities" and I'd like to have these two of different color (in my case, the main app color)
I've tried things such as getItemAtPosition on my ListView but nothing is working.. Here's the code related to that ListView:
mListView = (ListView) findViewById(R.id.list);
ArrayList<String> regions = getIntent().getExtras().getStringArrayList("regions_selection");
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        String regionId;
        if (position == 0) {
            regionId = "";
        } else {
            regionId = OptionsManager.getInstance().getOptions().getRegion(position - 1).getId();
        }
        SearchInformations.getInstance().setRegionId(regionId);
        startActivity(new Intent(PhoneRegionListActivity.this, PhoneClubListActivity.class));
    }
});
mListView.setAdapter(new ArrayAdapter<>(this, R.layout.list_item, regions));

A: Before setting the adapter (starting with KITKAT anytime) you can add header views which get wrapped automatically.
View all = getLayoutInflater().inflate(R.layout.list_item, mListView, false);
// setup view for all regions/cities
mListView.addHeaderView(all);
mListView.setAdapter(new ArrayAdapter<>(this, R.layout.list_item, regions));

A: I've been able to set different colors to different element according to their position this way:
if(position == 0){
    textView.setTextColor(ContextCompat.getColor(getContext(),R.color.orange));
}else{
    textView.setTextColor(ContextCompat.getColor(getContext(),R.color.black));
}

Here, the else is important otherwise, when scrolling, some other elements might change color. Otherwise, another way to avoid this issue is to reinitialize the view everytime with LayoutInflater.


text:
Q: magento admin form alter i try to override magento enterprise catalogevent block, but its same faltal error leading:Fatal error: Call to a member function setData() on a non-object in ..\www\app\code\core\Mage\Adminhtml\Block\Widget\Form\Container.php on line 129
my new module config.xml:
 <global>
        <blocks>
            <ss_todaysevents>
                <class>Ssd_Todaysevents_Block</class>
            </ss_todaysevents>
            <enterprise_catalogevent>
                <rewrite>
                    <adminhtml_event_edit_form>
                        Ss_TodaysEvents_Block_Adminhtml_Event_Edit_Form
                    </adminhtml_event_edit_form>
                </rewrite>
            </enterprise_catalogevent>
        </blocks>
    </global>

Ss_TodaysEvents_Block_Adminhtml_Event_Edit_Form class is in ..\www\app\code\local\Ss\TodaysEvents\Block\Adminhtml\Event\Edit\Form.php and has following code:
class Ss_TodaysEvents_Block_Adminhtml_Event_Edit_Form extends Enterprise_CatalogEvent_Block_Adminhtml_Event_Edit_Form
{
    protected function _prepareForm()
    {
        parent::_prepareForm();
        if (Mage::getConfig()->getModuleConfig('Ss_Brands')->is('active')) {
            $fieldset = $this->getForm()->getElements()->searchById('general_fieldset');
            $fieldset->addField('brand_name', 'select',
                                array(
                                     'label' => Mage::helper('brands')->__('Brand'),
                                     'title' => Mage::helper('brands')->__('Brand'),
                                     'name' => 'brands_id',
                                     'values' => Mage::helper('brands')->getBrandsArrayList(),
                                )
            );

        }
        return $this;
    }

}

What worng there? Thanks

A: If the sole purpose of your module is a rewrite, you needn't configure a class group (global/blocks/ss_todaysevents). You are directly mapping a class to another class group _ class name.
Magento does not strip whitespace in text nodes. In your adminhtml_event_edit_form node your classname should not have whitespace around it, i.e.:
<adminhtml_event_edit_form>Ss_TodaysEvents_Block_Adminhtml_Event_Edit_Form</adminhtml_event_edit_form>


text:
Q: empty values in forEach after a HTTPrequest I am working on a project in which I have to get students enrolled courses and courses list.
getting course
this.courses = <Array<Course>>[];
this.coursesService.getCourses().subscribe((response: Array<Course>) => {
this.courses = response;
console.log(this.courses);

});
getting Students enrolled course
this.id = this.router.snapshot.paramMap.get('id');
this.studentService.getStudentsById(this.id).subscribe((response: Student) => {
  this.student = response;
  console.log(this.student);
});

my code for getting avail
this.courses.forEach(function(item, i, object) {
  this.student.enrollments.forEach(function(enrollments, j , objectb) {
      if (item === enrollments) {
        object.splice(i, 1);
      }
  });
});

So when my page load. it didnt splice/remove the item in the courses which he is currently enrolled.I think the forEach function executes before it has values. is this about the subsribe? or im just doing it all wrong

A: Since getCourses() is asynchronous, the program won't wait for the response to run the remaining code. therefore by the time, it runs the callback, it would have run the foreach code.
the solution is to call the foreach inside the callback.
this.courses = <Array<Course>>[];
this.coursesService.getCourses().subscribe((response: Array<Course>) => {
this.courses = response;

this.id = this.router.snapshot.paramMap.get('id');
this.studentService.getStudentsById(this.id).subscribe((response:
Student) => {
  this.student = response;
      this.courses.forEach(function(item, i, object) {
  this.student.enrollments.forEach(function(enrollments, j , objectb) {
      if (item === enrollments) {
        object.splice(i, 1);
      }
  });
});
});
});


text:
Q: Reactjs: render in dependence of render() function argument doesn't work I use React and Redux and I want to avoid excessive store updating. My input component get its initial value from store, then it is changed by user, then it updates store when user press submit button. My thoughts are to run render() method  with argument and pass content to the component in dependence of render() argument. According to console output all go fine, but I see no anticipating changes in DOM!
Please help, I stuck.

import React, {Component} from 'react';

export default class Clock extends Component {
  render(flag){
    let x = null;
    if( flag ){
      x = 5;
     console.log("Forced render, x = " + x);
   }else{
     x = 1;
     console.log("Render when mounts, x = " + x);
   }

    return (

 { x }

    )
  }

  handleClick(){
    console.log("Click!")
    this.render( true );
  }
}

Console output:
Clock.js:15 Render when mounts, x = 1
Clock.js:24 Click!
Clock.js:12 Forced render, x = 5
Clock.js:24 Click!
Clock.js:12 Forced render, x = 5

I want to see

 5

but I get

 1

No DOM changes.... (

A: Use hadlClick to change the state. It will automatically re-render and then use the state to change the content.
export default class Clock extends Component {
  state = {
      flag: false
  }

  handleClick = () => {
    this.setState( prevState => ({flag: !prevState.flag }) );
  }

  render(){
    return (

 { this.state ? 5 : 1;}

    )
  }

}


text:
Q: How C# public void static Main(String[] args){} and public int static Main(String[] args) two overloaded method work together? How CLR knows which method to call since they are returning different value(One is void and another is int) ? In sense of Overloading this is also not right, a method with same parameter with different return type.
example:
class Program
{
    static int Main(String[] args) //Main with int return type but Parameter String[] args
    {
            return 0;
    }

    /* this main method also gonna get called by CLR even though return type void  and Same parameter String[] args.
   static void Main(String[] args) //Main with int return type but String[] args
   {

   } */

    private static void func(int one)
    {
        Console.WriteLine(one);
    }

    private static int func(int one) //compiler error. two overloaded method cant have same parameter and different return type.
    {
        return 1;
    }
}

but main method is not maintaining overloading rules.

A: in .NET, an executable can have only one entry point i.e. only one Main method is allowed. To be more specific, the Main method is considered as an entry point only if the sigature matches any of the below 2 and the method is static.

*

*Main(String[])

*Main()

If, you provide a main method whose signature is different from above two, it is not considered as Main method. So, below code is allowed,
class Program
{
    static void Main ()          //Entry point
    {
    }

    static void Main(int number)
    {
    }
}

The below code doesn't compile because, it finds matching signature at two places.
class Program
{
    static void Main ()          //Entry point
    {
    }

    static void Main(String[] args)   //another entrypoint!!! Compile Error
    {
    }
}

Below code also doesn't compile because there is no entry point at all,
class Program
{
    static void Main (int a)      //Not an Entry point
    {
    }

    static void Main(float b)    //Not an entry point
    {
    }
}


text:
Q: Background not 100% of page Wondering if anyone could help me resolve this problem, when I make the window smaller, I want it to scroll and not be responsive BUT I need the backgrounds to follow to the end. They just stop at window size.
I've tried:
body, html {
    margin: 0;
    width: 100%;
    height: 100%;
}

But it did not work.
Check it live here to see the problem in action.

A: the problem is you have a container that is 1100px and you are centering your image inside that container (with margin: 120px auto 0 auto) so it's doing what it should - the container hits the edge and image stays centered inside. If you want it to move all the way to the edge then you need to take it out of the container and just center it within the page.


text:
Q: Linear Regression Prediction Interval for precise y values When calculating the prediction intervals for a regression function, can the y values be precise values "without errors"?
As far as I know, in regression function calculation only the x values are assumed to have no error and not the y values (see requirements below). But in computational chemistry the calculated values are precise per definition, as same input gives same output, so they don't have standard deviation or sth like that.
The mathematical requirements are, according to my literature (german DIN):

*

*independent and normally distributed values

*homogeneity between lowest and highest value's variance

*a linear functional relationship where the x values count as errorless and the y values are assumed to have errors

They state: If those requirements are not satisfied, then the calculation scheme cannot be used and another scheme has to be chosen. And that last requirement is, what the question is about: What if both, x and y values, have "no error" ... is the system still usable or do I need something more appropriate?
For clarification, this is the system that should be treated:
$\hskip3.5cm$

A: First of all, deterministic (i.e. the same computation always yields the same result) does not imply error-free (not even free of random error!).

That being said, both ways of modeling, $y = f (x)$ as well as $x = f (y)$ are used in chemometrics. The former is known as ordinary or classical regression or calibration, the latter is referred to as inverse calibration.
Both ways of calibration have different characteristics.

*

*As the comments already pointed out, one important difference is in the  assumption where most of the variance is: on $x$ or on $y$.

*In addition, if the purpose of the model is prediction, you should predict forwards, i.e. in the direction that is modeled. That is, if you want to predict experimental results, model $experiment = f (theory)$.

*On the other hand, if you assume the error is on your theoretical model and you are interested in the relationship between theoretical model and experimental results (remember: experimental science makes the fundamental point that if experiment and theory do not agree, it is theory that needs to change) and you e.g. need to measure the slope between experiment and theory, then model $theory = f (experiment)$

*(In chemical analysis as in measuring concentrations, there are more important characteristics, wrt. to how multivariate measurements are used, and whether all constituents of the system are known - but these are probably not relevant for your problem).

I work with vibrational spectra which are sometimes computed for molecules in vacuum and then a correction factor is applied to account for the difference between vacuum (theory) and solution (reality/experiment). While I may be biased because I'm experimental spectroscopist, I'd say that at least in this situation it is very clear where the major source of error is...

About the DIN: are you referring to DIN 32465 or 38402?
They give formulas that are valid only under the stated assumptions (which are also in chemical analysis very often not met, particularly the variance homogeneity (also your graph looks like increasing variance with increasing values). The consequence is that you cannot use the "shortcut" formulas but have to do the proper calculation. In particular, you'd underestimate the uncertainty for high values and overestimate uncertainty for low values. From a statistics point of view, a weighted regression would be appropriate.
However, partiularly if you need to measure figures of merit such as limit of detection LOD or limit of quantitation LOQ, there are straightforward (though tedious) methods to do this almost without assumptions.


text:
Q: How do i compare dates with a value? PHP I am currently working on a project. I'm suposed to compare a date from my database and the curent date. If the curent date is bigger than the date from the database i am suposed to cound how many times the duration of the item fits in the database date till its bigger than the curent date.
All i got is the curent date, the duration of the item and the date in the database.
What i did befor was use this while loop:
while(date('Y-m-d') > $value->start) {
    $value->start= date('Y-m-d', strtotime("+" . $value->contractDuration . " months", strtotime($value->start)));
};

But i'm not allowed to use a while loop. Any clue how to get the same result?

A: $start=$value->start;
$contractDuration=$value->contractDuration;
try below code.
$start = '2018-04-09';
$contractDuration = 1;
$contractDurationDate = strtotime("-" . $contractDuration . " months");
$now=strtotime(date('Y-m-d'));
$start=strtotime($start);
if ($contractDurationDate < $now && $start< $now) {
    echo 'Contract duration is active';
} else {
    echo 'Contract Expired';
}

A: Try with below code. It might help you
$now = time();
$target = strtotime($date_from_db);
$diff = $now - $target;
if ( $diff > 900 ) {
  // something
}

or, more succinctly:
if( time() - strtotime($date_from_db) > 900 ) {
  // something
}

A: I quite like using DateTime and the use of date_diff for this:
<?php

$databaseDate = new DateTime("2018-01-02");
$today = new DateTime();

if($today > $databaseDate){
    echo date_diff($today, $databaseDate)->format("%a")." days";

}

Will output 160 days.
https://3v4l.org/3FfKp
If you want months, replace %a with %m