text:
Q: How to "Add Service Reference" for a WCF service in Eclipse? I want to consume a WCF service with DataContracts from my Android app, and I'm using Eclipse as my IDE.
In .NET when I add a service reference I automatically get metadata and automatically-generated code for calling that service.
Is there a way to do so in Java/Android/Eclipse? I wouldn't want to re-code all the data contracts, nor do I want to have to manually update my code if the service contract changes.  (In .NET it's just a case of clicking "Update service reference").
How is this done in the Java world?

A: Please follow the below steps to add a web reference for eclipse:

*

*Select a file container in eclipse(folder) --> Right click and  select Import

*Now from the options in the dialog select Import Web Reference and click Next

*Enter some general settings related to the web service to import and click Next

*Click Next again as we dont need to set anything in the advance settings dialog

*Now you are done and all the generated files are available to use

Please refer this link for more information along with screenshots


text:
Q: Broken colors in DayNight Theme after loading Admob/Firebase ad I use Theme.AppCompat.DayNight.NoActionBar theme for my app. When I load adMob interstital some colors are broken in "night" mode (i.e. in RecyclerView).
Screen:

Those incorrect colors are from "notnight" values.
When I close the app and run it again everything is okay.
When I kill the app I have the same situation.
Activity code:
public class MainActivity extends AppCompatActivity {

    static {
        AppCompatDelegate.setDefaultNightMode(
                AppCompatDelegate.MODE_NIGHT_AUTO);
    }

    private ArrayList<String> planetList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        populateRecycler();

        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view);

        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);

        PlanetAdapter adapter = new PlanetAdapter(planetList, getApplicationContext());
        recyclerView.setAdapter(adapter);

        InterstitialAd interstitialAd = new InterstitialAd(this);
        interstitialAd.setAdUnitId("ca-app-pub-543543543/543543543");
        AdRequest adRequest = new AdRequest.Builder().build();
        interstitialAd.loadAd(adRequest);
    }

    private void populateRecycler() {
        for (int i = 0; i < 20; i++) {
            planetList.add("TEST");
        }
    }

}

When I comment interstitialAd.loadAd(adRequest) everything is ok.
You can find whole project here:
github

A: The issue is supposedly caused by the WebView resetting the UI mode, and this can be worked around by instantiating WebView manually.
I haven't seen the issue after doing this (in Application.oncreate() in this particular app):
    if (nightMode != AppCompatDelegate.MODE_NIGHT_NO) {
        Log.d(TAG, "Manually instantiating WebView to avoid night mode issue.");
        try {
            new WebView(getApplicationContext());
        } catch (Exception e) {
            Log.e(TAG, "Got exception while trying to instantiate WebView to avoid night mode issue. Ignoring problem.", e);
        }
    }
    AppCompatDelegate.setDefaultNightMode(nightMode);

Source: https://groups.google.com/forum/#!msg/google-admob-ads-sdk/OZzHq_-wAFY/K50jClZcBAAJ

redpajama_set_name: RedPajamaStackExchange


text:
Q: Short story I read - Outsiders enter hedonistic utopian society where citizens live forever by transferring bodies, havoc ensues I read this short story probably 5 to 10 years ago. There is this utopian land where the people are basically immortal thanks to being able to transfer into a new body when they get old, or just sick of the body that they have. There's a wait time, though, to get a new body. If someone has to vacate their body, or wants a new one, their consciousness is uploaded into this central computer thing while they wait for the new body. You can visit them there in the central place to talk to them.
Wait times vary for new bodies and I remember the characters discussing the pros and cons of deciding to get a new body depending on the current wait time, and hoping that their next body has better knees, or less aches and pains, or problems or whatever.
The society is hedonistic - they have endless cocktail parties and lots of sex - polyamory all around regardless of gender.
Somehow these outsiders enter this hedonistic utopia, these two(?) guys that are basically idiots. The immortal people welcome them but the outsiders screw it up. One of the old men transfers his consciousness into the body of a young woman, and then ends up hitting on one of the outsiders. The outsider has a homophobic freak-out and murders the young woman, I think by hitting her over the head with a heavy vase or something. I think the outsiders try to hide the body, but they kinda screw that up too, and of course everyone finds out.
This murder is the first death that the society has known.
Anyways, trying to think of what this story is is driving me nuts. It's probably a short story that's fairly old, maybe 1950s-1980s, but maybe not. It's at least pre-2010. It probably wasn't very well written but for some reason it's stuck in my head now. Thank you in advance!

A: Though you have indicated this is a short story I believe this may be the Robin Cook 2000 novel Abduction.
Points that match:
I read this short story probably 5 to 10 years ago.

Partial check. The novel came out in 2000.

There is this utopian land where the people are basically immortal thanks to being able to transfer into a new body when they get old, or just sick of the body that they have.

