text:
Q: mongoose .save() not going into .save() function I am facing problems with mongoose .save() function.
Index.js
var mongoose = require('mongoose');
var companySchema = rootRequire('models/company');
mongoose.connect('mongodb://localhost:27017/test');

var company = new companySchema({activate: false, company_code: '123', name: 'A123' });
console.log(company);
company.save(function(err){
    if(err){
    console.log("now it can be associated with db",err);
    }
    else{
        console.log("bingo");
    }
});

My console log output is

{ activate: false,   _id: 582997952a3134cc08672607,   name: 'A123',
  company_code: '123' }

I did't received any of log

console.log("now it can be associated with db",err);

or

console.log("bingo");

My company.js looks like
var mongoose = require('mongoose'),
Schema = mongoose.Schema;

var companySchema = new Schema({

    name: {
        type: String,
        required: true,
        sparse: true,
        unique: true
    },
    company_code: {
        type: String,
        required: true
    },
    activate: {
        type: Boolean,
        default: false
    },
    logo: {
        type: String
    }

}, {
    collection: 'company'
});

var Company = mongoose.model('company',companySchema)

module.exports = Company;

A: Working with a single file solved my problem but not feasible option.
var mongoose = require('mongoose'),
Schema = mongoose.Schema;

//Company Schema
var companySchema = new Schema({

    name: {
        type: String,
        required: true,
        sparse: true,
        unique: true
    },
    company_code: {
        type: String,
        required: true
    },
    activate: {
        type: Boolean,
        default: false
    },
    logo: {
        type: String
    }

}, {
    collection: 'company'
});

var Company = mongoose.model('company',companySchema)
//console.log(Company);

mongoose.connect('mongodb://localhost:27017/test');
var company = new Company({activate: false, company_code: '123', name: 'OSPL3' });

console.log(company);
company.save(function(err){
    console.log('comses');
    if(err){
    console.log("now it can be associated with db",err);
    }
    else{
        console.log("bingo");
    }
});

Weather my problem associated with rootRequire?

A: I tried your code to execute and I've just added one line
var rootRequire = require('root-require');
into index.js and it works fine to me.

A: Mongoose should included before schema design.
If you'll look at my previous answer and code it will be more clear


text:
Q: Calling unknown settings C# Project in Visual Studio 2013
I need to build a X-Walk (cross reference) between a database's field names and a list of 'Standard' names.
Because this list needs to be maintained and occasionally updated, my inclination is to create a Settings class and then call the setting to get the cross reference.
e.g.
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("SIZE")]
public string MySize {
    get {
        return ((string)(this["MySize"]));
    }
}

and then it would obviously be called thus:
private string str = MyProject.AttributeXref.Default.MySize;

Here is where the rub comes... at run-time the code I have to respond to will be passing the 'Attributes' by name and I have to perform the lookup. If all I have is 'MySize' and not
MyProject.AttributeXref.Default.MySize;
should I be doing something similar to
MyProject.AttributeXref.{0}
Or...
Am I going about this all wrong?

A: and the answer is...
var a = "MySize";
var b = MyProject.AttributeXref[a];
Console.WriteLine("MySize = " + b);

Output - MySize = SIZE

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to test a method with specific file.encoding option? In a Maven application I need to test a method with a different encoding and just one of them. The others must use the encoding provided by System.getProperty("file.encoding").
For example:
@Test
public void test1() {...} // regular encoding

@Test
public void test2() {...} // regular encoding

@Test
public void test3() {...} // regular encoding

[...]

@Test
public void testEncoding() {...} // custom encoding!!!

I cannot change the encoding with System.setProperty("file.encoding", "...") because is cached and I want a procedure that can be versionable (i.e. independent by an IDE like IDEA or Eclipse and working for anyone has downloaded the code).
Is there any way via JUnit or Maven plugin to do so?

A: Method 1: Optional Charset parameter
You do not need to test your method using the file.encoding property.
As you probably know, this property will only set the DEFAULT encoding for methods which have an optional encoding/charset parameter.
However, all those methods (without the charset parameter) are considered a bad habit. That said, overload your methods with an optional parameter Charset and the method without this optional parameter should pass in Charset.defaultCharset().
This way you can easily test your methods accordingly.
Method 2: Maven-Invoker-Plugin
Use the maven-invoker-plugin to create isolated tests in src/it/<testname>. Those are fully isolated maven projects.
Examples can be found in almost any maven project. You can pass system arguments via surefire for example.
If this


text:
Q: Reading MLX90303 over SPI I am trying to take readings from the Melexis Tri-axis Hall effect sensor MLX90393, but all I seem to get is garbage.
I am reading the sensor over SPI, with a 1MHz clock. Here is an example of a couple of SPI transactions with the device, just to show that the waveform is nice. I have shown the two transactions closer together than they really are, just to fit them on the image. In reality they are 3ms apart.

Here is a description of the full set of transactions:

*

*Reset. Send F000 (then wait 3ms)

*Write Mem adr 00 with 000C (wait 100us)

*Write Mem adr 01 with C380 (wait 100us)

*Write Mem adr 02 with 0068 (wait 100us)

*Start single measurement read: Send 3E (wait 1ms)

*Read Measurement: Send 4E, receive FF75 8FEF FFFB (wait 100ms)

Then I loop 5. and 6. over and over.
The values I get back seem to make no sense. They certainly don't look like a slightly noise analog signal, which is what I would expect. For example, multiple reads from channel 0 look like: FFFB 0707 0707 8FEF 0707 F3AF FF75
What am I doing wrong?

A: Your SPI mode does not match the datasheet, it indicates CPOL = 1, aka your spi clock should idle high.


text:
Q: How to call abstract method in super class constructor in TypeScript 1.8 I need to call an abstract method from the abstract class constructor.
This worked fine until TypeScript 1.8.x.
export abstract class BaseController {
   field1:any;
   constructor(){
       this.initialize();
   }

   initialize():void{
       this.field1 = this.getField1Value();
   }

   abstract getField1Value(): any;
}

export class DerivedController extends BaseController{
    constructor(private dataService:any){
        super();
    }

    getField1Value():any{
        //do some data manipulation and then return a object
        return this.dataService.getField1Value();
    }
}

How to make something like this to work?
Those are Angular controllers. So basically what I'm doing is initializing some fields in derived controllers.
Sample TS Playground:
TSPlayground sample


text:
Q: The relativistic mechanics of a battery that is being charged and accelerated at the same time This might be an interesting question:
Let's attach a battery into one end of an electric cable. Then we rotate the battery around, with accelerating speed, using 100 Watts of power, while the battery rotates around frictionlessly. (The battery moves in a circle whose radius is the length of the cable)
At the same time we apply 200 Watts of electric power into the cable, this energy travels through the cable into the battery.
We apply 100 Watts of mechanical energy into our end of the cable, and we apply 200 Watts of electric energy into our end of the cable, then the mechanical energy and the electric energy travel into the battery.
The question: What is the speed of the battery after a very long time?
ADDITION:
Is this question too easy or too difficult?
Naively I would think that after 1 Giga seconds the battery has 200 Giga Joules of electric energy, and 100 Giga Joules of kinetic energy.
If an object has rest energy of 200 Giga Joules and kinetic energy of 100 Giga Joules, then the object can be said to be a non-relativistic object.

A: The speed of the battery will be independent of the electrical energy you've supplied to it. If you look at $E=mc^2$, you need a hell of a lot of energy to change the mass of the battery, and as mass is defined as the measurement of the resistance of a body to acceleration, you'd need a hell of a lot of electrical energy to affect the acceleration of the battery.

A: Essentially you're asking: what speed does a battery on the end of a rigid cable, undergoing rotational acceleration, get to as it's supplied electrical energy to increase its rest energy?
There are three main effects to consider

*

*the rotating current will radiate energy at a certain rate which will set a limit on the electrical energy that can be supplied to the battery.

*rotating reference frames lead to paradoxes that even today people continue to argue about, the most famous being the Ehrenfest paradox

*mechanical properties of the cable will determine the point at which it fractures.

I would conclude from the above that eventually the cable will break apart mainly because of the last effect at speeds that are not relativistic.


text:
Q: Jupyter and conda: error when cloning environment I have created multiple conda environments in order to test compatibility of installed packages. I use conda create -n test02 --clone test01 to create environment test02 as a clone of test01. I activate test02, install new packages and start instance of python from which I import new packages with no problem. The problem arises when I launch jupyter notebook or qtconsole and try to import newly installed package and get import error: no module named 'xxx'. I do a sys.executable and see that jupyter is running python from the old environment (test01) I cloned the new one from. Why is this happening? Can I change it in config file somewhere and where might I find this file?

edit: more info
jupyter --paths for both environments share path entry for config and data in the same environment directory
(test01) PS C:\Users\Aka> jupyter --paths
config:
    C:\Users\Aka\.jupyter
    c:\users\aka\miniconda3\envs\test01\etc\jupyter
    C:\ProgramData\jupyter
data:
    C:\Users\Aka\AppData\Roaming\jupyter
    c:\users\aka\miniconda3\envs\test01\share\jupyter
    C:\ProgramData\jupyter
runtime:
    C:\Users\Aka\AppData\Roaming\jupyter\runtime
(test01) PS C:\Users\Aka> conda activate test02
(test02) PS C:\Users\Aka> jupyter --paths
config:
    C:\Users\Aka\.jupyter
    c:\users\aka\miniconda3\envs\test01\etc\jupyter
    C:\ProgramData\jupyter
data:
    C:\Users\Aka\AppData\Roaming\jupyter
    c:\users\aka\miniconda3\envs\test01\share\jupyter
    C:\ProgramData\jupyter
runtime:
    C:\Users\Aka\AppData\Roaming\jupyter\runtime

edit2: I forgot to mention that I installed Jupyter using pip.
to recreate the problem I did:
conda create -n env1
conda activate env1
pip install jupyter
jupyter --paths

config:
      C:\Users\Aka.jupyter
      c:\users\aka\miniconda3\envs\env1\etc\jupyter
      C:\ProgramData\jupyter
  data:
      C:\Users\Aka\AppData\Roaming\jupyter
      c:\users\aka\miniconda3\envs\env1\share\jupyter
      C:\ProgramData\jupyter
  runtime:
      C:\Users\Aka\AppData\Roaming\jupyter\runtime

conda create --clone env1 -n env2
conda activate env2
jupyter --paths

config:
      C:\Users\Aka.jupyter
      c:\users\aka\miniconda3\envs\env1\etc\jupyter
      C:\ProgramData\jupyter
  data:
      C:\Users\Aka\AppData\Roaming\jupyter
      c:\users\aka\miniconda3\envs\env1\share\jupyter
      C:\ProgramData\jupyter
  runtime:
      C:\Users\Aka\AppData\Roaming\jupyter\runtime