Check. The Moho (a hidden human race living in the Mohorovičić Discontinuity and can transfer into clone bodies and are essentially immortal.

There's a wait time, though, to get a new body. If someone has to vacate their body, or wants a new one, their consciousness is uploaded into this central computer thing while they wait for the new body. You can visit them there in the central place to talk to them.

Check. Consciousness can be uploaded to a "master computer" location.

Wait times vary for new bodies and I remember the characters discussing the pros and cons of deciding to get a new body depending on the current wait time, and hoping that their next body has better knees, or less aches and pains, or problems or whatever.

Check. In some cases the choice is to accept a new body that is a child. Others wait until they are adult in form.

The society is hedonistic - they have endless cocktail parties and lots of sex - polyamory all around regardless of gender.

Check. The Moho population are genetically engineered, almost perfect humans. They are vey sexually open.

Somehow these outsiders enter this hedonistic utopia,

Partial check:  "A team of researchers in a remote region of the Atlantic become trapped inside an ancient undersea volcano when their submersible is inexplicably drawn in."  This is actually more than just two people though:
  Perry Berg
  Dr. Suzanne Newell
  Donald Fuller
  Richard Adams
  Michael Donaghue

these two(?) guys that are basically idiots.

Check. At least two of the guys are idiots that, without giving away too much of the plot, really make a mess of things.

The immortal people welcome them but the outsiders screw it up. One of the old men transfers his consciousness into the body of a young woman, and then ends up hitting on one of the outsiders.

Partial match. The Moho do not understand the repugnance some of the outsiders have for homesexuality.  In an effort to "help" one of the Moho females seduces one of the outsiders. In a very casual manner during intimacy, she brings in an Moho male. The homophobic outsider male kills the young Moho woman and/or young Moho male and then tries to hide the body. I think inside a vase.

The outsider has a homophobic freak-out and murders the young woman, I think by hitting her over the head with a heavy vase or something. I think the outsiders try to hide the body, but they kinda screw that up too, and of course everyone finds out.

Check, check & check.

This murder is the first death that the society has known.

Virtual check. It is the first murder in hundreds (if not thousands) of years.

Anyways, trying to think of what this story is is driving me nuts. It's probably a short story that's fairly old, maybe 1950s-1980s, but maybe not. It's at least pre-2010. It probably wasn't very well written but for some reason it's stuck in my head now. Thank you in advance!

Because of the "Lost World/Pellucidar/Atlantis" type setting, the book does have the feel of a an older "pulp fiction" type book. I kept thinking of the Pellucidar books by ERB when I was reading it. Too, I would have to say IMHO it is not one of Robin Cook's better novels.

If this is the story of which you are thinking, you may remember the twist ending:

 Fearing for their own safety and the discovery of their civilization, the Moho-dwellers feel they cannot allow their abductees to return to the surface. The research team manages to recover its submersible and mounts an attempt to return to the surface. However, at the last moment they encounter a large Moho craft and emerge to the ocean's surface in the late 18th century. The group abruptly discovers that the craft was actually some sort of advanced Moho time machine and/or spacecraft that sent them 200 years into the past to prevent them from alerting the surface world to the presence of the Moho-dwellers.


text:
Q: strange string overwriting behavior in python 2.7.6 / Tkinter I'm a fairly experienced programmer but new to Python.  I've been tinkering with some tutorial code for Tkinter.  This program runs and prints in a terminal, processing events on a window:
from Tkinter import *

root = Tk()

mystring = ''

def keypress(event):
    globals()['mystring'] = globals()['mystring'] + event.char

def reveal(event):
    print mystring

def leftclick(event):
    frame.focus_set()
    print "clicked at", event.x, event.y

frame = Frame(root, width=100, height=100)
frame.bind("<Key>", keypress)
frame.bind("<Button-1>", leftclick)
frame.pack()
root.bind("<Return>", reveal)
root.mainloop()

So you run this in the terminal and click on the resultant window to give it the focus.  Then, each time you press a key, that letter gets added to the end of mystring.  When you press <enter>, the string you have so far is printed to the terminal.  Thus, if you type abc<enter>, it prints out abc.  So far so good.
Now, check out this sequence of events:
Input: abcd<enter>
Output: abcd
Input: efg<enter>
Output: efgd
Input: hi<enter>
Output: higd
Input: jklmnop<enter>
Output: jklmnop
Input: qrs<enter>
Output: qrsmnop
It's as though each reveal call resets mystring's pointer to the beginning of the string, without re-initializing mystring.  Here's where it gets really weird: if you replace
root.bind("<Return>", reveal)

with
frame.bind("<Return>", reveal)

then the strange behavior goes away.  Any new characters get appended at the end of the string, just as you'd expect.  So somehow it's Tkinter that's doing this.
I don't really need to fix this, and I doubt anyone can explain it.  I'm just kind of tossing it up there for the benefit of the internet.  Use frame.bind(), I guess is the moral of the story.

A: Your event binding is also capturing the carriage return and appending it to mystring, so your data will look like "abcd\refg\rhi\r\jklmnop\rqrs\r". If you print that string to the terminal you'll see the same odd results.
If you change your keypress function to look like this you'll probably get the output you expect:
def keypress(event):
    if event.char != "\r":
        globals()['mystring'] = globals()['mystring'] + event.char


text:
Q: How to resolve this error I am getting while running SQl Sever agent job? A job,  in which a proc is reading excel file using openrowset function and then exporting a file using bcp command. It was working perfectly until recently. When I run job it gives me this error:-

NT AUTHORITY\LOCAL SERVICE. Cannot initialize the data source object
  of OLE DB provider "Microsoft.Jet.OLEDB.4.0" for linked server
  "(null)". [SQLSTATE 42000] (Error 7303)  Configuration option 'show
  advanced options' changed from 1 to 1. Run the RECONFIGURE statement
  to install. [SQLSTATE 01000] (Error 15457)  Configuration option 'Ad
  Hoc Distributed Queries' changed from 1 to 1. Run the RECONFIGURE
  statement to install. [SQLSTATE 01000] (Error 15457)  OLE DB provider
  "Microsoft.Jet.OLEDB.4.0" for linked server "(null)" returned message
  "Unspecified error". [SQLSTATE 01000] (Error 7412).  The step failed.

Here is stored procedure code:-
ALTER PROCEDURE [dbo].[Read_Excel]
     @ExcelFilePath varchar(500)
    ,@OutPutFilePath nvarchar(500)
    ,@ServerName nvarchar(500)
    ,@DatabaseName nvarchar(100)
    ,@UserName nvarchar(50)
    ,@Password nvarchar(50)
    ,@Delimiter char(1)
AS
BEGIN
    SET NOCOUNT ON;
    DECLARE @Query nvarchar(1000)
    DECLARE @Cmd varchar(1000)
    DECLARE @FileExists int

    -- Check File Existence
    EXEC master..xp_fileexist @ExcelFilePath, @FileExists OUTPUT --returns 1 if exists, 0 if file is not there
    if @FileExists <> 1
        BEGIN PRINT 'There is no excel file available: ' + @ExcelFilePath RETURN END

    -- Allow Ad hoc Distributed Queries in order to run OpenRowset Function
    EXEC SP_CONFIGURE 'show advanced options', 1
    RECONFIGURE
    EXEC SP_CONFIGURE 'Ad Hoc Distributed Queries', 1
    RECONFIGURE

    -- Clear tbl_excel Table
    TRUNCATE TABLE tbl_Excel
    --Read EXCEL File using OPENROWSET Function
    SET @Cmd = 'INSERT INTO tbl_Excel
                SELECT * FROM OPENROWSET(''Microsoft.Jet.OLEDB.4.0'', ''Excel 8.0;HDR=YES;IMEX=1;Database=' + @ExcelFilePath + ''',
                ''SELECT * FROM [Sheet1$]'')'
    EXEC(@Cmd)
    -- Allow Ad hoc Distributed Queries in order to run OpenRowset Function
    EXEC SP_CONFIGURE 'show advanced options', 1
    RECONFIGURE
    EXEC SP_CONFIGURE 'Ad Hoc Distributed Queries', 0
    RECONFIGURE

    --Query View
    SET @Query = 'SELECT id1, name1, name2, address1, address2 FROM [' + @DatabaseName + '].[dbo].[tbl_Excel]'
    SET @Cmd = 'bcp "' + @Query + '" queryout "' +  @OutPutFilePath +
                 '" -c -S' + @ServerName + ' -U' + @UserName + ' -P' +
                @Password + ' -t' + @Delimiter + ''
    EXEC master..xp_cmdshell @Cmd
END

Thanks in advance.

A: Have you tried to change SQL Server Agent Log on? (Services->SQL Server Agent, right click Log On) to your user account?
or try to not use JET instead use ACE
SET @Cmd = 'INSERT INTO tbl_Excel
    SELECT * FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0', 'Excel 8.0;HDR=YES;IMEX=1; 'Database=' + @ExcelFilePath + ', 'SELECT * FROM [Sheet1$]')'


text:
Q: unable to find absolute URL I'm writing some code to find absolute URLS of a single webpage:
http://explore.bfi.org.uk/4ce2b69ea7ef3
So far I get all the links of that page and print the absolute urls
Here is part of the code:
 Elements hyperLinks = htmlDoc.select("a[href]");

    for(Element link: hyperLinks)
    {
        System.out.println(link.attr("abs:href"));
    }

This prints out alot or urls just like the one above. However, it seems to skip a few URLS aswell. The ones it skips are the ones I actually need.
This is one of the a[href] elements its not turning into the absolute URL:

Royal Review

It will print this line if I just print "link" but when I put "abs:href", it will just print blank.
I am new to Java and appreciate any feedback!

A: You shouldn't use "a[href]", use "a" instead following this example:
Document doc = Jsoup.connect("http://jsoup.org").get();

Element link = doc.select("a").first();
String relHref = link.attr("href"); // == "/"
String absHref = link.attr("abs:href"); // "http://jsoup.org/"

So in your case:
Elements hyperLinks = htmlDoc.select("a");

    for(Element link: hyperLinks)
    {
        System.out.println(link.attr("abs:href"));
    }


text:
Q: IP Address when Multiple NICs are Involved I am writing a TCP server application using Winsock. The machine on which my server will run and the machine on which the client will run both have 2 NICs. The IP addresses involved are:

*

*Server NIC 1: 192.168.132.14 <-- This is the one I want to bind

*Server NIC 2: 192.168.132.15

*Client NIC 1: 192.168.132.16

*Client NIC 2: 192.168.132.17

QUESTION 1:
In my server application, if I use INADDR_ANY when binding my listening socket, which of my two IP addresses will be used? Would I be correct to assume that there's no telling and that I should just use inet_addr("192.168.132.14") in place of INADDR_ANY?
QUESTION 2:
How can the client control which IP address he uses when connecting to me? Would he simply call bind() before calling connect()? Am I liable to see him as connecting from either address (no telling which one) if he does not?

A: When calling listen() on a server socket, binding to INADDR_ANY will bind the socket to all available local IPs on the machine.  That allows a client to connect to any of the server's IPs.  If the server uses inet_addr() instead, that will be the only IP that the server can accept client connections on.
When calling connect() on a client socket, it has to indicate a specific IP that the server is listening on.  If the client wants to pick which local IP it binds to for its endpoint of the connection, it can call bind() on itself before calling connect().  If the client does not bind to a specific IP, or it binds to INADDR_ANY, the socket will use the first IP it finds that has an available route to the server IP being connected to.
Once the connection has been established, both parties can call getsockname() and getpeername() on their respective socket endpoints at any time to discover which IPs (and ports) are actually in use for that connection.


text:
Q: Spring Data JPA 1.9.2 + Hibernate 4.3+ Issue I use Spring 4.2.4, Spring Data Jpa 1.9.2 and faced a problem when try to update my hibernate-entitymanager dependency from 4.2.21 to any version from 4.3.0 to 5.0.6.
Issue is that crash when creating entityManagerFactory bean.
crashe occures in method factory.afterPropertiesSet();
If I remove this method then factory.getObject returns null...
there are source of my entityManagerFactory bean
@Configuration
@PropertySource("classpath:application.properties")
@EnableTransactionManagement
@EnableJpaRepositories("com.test.springtomcat.server.repositories")
public class PersistanceConfig {

    @Bean
    public DataSource dataSource(){
        DriverManagerDataSource dataSource = new DriverManagerDataSource();

        dataSource.setDriverClassName("org.postgresql.Driver");
        dataSource.setUrl("jdbc:postgresql://localhost:5432/SpringDB");
        dataSource.setUsername("postgres");
        dataSource.setPassword("1");
        return dataSource;
    }

    @Bean
    @Autowired
    public EntityManagerFactory entityManagerFactory(DataSource dataSource){
        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        vendorAdapter.setGenerateDdl(true);
        vendorAdapter.setDatabasePlatform("org.hibernate.dialect.PostgreSQL82Dialect");
        vendorAdapter.setDatabase(Database.POSTGRESQL);

        LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
        factory.setJpaVendorAdapter(vendorAdapter);
        factory.setPackagesToScan("com.test.springtomcat.server.repositories");
        factory.setDataSource(dataSource);
        factory.afterPropertiesSet();
        return factory.getObject();
    }
}

log is here
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in com.test.springtomcat.server.config.PersistanceConfig: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.persistence.EntityManagerFactory]: Factory method 'entityManagerFactory' threw exception; nested exception is java.lang.IncompatibleClassChangeError: Implementing class
        at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1123)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1018)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:510)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
        at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772)
        at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:839)
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538)
        at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:446)
        at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:328)
        at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
        at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4748)
        at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5197)
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:155)
        at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:724)
        at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:700)
        at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:718)
        at org.apache.catalina.startup.HostConfig.manageApp(HostConfig.java:1660)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:497)
        at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:300)
        at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819)
        at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801)
        at org.apache.catalina.mbeans.MBeanFactory.createStandardContext(MBeanFactory.java:463)
        at org.apache.catalina.mbeans.MBeanFactory.createStandardContext(MBeanFactory.java:413)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:497)
        at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:300)
        at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819)
        at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801)
        at javax.management.remote.rmi.RMIConnectionImpl.doOperation(RMIConnectionImpl.java:1471)
        at javax.management.remote.rmi.RMIConnectionImpl.access$300(RMIConnectionImpl.java:76)
        at javax.management.remote.rmi.RMIConnectionImpl$PrivilegedOperation.run(RMIConnectionImpl.java:1312)
        at javax.management.remote.rmi.RMIConnectionImpl.doPrivilegedOperation(RMIConnectionImpl.java:1404)
        at javax.management.remote.rmi.RMIConnectionImpl.invoke(RMIConnectionImpl.java:832)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:497)
        at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:323)
        at sun.rmi.transport.Transport$1.run(Transport.java:200)
        at sun.rmi.transport.Transport$1.run(Transport.java:197)
        at java.security.AccessController.doPrivileged(Native Method)
        at sun.rmi.transport.Transport.serviceCall(Transport.java:196)
        at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:568)
        at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:826)
        at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$256(TCPTransport.java:683)
        at java.security.AccessController.doPrivileged(Native Method)
        at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:682)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
        at java.lang.Thread.run(Thread.java:745)
    Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.persistence.EntityManagerFactory]: Factory method 'entityManagerFactory' threw exception; nested exception is java.lang.IncompatibleClassChangeError: Implementing class
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
        at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
        ... 59 more
    Caused by: java.lang.IncompatibleClassChangeError: Implementing class
        at java.lang.ClassLoader.defineClass1(Native Method)
        at java.lang.ClassLoader.defineClass(ClassLoader.java:760)
        at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
        at org.apache.catalina.loader.WebappClassLoaderBase.findClassInternal(WebappClassLoaderBase.java:2496)
        at org.apache.catalina.loader.WebappClassLoaderBase.findClass(WebappClassLoaderBase.java:862)
        at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1304)
        at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1169)
        at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.buildBootstrapServiceRegistry(EntityManagerFactoryBuilderImpl.java:311)
        at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.<init>(EntityManagerFactoryBuilderImpl.java:166)
        at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.<init>(EntityManagerFactoryBuilderImpl.java:149)
        at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider$1.<init>(SpringHibernateJpaPersistenceProvider.java:49)
        at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:49)
        at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:343)
        at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:318)
        at com.test.springtomcat.server.config.PersistanceConfig.entityManagerFactory(PersistanceConfig.java:56)
        at com.test.springtomcat.server.config.PersistanceConfig$$EnhancerBySpringCGLIB$$37bc929c.CGLIB$entityManagerFactory$0(<generated>)
        at com.test.springtomcat.server.config.PersistanceConfig$$EnhancerBySpringCGLIB$$37bc929c$$FastClassBySpringCGLIB$$54d097b8.invoke(<generated>)
        at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
        at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:355)
        at com.test.springtomcat.server.config.PersistanceConfig$$EnhancerBySpringCGLIB$$37bc929c.entityManagerFactory(<generated>)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:497)
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162)
        ... 60 more

There are "standart" version incompatibility exception (java.lang.IncompatibleClassChangeError) when some interfaces or absract classes were changed. My entityManagerFactory creating method corresponding official documentation and even updated tutorial. Can anyone help me with this issue? what i doing wrong?
UPDATED
After manually undeploy and clean project have another exception NoClassDefFoundError.
log below
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in com.test.springtomcat.server.config.PersistanceConfig: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.persistence.EntityManagerFactory]: Factory method 'entityManagerFactory' threw exception; nested exception is java.lang.NoClassDefFoundError: javax/transaction/SystemException
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1123)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1018)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:510)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:839)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:446)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:328)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4748)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5197)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:155)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:724)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:700)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:718)
    at org.apache.catalina.startup.HostConfig.manageApp(HostConfig.java:1660)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:300)
    at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819)
    at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801)
    at org.apache.catalina.mbeans.MBeanFactory.createStandardContext(MBeanFactory.java:463)
    at org.apache.catalina.mbeans.MBeanFactory.createStandardContext(MBeanFactory.java:413)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:300)
    at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819)
    at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801)
    at javax.management.remote.rmi.RMIConnectionImpl.doOperation(RMIConnectionImpl.java:1471)
    at javax.management.remote.rmi.RMIConnectionImpl.access$300(RMIConnectionImpl.java:76)
    at javax.management.remote.rmi.RMIConnectionImpl$PrivilegedOperation.run(RMIConnectionImpl.java:1312)
    at javax.management.remote.rmi.RMIConnectionImpl.doPrivilegedOperation(RMIConnectionImpl.java:1404)
    at javax.management.remote.rmi.RMIConnectionImpl.invoke(RMIConnectionImpl.java:832)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:323)
    at sun.rmi.transport.Transport$1.run(Transport.java:200)
    at sun.rmi.transport.Transport$1.run(Transport.java:197)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.rmi.transport.Transport.serviceCall(Transport.java:196)
    at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:568)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:826)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$256(TCPTransport.java:683)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:682)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.persistence.EntityManagerFactory]: Factory method 'entityManagerFactory' threw exception; nested exception is java.lang.NoClassDefFoundError: javax/transaction/SystemException
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
    ... 59 more
Caused by: java.lang.NoClassDefFoundError: javax/transaction/SystemException
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:348)
    at org.jboss.logging.Logger$1.run(Logger.java:2554)
    at java.security.AccessController.doPrivileged(Native Method)
    at org.jboss.logging.Logger.getMessageLogger(Logger.java:2529)
    at org.jboss.logging.Logger.getMessageLogger(Logger.java:2516)
    at org.hibernate.jpa.internal.HEMLogging.messageLogger(HEMLogging.java:28)
    at org.hibernate.jpa.internal.HEMLogging.messageLogger(HEMLogging.java:24)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.<clinit>(EntityManagerFactoryBuilderImpl.java:100)
    at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:49)
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:343)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:318)
    at com.test.springtomcat.server.config.PersistanceConfig.entityManagerFactory(PersistanceConfig.java:61)
    at com.test.springtomcat.server.config.PersistanceConfig$$EnhancerBySpringCGLIB$$d721742f.CGLIB$entityManagerFactory$0(<generated>)
    at com.test.springtomcat.server.config.PersistanceConfig$$EnhancerBySpringCGLIB$$d721742f$$FastClassBySpringCGLIB$$e2401753.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:355)
    at com.test.springtomcat.server.config.PersistanceConfig$$EnhancerBySpringCGLIB$$d721742f.entityManagerFactory(<generated>)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162)
    ... 60 more
Caused by: java.lang.ClassNotFoundException: javax.transaction.SystemException
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1335)
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1169)
    ... 83 more

A: I used Spring 4.2.3.RELEASE + Spring Data Jpa 1.9.1.RELEASE + Hibernate 5.0.4.Final and works fine.
This IncompatibleClassChangeError can be many things make sure that you don't have other hibernate versions in the classpath.
What causes java.lang.IncompatibleClassChangeError?
https://docs.oracle.com/javase/7/docs/api/java/lang/IncompatibleClassChangeError.html

A: I found solution! as I described in question the IncompatibleClassChangeError wa a phantom exception that changed with NoClassDefFoundError exception after clean and manually undeploy previous version from tomcat (thanks to user2669657) .
NoClassDefFoundError resolved by added dependency on jta 1.1. (Java Transaction API) that required by the hibernate-entityManager but maven does't known that.


text:
Q: Validation using angular 2 Hi using angular 2 for password field I have to set " Password should have at least 1 uppercase, 1 lowercase, 1 number, 1 special character, minimum of 8 characters, and maximum of 16 characters"
In that I have done "minimum of 8 characters, and maximum of 16 characters".
But I am unable to set for remaining things least 1 uppercase, 1 lowercase, 1 number, 1 special character.

   Password
   <input class ="form-control" name ="password" #password="ngModel" [(ngModel)] = "angulaService.selectedAngula.password"
   placeholder="password"  minlength="8" maxlength="16" >

Password is required

Password must be min  8 characters long

Password is required

Password should not be greater than  16 characters long

Please help me in this
Thanks in Advance

A: Example of uppercase validator:
import { Directive } from '@angular/core';
import {NG_VALIDATORS, AbstractControl, ValidationErrors, Validator} from '@angular/forms';

@Directive({
  selector: '[uppercaseValidator]',
  providers: [{provide: NG_VALIDATORS, useExisting: UppercaseValidatorDirective, multi: true}]
})
export class UppercaseValidatorDirective implements Validator {
  validate(control: AbstractControl): ValidationErrors | null {
    const value = control.value
    return /[A-Z]/.test(value) ? null : { uppercase: 'Must contain at least one upper case character'}
  }
}

Usage:
app.component.html
<form>
  <input uppercaseValidator [(ngModel)]="uppercase" #uppercaseCtrl="ngModel" name="uppercase"/>

At least one character must be uppercased

</form>

app.component.ts
<form>
  <input uppercaseValidator [(ngModel)]="uppercase" #uppercaseCtrl="ngModel" name="uppercase"/>

At least one character must be uppercased

</form>

Live demo
Create other validators by following the same steps of creating a custom  validation directive. You just need to change the regexp and error message. You can use following regexp:

*

*uppercase: /[A-Z]/

*lowercase: /[a-z]/

*number: /[0-9]/

*special character: depends on what you consider a special character.

A: Better use Regex for this,
^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&])[A-Za-z\d$@$!%*?&]

(you are already checking for min length and max length, so no need to put length limitation in regex, but you can still do that via regex. Although I would suggest keep both of the error separated.)


text:
Q: Change date every 56 rows in excel my objective is to have the same date repeated in the first 56 rows and then to vary to the next day in row 57.
That is:
if I start with date 8/31/2013 I expect to have this same date in the following 56 rows and then change it in 57 to 9/01/2013.
So far I have been working with this formula:
=IF(MOD(ROW(),56)=1,OFFSET(B2,-56,-1)+1,"")
I got to have the dates every 56 rows but still, I need to fill row 2-55 with the same date. Is there any formula or VBA code that helps me do that?

A: In B1 put your desired start date.  Then in B2 put and copy down:
 =$B$1+INT((ROW()-1)/56)


text:
Q: Why dplyr group_by, summarise, and weighted mean is throwing an error I am running into a (new since updating R and other packages) error when trying to calulated weighted means of a grouped variable. Reproducible example is below. This used to work fine but now something seems to have changed. I get the following error:
Error: Problem with summarise() input avg.
x 'x' and 'w' must have the same length
ℹ Input avg is weighted.mean(outcome, na.rm = T, w = df$wt).
ℹ The error occurred in group 1: groups = "A".
# Reprex

library(dplyr)

# Data
df <- data.frame(
  groups = rep(c("A", "B", "C"), each = 10),
  outcome = rnorm(30),
  weight = rnorm(30))

# This Works
df %>%
  group_by(groups) %>%
  summarise(avg = mean(outcome, na.rm = T))