If I were to install jupyter with conda into a brand new environment and then clone the environment, jupyter behaves as expected. Note: I installed jupyter with pip because I am using python 3.5 because of other packages I need and installing jupyter with conda in my environments kept breaking it. I reached out to conda-forge for help but they said "sorry, we don't support python 3.5".

A: Jupyter only needs to be install in a single location - either a Conda env or at the system-level.
Jupyter installed in Conda env
To use other envs as kernels, one needs to install nb_conda_kernels in the env with Jupyter, and ipykernel in any env you wish to use as a kernel. Always launch jupyter notebook from the env with Jupyter and the others will be available automatically.
Jupyter outside Conda
If Jupyter is installed at a system level, one must manually register the Conda envs one wishes to use as kernels:
conda activate my_env
conda install ipykernel
python -m ipykernel install --user --name my_env_name

Then launch Jupyter from anywhere.


text:
Q: How can I convert normal array of objects to multilevel array in javascript? My normal array object like this :
var b = [
    {id: 1, name: 'England',parent_id: null},
    {id: 2, name: 'Spain',parent_id: null},
    {id: 3, name: 'Chelsea',parent_id: 1},
    {id: 4, name: 'Manchester United',parent_id: 1},
    {id: 5, name: 'Real Madrid',parent_id: 2},
    {id: 6, name: 'Barcelona',parent_id: 2},
    {id: 7, name: 'Hazard',parent_id: 3},
    {id: 8, name: 'Morata',parent_id: 3},
    {id: 9, name: 'Pogba',parent_id: 4},
    {id: 10, name: 'Lukaku',parent_id: 4},
    {id: 11, name: 'Ronaldo',parent_id: 5},
    {id: 12, name: 'Bale',parent_id: 5},
    {id: 13, name: 'Messi',parent_id: 6},
    {id: 14, name: 'Suarez',parent_id: 6},
];

I want to convert the object array to be like this :
var b = [
    {
        name: 'England',
        children: [
            {
                name: 'Chelsea',
                children: [
                    {name: 'Hazard'},
                    {name: 'Morata'}
                ]
            },
            {
                name: 'Manchester United',
                children: [
                    {name: 'Pogba'},
                    {name: 'Lukaku'}
                ]
            }
        ]
    },
    {
        name: 'Spain',
        children: [
            {
                name: 'Real Madrid',
                children: [
                    {name: 'Ronaldo'},
                    {name: 'Bale'}
                ]
            },
            {
                name: 'Barcelona',
                children: [
                    {name: 'Messi'},
                    {name: 'Suarez'}
                ]
            },
        ]
    }
];

It seems it will be separated using key parent_id
But i'm still confused to implement it
How can I convert the array object like that?
Please help me guys

A: *

*.filter() the b so it contains only items with parent_id: null

*.map() remaining items, assigning children to them

*.map() children for each of the root level parents to return them without parent_id field (optional, not in the example)

var b = [
    {id: 1, name: 'England',parent_id: null},
    {id: 2, name: 'Spain',parent_id: null},
    {id: 3, name: 'Chelsea',parent_id: 1},
    {id: 4, name: 'Manchester United',parent_id: 1},
    {id: 5, name: 'Real Madrid',parent_id: 2},
    {id: 6, name: 'Barcelona',parent_id: 2},
    {id: 7, name: 'Hazard',parent_id: 3},
    {id: 8, name: 'Morata',parent_id: 3},
    {id: 9, name: 'Pogba',parent_id: 4},
    {id: 10, name: 'Lukaku',parent_id: 4},
    {id: 11, name: 'Ronaldo',parent_id: 5},
    {id: 12, name: 'Bale',parent_id: 5},
    {id: 13, name: 'Messi',parent_id: 6},
    {id: 14, name: 'Suarez',parent_id: 6},
];

const done = b.filter(person => !person.parent_id).map(person => {

  return {
    id      : person.id,
    name    : person.name,
    children: b.filter(child => child.parent_id == person.id)
  }

});

console.log(done);


text:
Q: How to allow file-access-from-files? I have been working through the HTML5 canvas tutorial(s). Currently on Pixel manipulation: https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Pixel_manipulation_with_canvas, and hit on a problem/issue.
The issue concerns canvas and getImageData() method. The work-around (when working with local files) seems to be to store and load the image from same directory as our HTML page. Not the most elegant solution, and I have similar issue with Google Chrome, but I am able to fix this in Chrome by launching app from Terminal and setting --args. The issue is not present in Safari, (all on OS X).
Is there a similar (or better) way of launching Firefox to allow 'file-acces-from-files' locally?
I hope this makes sense. Many thanks in anticipation.
-u


text:
Q: How to use assignin for multiple variables? I have a nested function which calls a script basicially containing some definitions of constants and strings. I need to pass these variables to the base workspace. I know I could define them as global which is supposed to be not the best solution, is it?
The conventional way, using the output arguments of the function seems to be too complicated in my case. (It's actually just a one time call, so I don't want to blow up my code) So I thought about using assignin and who but neither it does seem to work for cell arrays nor for comma separated lists. Probably I'm just missing some syntax refinements.
function myFunction()

myScriptWithDefinitions;

% who returns a cell array with all variables from my script
temp = who;
% now I try to assign these variables to my base workspace
% these are my attempts, none of them working
assignin('base',who);
assignin('base',temp{:});
assignin('base',{temp{:}});

...
end

I'm aware that I acually need to pass both, a list of names and a list of values.
any further ideas?

Edit:  something like
assignin('base',{'A','B'},{2,5})
% or
assignin('base',{'A',2},{'B',5})

does not work, so I guess assignin in general is not an option.

A: with assignin you can only assign-in 1 variable at once.
With "who" you get a cell-array of strings, that contains the names of the variables. Now if you have this list:
myVarList=who;

you can loop over and assign the variables to the workspace:
myVarList=who;

for indVar = 1:length(myVarList)
    assignin('base',myVarList{indVar},eval(myVarList{indVar}))
end

Note: this is an eval-solution... if someone knows a quick replacement for that, please let me know :)


text:
Q: Force Messages to Stay Logged in on OSX we have been using messages.app for communication in the office, but we often find that the client doesn't stay logged in.  We have it set to auto-start at user login, we have it set to login when users resume activity, but many times, users still end up logged out.  They don't realize it, and others in the office are trying to send them messages.
Is anyone aware of a way to force messages to stay logged in?

A: You could run a script every minute to update the status to available.
To do this, save the following AppleScript, I called messages-available.scpt, but your can rename if you want.
tell application "System Events"
    tell process "Messages"
        tell menu bar 1
            tell menu bar item "Messages"
                tell menu "Messages"
                    tell menu item "My Status"
                        tell menu "My Status"
                                click menu item "Available"
                            end if
                        end tell
                    end tell
                end tell
             end tell
        end tell
    end tell
end tell

Give permissions: chmod 775 messages-available.scpt.
The script do click on Available menu item in Messages.
Go to folder /Users/your-username/Library/LaunchAgents and save there the following plist file. I named it com.username.messages-available.plist, but again, feel free to change it.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key>
  <string>com.your-username.messages-available</string>

  <key>ProgramArguments</key>
  <array>
    <string>/usr/bin/osascript</string>
    <string>/Users/your-username/bin/messages-available.scpt</string>
  </array>

  <key>Nice</key>
  <integer>1</integer>

  <key>StartInterval</key>
  <integer>60</integer>

  <key>RunAtLoad</key>
  <true/>

  <key>StandardErrorPath</key>
  <string>/tmp/com.your-username.messages-available.err</string>

  <key>StandardOutPath</key>
  <string>/tmp/com.your-username.messages-available.out</string>
</dict>
</plist>

The file is pretty self-explanatory. We will launch the command /usr/bin/osascript /Users/your-username/bin/messages-available.scpt every 60 seconds, will be launched at load, will save errors on /tmp/com.username.messages-available.err and logs on /tmp/com.username.messages-available.out.
Replace your-username appropriately.
Last step, tell the Mac launchd daemon to load it.
launchctl load com.your-username.messages-available.plist

To stop the script, just replace the word load with unload in the above sentence. When your restart your computer the script will be load again. To prevent it, move it to another folder.

A: In response to jherran, instead of GUI scripting to set the status to available, the following script should work.
tell application "Messages" to log in


text:
Q: Spring Transaction failed to open on service I wanted to set @Transactional on my services instead of my DAOs... in order to open transaction and be able to use some lazy collections within my services without getting some "LazyInitializationException".
Untill now the @Transactional were on the DAOs, and transactions were opened and closed when entering in the DAOs and exiting from them.
Now, with @Transactional on my services, transactions are not even opened. So the service call the DAO with no transaction opened and we got the folowing exception: org.hibernate.SessionException: Session is closed!
We're using JPA over Hibernate, here is an extract from our configuration:
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />

<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>

<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean"/>

<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>

<tx:annotation-driven />

EDIT, thanks for your replys/comments:
So, i'm declaring the @Transactional on the whole service (implementation and not interface) and not on methods in order to be sure that the @Transactional will apply to all.
@Transactional
public class MyServiceImpl implements MyService {
  public void method1(){...}
  public void method2(){...}
}

I also give you the way my DAOs are configured, they all extend the following class:
public abstract class JpaDAOSupport {
  protected EntityManager em;
  @PersistenceContext(type = PersistenceContextType.TRANSACTION)
  public void setEm(EntityManager em) {
    this.em = em;
  }
}

EDIT2:
I simplified my application in order to have only 1 service, and 1 DAO.
MyService:
@Transactional
public class MyServiceImpl implements MyService {

  private MyDAO myDAO;

  public void setMyDAO(MyDAO myDAO) {
    this.myDAO = myDAO;
  }

  @Override
  public void method1() {
    List<String> things = myDAO.getAll();
    System.out.println("Test size: " + things.size());
  }

  @Override
  public void method2() {
    List<String> things = myDAO.getAll();
    for (String thing : things) {
      System.out.println(thing);
    }
  }
}

MyDAO
@Repository
public class MyDAOImpl extends JpaDAOSupport implements MyDAO {

  @SuppressWarnings("unchecked")
  @Override
  public List<String> getAll() {
    Query query = em.createQuery("FROM " + Cfg.class.getName());
    List<Cfg> result = query.getResultList();
    List<String> realResult = new ArrayList<String>();
    for (Cfg cfg : result) {
      realResult.add(cfg.getKey());
    }
    return realResult;
  }
}