# This throws an error
df %>%
  group_by(groups) %>%
  summarise(w_avg = weighted.mean(outcome, na.rm = T, w = df$weight))

A: Try this:
# This throws an error
df %>%
    group_by(groups) %>%
    summarise(w_avg = weighted.mean(outcome, na.rm = T, w = weight))


text:
Q: Woocommerce, ordering products by default on shortcode pages In my woocommerce store I have a Sale Products page. In this page I use the shortcode to display the products on sale
[sale_products per_page="40" columns="3"]

In the store the products are ordered according to their position in a list in the backend (accessible via the Products->sort products link). This sorts them on normal category pages but on a shortcode page they are sorted by title. I know there is an orderby attribute I can add but is there an argument that will achieve this?

A: You can try to order by menu_order like this:
[sale_products per_page="40" columns="3" orderby="menu_order"]

if the corresponding callback is using WP_Query() to query the products.


text:
Q: Design of notifying about model changes in iOS game I'm developing a rogue like game (iOS/Cocos2d). I have a object of class Map, which has bunch of GameObjects.
I have GameViewController class. When something in model happens (creature killed, player moved, anything), I need to notify GameViewController about this changes. How to do that?
I see two options:

*

*GameViewController instance could be a delegate of Map and a delegate of every GameObject.

*GameViewController will listen NSNotifications from Map and GameObjects.

Which way is better? Why?

A: Cocos is a strongly singleton-based library, so the singleton method is quite common in Cocos games. That does not mean, however, it is the logical default choice.
Your second option is generally a wiser and safer approach for any program, not just Cocos. NSNotifications allow you to notify objects from other objects without getting into a potentially buggy state of passing numerous references or singletons around in your program. If you can achieve your goals with a few notifications, this is the way to go.
If you find you are using NSNotifications to an extreme degree, like multiple notifications every second, then you should consider either passing references around between your objects via pointers, or creating your parent class or main Cocos scene class as a singleton.
Just remember that when you get singletons involved, though they are easy to implement, it is just as easy to abuse them. You don't want to get into the habit of having children classes control the behavior of their siblings just because they can access the parent and the parent's methods easily.


text:
Q: Which python Linux IDEs support GAE's webapp2 framework? I am a newbie in the world of python and I want to change that. So far all my projects have in done in text editors like gedit, but for my final I need to do something more complex and I actually want a tool that helps me do it and that does not get in the way.
My final project is a dynamic website in GAE using the webapp2 framework. My objective is to find a free python IDE that supports that.
So far, after checking some of the options in the wiki,  my search is stalled:

*

*PyCharm supports webapp2, but only in the professional version

*Komodo only has addons for Django

I was wondering, if anyone out there knows of a good IDE (with auto-completion at least) that supports webapp2, or that has some really good plugin for doing that and that it is free (no trial versions please)
I understand this question may have multiple possible answers, but I would really appreciate any possible help here. Kudos++ will be given to the most promising answers as usual.

A: After much deliberation, I tested Eclipse with the pydev plugin, and the trial version of pycharm. I decided to go with pycharm, as it is better in pretty much everything.


text:
Q: How to install Oracle 11g?
Possible Duplicate:
How can I install Oracle 11g R2 in Ubuntu 12.04 LTS?

Question:
I'm trying to install oracle 11g on Ubuntu 11.10.
I got pretty far, using these 3 tutorials:
https://forums.oracle.com/forums/thread.jspa?messageID=9596361
http://blog.craigpoma.com/2010/07/installing-oracle-11gr2-on-fedora-13.html
http://lesscode.blogspot.com/2010/04/install-oracle-11g-r2-on-ubuntu-104.html
But now, I'm stuck with this one:

INFO:
  /u01/app/oracle/product/11.2.0/dbhome_1/network/lib//libnlsnr11.a(nsglsn.o):
  In function nsglonsterm': nsglsn.c:(.text+0xc29): undefined reference
  toons_subscriber_close' nsglsn.c:(.text+0xc3b): undefined reference
  to ons_shutdown_nowait'
  /u01/app/oracle/product/11.2.0/dbhome_1/network/lib//libnlsnr11.a(nsglsn.o):
  In functionnsglma': nsglsn.c:(.text+0x1ffb): undefined reference to
  ons_subscriber_receive' nsglsn.c:(.text+0x251d): undefined reference
  toons_notification_body' nsglsn.c:(.text+0x2a4b):  INFO: undefined
  reference to ons_subscriber_relinquish' nsglsn.c:(.text+0x2a62):
  undefined reference toons_subscriber_receive'
  /u01/app/oracle/product/11.2.0/dbhome_1/network/lib//libnlsnr11.a(nsglsn.o):
  In function nsglonsinit': nsglsn.c:(.text+0x2d43c): undefined
  reference toons_init' nsglsn.c:(.text+0x2d457): undefined reference
  to ons_subscriber_create_async' nsglsn.c:(.text+0x2d473): undefined
  reference toons_subscriber_status' nsglsn.c:(.text+0x2dc94):
  undefined reference to `ons_shutdown_nowait'

I think I see the problem
(the double slash in /network/lib//libnlsnr11.a )
But I don't know how to solve it...
The offending makefile seems to be this one:
(/u01/app/oracle/product/11.2.0/dbhome_1/network/lib/ins_net_server.mk )
# $Id: cus_net_server.mk 08-mar-2002.10:43:34 donlee Exp $
#
# cus_net_server.mk - "make" command file to reload tnslsnr, lsnrctl
#
# Used to reload tnslsnr, lsnrctl, after changing network protocol adapter.
#
# NOTE: ORACLE_HOME must be either:
#   . set in the user's environment
#   . passed in on the command line
#   . defined in a modified version of this makefile
#
# MODIFIED  (MM/DD/YY)
# donlee     03/08/02  - cannot use $<
# donlee     02/27/02  - define/use macro covers for INSTALL_TARGS
# donlee     02/26/02  - use relevant LINKLINE macros
# donlee     02/08/01 -  rm unneeded macro defs
# donlee     02/08/01  - rm unnecessary def of ECHO
# mkrohan    10/12/00  - Switch from LINKEXSYSLIBS to LINKLDLIBS
# mkrohan    05/20/00  - Bug #1304913
#

include $(ORACLE_HOME)/network/lib/env_network.mk

INSTALL_TARGS=clean $(INSTALL_NET_SERVER_TARGS)

tnslsnr: $(S0NSGL) $(SNSGLP) $(NSGLPNP)
    $(SILENT)$(ECHO) " - Linking $(TNSLSNR)"
    $(RMF) $@
    $(TNSLSNR_LINKLINE)

itnslsnr: tnslsnr
    -$(MV) -f $(BINHOME)tnslsnr $(BINHOME)tnslsnr0
    -$(MV) tnslsnr $(BINHOME)tnslsnr
    -$(CHMOD) 751 $(BINHOME)tnslsnr

lsnrctl: $(S0NSGLC)
    $(SILENT)$(ECHO) " - Linking $(LSNRCTL)"
    $(RMF) $@
    $(LSNRCTL_LINKLINE)

ilsnrctl: lsnrctl
    -$(MV) -f $(BINHOME)lsnrctl $(BINHOME)lsnrctl0
    -$(MV) lsnrctl $(BINHOME)lsnrctl
    -$(CHMOD) 751 $(BINHOME)lsnrctl

preinstall:
    -$(CHMOD) 755 $(BINHOME)

install: preinstall $(INSTALL_TARGS)

clean:

Which includes this one:
/u01/app/oracle/product/11.2.0/dbhome_1/network/lib/env_network.mk
but this file is too large to post here...
See here for the download link:
http://www.oracle.com/technetwork/database/enterprise-edition/downloads/index.html


text:
Q: Gateway Timeout error (504) on webapp even though i can see scraper is not done completing the fetch google-ip-forwarding: Could not parse IP address: "local"."
This is the error I got in the GCE logs - I am running two applications - a webapp and a scraper.
The error i'm facing comes in when i make a request from the webapp - I can see the scraper running to completion. However, the webapp doesn't wait for the scraper to complete the process and returns a gateway timeout (504) error within 30 seconds. Could someone please suggest where i might be missing something?
Moreover, it seems to be working all fine on local and returns results as expected. But carries out the aforementioned behaviour on production. Code included below:
exports.fetchNewShippingInfo = async (seller, pan, startDate, endDate ) => {
    return await axios.get(scraperServiceUrl+'/getShippingData', {
                params : {
                    iec_code : seller.iecCode,
                    count: 100,
                    pan_no : pan,
                    st_date : startDate,
                    end_date : endDate
                },
        }).then(async (response) => {
            console.log("Got successfully", response.data.results.data);
            let newData = JSON.parse(await response.data.results.data);
            for (var i=0; i<newData.length; i++){
                try {
                let shb_no = newData[i]['SHB No'];
                let temp_date = undefined;
                let bill_date = undefined;
                temp_date = newData[i]['SHB Date'].split('.').join('/');
                bill_date = moment(temp_date,
                            "DD/MM/YYYY").format('YYYY-MM-
                             DD[T]HH:mm:ss');
                let shipments = await Shipment.findOne({company :
                                      seller, shippingBillNo : shb_no});
                    if(shipments){
                    shipments.data = refine_keys(newData[i]);
                    shipments.billId = undefined;
                    await shipments.save();
                    }
                    if(shipments == undefined){
                        let new_shipment = new Shipment({
                            company : seller,
                            data : refine_keys(newData[i]),
                            billDate : bill_date,
                            shippingBillNo : newData[i]['SHB No']
                        })
                        console.log("Extracting data..");
                        await new_shipment.save();
                    }
                } catch (error){
                        console.log("Error: ", error);
                }
                }
                console.log("Extracted and Saved Data Successfully!");

        }).catch((error) => {
            if(error.response){
                console.log('Error Response: ', error.response);
            } else {
            console.log('Error: ', error);
            }
        })
}

Where - the /getshippingData route leads to:
exports.shippingDetails = async (req,res) => {
    let iec_code = req.query.iec_code;
    let pan_no = req.query.pan_no;
    let st_date = req.query.st_date;
    let end_date = req.query.end_date;
    let count = req.query.count;
    let model = await BrcModel.findOne({iecCode : iec_code});
    let newShippingData = undefined;
    let newData = await brcData(iec_code, count, pan_no, st_date,
                  end_date);
    res.status(200).json(jsonHelper.getResponse("Success",null,{data :
                                          JSON.stringify(newData)}));
  }

I can see the shippingDetails code run to completion in the log. With 'newData' being resolved - but fetch newShippingInfo doesn't wait for response and catches a 504 error after 30 seconds itself.


text:
Q: find data containing in last column of excel of a specific row I am trying to find data containing in last column of excel of a specific row.i want to find it for row number2 only.
using code below
Excel.Range last = sheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing);
int lastUsedRow = last.Row;
int lastUsedColumn = last.Column;

A: You can do something like this--

Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(@"C:\test.xlsx");
Excel.Worksheet xlWorksheet = (Excel.Worksheet) xlWorkbook.Sheets[1];
Excel.Range xlRange = xlWorksheet.UsedRange;
int rowCount = xlRange.Rows.Count;
int colCount = xlRange.Columns.Count;
var cellvalue = (xlRange.Cells[2,colCount-1] as Excel.Range).Value2.ToString();


text:
Q: Logging from one docker container to another I think I am missing something linking docker containers.
I have 2 containers, 1 running Jenkins and 1 running elk stack.
From the host I can easily get logs to flow to elk.. and linking the Jenkins container to the elk one via --link gets some generic events into the elk stack.
But want I really want is the Jenkins container to (via the Jenkins Notification plugin) to log builds into elk  no matter what I try tcp or http the the port I use on the docker host nothing shows up.
On the host the port 3333 is input to the elk container (3333 is the port for logstash).
From the docker host I can just do something like "echo "hello new World" | nc localhost 3333" and elk picks it up.
I am starting elk first with this:
docker run -d --name elk-docker -p 8686:80 -p 3333:3333 -p 9200:9200 elk-docker

Then Jenkins with this:
docker run -p 8585:8080 -v $PWD/docker/jenkins/jenkins_home:/var/lib/jenkins -t jenkins-docker

I have also tried this linking the two with no success.
docker run -p 8585:8080 --link elk-docker:elk -v $PWD/docker/jenkins/jenkins_home:/var/lib/jenkins -t jenkins-docker

In Jenkins I have the job notifiers plug-in installed and I was trying to use a simple TCP to port 333 and get the main events of the Jenkins job showing up in Elk by using the URL 172.17.0.5:3333. 172.17.0.5 is the IP of the logstash container.


text:
Q: Duvida sobre X-Frame-Options Ontem tive um problema com o  X-Frame-Options, como pode ser visto neste post. Porém, adicionei a solução, e funcionou perfeitamente.
Eu adicionei a solução, porém não tenho ideia do que ela faz, e gostaria de uma explicação.
A solução adicionada em meu  Global.asax  foi:
protected void Application_PreSendRequestHeaders()
{
    Response.Headers.Remove("X-Frame-Options");
     Response.AddHeader("X-Frame-Options", "AllowAll");

}

Minha dúvida agora é:
O que é  X-Frame-Options?
Como se utiliza, e por que causa o tipo de problema demonstrado?

A: X-Frame-Options serve para indicar ao browser se e quando seu site pode aparecer dentro de um <iframe> de outro site. A documentação está aqui.
A priori, a configuração é feita no servidor.
Você até pode colocar um comportamento específico para o X-Frame-Options (como no caso da sua aplicação), o que está ok, visto que desabilitar esse item do cabeçalho pode fazer com que seu site apareça dentro de outros de forma indesejada.


text:
Q: My picture won't slide and even change position i JavaSctipt i'm new in JavaScript Programming. I have some problem. I added some picture that i want to be slideshow with previous and next buttons.
const carouselSlide = document.querySelector('.carouselImage');
const carouselImages = document.querySelectorAll('.carouselImage img');

//Buttons
const prevBtn = document.querySelector('#prevBtn');
const nextBtn = document.querySelector('#nextBtn');

//Counter
let counter = 1;
const  size = carouselImages[0].clientWidth;

carouselSlide.style.transform = 'translateX(' + (-size * counter) + 'px)';

nextBtn.addEventListener('click',()=>{
    carouselSlide.style.transform = 'transform 0.4s ease-in-out';
    counter++;
    carouselSlide.style.transform = 'translateX(' + (-size * counter) + 'px)';

});

First image and last image are duplicated becouse I want smoothness in this.
Look on the HTML Code
<!DOCTYPE html>

    <meta charset="utf-8"/>
    <title>Benedykt Borowski</title>
    <meta name="description" content="Młody człowiek cieszącym się życjem"/>
    <meta name="keyword" content="Młody, blog, programista, cieszący się życiem"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Lato:wght@300&display=swap" rel="stylesheet">
    <link href="CSS/styleshets.css" rel="stylesheet">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Lato:wght@300;700&display=swap" rel="stylesheet">

Banedykt Borowski

 Home

About me

My bedroom

My workspace

My travels

My work

My Studing

">

Witam,

        Jestem młodym człowiekiem chcącym pokazać wszystkim ludziom kim jestem,
            co robie, jak korzystam z życia i oczywiście jak żyje.

Odrazu odsyłam do zakładek po lewej stronie!

        Tam dowiecię się o mnie trochę więcej :D

A jeżeli chcecie poczytać odrazu to na dole pare rzeczy!

 Może zacznijmy od moich stanowisk które posiadałem  przez większość życia

        <button id="prevBtn">Previous</button>
        <button id="nextBtn">Next</button>

And CSS file:
.Menu-side-bar{
    background-color: aliceblue;
    list-style-type:none;
    width: 10%;
    text-align: left;
    font-family: 'Lato', sans-serif;;
    font-weight: 300;

}
.Menu-side-bar ul{
    padding: 5%;
}
.Menu-side-bar li{
    padding: 3%;
}
.Menu-side-bar a{
    text-decoration: none;
    color: black;
}
.Menu-side-bar li:hover{
    color: white;
    background-color:green ;
}
.active{
   color: white;
    background-color:green ;
}
#ParentDiv{
width: 100%;
text-align: center;
}
#IndexName{
    display: inline-block;
    width: 100%;
    color: black;
    background-color: aliceblue;
}
#IndexMenu{
    float: left;
}
#indexText{
    float: left;
}
.drop-down-menu{
display: none;
}
.Menu-side-bar li:hover .drop-down-menu{
    display: block;
    position: absolute;
    background-color: aliceblue;
    width: 10%;
    padding: 0.1%;
    margin-left: -0.3%;
}
#indexFirstWords{
    width: 50%;
    text-align: center;
    display: inline-block;
    font-family: 'Lato', sans-serif;
    font-weight: 700;
}
.carouselSlide{
    width: 27%;
    margin: auto;

}
.carouselImage{
    display: flex;
    width: 100%;
    height: 500px;
}

Don't know what happend there, my friend is doing it and it works perfectly.
Thanks for all help!


text:
Q: Python Error Using Argparse I made a program that converts a csv file to a xml file using argparse. First it will read the csv file as an inputfile then converts it to a xml file. Here is my code:
import sys, argparse
import csv
import indent
from xml.etree.ElementTree import ElementTree, Element, SubElement, Comment, tostring

parser=argparse.ArgumentParser(description='Convert wordlist text files to various formats.', prog='Text Converter')
parser.add_argument('-v','--verbose',action='store_true',dest='verbose',help='Increases messages being printed to stdout')
parser.add_argument('-c','--csv',action='store_true',dest='readcsv',help='Reads CSV file and converts to XML file with same name')
parser.add_argument('-x','--xml',action='store_true',dest='toxml',help='Convert CSV to XML with different name')
parser.add_argument('-i','--inputfile',type=argparse.FileType('r'),dest='inputfile',help='Name of file to be imported',required=True)
parser.add_argument('-o','--outputfile',type=argparse.FileType('w'),dest='outputfile',help='Output file name')
args = parser.parse_args()

def main(argv):
    reader = read_csv(args.inputfile)
    if args.verbose:
        print ('Verbose Selected')
    if args.toxml:
        if args.verbose:
            print ('Convert to XML Selected')
        generate_xml(reader, args.outputfile)
    if args.readcsv:
        if args.verbose:
            print ('Reading CSV file')
    if not (args.toxml or args.readcsv):
        parser.error('No action requested')
    return 1

def read_csv(inputfile):
      return list(csv.reader(inputfile))

def generate_xml(reader,outfile):
    root = Element('Solution')
    root.set('version','1.0')
    tree = ElementTree(root)

    head = SubElement(root, 'DrillHoles')
    head.set('total_holes', '238')

    description = SubElement(head,'description')
    current_group = None
    i = 0
    for row in reader:
        if i > 0:
            x1,y1,z1,x2,y2,z2,cost = row
            if current_group is None or i != current_group.text:
                current_group = SubElement(description, 'hole',{'hole_id':"%s"%i})

                collar = SubElement (current_group, 'collar',{'':', '.join((x1,y1,z1))}),
                toe = SubElement (current_group, 'toe',{'':', '.join((x2,y2,z2))})
                cost = SubElement(current_group, 'cost',{'':cost})
        i+=1
    indent.indent(root)
    tree.write(outfile)

if (__name__ == "__main__"):
    sys.exit(main(sys.argv))

then on the command prompt i write, Argparse.py -i 1250_12.csv -o output.xml -x
where argparse is the program name and 1250_12.csv is csv file name and output.xml is what i want the output name to be and -x is an action converting csv to xml.
this program was working 10 min ago and now it gets an error saying:
x1,y1,z1,x2,y2,z2,cost = row
Value error: need more than 1 value to unpack

A: It appears that there are lines in your CSV that do not have exactly 7 columns. Perhaps there are some empty lines?
You could use a try..except to catch and handle the error:
def generate_xml(reader,outfile):
    root = Element('Solution')
    root.set('version','1.0')
    tree = ElementTree(root)

    head = SubElement(root, 'DrillHoles')
    head.set('total_holes', '238')

    description = SubElement(head,'description')
    current_group = None
    next(reader) # skip the first line
    for row in reader:
        try:
            x1,y1,z1,x2,y2,z2,cost = row
        except ValueError as err:
            sys.stderr.write('{e}: {r!r}'.format(e=err, r=row))
        if current_group is None or i != current_group.text:
            current_group = SubElement(description, 'hole',{'hole_id':"%s"%i})
            collar = SubElement (current_group, 'collar',{'':', '.join((x1,y1,z1))}),
            toe = SubElement (current_group, 'toe',{'':', '.join((x2,y2,z2))})
            cost = SubElement(current_group, 'cost',{'':cost})
    indent.indent(root)
    tree.write(outfile)

Also, if you set reader = csv.reader(inputfile) instead of making it a list, then your program will require less memory since reader will be an iterator instead of a list of rows.
Morever, to skip the first line with next(reader), reader must be an iterator, not a list. So for the above to work, also change:
reader = read_csv(args.inputfile)

to
reader = csv.reader(inputfile)


text:
Q: aws s3: Extra charge against us-east-1 when putting to ap-northeast-1 Our AWS statement came in and we noticed we're being doubly charged for the number of requests.
First charge is for Asia Pacific (Tokyo) (ap-northeast-1) and this is straightforward because it's where our bucket is located.  But there's another charge against US East (N. Virginia) (us-east-1) with a similar number of requests.
Long story short, it appears this is happening because we're using the aws s3 command and we haven't specified a region either via the --region option or any of the fallback methods.
Typing aws configure list shows region: Value=<not set> Type=None Location=None.
And yet our aws s3 commands succeed, albeit with this seemingly hidden charge.  The presumption is, our requests first go to us-east-1, but since there isn't a bucket there by the name we specified, it turns around and comes back to ap-northeast-1, where it ultimately succeeds while getting accounted twice.
The ec2 instance where the aws command is run is itself in ap-northeast-1 if that counts for anything.
So the question is, is the presumption above a reasonable account of what's happening?  (i.e. Is it expected behaviour.)  And, it seems a bit insidious to me but is there a proper rationale for this?

A: What you are seeing is correct. The aws s3 command needs to know the region in order to access the S3 bucket.
Since this has not been provided, it will make a request to us-east-1, which is effectively the default - see the AWS S3 region chart to see that us-east-1 does not require a location constraint.
If the S3 receives a request for a bucket which is not in that region then it returns a PermanentRedirect response with the correct region for the Bucket. The AWS CLI handles this transparently and repeats the request with the correct endpoint which includes the region.
The easiest way to see this in action is to run commands in debug mode:
aws s3 ls ap-northeast-1-bucket --debug

The output will include:
DEBUG - Response body:
<?xml version="1.0" encoding="UTF-8"?>
<Error>PermanentRedirect<Message>The bucket you are attempting to access
must be addressed using the specified endpoint. Please send all future requests to
this endpoint.</Message>
<Endpoint>ap-northeast-1-bucket.s3.ap-northeast-1.amazonaws.com</Endpoint>
<Bucket>ap-northeast-1</Bucket>
<RequestId>3C4FED2EFFF915E9</RequestId><HostId>...</HostId></Error>

The AWS CLI does not assume the Region is the same as the calling EC2 instance, it's a long running confusion/feature request.
Additional Note: Not all AWS services will auto-discover the region in this way and will fail if the Region is not set. S3 works because it uses a Global Namespace which inherently requires some form of discovery service.


text:
Q: Avatar has contents that are not what they are reported to be when i try to upload an image using paper clip this is the error i face and here is the code for the paper clip insert
"has_attached_file :avatar, styles: { medium: "300x300>", thumb: "100x100#>" }, default_url: "/images/:style/missing.png"
     validates_attachment_content_type :avatar, content_type: /\Aimage/.*\Z/"

A: You should read the documentation paperclip, there step by step explains the requirements and the process to follow.
The Unix file command is required for content-type checking. This utility isn't available in Windows, but comes bundled with Ruby Devkit, so Windows users must make sure that the devkit is installed and added to the system PATH
If you're using Windows 7+ as a development environment, you may need to install the file.exe application manually.
Download & install file from this url
Next, you need to integrate with your environment

*

*Open config/environments/development.rb

*Add the following line: Paperclip.options[:command_path] = 'C:\Program Files (x86)\GnuWin32\bin'

*Restart your Rails server


text:
Q: Darkmode checkbox input get checked only from the second click When running on a browser, the switch below activates/disactivates darkmode from the first click, but get checked/un-checked only from the second click.
** Originally I used the checked property only and later added the checked attribute to try and fix the issue (as you can see- it didn't help).
It acts the same also in case the JavaScript handles the checked attribute only.
The purpose is to have it work in a multiple pages site (hence the localStorage involvment).
I failed to understand why it happens.
Any suggestions?
all-pages.js:
const htmlTag = document.querySelector('html');
const switchBtn = document.querySelector('.slider');
const darkCheckbox = document.querySelector('.dark-cb');

function darkMode() {
  if (localStorage.getItem('dark') == 'true') {
    darkCheckbox.checked = true;
    darkCheckbox.setAttribute('checked', 'checked');
    htmlTag.classList.add('dark');
    switchBtn.classList.add('dark');
  } else {
    darkCheckbox.checked = false;
    darkCheckbox.removeAttribute('checked');
    htmlTag.classList.remove('dark');
    switchBtn.classList.remove('dark');
  }
}

switchBtn.addEventListener('click', function() {
  localStorage.setItem('dark', htmlTag.className.indexOf('dark') == -1);
  darkMode();
});

window.onload = darkMode();

style.css:
html {
  min-height: 100%;
}

.switch {
  position: absolute;
  top: 10px;
  left: 20px;
  width: 60px;
  height: 34px;
}

/* Hide default HTML checkbox */

.switch input {
  opacity: 0;
  width: 0;
  height: 0;
}

/* The slider */

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: skyblue;
  -webkit-transition: .4s;
  transition: .4s;
}

.slider::before {
  position: absolute;
  content: "";
  height: 26px;
  width: 26px;
  left: 4px;
  bottom: 4px;
  background-color: #FFFF66;
  -webkit-transition: .4s;
  transition: .4s;
}

input:checked+.slider {
  background-color: darkblue;
}

input:focus+.slider {
  box-shadow: 0 0 1000px darkblue;
}

input:checked+.slider::before {
  -webkit-transform: translateX(26px);
  -ms-transform: translateX(26px);
  transform: translateX(26px);
}

/* Rounded sliders */

.slider.round {
  border-radius: 34px;
}

.slider.round::before {
  border-radius: 50%;
}

.dark {
  filter: invert(1);
}

index.html:

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

            <input type="checkbox" class='dark-cb'>

A: IF I understood correctly you are having problems with the fancy checkbox appearing to be checked upon first clicking but the toggling of classes to the HTML element etc works fine.
To that end I hope the following might prove useful.
Because of the restrictions imposed here with Snippets not being able to access localStorage I cannot create a snippet to demonstrate but perhaps this jsFiddle will help illustrate

                <input type='checkbox' name='dark-cb' class='dark-cb'>

Modified the darkMode function so that the checking / unchecking of the checkbox programmatically nowonly happens when there is no MouseEvent/Click. Also tweaked the CSS to use variables so that the layout can be modified quickly and programmatically if required.

A: Ok. I see what you mean. Please try this one:
    <!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Dark/Light Mode Switch</title>

        <input type='checkbox' name='checkbox' id="checkbox" class='dark-cb'>

    Testing Dark/Light Mode Switch

A: Change your darkMode function to the one below. Then your problem is solved!
function darkMode() {
    if (localStorage.getItem('dark') === 'false' ) {
        darkCheckbox.checked = false;
        darkCheckbox.removeAttribute('checked');
        htmlTag.classList.remove('dark');
        switchBtn.classList.remove('dark');
    } else {
        darkCheckbox.checked = true;
        darkCheckbox.setAttribute('checked', 'checked');
        htmlTag.classList.add('dark');
        switchBtn.classList.add('dark');
    }
}

A: Some modification solved the issue.
Slightly modified CSS:
.switch input {
  opacity: 0;
  z-index: 100;
  cursor: pointer;
  width: 52px;
  height: 30px;
}

Modified JS:
const htmlTag = document.querySelector('html');
const switchBtn = document.querySelector('.slider');
const darkCheckbox = document.querySelector('.dark-cb');

function darkMode() {
  if (localStorage.getItem('dark') == 'true') {
    darkCheckbox.defaultChecked = true;
    htmlTag.classList.add('dark');
    switchBtn.classList.add('dark');
  } else {
    darkCheckbox.defaultChecked = false;
    htmlTag.classList.remove('dark');
    switchBtn.classList.remove('dark');
  }
}

darkCheckbox.addEventListener('click', function() {
  let isDark = (localStorage.getItem('dark') == 'true') ? 'false' : 'true';
  if (localStorage.getItem('dark') == null) {isDark = 'true';}
  localStorage.setItem('dark',isDark);
  darkMode();
});

window.onload = darkMode;

*

*I changed the localStorage.getItem('dark') value to be accepted by the isDark variable

*I used .defaultChecked instead of .checked for the input.

*I made the .addEventListnter() be triggered by the darkCheckbox, not switchBtn (that is why I used z-index: 100 on the CSS, to bring the input to the front).


text:
Q: Creating single node module to access multiple extended classes in separate files authored in coffeescript I'd like to create a single node library that includes multiple classes, each authored using coffee-script in a different file and extending from one another. For instance, say I have the following files in node_modules/mymodule/src:
File 1:
  class Base
    constructor: (@foo) ->

  module.exports = Base

File 2:
  Base = require './Base.coffee'

  class Derived extends Base
    constructor: (@bar) ->
      super

  module.exports = Derived

File 3:
  Base = require './Base.coffee'

  class Derived2 extends Base
    constructor: (@baz) ->
      super

  module.exports = Derived2

Is there some way I can bind these 3 classes in such a way so that I can define "mymodule" in package.json file and then access the module and its classes like so?
File using mymodule:
  my module = require 'mymodule'

  Base = new mymodule.Base
  Derived = new my module.Derived
  Derived2 = new my module.Derived2
  #Do stuff

I don't know what to do in package.json to make this happen, and I can't find documentation on this anywhere. Is this possible?

A: You can use main to configure the entry point you your module and expose your classes there. (I haven't done this with coffee-script).

The main field is a module ID that is the primary entry point to your program. That is, if your package is named foo, and a user installs it, and then does require("foo"), then your main module's exports object will be returned.
This should be a module ID relative to the root of your package folder.

Configure your main to point at index.js or similar.  Your index.js would then look something like this:
module.exports.Base     = require('./pathtobase/Base.coffee');
module.exports.Derived  = require('./pathtobase/Derived.coffee');
module.exports.Derived2 = require('./pathtobase/Derived2.coffee');


text:
Q: Main route on main page I need to create a route where the user can open a specific page such as
http://www.mywebsite.com/profilename
When this is inputted the page which will show a profile with correct information should be shown. Basically like facebook.
What is the route which I need to create. I did this but then there will be a redirect loop when for example someone types http://www.mywebsite.com/users, which will for example show a list of users
        routes.MapRoute(
        name: "HomeIndexWithParam",
        url: "{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional });

A: You will need to create several routes to get this working. When working with routes, remember that order matters, so place the most specific routes first.
First, you'll create the routes for predetermined controllers. These are routes that are the same all the time. In this case, the "Users" route:
routes.MapRoute(
    name: "Users",
        url: "users",
        defaults: new { controller = "Users", action = "Index" });

Then you'll follow that with the route that will be responsible for the user profiles:
routes.MapRoute(
        name: "UserProfile",
        url: "{username}",
        defaults: new { controller = "User", action = "Profile" });

I would recommend that if the "username" follows a predetermined pattern (username is between 4 and 16 characters, only allow numbers and text, etc.), that you add a constrain so it only executes when the constraint is met
In the Profile action method in the user controller, you will take in the username and if the username is found, return the view for the user's profile page. Otherwise redirect the user to the home page.
Finally, you'll have the default route:
routes.MapRoute(
        name: "Home",
        url: "",
        defaults: new { controller = "Home", action = "Index" });

Hope this makes sense.


text:
Q: Definition of "precision" of an estimator What is the exact definition of precision of a statistical estimator? Any references to textbooks are appreciated.

A: Precision is typically defined as the reciprocal of the variance of an estimator. A high variance estimator has low precision and vice versa.

A: Precision can be defined as 1/variance, or 1/standard deviation. See Wikipedia's article on Normal distribution (section "Alternative formulations") and references provided therein.


text:
Q: How to remove an excel file with same name as pdf counterpart? Imagine you want to remove a file in a directory which is Excel, but only if it is the same name as a PDF in the same directory.
Have tried the following:
import os

    #if both excel and pdf, remove excel
    directory = r"C:\Users\Max12\Desktop\xml\git\yourubl\attachments\75090058\Status\Verwerking"
    pdffile = os.path.join(directory, '.pdf')
    excelfile = os.path.join(directory, '.xlsx')

    if pdffile == excelfile:
        os.remove(excelfile)

Please help

A: You can use pathlib to accomplish that straightforward:
import pathlib

directory = pathlib.Path(r"C:\Users\Max12\Desktop\xml\git\yourubl\attachments\75090058\Status\Verwerking")

for f in directory.glob('*.xlsx'):
    if f.with_suffix('.pdf').exists():
        f.unlink()

A: Replace your if with the following if condition and try,
if os.path.exists(pdffile) and os.path.exists(excelfile):
    os.remove(excelfile)

Your code doesn't mention anything about file names. You can find all pdf filenames in a directory using glob Reference

A: For all files in your directory you may want to use sets:
pdf = set([f[:-4] for f in os.listdir(mypath) if os.path.isfile(os.path.join(mypath, f)) and f.endswith('.pdf')])
xl = set([f[:-5] for f in os.listdir(mypath) if os.path.isfile(os.path.join(mypath, f)) and f.endswith('.xlsx')])

to_del = [str(i)+'.xlsx' for i in list(a&b)]
for f in to_del:
  os.remove(os.path.join(mypath, f))


text:
Q: iOS 8.1 Fullscreen Safari iPod Touch 5th generation I have 3 html pages. I want to open this pages with my iPod Touch in fullscreen mode. These 3 pages are connected to each other. Here is a little example:

Every .html page contains this code:

<!DOCTYPE html>
<html>
 <head>
  <meta http-equiv="Content-Language" content="en" >
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" >

  <meta name="apple-touch-fullscreen" content="yes" />
  <meta name="apple-mobile-web-app-capable" content="yes" />
  <meta name="apple-mobile-web-app-status-bar-style" content="black">

  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
 </head>
 <body>
  <!--
          ...
        -->
 </body>
</html>

I followed the steps on this page here (look at the images (Point: iPhone (IOS))) to make a "web-app" in fullscreen mode. Now i made the index.html as "web-app" on the homescreen. When I press the icon, I see the index.html in fullscreen mode.
Now I want to press a button and get the next page in fullscreen too, butat the moment the next page will shown in the normal safari browser without the fullscreen mode. How can I solve this problem?


text:
Q: Is there a way to refresh an array of SQLAlchemy objects? I am trying to seed my Postgres database using the below python function
def seed_users(db: Session, number: int = 50):
    users = []
    for _ in range(number):
        user_seed = {
            'first_name': f.first_name(),
            'last_name': f.last_name(),
            'email_address': f.ascii_company_email()
        }
        users.append(models.User(**user_seed))

    db.bulk_save_objects(users)
    db.commit()
    db.refresh(users)
    return users

f is a Faker object. But it throws sqlalchemy.orm.exc.UnmappedInstanceError: Class 'builtins.list' is not mapped error.
How can I refresh all the newly created rows?

A: I know that this answer may be a little late, but I found that refresh should be performed on each object seperately.
for user in users:
    db.refresh(user)

I had the same issue and this did the trick!


text:
Q: Firebase database: Permission denied for reading? I'm trying to read from my firebase database and put it with adapter to Recyclerview, but every time I get this:
08-20 18:26:53.754 3430-3653/blabla.com.notescloud W/SyncTree: Listen at / failed: DatabaseError: Permission denied
08-20 18:26:53.764 3430-3430/blabla.com.notescloud W/FirebaseRecyclerAdapter: com.google.firebase.database.DatabaseException: Firebase Database error: Permission denied
     at com.google.firebase.database.DatabaseError.toException(Unknown Source)
     at com.firebase.ui.database.FirebaseRecyclerAdapter.onCancelled(FirebaseRecyclerAdapter.java:175)
     at com.firebase.ui.database.ObservableSnapshotArray.notifyListenersOnCancelled(ObservableSnapshotArray.java:135)
     at com.firebase.ui.database.FirebaseArray.onCancelled(FirebaseArray.java:129)
     at com.google.android.gms.internal.zzdpw.zza(Unknown Source)
     at com.google.android.gms.internal.zzdvg.zzbur(Unknown Source)
     at com.google.android.gms.internal.zzdvo.run(Unknown Source)
     at android.os.Handler.handleCallback(Handler.java:751)
     at android.os.Handler.dispatchMessage(Handler.java:95)
     at android.os.Looper.loop(Looper.java:154)
     at android.app.ActivityThread.main(ActivityThread.java:6077)
     at java.lang.reflect.Method.invoke(Native Method)
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)

My rules are ok(for the record, writing to the database work very good):
{
  "rules": {
    "users": {
      "$uid": {
        ".write": "$uid === auth.uid",
        ".read": "$uid === auth.uid"
      }
    }
  }
}

My database:
database
This is the recycler setup in my main activity:
rv = findViewById(R.id.rv_notes); //RecyclerView
rv.setLayoutManager(new LinearLayoutManager(this));

ref = FirebaseDatabase.getInstance().getReference(); // Getting a reference of the database

mAdapter = new FirebaseRecyclerAdapter<Note, NoteHolderView>(
        Note.class,
        android.R.layout.two_line_list_item,
        NoteHolderView.class,
        ref) {
    @Override
    public void populateViewHolder(NoteHolderView holder, Note note, int position) {
        holder.setmTitleField(note.getmTitle());
        holder.setmTimeField(note.getTimeFormatted(getApplicationContext()));
    }
};
rv.setAdapter(mAdapter);

Hope you will be able to help me solve this problam.
Thanks.

A: You are trying to read at the top of your database, and since you didnt specified rules for that, it is automatically denied.
Try this
ref = FirebaseDatabase.getInstance()
                      .getReference()
                      .child("users")
                      .child(FirebaseAuth.getCurrentUser().getUid());

A: You can access the collection by putting  / prefix to Collection so that means it get called.Like mine I have tried this and it worked fine Hope this helps.
 db=FirebaseDatabase.getInstance();
    dbref=db.getReference("/Course_list");

in this code I have added the "/" prefix to collection.


text:
Q: How to have multiple note page in Rmarkdown beamer presentation In Markdown beamer presentation output, my multiple notes pages are being combined into one note page. When I looked into the .tex file (from my keep_text=TRUE option), it is because the notes commands are put between \begin{frame} ... \end{frame} instead of outside \end{frame}. Below is my reproducible code in Rmarkdown beamer presentation document. Any help will be appreciated.
---
output:
   beamer_presentation
   keep_tex: yes
---

## slide title

- item 1

- item 2

\note{
long paragraph 1
}

\note{
long paragraph 2
}

I get this output

But what I wanted was:

A: You can temporarily switch from markdown to real latex and end the frame before adding the notes:
---
output:
  beamer_presentation:
    keep_tex: true
header-includes:
  - \setbeameroption{show notes}
---

## slide title

- item 1

- item 2

``` {=latex}
\end{frame}
\note{
long paragraph 1
}