Persistence config file:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">

  <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />

  <bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>

  <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean"/>

    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
    </bean>

    <tx:annotation-driven transaction-manager="transactionManager" />

  <bean id="my.package.dao.MyDAO" class="my.package.dao.jpa.MyDAOImpl" />

  <bean id="my.package.service.MyService" class="my.package.service.impl.MyServiceImpl" init-method="method1">
    <property name="myDAO" ref="my.package.dao.MyDAO" />
  </bean>
</beans>

Note that i don't have access to the attribute "mode" for tx:annotation-driven.
Here are the spring logs in mode DEBUG of the start up:
[...]
k.beans.factory.support.DefaultListableBeanFactory  Creating shared instance of singleton bean 'entityManagerFactory'
k.beans.factory.support.DefaultListableBeanFactory  Creating instance of bean 'entityManagerFactory'
k.beans.factory.support.DefaultListableBeanFactory  Eagerly caching bean 'entityManagerFactory' to allow for resolving potential circular references
g.springframework.beans.CachedIntrospectionResults  Getting BeanInfo for class [org.springframework.orm.jpa.LocalEntityManagerFactoryBean]
g.springframework.beans.CachedIntrospectionResults  Caching PropertyDescriptors for class [org.springframework.orm.jpa.LocalEntityManagerFactoryBean]
g.springframework.beans.CachedIntrospectionResults  Found bean property 'beanClassLoader' of type [java.lang.ClassLoader]
g.springframework.beans.CachedIntrospectionResults  Found bean property 'class' of type [java.lang.Class]
g.springframework.beans.CachedIntrospectionResults  Found bean property 'dataSource' of type [javax.sql.DataSource]
g.springframework.beans.CachedIntrospectionResults  Found bean property 'entityManagerFactoryInterface' of type [java.lang.Class]
g.springframework.beans.CachedIntrospectionResults  Found bean property 'entityManagerInterface' of type [java.lang.Class]
g.springframework.beans.CachedIntrospectionResults  Found bean property 'jpaDialect' of type [org.springframework.orm.jpa.JpaDialect]
g.springframework.beans.CachedIntrospectionResults  Found bean property 'jpaProperties' of type [java.util.Properties]
g.springframework.beans.CachedIntrospectionResults  Found bean property 'jpaPropertyMap' of type [java.util.Map]
g.springframework.beans.CachedIntrospectionResults  Found bean property 'jpaVendorAdapter' of type [org.springframework.orm.jpa.JpaVendorAdapter]
g.springframework.beans.CachedIntrospectionResults  Found bean property 'nativeEntityManagerFactory' of type [javax.persistence.EntityManagerFactory]
g.springframework.beans.CachedIntrospectionResults  Found bean property 'object' of type [javax.persistence.EntityManagerFactory]
g.springframework.beans.CachedIntrospectionResults  Found bean property 'objectType' of type [java.lang.Class]
g.springframework.beans.CachedIntrospectionResults  Found bean property 'persistenceProvider' of type [javax.persistence.spi.PersistenceProvider]
g.springframework.beans.CachedIntrospectionResults  Found bean property 'persistenceProviderClass' of type [java.lang.Class]
g.springframework.beans.CachedIntrospectionResults  Found bean property 'persistenceUnitInfo' of type [javax.persistence.spi.PersistenceUnitInfo]
g.springframework.beans.CachedIntrospectionResults  Found bean property 'persistenceUnitName' of type [java.lang.String]
g.springframework.beans.CachedIntrospectionResults  Found bean property 'singleton' of type [boolean]
k.beans.factory.support.DefaultListableBeanFactory  Invoking afterPropertiesSet() on bean with name 'entityManagerFactory'
ingframework.orm.jpa.LocalEntityManagerFactoryBean  Building JPA EntityManagerFactory for persistence unit 'null'
ework.web.context.support.XmlWebApplicationContext  Bean 'entityManagerFactory' is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
k.beans.factory.support.DefaultListableBeanFactory  Finished creating instance of bean 'entityManagerFactory'
k.beans.factory.support.DefaultListableBeanFactory  Finished creating instance of bean 'org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor#0'
k.beans.factory.support.DefaultListableBeanFactory  Creating shared instance of singleton bean 'org.springframework.aop.config.internalAutoProxyCreator'
k.beans.factory.support.DefaultListableBeanFactory  Creating instance of bean 'org.springframework.aop.config.internalAutoProxyCreator'
org.springframework.core.CollectionFactory          Creating [java.util.concurrent.ConcurrentHashMap]
k.beans.factory.support.DefaultListableBeanFactory  Eagerly caching bean 'org.springframework.aop.config.internalAutoProxyCreator' to allow for resolving potential circular references
g.springframework.beans.CachedIntrospectionResults  Getting BeanInfo for class [org.springframework.aop.framework.autoproxy.InfrastructureAdvisorAutoProxyCreator]
g.springframework.beans.CachedIntrospectionResults  Caching PropertyDescriptors for class [org.springframework.aop.framework.autoproxy.InfrastructureAdvisorAutoProxyCreator]
g.springframework.beans.CachedIntrospectionResults  Found bean property 'advisorAdapterRegistry' of type [org.springframework.aop.framework.adapter.AdvisorAdapterRegistry]
g.springframework.beans.CachedIntrospectionResults  Found bean property 'applyCommonInterceptorsFirst' of type [boolean]
g.springframework.beans.CachedIntrospectionResults  Found bean property 'beanClassLoader' of type [java.lang.ClassLoader]
g.springframework.beans.CachedIntrospectionResults  Found bean property 'beanFactory' of type [org.springframework.beans.factory.BeanFactory]
g.springframework.beans.CachedIntrospectionResults  Found bean property 'class' of type [java.lang.Class]
g.springframework.beans.CachedIntrospectionResults  Found bean property 'customTargetSourceCreators' of type [[Lorg.springframework.aop.framework.autoproxy.TargetSourceCreator;]
g.springframework.beans.CachedIntrospectionResults  Found bean property 'exposeProxy' of type [boolean]
g.springframework.beans.CachedIntrospectionResults  Found bean property 'frozen' of type [boolean]
g.springframework.beans.CachedIntrospectionResults  Found bean property 'interceptorNames' of type [[Ljava.lang.String;]
g.springframework.beans.CachedIntrospectionResults  Found bean property 'opaque' of type [boolean]
g.springframework.beans.CachedIntrospectionResults  Found bean property 'optimize' of type [boolean]
g.springframework.beans.CachedIntrospectionResults  Found bean property 'order' of type [int]
g.springframework.beans.CachedIntrospectionResults  Found bean property 'proxyClassLoader' of type [java.lang.ClassLoader]
g.springframework.beans.CachedIntrospectionResults  Found bean property 'proxyTargetClass' of type [boolean]
k.beans.factory.support.DefaultListableBeanFactory  Finished creating instance of bean 'org.springframework.aop.config.internalAutoProxyCreator'
ework.web.context.support.XmlWebApplicationContext  Unable to locate MessageSource with name 'messageSource': using default [org.springframework.context.support.DelegatingMessageSource@7d2796]
ework.web.context.support.XmlWebApplicationContext  Unable to locate ApplicationEventMulticaster with name 'applicationEventMulticaster': using default [org.springframework.context.event.SimpleApplicationEventMulticaster@1335207]
ework.ui.context.support.UiApplicationContextUtils  Unable to locate ThemeSource with name 'themeSource': using default [org.springframework.ui.context.support.ResourceBundleThemeSource@6bbe7]
k.beans.factory.support.DefaultListableBeanFactory  Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@1989b5: defining beans [org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor#0,org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor#0,entityManagerFactory,transactionManager,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,my.package.dao.MyDAO,my.package.service.MyService]; root of factory hierarchy
k.beans.factory.support.DefaultListableBeanFactory  Returning cached instance of singleton bean 'org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor#0'
k.beans.factory.support.DefaultListableBeanFactory  Returning cached instance of singleton bean 'org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor#0'
k.beans.factory.support.DefaultListableBeanFactory  Returning cached instance of singleton bean 'entityManagerFactory'
k.beans.factory.support.DefaultListableBeanFactory  Creating shared instance of singleton bean 'transactionManager'
k.beans.factory.support.DefaultListableBeanFactory  Creating instance of bean 'transactionManager'
k.beans.factory.support.DefaultListableBeanFactory  Eagerly caching bean 'transactionManager' to allow for resolving potential circular references
g.springframework.beans.CachedIntrospectionResults  Getting BeanInfo for class [org.springframework.orm.jpa.JpaTransactionManager]
g.springframework.beans.CachedIntrospectionResults  Caching PropertyDescriptors for class [org.springframework.orm.jpa.JpaTransactionManager]
g.springframework.beans.CachedIntrospectionResults  Found bean property 'class' of type [java.lang.Class]
g.springframework.beans.CachedIntrospectionResults  Found bean property 'dataSource' of type [javax.sql.DataSource]
g.springframework.beans.CachedIntrospectionResults  Found bean property 'defaultTimeout' of type [int]
g.springframework.beans.CachedIntrospectionResults  Found bean property 'entityManagerFactory' of type [javax.persistence.EntityManagerFactory]
g.springframework.beans.CachedIntrospectionResults  Found bean property 'failEarlyOnGlobalRollbackOnly' of type [boolean]
g.springframework.beans.CachedIntrospectionResults  Found bean property 'globalRollbackOnParticipationFailure' of type [boolean]
g.springframework.beans.CachedIntrospectionResults  Found bean property 'jpaDialect' of type [org.springframework.orm.jpa.JpaDialect]
g.springframework.beans.CachedIntrospectionResults  Found bean property 'jpaProperties' of type [java.util.Properties]
g.springframework.beans.CachedIntrospectionResults  Found bean property 'jpaPropertyMap' of type [java.util.Map]
g.springframework.beans.CachedIntrospectionResults  Found bean property 'nestedTransactionAllowed' of type [boolean]
g.springframework.beans.CachedIntrospectionResults  Found bean property 'resourceFactory' of type [java.lang.Object]
g.springframework.beans.CachedIntrospectionResults  Found bean property 'rollbackOnCommitFailure' of type [boolean]
g.springframework.beans.CachedIntrospectionResults  Found bean property 'transactionSynchronization' of type [int]
g.springframework.beans.CachedIntrospectionResults  Found bean property 'transactionSynchronizationName' of type [java.lang.String]
g.springframework.beans.CachedIntrospectionResults  Found bean property 'validateExistingTransaction' of type [boolean]
k.beans.factory.support.DefaultListableBeanFactory  Returning cached instance of singleton bean 'entityManagerFactory'
k.beans.factory.support.DefaultListableBeanFactory  Creating shared instance of singleton bean 'org.springframework.transaction.config.internalTransactionAdvisor'
k.beans.factory.support.DefaultListableBeanFactory  Creating instance of bean 'org.springframework.transaction.config.internalTransactionAdvisor'
rk.autoproxy.InfrastructureAdvisorAutoProxyCreator  Did not attempt to auto-proxy infrastructure class [org.springframework.transaction.interceptor.BeanFactoryTransactionAttributeSourceAdvisor]
k.beans.factory.support.DefaultListableBeanFactory  Eagerly caching bean 'org.springframework.transaction.config.internalTransactionAdvisor' to allow for resolving potential circular references
g.springframework.beans.CachedIntrospectionResults  Getting BeanInfo for class [org.springframework.transaction.interceptor.BeanFactoryTransactionAttributeSourceAdvisor]
g.springframework.beans.CachedIntrospectionResults  Caching PropertyDescriptors for class [org.springframework.transaction.interceptor.BeanFactoryTransactionAttributeSourceAdvisor]
g.springframework.beans.CachedIntrospectionResults  Found bean property 'advice' of type [org.aopalliance.aop.Advice]
g.springframework.beans.CachedIntrospectionResults  Found bean property 'adviceBeanName' of type [java.lang.String]
g.springframework.beans.CachedIntrospectionResults  Found bean property 'beanFactory' of type [org.springframework.beans.factory.BeanFactory]
g.springframework.beans.CachedIntrospectionResults  Found bean property 'class' of type [java.lang.Class]
g.springframework.beans.CachedIntrospectionResults  Found bean property 'classFilter' of type [org.springframework.aop.ClassFilter]
g.springframework.beans.CachedIntrospectionResults  Found bean property 'order' of type [int]
g.springframework.beans.CachedIntrospectionResults  Found bean property 'perInstance' of type [boolean]
g.springframework.beans.CachedIntrospectionResults  Found bean property 'pointcut' of type [org.springframework.aop.Pointcut]
g.springframework.beans.CachedIntrospectionResults  Found bean property 'transactionAttributeSource' of type [org.springframework.transaction.interceptor.TransactionAttributeSource]
k.beans.factory.support.DefaultListableBeanFactory  Creating shared instance of singleton bean 'org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0'
k.beans.factory.support.DefaultListableBeanFactory  Creating instance of bean 'org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0'
org.springframework.core.CollectionFactory          Creating [java.util.concurrent.ConcurrentHashMap]
k.beans.factory.support.DefaultListableBeanFactory  Eagerly caching bean 'org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0' to allow for resolving potential circular references
g.springframework.beans.CachedIntrospectionResults  Getting BeanInfo for class [org.springframework.transaction.annotation.AnnotationTransactionAttributeSource]
g.springframework.beans.CachedIntrospectionResults  Caching PropertyDescriptors for class [org.springframework.transaction.annotation.AnnotationTransactionAttributeSource]
g.springframework.beans.CachedIntrospectionResults  Found bean property 'class' of type [java.lang.Class]
k.beans.factory.support.DefaultListableBeanFactory  Finished creating instance of bean 'org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0'
k.beans.factory.support.DefaultListableBeanFactory  Finished creating instance of bean 'org.springframework.transaction.config.internalTransactionAdvisor'
k.beans.factory.support.DefaultListableBeanFactory  Invoking afterPropertiesSet() on bean with name 'transactionManager'
k.beans.factory.support.DefaultListableBeanFactory  Returning cached instance of singleton bean 'org.springframework.transaction.config.internalTransactionAdvisor'
k.beans.factory.support.DefaultListableBeanFactory  Finished creating instance of bean 'transactionManager'
k.beans.factory.support.DefaultListableBeanFactory  Returning cached instance of singleton bean 'org.springframework.aop.config.internalAutoProxyCreator'
k.beans.factory.support.DefaultListableBeanFactory  Returning cached instance of singleton bean 'org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0'
k.beans.factory.support.DefaultListableBeanFactory  Creating shared instance of singleton bean 'org.springframework.transaction.interceptor.TransactionInterceptor#0'
k.beans.factory.support.DefaultListableBeanFactory  Creating instance of bean 'org.springframework.transaction.interceptor.TransactionInterceptor#0'
rk.autoproxy.InfrastructureAdvisorAutoProxyCreator  Did not attempt to auto-proxy infrastructure class [org.springframework.transaction.interceptor.TransactionInterceptor]
k.beans.factory.support.DefaultListableBeanFactory  Eagerly caching bean 'org.springframework.transaction.interceptor.TransactionInterceptor#0' to allow for resolving potential circular references
g.springframework.beans.CachedIntrospectionResults  Getting BeanInfo for class [org.springframework.transaction.interceptor.TransactionInterceptor]
g.springframework.beans.CachedIntrospectionResults  Caching PropertyDescriptors for class [org.springframework.transaction.interceptor.TransactionInterceptor]
g.springframework.beans.CachedIntrospectionResults  Found bean property 'class' of type [java.lang.Class]
g.springframework.beans.CachedIntrospectionResults  Found bean property 'transactionAttributeSource' of type [org.springframework.transaction.interceptor.TransactionAttributeSource]
g.springframework.beans.CachedIntrospectionResults  Found bean property 'transactionAttributeSources' of type [[Lorg.springframework.transaction.interceptor.TransactionAttributeSource;]
g.springframework.beans.CachedIntrospectionResults  Found bean property 'transactionAttributes' of type [java.util.Properties]
g.springframework.beans.CachedIntrospectionResults  Found bean property 'transactionManager' of type [org.springframework.transaction.PlatformTransactionManager]
k.beans.factory.support.DefaultListableBeanFactory  Returning cached instance of singleton bean 'transactionManager'
k.beans.factory.support.DefaultListableBeanFactory  Returning cached instance of singleton bean 'org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0'
k.beans.factory.support.DefaultListableBeanFactory  Invoking afterPropertiesSet() on bean with name 'org.springframework.transaction.interceptor.TransactionInterceptor#0'
k.beans.factory.support.DefaultListableBeanFactory  Finished creating instance of bean 'org.springframework.transaction.interceptor.TransactionInterceptor#0'
k.beans.factory.support.DefaultListableBeanFactory  Returning cached instance of singleton bean 'org.springframework.transaction.config.internalTransactionAdvisor'
k.beans.factory.support.DefaultListableBeanFactory  Creating shared instance of singleton bean 'my.package.dao.MyDAO'
k.beans.factory.support.DefaultListableBeanFactory  Creating instance of bean 'my.package.dao.MyDAO'
g.springframework.beans.CachedIntrospectionResults  Getting BeanInfo for class [my.package.dao.jpa.JpaDAOSupport]
g.springframework.beans.CachedIntrospectionResults  Caching PropertyDescriptors for class [my.package.dao.jpa.JpaDAOSupport]
g.springframework.beans.CachedIntrospectionResults  Found bean property 'class' of type [java.lang.Class]
g.springframework.beans.CachedIntrospectionResults  Found bean property 'em' of type [javax.persistence.EntityManager]
amework.beans.factory.annotation.InjectionMetadata  Found injected method on class [my.package.dao.jpa.MyDAOImpl]: PersistenceElement for public void my.package.dao.jpa.JpaDAOSupport.setEm(javax.persistence.EntityManager)
k.beans.factory.support.DefaultListableBeanFactory  Eagerly caching bean 'my.package.dao.MyDAO' to allow for resolving potential circular references
g.springframework.beans.CachedIntrospectionResults  Getting BeanInfo for class [my.package.dao.jpa.MyDAOImpl]
g.springframework.beans.CachedIntrospectionResults  Caching PropertyDescriptors for class [my.package.dao.jpa.MyDAOImpl]
g.springframework.beans.CachedIntrospectionResults  Found bean property 'all' of type [java.util.List]
g.springframework.beans.CachedIntrospectionResults  Found bean property 'class' of type [java.lang.Class]
g.springframework.beans.CachedIntrospectionResults  Found bean property 'em' of type [javax.persistence.EntityManager]
amework.beans.factory.annotation.InjectionMetadata  Processing injected method of bean 'my.package.dao.MyDAO': PersistenceElement for public void my.package.dao.jpa.JpaDAOSupport.setEm(javax.persistence.EntityManager)
k.beans.factory.support.DefaultListableBeanFactory  Returning cached instance of singleton bean 'entityManagerFactory'
k.beans.factory.support.DefaultListableBeanFactory  Returning cached instance of singleton bean 'org.springframework.transaction.config.internalTransactionAdvisor'
org.springframework.core.CollectionFactory          Creating [java.util.concurrent.ConcurrentHashMap]
g.springframework.aop.framework.JdkDynamicAopProxy  Creating JDK dynamic proxy: target source is SingletonTargetSource for target object [my.package.dao.jpa.MyDAOImpl@1298826]
k.beans.factory.support.DefaultListableBeanFactory  Finished creating instance of bean 'my.package.dao.MyDAO'
k.beans.factory.support.DefaultListableBeanFactory  Creating shared instance of singleton bean 'my.package.service.MyService'
k.beans.factory.support.DefaultListableBeanFactory  Creating instance of bean 'my.package.service.MyService'
k.beans.factory.support.DefaultListableBeanFactory  Eagerly caching bean 'my.package.service.MyService' to allow for resolving potential circular references
g.springframework.beans.CachedIntrospectionResults  Getting BeanInfo for class [my.package.service.impl.MyServiceImpl]
g.springframework.beans.CachedIntrospectionResults  Caching PropertyDescriptors for class [my.package.service.impl.MyServiceImpl]
g.springframework.beans.CachedIntrospectionResults  Found bean property 'class' of type [java.lang.Class]
g.springframework.beans.CachedIntrospectionResults  Found bean property 'myDAO' of type [my.package.dao.MyDAO]
k.beans.factory.support.DefaultListableBeanFactory  Returning cached instance of singleton bean 'my.package.dao.MyDAO'
k.beans.factory.support.DefaultListableBeanFactory  Invoking init method  'method1' on bean with name 'my.package.service.MyService'
anagerCreator$SharedEntityManagerInvocationHandler  Creating new EntityManager for shared EntityManager invocation
.springframework.orm.jpa.EntityManagerFactoryUtils  Closing JPA EntityManager
k.beans.factory.support.DefaultListableBeanFactory  Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@1989b5: defining beans [org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor#0,org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor#0,entityManagerFactory,transactionManager,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,my.package.dao.MyDAO,my.package.service.MyService]; root of factory hierarchy
k.beans.factory.support.DefaultListableBeanFactory  Retrieved dependent beans for bean 'my.package.dao.MyDAO': [my.package.service.MyService]
k.beans.factory.support.DefaultListableBeanFactory  Retrieved dependent beans for bean 'transactionManager': [org.springframework.transaction.interceptor.TransactionInterceptor#0]
k.beans.factory.support.DefaultListableBeanFactory  Retrieved dependent beans for bean 'org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0': [org.springframework.transaction.config.internalTransactionAdvisor, org.springframework.transaction.interceptor.TransactionInterceptor#0]
k.beans.factory.support.DefaultListableBeanFactory  Retrieved dependent beans for bean 'entityManagerFactory': [transactionManager, my.package.dao.MyDAO]
mework.beans.factory.support.DisposableBeanAdapter  Invoking destroy() on bean with name 'entityManagerFactory'
ingframework.orm.jpa.LocalEntityManagerFactoryBean  Closing JPA EntityManagerFactory for persistence unit 'null'
org.springframework.web.context.ContextLoader       Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'my.package.service.MyService' defined in class path resource [config/persistenceContext.xml]: Invocation of init method failed; nested exception is org.springframework.orm.jpa.JpaSystemException: org.hibernate.SessionException: Session is closed!; nested exception is javax.persistence.PersistenceException: org.hibernate.SessionException: Session is closed!

I'd like to understand why the transactions are not opened, and how could i solve this problem ?
Thanks,

A: Sounds like it could possibly be one of:

*

*Your @Transactional annotation is on an interface, and you're using the wrong type of proxy

*Your calling the @Transactional method internally
@Transactional docs

Spring recommends that you only annotate concrete classes (and methods of concrete classes) with the @Transactional annotation, as opposed to annotating interfaces. You certainly can place the @Transactional annotation on an interface (or an interface method), but this works only as you would expect it to if you are using interface-based proxies. The fact that Java annotations are not inherited from interfaces means that if you are using class-based proxies (proxy-target-class="true") or the weaving-based aspect (mode="aspectj"), then the transaction settings are not recognized by the proxying and weaving infrastructure, and the object will not be wrapped in a transactional proxy, which would be decidedly bad.
Note
In proxy mode (which is the default), only external method calls coming in through the proxy are intercepted. This means that self-invocation, in effect, a method within the target object calling another method of the target object, will not lead to an actual transaction at runtime even if the invoked method is marked with @Transactional.

EDIT:
You should also check the docs for the LocalEntityManagerFactoryBean you're using. Based on my quick read there, it seems you're missing a property that might be needed. It also mentions some specifics about weaving, which may be playing a role here.
Spring ORM JPA LocalEntityManagerFactoryBean docs

A: Ok, in fact the problems were

*

*config problem

*transactions can't be openned on the init-method, because no (transactional) proxy is created yet.

For 1.:

    <!-- transaction manager for use with a single JPA EntityManagerFactory for transactional data access to a single datasource -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"
    p:entityManagerFactory-ref="entityManagerFactory"
/>

<!-- uses the persistence unit defined in the META-INF/persistence.xml JPA configuration file -->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
p:dataSource-ref="dataSource">
    <property name="jpaProperties">
        <props>
            <prop key="hibernate.dialect">${hibernate.dialect}</prop>
            <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
            <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
        </props>
    </property>
</bean>

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"
    p:driverClassName="${dataSource.driverClassName}"
    p:url="${dataSource.url}"
    p:username="${dataSource.username}"
    p:password="${dataSource.password}"
/>

about 2. :

*

*using a TransactionTemplate

*register an ApplicationListener and listen for ContextRefreshedEvent

A: Looks like the old proxy problem. -- Use real AspectJ weaving instead of this Spring Proxy stuff to get rid of the problem (for ever).
@see: Spring: Annotation-driven Transaction Manager

A: Apart from the above reasons, this could also be an issue with JRE version. Actually I faced the same. The application was running properly in JRE 6, but as I migrated to JRE 7, it raised this exception.
Solution : Specified Tomcat to use JRE 6 explicitly (using Eclipse) instead of JRE 7


text:
Q: Why console.log displays incorrect object's values? I don't understand why console.log displays that d1 contains [100,200,300] before I even introduced these numbers. Regular for loop displays internals of d1 correctly though. Can someone please explain this behavior/bug of console.log in Google Chrome?
https://jsfiddle.net/ZSvyt/
var container = {};
container["0"] = [10, 20, 30];
var d1 = container;

console.log('before console.log');
console.log(d1); // <--- IT DISPLAYS [100, 200, 300]. WHY?

// before for loop
console.log('before for loop');
for (var i = 0; i < d1["0"].length; i++) {
    console.log(d1["0"][i]);
}

container["0"] = [100, 200, 300];

console.log('after console.log');
console.log(d1);

// after for loop
console.log('after for loop');
for (var i = 0; i < d1["0"].length; i++) {
    console.log(d1["0"][i]);
}

Output:
before console.log
Object {
    0: Array[3]
}
0: Array[3]
0: 100
1: 200
2: 300

before for loop
10
20
30

after console.log
Object {
    0: Array[3]
}
0: Array[3]
0: 100
1: 200
2: 300

after for loop
100
200
300

A: that's because what is in the console is the reference of dt not a copy.
you can copy  the object and log it (the code from this question ).
or you can log the string that represents it using JSON.stringify.
console.log( JSON.stringify(dt) ); will print it as string.
Also if you are using lodash then you can use console.log(_.cloneDeep(dt)) to clone and log the correct values inside the object at that very moment.


text:
Q: Is it possible to use continuous aggregate on timescaledb pre-built container I am using timescale/timescaledb:latest-pg14 image for development (production is on timescale cloud) and is trying to create a continuous aggregate of a hypertable, but got the error:
ERROR:  unrecognized parameter namespace "timescaledb"
SQL state: 22023

I have seen that this feature is only available on the community edition of timescale, so I am wondering if it is possible to use this feature in the pre-built container since they did not specify which license this pre-built container is.
Note:

*

*The image_id is 068da8e48541, I pulled it around March 2022, so don't know the exact version.

*The timescale version is 2.5.2

*postgresql version is 14

A: Upgrading to timescale/timescaledb:2.6.1-pg14 fixes the issue.


text:
Q: Can I program a platform independent PLL in VHDL? Most FPGA developement boards have a 50 MHz clock source onboard. However, the FPGAs are typically able to work faster than this. For multiplying the clock speed it seems to be needed to use a custom vendor specific IP of the FPGA, that must be configured and placed in the design.
Is there a way around this? Can I program/define my own PLL in VHDL, that is preferably synthesized using the internal hard coded PLL blocks of the FPGA and works for Altera and Xilinx without having to manually insert the PLL to a project via MegaWizard & Cons?

A: You can do this by including vendor specific primitives in your code.
Both Xilinx and Altera have PLL primitives that can be instantiated in the source code with no gui.
Xilinx:
PLL2_ADV and PLL_BASE (from page 351 onward)
Altera:
altpll User guide
While the Altera AltPLL IP does have a gui (and they highly recommend you use it, due to the wide range of PLL configuration parameters they have available), you don't actually have to use the GUI. Or, you can use the GUI once and then just keep the vhdl file it generates. I tested this by removing the IP gui file (.qip) from the project and added the source only, and it synthesized fine.
In both cases, you'll need to include the libraries at the top of your code.
-- Altera
LIBRARY altera_mf;
USE altera_mf.all;

-- Xilinx
LIBRARY UNISIM;
USE UNISIM.vcomponents.all;

The biggest issue is differentiating between vendors. The --pragma directive doesn't have a way to distinguish between vendors, so you'll need to use generate statements to do so. See this answer for more info about that: what is #define equivalent in VHDL


text:
Q: Download files by links from .csv file I have .csv file which has two columns: name and http link:
name,link
IN0895,http://sample.com/images/example.jpg
IN0895,http://sample.com/images/example2.jpg
IN0872,http://sample.com/images/name.jpg
IN0872,http://sample.com/images/screen.jpg

I want create folder with name from first column and download file there (from second column). If folder already exists, just download file and put there.
How this can be done using bash, wget, curl or something else of your choice?

A: Fields in CSV file are comma separated in your example.
filename for CSV file is given at commandline when you call the script.
modify script permissions.
test it in a temp folder first so you don't clutter and have to clean up if it doesn't work.
not tested
#!/usr/bin/env bash
filename="$1"
while IFS="," read f1 f2
do
  mkdir -p "$f1";
  wget -P "$f1" "$f2"
done < "$filename"

mkdir -p checks if directory exists and makes directory if it doesn't
wget -P is Prefix (Parent folder) for folder to download to in case you are downloading more than one thing from URL.
f1 and f2 are the 2 fields in CSV file. f1 is the first field which will be the directory name and f2 is the URL.

A: I wrote something that does this in python. Keep in mind you have to install wget via pip install wget first.
import pandas as pd
import wget

#read in data
data = pd.read_csv("file.csv")

# assuming you have a column named Column1 which contains the link, iterate #through and download
for index, row in data.iterrows():
    link = wget.download(row['Column1'])

A:   <?php
  // This is the class which is use for cURL operation..
  class curl_image {
      // Here two variable $name for Rename image, $img_url take image path
      function image($name,$img_url)
      {
         // Here we define a file path where download image will save...
         $path = "E:/xampp/htdocs/beauty_code_image/";

         // Now initialize curl instance here with related method
         $ch = curl_init($img_url);
         $fp = fopen($path . $name, 'wb');
         curl_setopt($ch, CURLOPT_FILE, $fp);
         curl_setopt($ch, CURLOPT_HEADER, 0);

         // cURL excute if above information is right otherwise show error msg
         $result = curl_exec($ch);

         // print_r($result);       it just for display cURL is executed or not
         curl_close($ch);       // Close cURL here
         fclose($fp);
      }
  }

   // Initialize class object here
   $obj = new curl_image();

   // Here we check file is exist
   if(isset($_FILES['file']['name']))
   {
        // We check here data is in valid mentioned format or not
        $csvMimes = array('application/vnd.msexcel','text/plain','text/csv','text/tsv');
        if(!empty($_FILES['file']['name']) && in_array($_FILES['file']['type'],$csvMimes)){
            if(is_uploaded_file($_FILES['file']['tmp_name'])){

                 //open uploaded csv file with read only mode
                 $csvFile = fopen($_FILES['file']['tmp_name'], 'r');

                 // fetch csv file here using Php inbuild function
                 fgetcsv($csvFile);
                 while(($line = fgetcsv($csvFile)) !== FALSE){
                   // Here object fetch the method which download image & rename it with SKU name
                    $obj->image($line[0].'.jpg',$line[1]);
                  }
             }
             // Close CSV file
             fclose($csvFile);
        }
   }

    ?>

      <form action="" method="post" enctype="multipart/form-data" id="importFrm">
        <input type="file" name="file" />
      <input type="submit" class="btn btn-primary" name="importSubmit" value="IMPORT">
               </form>

`enter code here`


text:
Q: Compose many characters from text to string in C How can I compose many characters to one string so that I can reverse that string later?
I read characters with getchar() from stdin. I print it in a loop like this:
  do
  {
    character = getchar();
    printf("%c", character);
  }
 while(character != EOF)

But I have to print it reversed. How can I do that?

A: You need to store the characters in a buffer (char buffer[255] for example).


text:
Q: How to ensure that MapReduce tasks are independent of each other? I'm curious, but how does MapReduce, Hadoop, etc., break a chunk of data into independently operated tasks? I'm having a hard time imagining how that can be, considering it is common to have data that is quite interrelated, with state conditions between tasks, etc.

A: If the data IS related it is your job to ensure that the information is passed along. MapReduce breaks up the data and processes it regardless of any (not implemented) relations:
Map just reads data in blocks from the input files and passes them to the map-function one "record" at a time. Default-record is a line (but can be modified).
You can annotate the data in Map with its origin but what you can basically do with Map is: categorize the data. You emit a new key and new values and MapReduce groups by the new key. So if there are relations between different records: choose the same (or similiar *1) key for emitting them, so they are grouped together.
For Reduce the data is partitioned/sorted (that is where the grouping takes places) and afterwards the reduce-function receives all data from one group: one key and all its associated values. Now you can aggregate over the values. That's it.
So you have an over-all group-by implemented by MapReduce. Everything else is your responsibility. You want a cross product from two sources? Implement it for example by introducing artifical keys and multi-emitting (fragment and replicate join). Your imagination is the limit. And: you can always pass the data through another job.
*1: similiar, because you can influence the choice of grouping later on. normally it is group be identity-function, but you can change this.


text:
Q: Need to optimize this PHP script for "recent posts". Fatal error when post count is high The code below is resulting in an error on a site in which there are ~ 1500 posts. It performs fine when post count is nominal, however, this heavy load is exposing the weakness of the code and I'd like to optimize it.
Interestingly, when I disable this menu and instead  use the "Recent Posts" widget, the posts are drawn fine. So I'd probably do good to borrow from that code if I knew where to find it, or better yet, If I could call the widget directly in my theme, passing it a post count variable.

Fatal error: Allowed memory size of
  33554432 bytes exhausted (tried to
  allocate 16384 bytes) in
  /home1/est/public_html/mysite/wp-includes/post.php
  on line 3462

The code is below. Its purpose is to list "recent posts".
global $post;
$cat=get_cat_ID('myMenu');
$cathidePost=get_cat_ID('hidePost');
$myrecentposts = get_posts(array('post_not_in' => get_option('sticky_posts'), 'cat' => "-$cat,-$cathidePost",'showposts' => $count-of-posts));
$myrecentposts2 = get_posts(array('post_not_in' => get_option('sticky_posts'), 'cat' => "-$cat,-$cathidePost",'showposts' => -1));
$myrecentpostscount = count($myrecentposts2);

if ($myrecentpostscount > 0)
{ ?>

<?php if ($myHeading !=="") { echo $myHeading; } else { echo "Recent Posts";} ?>

    <?php
    $current_page_recent = get_post( $current_page );
    foreach($myrecentposts as  $idxrecent=>$post) {
        if($post->ID == $current_page_recent->ID)
            {
                $home_menu_recent = ' class="current_page_item';
            }
            else
            {
                $home_menu_recent = ' class="page_item';
            }
            $myclassrecent = ($idxrecent == count($myrecentposts) - 1 ? $home_menu_recent.' last"' : $home_menu_recent.'"');
        ?>
    <li<?php echo $myclassrecent ?>><a href="<?php the_permalink(); ?>"><?php the_title(); ?>

    <?php } ; if (($myrecentpostscount > $count-of-posts) && $count-of-posts > -1){ ?>
<a href="<?php bloginfo('url'); ?>/recent">View All Posts
<?php } ?>

A: Don't take this the wrong way. I'm not going to solve your memory problem at all in this answer. I will post another answer with a reason I believe you could have the mem problem The following is just a suggestion I hope you take as helpful: You have so much html jumbled in between your layout logic it is going to take you 3x as long to do figure out what is breaking and why.
Following the principles of refactoring I'm going to give one example and show how you can clean this up to the point where you can actually debug it yourself.
I'm taking this section of code to refactor a bit:
if ($myrecentpostscount > 0)
{ ?>

<?php if ($myHeading !=="") { echo $myHeading; } else `{ echo "Recent Posts";} ?></h4><ul>`

First, pull the logic out of the template display (reformat for readability at the same time:
if ($myrecentpostscount > 0)
{
    if ($myHeading !=="")
    {
        $displayHeading =  $myHeading;
    }
    else
    {
        $displayHeading =  "Recent Posts";
    }

?>

Second, replace temporary variables with function calls [$myHeading]
/**
* This function determines if a heading is null, and returns the default if it is.
*/
function getDisplayHeading($customHeading)
{
    if ($customHeading == "")
    {
        return "Recent Posts";
    }
    return $customHeading;
}

if ($myrecentpostscount > 0)
{
    ?>

    <?php echo getDisplayHeading($myHeading); ?>

Now finally, when you have all your logic at the top of the page, you can profile each function to see how much memory it uses and at which point too much memory is used in your page request. I'm going to post another answer to try to help there though, because I believe I have an idea.

A: In your code, you do the following thing:
$myrecentposts = get_posts(array('post_not_in' => get_option('sticky_posts'), 'cat' => "-$cat,-$cathidePost",'showposts' => $count-of-posts));
$myrecentposts2 = get_posts(array('post_not_in' => get_option('sticky_posts'), 'cat' => "-$cat,-$cathidePost",'showposts' => -1));
$myrecentpostscount = count($myrecentposts2);

You are actually fetching all of the posts, then counting them in code... I don't have the source of the "get_posts" function, but I would bet about 10 bucks that if you create a new function called "get_post_count" that doesn't fetch all the posts into the page, but rather does something like a "select count(*)" and gives you 1 result, you will eliminate your memory prob. If you post the body of your get_posts function we can probably help determine the easiest way to make a get_post_count function.

A: When you see the Allowed memory size of exhausted, is usually means that you have an endless loop on your hands. Check to make sure there are parameters to stop it from looping forever.


text:
Q: Copying from one sheet to another using buttons based on value I'm using microsoft excel 2013.
So i have two sheets. "Cases" and "Summarize". All of my important info is on the Cases sheet. Is there way i can be on the "Summarize" sheet, push a button and copy all the cellrows with the value "RLH" from cases over to the summarize sheet?
I've filled the entire row up to N. And i want that entire row to be copied into the summarize sheet when I push the button. The "RLH" value is on the N(last) column.
I know how to create the button and how to insert the code. I've been googling my ass of, but I cant seem to find anything that fits me.
All help is greatly appreciated.

A: Here is very simple. that will get you started
assign to Button
Option Explicit
Sub Mybutton()
    '// declare a variable
    Dim cRng As Range
    Dim rngA As Long
    Dim rngB As Long
    Dim Cols As Long
    Dim sCases As Worksheet
    Dim sSummarize As Worksheet

    '// Set the sheets name
    Set sCases = Sheets("Cases")
    Set sSummarize = Sheets("Summarize")

    '// goes through each cell in Sheets"Cases"
    '// and copes the Value "RLH" to Sheets"Summarize"
    '// it starts from last row in column A & looks up
    rngA = sCases.Cells(Rows.Count, "N").End(xlUp).Row
    Cols = sCases.UsedRange.Columns.Count
    For Each cRng In sCases.Range("A2:A" & rngA)
        If cRng.Value = "RLH" Then '<<<<<<<<< Value = "RLT"
            rngB = sSummarize.Cells(Rows.Count, "A").End(xlUp).Row + 1
            sSummarize.Range("A" & rngB).Resize(1, Cols) = cRng.Resize(1, Cols).Value
        End If
    '// loop
    Next cRng

    Set sSummarize = Nothing
    Set sCases = Nothing
End Sub

hope this helps
you may also find help full on the following link  MSDN Getting Started with VBA.


text:
Q: Is the response "I am fine, thank you. And you?" outdated? This is what I learned from the middle school English class 10 years ago as the correct way to respond to "How are you?". The textbook was co-published by Longman, I suppose it was British English. When I go abroad I find few people say this.
Is this saying old fashioned or outdated?

A: Strangely, this phrase is in great use but most of the users are new to English. This particular response will almost immediately flag you as learning the language and people will very likely tone down their vocabulary and talking speed in an attempt to make things easier for you. It has the same vibe as, "My name is Matthew. What is your name?" or asking a child, "How old are you? Are you five?"
If you want a more commonplace phrase I think both HaL and snumpy have good suggestions.

A: I am fine, thank you. And you? is still used, but I consider it to be overly formal. It could also be considered very polite, however, and I would probably use a phrase similar to this as a response when being introduced to someone older than me, like a friend's parent or grandparent, for instance.
In the US, the short version of this phrase is a common response, especially with people you already know or see often: Fine, thanks. You?

A: While it is a perfectly acceptable answer in both the US and Britain, it is rarely used nowadays.  Responses vary wildly depending on where you are and to whom you are speaking (race and age and environment (rural/suburban/urban) all seem to have an effect on the exact rendition of this basic greeting).
I believe the most standard response would be:

Fine, thanks. And you?

Though my generation typically entertains the following salutation:

Sup? (or Whassup?)
  Not much. You?
  Not much.

A: As for many expressions, words, idioms, etc regarding a language, it's also a metter of context and situation.
If you talk to your friends you can even end up saying "Hey, sup?" but with someone you must give respect to, you are much more likely to use the expression you mentioned.
This is not the only thing to consider but I wanted to emphasize it.

A: Actually no one ever says "Fine, thanks and you" in America. Everyone one always says "I'm good." I find it funny that the Spanish teachers in the school I work at teach "fine thanks and you."


text:
Q: Работа с AF_UNIX SOCK_DGRAM SO_BROADCAST сокетом Здравствуйте, пишу чатик, начал с параллельного эхо-сервера.
Теперь пытаюсь сделать так, чтобы сообщения от одного подключенного клиента рассылались всем подключенным клиентам.
В процессе-родителе создаю сокет в файловом пространстве, и делаю его широковещательным:
  int commfd;
  struct sockaddr commaddr;

  if( ( commfd = socket( AF_UNIX, SOCK_DGRAM, 0 ) ) < 0 )
    perror( "error in common socket" );

  bzero( &commaddr, sizeof( commaddr ) );
  commaddr.sa_family = AF_UNIX;
  strcpy( commaddr.sa_data, COMM_SOCK_NAME );

  if( bind( commfd, &commaddr, sizeof( commaddr ) ) < 0 )
    perror( "error in bind for commfd" );

  int n=1;
  if( setsockopt( commfd, SOL_SOCKET, SO_BROADCAST, &n, sizeof(n) ) < 0 )
    perror( "error in setsockopt" );

И в дочернем процессе-обработчике клиента подключаюсь к этому сокету, и через select жду, пока сокет этот будет доступен на чтение.
В общем суть задумки: клиент пишет сообщение серверу (а на сервере для этого клиента свой процесс-обработчик), это сообщение отсылается назад этому же клиенту, и это же сообщение пишется в широковещательный сокет. В это же время процессы - обработчики других клиентов ждут того самого сообщения, принимают, и выводят на экран.
Но не срабатывает select в обработчике, что я не так делаю?
Весь код сервера здесь: http://paste.ubuntu.com/7617694/
A: UNIX-cокеты не поддерживают широковещательную передачу. Приём-передача широковещательных udp-пакетов осуществляется с использованием (кроме опции SO_BROADCAST) широковещательных адресов, которые не предусмотрены в AF_UNIX. Так же невозможно забиндить более одного сокета на один AF_UNIX-адрес, что потребовалось бы для приёма.


text:
Q: Wordpress functions not working outside of root wordpress directory Not quite sure why this is happening, hopefully someone can help. I have a wordpress installation, lets say for arguments sake it's installed to http://www.example.com/wordpress. I have a file called test.php with the following code:
<?php
include '/php_path_to_blog/wp-blog-header.php';
echo get_current_user_id();
?>

Now the odd part is if i have a user logged in and place this file within my wordpress directory and call it by going to http://www.example.com/wordpress/test.php it outputs the correct user id of the current logged in user. However if I move the file to the root directory of the site and call it by going to http://www.example.com/test.php, it outputs 0 as if there were no user logged in.
It seems that some functions work properly outside of the installation directory and some don't.
Any help would be greatly appreciated.

A: Please declare varaibale global $wpdb; I think this will work.
<?php
global $wpdb;
include '/php_path_to_blog/wp-blog-header.php';
echo get_current_user_id();
?>

A: Three problems:

*

*You're using include, not require. See WP Codex for instructions and examples on doing this right.

*Function method/name are incorrect. Function Reference/get currentuserinfo - Wordpress Codex

*Trying to do the echo within the include. See first link for proper examples of site integration.


text:
Q: splitting list with equal contents for example I have the following list:
contents= ["i have two pens","prices = 5$","made in ____ and ____"]

I want to split them such a way that it has the same content as following:
array[0]= ["i", "have", "two", "pens", ""]
array[1]= ["prices", "=", "5$", " ", " "]
array[2]= ["made", "in", "____", "and" ,"____"]

that means, each array has equal number of contents (5 here). The code I am using is:
array = [phrase.split() for phrase in contents]

but surely, it doesn't split them with equal contents. Can anyone suggest me how can I solve this using python?

A: You would need to check which is the longest array and then pad the other ones, like this:
array = [phrase.split() for phrase in contents]
x = max(len(i) for i in array)
result = [i + [''] * (x - len(i)) for i in array]

Complicated but gives you the result you're looking for.

A: This is another choice, May be also complicated.
from itertools import izip_longest

array = [phrase.split() for phrase in contents]
l = izip_longest(*array, fillvalue=u'')
result = [list(t) for t in zip(*l)]

A: A quick demo to expand on my comment, using izip_longest from itertools:
>>> from itertools import izip_longest
>>> contents = ["i have two pens",
                "prices = 5$",
                "made in ____ and ____"]
>>> array = [phrase.split() for phrase in contents]
>>> for t in izip_longest(*array, fillvalue=" "):
        print t

('i', 'prices', 'made')
('have', '=', 'in')
('two', '5$', '____')
('pens', ' ', 'and')
(' ', ' ', '____')

You don't need to modify array, this pads for you as you iterate over the sublists.


text:
Q: Electron building issue for server along with the front end I have an electron app that has the folder structure -

Public -> index.html, main.js
Server -> server.js
src -> (all the front end app styling and components)

The server runs on localhost:3001 and listens to Post and Get commands from the front end that submits requests to the localhost:3001/exampleReq
This is my package.json for the root
 {
  "name": "test",
  "version": "1.0.0",
  "private": true,
  "proxy": "http://localhost:3001",
  "dependencies": {
    "@electron/remote": "^1.0.2",
    "@reduxjs/toolkit": "^1.6.1",
    "@testing-library/jest-dom": "^5.11.4",
    "@testing-library/react": "^11.1.0",
    "@testing-library/user-event": "^12.1.10",
    "@types/jest": "^24.9.1",
    "@types/node": "^12.12.37",
    "@types/react": "^16.9.34",
    "@types/react-dom": "^16.9.7",
    "@types/react-table": "^7.0.16",
    "@types/styled-components": "^5.1.0",
    "@types/yup": "^0.28.0",
    "antd": "4.17.0-alpha.0",
    "body-parser": "^1.19.0",
    "bootstrap": "^5.0.0-beta1",
    "electron-is-dev": "^1.2.0",
    "immutability-helper": "^3.1.1",
    "react": "^17.0.1",
    "react-beautiful-dnd": "^13.1.0",
    "react-dnd": "latest",
    "react-dnd-html5-backend": "latest",
    "react-dom": "^17.0.1",
    "react-filetree-electron": "^1.2.2",
    "react-highlight-words": "^0.17.0",
    "react-redux": "^7.2.5",
    "react-scripts": "4.0.1",
    "react-virtualized-auto-sizer": "^1.0.6",
    "react-window": "^1.8.6",
    "styled-components": "^5.1.0",
    "typescript": "^4.4.3",
    "web-vitals": "^0.2.4"
  },
  "main": "public/main.js",
  "homepage": "./",
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "electron:serve": "concurrently -k \"cross-env BROWSER=none yarn start\" \"yarn electron:start\" \"cd server && yarn start server\"",
    "electron:build": "yarn build && electron-builder -c.extraMetadata.main=build/main.js",
    "electron:start": "wait-on tcp:3000 && electron ."
  },
  "build": {
    "extends": null,
    "appId": "com.example.electron-cra",
    "files": [
      "dist/**/*",
      "build/**/*",
      "node_modules/**/*",
      "package.json"
    ],
    "directories": {
      "buildResources": "assets"
    }
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "concurrently": "^5.3.0",
    "cross-env": "^7.0.3",
    "electron": "^11.2.1",
    "electron-builder": "^22.9.1",
    "prettier": "^2.2.1",
    "wait-on": "^5.2.1"
  },
  "workspaces": [
    "src/Auto"
  ]
}

When I run yarn electron:serve everything works and both the app and server run.
When I do yarn electron:build the front end stuff gets compiled but not the server. I don't believe the server is being linked at all.
This is the package.json for the server folder:
{
  "name": "server",
  "version": "1.0.0",
  "main": "server.js",
  "license": "MIT",
  "scripts": {
    "start": "nodemon server.js"
  },
  "type": "commonjs",
  "dependencies": {
    "cors": "^2.8.5",
    "express": "^4.17.1",
    "mongoose": "^6.0.7",
    "nodemon": "^2.0.13"
  }
}

Any ideas on how to fix the build part so that I can have an .exe or .dmg where once opened everything works the same as when running electron:serve?
Here's how electron:serve links the server
 "electron:serve": "concurrently -k \"cross-env BROWSER=none yarn start\" \"yarn electron:start\" \"cd server && yarn start server\""

A: Temporary solution to this would be to bring all the server code inside public. I guess this is an answer but would like to keep the folders separate if possible.


text:
Q: UnsatisfiedDependencyException and Circular Dependency I am trying to make some Spring Boot legacy code build and run, but it fails with:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'dataLoader' defined in file [......\bootstrap\DataLoader.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'organizationServiceImpl': Unsatisfied dependency expressed through method 'setAssessmentService' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'assessmentServiceImpl': Invocation of init method failed; nested exception is org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet

......

    at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'organizationServiceImpl': Unsatisfied dependency expressed through method 'setAssessmentService' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'assessmentServiceImpl': Invocation of init method failed; nested exception is org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:676)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:374)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1411)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:592)
    at ........
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'assessmentServiceImpl': Invocation of init method failed; nested exception is org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet
    at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:139)

DataLoader class is:
@Component
public class DataLoader implements ApplicationRunner {

    private final OrganizationService organizationService;

    private List<String> organizationNames = Arrays.asList(
        ...some long list of string literals...

    );

    public DataLoader(OrganizationService organizationService) {
        this.organizationService = organizationService;
    }

    @Override
    public void run(ApplicationArguments args) {
        if (CollectionUtils.isEmpty(organizationService.findAll())) {
            addOrganizations();
        }
    }

    private void addOrganizations() {
        organizationNames.forEach(name -> {
            OrganizationRequest organization = new OrganizationRequest();
            organization.setName(name);
            if (
            ....irrelevant code....
            }
            organizationService.save(organization);
        });
    }

}

and OrganizationServiceImpl class is:
@Service
public class OrganizationServiceImpl implements OrganizationService {

    private final OrganizationRepository organizationRepository;
    private final AddressService addressService;
    private final ContactService contactService;
    private final SupplierQualifierService supplierQualifierService;
    private final MonitoringScopeService monitoringScopeService;
    private final FinancialService financialsService;

    private DocumentService documentService;
    private AssessmentService assessmentService;

    @Getter
    private Map<Long, Set<QuestionType>> questionTypesForAssessmentByOrganization = new HashMap<>();

    public OrganizationServiceImpl(OrganizationRepository organizationRepository, AddressService addressService, ContactService contactService, SupplierQualifierService supplierQualifierService, MonitoringScopeService monitoringScopeService, FinancialService financialsService ) {
        this.organizationRepository = organizationRepository;
        this.addressService = addressService;
        this.contactService = contactService;
        this.supplierQualifierService = supplierQualifierService;
        this.monitoringScopeService = monitoringScopeService;
        this.financialsService = financialsService;
    }

    //workaround for circular dependency
    @Autowired
    public void setAssessmentService(AssessmentService assessmentService) {
        this.assessmentService = assessmentService;
    }

    // to prevent circular dependency problem ...
    @Autowired
    public void setDocumentService(DocumentService documentService) {
        this.documentService = documentService;
    }

    @Override
    public Organization findById(Long id) {
        Optional<Organization> organization = organizationRepository.findById(id);
        return organization.orElse(new Organization());
    }

    @Override
    public List<Organization> findAll() {
        return organizationRepository.findAll();
    }

    @Override
    public Organization save(OrganizationRequest request) {
    ....long not relevant code...

        return savedOrganization;
    }

    ....long not relevant code, some business logic...

}

AssessmentServiceImpl class is:
@Service
public class AssessmentServiceImpl implements AssessmentService {

private final AssessmentRepository assessmentRepository;
private final OrganizationService organizationService;
private final AnswerService answerService;
private final QuestionService questionService;

private Map<QuestionType, Integer> numberOfQuestionsByType = new HashMap<>();

public AssessmentServiceImpl(AssessmentRepository assessmentRepository, OrganizationService organizationService, AnswerService answerService, QuestionService questionService) {
    this.assessmentRepository = assessmentRepository;
    this.organizationService = organizationService;
    this.answerService = answerService;
    this.questionService = questionService;
}

@PostConstruct
public void postConstruct() {
    for (QuestionType type : QuestionType.values()) {
        numberOfQuestionsByType.put(type, questionService.findByQuestionType(type).size());
    }
}

... some business logic code....

}
Chain of failed dependency injection is:
Error creating bean with name 'dataLoader':
Error creating bean with name 'organizationServiceImpl':
Error creating bean with name 'assessmentServiceImpl':

But I don't see direct cause for it.
I see that original developer ran into cyclic dependency issues, but from what I Googled it seems this should be appropriate solution:
//workaround for circular dependency
@Autowired
public void setAssessmentService(AssessmentService assessmentService) {
   this.assessmentService = assessmentService;
}

// to prevent circular dependency problem ...
@Autowired
public void setDocumentService(DocumentService documentService) {
    this.documentService = documentService;
}

A: The error-message states that when creating the bean it has troubles with your datasource:
InvalidDataAccessResourceUsageException: could not extract ResultSet
I suspect a problem when reading the database. There is no circular dependency issue. It is a perfect bean-creation chain. Spring detects a circular dependency and shows a diffrent error message.
Try to uncomment the code in the @PostConstruct and run the application again.
@PostConstruct
public void postConstruct() {
    for (QuestionType type : QuestionType.values()) {
        numberOfQuestionsByType.put(type,
           questionService.findByQuestionType(type).size());
    }
}

A: The stacktrace is pretty straight forward , your bean creation of AssessmentService in AssessmentServiceImpl is failing because of sql SQLGrammarException:
nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet

which means that hibernate is having issues executing the query that you provided in your bean post construct.
Most probably this code : questionService.findByQuestionType(type).size() is causing the issue for you during bean creation. Analyse the logs more to confirm or share the full logs.
Check the Entity class to ensure everything is mapped correctly and all the annotations are provided correctly. Try enabling the  hibernate logs for more detailed log for analysis.

A: The problem is, you are trying to fetch some response from the DB, into a resultset. The query does not return the entire object, instead only a part of the object or combination of two or more classes. Your hibernate class does not have the matching constructor, thus it is unable to initialize your object.

A: Thank for all the comments, it brought me back to the right track.
Problem was in hibernate settings:
hibernate:
  ddl-auto: none

so I changed it to:
hibernate:
  ddl-auto: create

and it works now.


text:
Q: Does prunsrv.exe use multiple threads to run a Java application as a service? Configured a jvm mode Java Windows service following this tutorial: (https://joerglenhard.wordpress.com/2012/05/29/build-windows-service-from-java-application-with-procrun/). I am printing log messages by thread ID to a file in the start and stop methods as follows:
 private static boolean stop = false;
    public static void main( String[] args )
    {
    log.debug(Integer.toHexString(System.identityHashCode(Thread.currentThread())));
    if (args.length == 0) {
        log.debug("no args provided, give start/stop as argument");
        return;
    }
    String mode = args[0];
    if ("start".equals(mode)) {
        log.debug("start " + Integer.toHexString(System.identityHashCode(Thread.currentThread())));
        startService(args);
    } else if ("stop".equals(mode)) {
        log.debug("stop " + Integer.toHexString(System.identityHashCode(Thread.currentThread())));
        stopService(args);
    }
    log.debug("End of main " + Integer.toHexString(System.identityHashCode(Thread.currentThread())));
    }

This is the log output showing the services starting and stopping:
22/Aug/2016 19:22:00,962- App: 441772e
22/Aug/2016 19:22:00,962- App: start 441772e
22/Aug/2016 19:22:00,962- App: startService
22/Aug/2016 19:23:21,259- App: 1ef37254
22/Aug/2016 19:23:21,259- App: stop 1ef37254
22/Aug/2016 19:23:21,259- App: stopService
22/Aug/2016 19:23:21,259- App: End of main 1ef37254
22/Aug/2016 19:23:22,181- App: End of main 441772e

The threads IDs appear in the log file which indicates that a new process is started for start service and stop service. Even though the variable stop is a private static boolean the log file shows that the service are different process (Right?). So, why are multiple Windows processes being created to start and stop my service?

A: I dont know.... Maybe, prunsrv called main function with option start in new thread ("thread1" for example), and listened in the next command. When you stop service, prunsrv called main function with option stop in new thread ("thread2" for example). prunsrv, thread1 and thread2 have common memory.


text:
Q: 18.04 - Wifi Hotspot does not come up after reboot I had a working WiFi Hotspot config, but after reboot it doesn't come up.
Syslog tells me : https://pastebin.com/Te4ik2Yq
looks like the "Problem" is here:
Jul 23 08:51:37 testmachine01 NetworkManager[6346]: <info>  [1532335897.7097] dnsmasq-manager: starting dnsmasq...
Jul 23 08:51:37 testmachine01 NetworkManager[6346]: <info>  [1532335897.7121] device (wlp1s0): state change: ip-config -> ip-check (reason 'none', sys-iface-state: 'managed')
Jul 23 08:51:37 testmachine01 NetworkManager[6346]: dnsmasq: failed to create listening socket for 172.30.108.1: Address already in use
Jul 23 08:51:37 testmachine01 dnsmasq[7090]: failed to create listening socket for 172.30.108.1: Address already in use
Jul 23 08:51:37 testmachine01 dnsmasq[7090]: FAILED to start up
Jul 23 08:51:37 testmachine01 NetworkManager[6346]: <warn>  [1532335897.7131] dnsmasq-manager: dnsmasq exited with error: Network access problem (address in use, permissions) (2)
Jul 23 08:51:37 testmachine01 NetworkManager[6346]: <info>  [1532335897.7131] device (wlp1s0): state change: ip-check -> failed (reason 'ip-config-unavailable', sys-iface-state: 'managed')
Jul 23 08:51:37 testmachine01 NetworkManager[6346]: <warn>  [1532335897.7137] device (wlp1s0): Activation: failed for connection 'HotSpot'
Jul 23 08:51:37 testmachine01 NetworkManager[6346]: <info>  [1532335897.7144] device (wlp1s0): state change: failed -> disconnected (reason 'none', sys-iface-state: 'managed')

I don't have specifically dnsmasq installed, "just" using NetworkManager
Any help is highly appreciated

A: A Wifi hotspot use the same device than you use it to go on internet with this computer; this network card have 2 mode :

*

*receiver mode (default); this mode is compulsory if you want to download updates

*transmitter mode (case of the hotspot)
I pretty sure you can't start your hotspot because Ubuntu is downloading updates or something like that, so the network card is already used. The fact you said this issue occured after a reboot increased the chance of automatic updates download.
Solution : You just have to wait a little so this operation can finish, and then, you will be able to start your Wifi hotspot


text:
Q: React How do I extract data from a form when triggering onSubmit event? I am messing around with Riot's API that allows getting information of a player by the player's name. I am trying to get an API key (I only got a 24 hour key) and the target player's name from users' input.
export function PlayerSearch() {
    function handlesubmit(e) {
      console.log(e.target);
      e.preventDefault();
    }

    return (

    <form onSubmit={handlesubmit} method='GET' autoComplete="off">

        Your API key:
        <input
          placeholder='Your API key'
          onFocus={(e)=>{e.target.placeholder=''}}
          type="text"
          id="key"
          name="key" />

        Player name:
        <input
          placeholder='Player name'
          onFocus={(e)=>{e.target.placeholder=''}}
          type="text"
          id="name"
          name="name" />

        <input type='submit' />

    </form>

    );
}

And I got this in the console:

So how exactly do I extract the two inputs from the form?
In addition, is it possible that I can call another component and pass data as props to handle the submitted data so that the code is cleaner?

A: You should have a state to store your inputs:
const [formData, setFormData] = useState({ key: "", name: "" });

Then you need a function that gets called onChange of your input fields to update your state:
const onChange = (event) => {
    setFormData({ ...formData, [event.target.name]: event.target.value });
};

And you need to pass that function to your input onChange property:
<input
    placeholder="Your API key"
    onFocus={(e) => {
      e.target.placeholder = "";
    }}
    type="text"
    name="key"
    value={formData.key}
    onChange={onChange}
/>

Then you can access the state in your handleSubmit:
function handlesubmit(e) {
    console.log(formData);
    e.preventDefault();
}


text:
Q: Cassandra with SSTable Attached Secondary Index vs relational database I am new to nosql database such as Cassandra, and currently I saw this secondary index and sstable attached secondary index. Some how I am confused about the purpose to use secondary index in Cassandra, what's the difference between relational database and Cassandra with secondary index ? Which one has better performance when being queried ?

A: In Cassandra :
You should use SASI if:

*

*you need multi criteria search and you don't need ordering/grouping/scoring

*you mostly need 100 to 1000 of rows for your search queries

*you always know the partition keys of the rows to be searched for (this one applies to native secondary index too)

*you want to index static columns (SASI has no penalty since it indexes the whole partition)

You should avoid SASI if:

*

*you have very wide partitions to index, SASI only give the partition offset. The expensive linear scanning is still performed on Cassandra side, without the help of clustering column index for skipping blocks

*you have strong SLA on search latency, for example sub-second requirement

*you need search for analytics scenarios (SASI is not the right fit to fetch half of your table) unless you use SASI with co-located Apache Spark but even in this case, search engines win with 2 orders of magnitude for latency
ordering of the search results is important for you

If you decide to try SASI in production, please keep in mind that SASI does impact your write/flush throughput, compaction throughput as well as repair and streaming operations. It is quite expected because SASI index files follow SSTable life-cycle.
Source : http://www.doanduyhai.com/blog/?p=2058
In RDBMS : There is no restriction like this. you can order your result, perform aggregation and grouping.


text:
Q: How to add onClick event in Javascript variable I am having trouble with adding a onClick event within JavaScript variable. Not sure how the syntax should be written. Thanks for any help.
var jumpTo = 'https://google.com/ onClick="_gaq.push(['_trackEvent', 'link', 'Clicked',]);"'

A: try to escape the single quotes
var jumpTo = 'https://google.com/ onClick="_gaq.push([\'_trackEvent\', \'link\', \'Clicked\']);"'

lg
fastrde

A: i think this is what you're trying to achive:
html:
<input type="button" value="Click me" onclick="btn_click()" />

javascript:
function btn_click() {
    var url = 'https://google.com';
    _gaq.push(['_trackEvent', url, 'Clicked']);
    window.location.href = url;
}

hope that helps.