\note{
long paragraph 2
}
\begin{frame}
```

normal slide

https://rstudio.cloud/project/1051204


text:
Q: How to get around unexpected behaviour of java stream? Having the following simple example of a java stream
Stream<Integer> s123 = Stream.of(1, 2, 3);
List<String> abc = Arrays.asList("a", "b", "c");
s123.flatMap(i -> abc.stream())
    .peek(System.out::println)
    .findFirst()
    .ifPresent(System.out::println);

What would you expect the peek will print?
I was expecting just "a", since the findFirst should short circuit the evaluation of the stream. Unfortunately this is not what happens. The peek method prints "a", "b", "c". This seems to be the case since the stream is created by flatMap concatenating the same stream three times.
The problem I am facing is, if someone provides a method, which returns a stream, e.g.
Stream<String> multipleOf(int i, String ...s)

one really needs to know the implementation of this method when using the stream.
The real world example did not use peek (which I used for illustration here), but a map operation doing some heavy work. In the end it caused some serious performance problems, since a lot more elements where mapped than expected.
So when it comes to performance, it seems to be safest to rely on the good old for loop - although I do like the streams very much.
Any thoughts on how to deal with these problems are welcome.


text:
Q: How to combine 2 columns in a day-hour format and convert them into a year-month-day-hour format? I have a excel(dataframe) like this:
Day Hour Value
1   0      0.13
1   1      0.15
1   23     0.14
……
365   0    0.17
365   1    0.15
365   23   0.11

I want to convert the first two columns to the date of this year or any year and then put the day in the position of the month and day, and then concatenate the hours, like this:
DateTime                 Value
2022-01-01 0:00:00       0.13
2022-01-01 1:00:00       0.15
2022-01-01 23:00:00      0.14
……
2022-12-31 0:00:00       0.17
2022-12-31 1:00:00       0.15
2022-12-31 23:00:00      0.11

How to use pandas or numpy to do this?

A: I was able to solve this issue:
Code:
# Import libraries
import pandas as pd
import numpy as np
import math
from datetime import datetime

# Simulate the above dataframe
days = list(range(1,366))
hours = np.random.randint(0,24, 365)
df = pd.DataFrame({"day": days, "hour": hours})

# Checkif the year is a leap year

def isLeap(y):
    return (y % 100 != 0 and y % 4 == 0 or y % 400 == 0)

# Get day and month given the integer of a day, i.e when (when 1-365 is given)

def getMonthDay(d, y):

    calendar = {
        12: 31,
        11: 30,
        10: 31,
        9: 30,
        8: 31,
        7: 31,
        6: 30,
        5: 31,
        4: 30,
        3: 31,
        2: 28,
        1: 31
    }

    if (isLeap(y)):
        calendar[1] +=1

    m = 1
    days = d
    while days > 0:
        day = days
        days -= calendar[m]
        if days < 1:
            return m, day
        m += 1

    return None

# Function to apply on the Dataframe where you save as datetimeformat
def datetime_merge(day, hour, year=2022):
    e_month, e_day  = getMonthDay(day, year)
    e_datetime = datetime(year=year, day=e_day, month=e_month, hour=hour)

    return e_datetime

# Apply the Function
df["DateTime"] = df.apply(lambda x: datetime_merge(x.day, x.hour), axis=1)

# Result is

# You can then drop the unnecessary column
df.drop(["day", "hour"], axis=1)

# FinalResult


text:
Q: Fixing border highlight issue I have 2 inputs side by side as shown below:

.centered-query-cn {
  height: 150px;
  display: flex;
}

.browse-query {
  display: flex;
}

.browse-query input {
  display: flex;
  flex-grow: 1 !important;
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css" rel="stylesheet" />

          <input class="form-control form-control-lg" placeholder="term" type="text">
          <input class="form-control form-control-lg" placeholder="location" type="text">

When I click on the LHS input, the border gets highlighted, but it does not look right, as shown below:

The RHS input hides the highlighted border. Is there anyway I can fix this?

A: Set a relative position for the focused input, so it overlaps the unfocused field.
Anyway for accessibility reasons, actionable elements like inputs should be spaced far enough to make the interface clearer (e.g. you could set a gap for .browse-query). Also label elements for the fields should be provided (placeholders are not enough effective).

.centered-query-cn {
  height: calc(100vh - (334px + 6vh));
  min-height: 340px;
  margin: auto;
  display: flex;
}

.browse-query {
  display: flex;
}

.browse-query input {
  display: flex;
  flex-grow: 1 !important;
}

input:focus {
  position: relative;
  z-index: 1;
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css" rel="stylesheet" />

          <input class="form-control form-control-lg" placeholder="term" type="text">
          <input class="form-control form-control-lg" placeholder="location" type="text">


text:
Q: How to make a user loged in (authenticated) in django with Reactjs? i'm using Django rest api to connect django and react Here is the view i created in Django Views to verify the if the user is authenticated or not,
but even if the user is valide, whene i try to get the currect user i get Null
class LoginView(APIView):
    def get(self,request):
        data = request.data
        usr = authenticate(username=data["username"], password=data["password"])

        if usr in not None:
            login(request,usr)
            return Response(status=status.HTTP_200_OK)
        else:
            return Response(status = status.HTTP_404_NOT_FOUND)

A: Use one of the authentication methods provided in DRF documentation.
TokenAuthentication is the easiest one to implement, but I recommend you to read the whole section first so you understand the advantages and disadvantages of each method.


text:
Q: jQuery slideUp and slideDown problem In my rails app I have the menu that have to be hidden if mouse was unmooved for 5 seconds. It works fine with .hide() and .show(), but with .slideDown() and .slideUp() it starts to sliding up very fast, than sliding down and so on. Is there another approach to them?
Here is my code:
$(document).ready(function(){
var i = null;
$("#all").mousemove(function() {
    clearTimeout(i);
    $(this).css("cursor", "default");
    $("#menu").show();
    i = setTimeout('$("#menu").hide();$("#flash_notice").hide(); $(this).css("cursor", "none");', 5000);
}).mouseleave(function() {
    clearTimeout(i);
    $("#flash_notice").hide();
        $("#menu").hide();
    $(this).css("cursor", "none");

}); });

Another issue is with $(this).css("cursor", "none");, it's seems to be working, but from time to time, so I'm really confused, what should I do.
 Thank you in advance for any tip.
  Anyone?

A: You could try introducing a chained .stop() before .slideUp() and .slideDown(), which stops any previous animations and will animate from the current position.


text:
Q: Why is ArrayList.clear()/ArrayList.removeAll() clearing both lists I've declared? I had to return ArrayList of ArrayList<Integer> as it was predefined.
I was trying this code( for pascal triangle of n lines):
ArrayList<ArrayList<Integer>> a = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> b = new ArrayList<Integer>();
for(int i=1;i<=n;i++){
    int c=1;
    //ArrayList<Integer> b = new ArrayList<Integer>(); I declared
    //the arraylist here to solve the problem
    // Place 1: b.clear()
    for(int j=1;j<=i;j++){
        b.add(c);
        c=(c*(i-j))/j;
    }
    a.add(b);
    // Place 2: b.clear();
}
return a;

Expected output:
n=4 : [1 ] [1 1 ] [1 2 1 ] [1 3 3 1 ]
I wanted to know why i was not getting the desired output when i placed clear functions at:
Place 1 output: [1 3 3 1 ] [1 3 3 1 ] [1 3 3 1 ] [1 3 3 1 ] (Only the last row)
Place 2: [ ] [ ] [ ] [ ] (no output)
The same was the case with removeAll().

A: It is the same reference of the ArrayList even if you have cleared it. So, modifying one copy will modify all the others also. You should really be creating a new instance of ArrayList instead of clearing it. Modified code below:
ArrayList<ArrayList<Integer>> a = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> b;
for (int i = 1; i <= n; i++) {
    int c = 1;
    // ArrayList<Integer> b = new ArrayList<Integer>(); I declared
    // the arraylist here to solve the problem
    b = new ArrayList<Integer>(); // NEW INSTANCE INSTEAD OF CLEARING IT
    for (int j = 1; j <= i; j++) {
        b.add(c);
        c = (c * (i - j)) / j;
    }
    a.add(b);
}
return a;

A: Not sure whether you understood the problem
Since array b is declared outside for loop , after each iteration on the outer loop same object is used and continuing with old values.
To get desired out put, make new b object within outer loop
instead of
ArrayList<Integer> b = new ArrayList<Integer>();
for(int i=1;i<=n;i++){

try this
ArrayList<Integer> b = null;
for(int i=1;i<=n;i++){
b = new ArrayList<Integer>();


text:
Q: -(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender not geting called I am working on Storyboards.I have used a table view and on its cell i have created a Segue from this table view cell prototype to a new view controller.
also i have included a method
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{

    UITableViewCell *cell=sender;
    NSLog(@"%@",cell.textLabel.text);
    thirdViewController *thid=[segue destinationViewController];
    thid.strValue=cell.textLabel.text;

}

but it is not getting called.
When does this method get called..?
Any help will be Appreciated.
Thanks
Vikas

A: If you want to open new Viewcontroller then try with below line hope it helps you:
       UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
       Synergy *objSynergy = (Synergy *)[mainStoryboard instantiateViewControllerWithIdentifier:@"Synergy"];
      [self presentModalViewController:objSynergy animated:YES];

Synergy is my new controller name you replace it with your class name change this code according to your requirement.