text:
Q: How can I set up exim to use my ISP's SMTP server (on a non-Debian system)? I want to use exim to send emails via my ISP's SMTP server. However, the Arch wiki is quite confusing (exim is much simpler on a Debian system). I followed instructions in the final section, modifying the SMTP address from mail.internode.on.net to my SMTP server, and modifying *@* $1@bullet.homenet.org Ffr to *@* $1@my_emaildomain.com Ffr. This worked when I was connected to the internet via my ISP.
However, to use this on my work network, I need to authenticate. I tried to follow the instructions listed for Gmail, while changing the url, but this failed with
authenticator iinet_route: cannot find authenticator driver "manualroute"

How can I set up exim for authentication? (FWIW I'm with iinet.)
EDIT
I realised I had been putting the "Gmail"-like settings in the wrong parts. I moved them around, and am no longer getting the error messages. However, exim now fails silently. I get no error message, but no mail is delivered.
Here are the changes I made to the factory default:
--- exim.conf.factory_default   2015-08-03 02:14:31.000000000 +1000
+++ exim.conf   2015-11-10 08:09:54.196287461 +1100
@@ -402,7 +402,7 @@

   # Deny unless the sender address can be verified.

-  require verify        = sender
+  #require verify        = sender

   # Accept if the message comes from one of the hosts for which we are an
   # outgoing relay. It is assumed that such hosts are most likely to be MUAs,
@@ -552,14 +552,19 @@
 # If the DNS lookup fails, no further routers are tried because of the no_more
 # setting, and consequently the address is unrouteable.

-dnslookup:
-  driver = dnslookup
-  domains = ! +local_domains
-  transport = remote_smtp
-  ignore_target_hosts = 0.0.0.0 : 127.0.0.0/8
+#dnslookup:
+#  driver = dnslookup
+#  domains = ! +local_domains
+#  transport = remote_smtp
+#  ignore_target_hosts = 0.0.0.0 : 127.0.0.0/8
 # if ipv6-enabled then instead use:
 # ignore_target_hosts = <; 0.0.0.0 ; 127.0.0.0/8 ; ::1
-  no_more
+#  no_more
+
+iinet_route:
+  driver = manualroute
+  transport = iinet_relay
+  route_list = * mail.iinet.net.au

 # This alternative router can be used when you want to send all mail to a
@@ -735,6 +746,12 @@
 address_reply:
   driver = autoreply

+iinet_relay:
+  driver = smtp
+  port = 587
+  hosts_require_auth = <; $host_address
+  hosts_require_tls = <; $host_address
+

 ######################################################################
@@ -769,6 +786,7 @@
 # There are no rewriting specifications in this default configuration file.

 begin rewrite
+*@* test_exim_sender@mydomain.foo.com Ffr

@@ -821,6 +839,12 @@
 #  server_advertise_condition = ${if def:tls_in_cipher }

+iinet_login:
+  driver = plaintext
+  public_name = LOGIN
+  hide client_send = : smtp_account@iinet.net.au : PASSWORD_HERE
+
+
 ######################################################################
 #                   CONFIGURATION FOR local_scan()                   #
 ######################################################################

And here is my full configuration file.
EDIT 2
I also tried changing the port to 465, which also fails silently. (FWIW 587 works fine in msmtp.)
EDIT 3
Here is the information on a failed email, using exim -Mvl. The original attempt to send used echo body | /usr/bin/mail -s subject -r sender@mydomain.foo.com recipient@mydomain.foo.com
2015-11-10 11:53:39 Received from test_exim_sender@mydomain.foo.com U=sparhawk P=local S=428 id=20151110005339.ag4kfrHaJ%sender@mydomain.foo.com
2015-11-10 11:53:41 recipient@mydomain.foo.com R=iinet_route T=iinet_relay defer (-42): authentication required but authentication attempt(s) failed

EDIT 4
I ran the mail command again (as per edit 3), and got a slightly different error. I've also linked to the full output of exim -d+all -M messageID <ID>
$ sudo exim -Mvl 1ZwMHr-0008I4-92
2015-11-11 14:41:31 Received from eximsender@mydomain.foo.com U=lee P=local S=426 id=20151111034131.VRuQn__aN%sender@mydomain.foo.com
2015-11-11 14:41:31 recipient@mydomain.foo.com R=iinet_route T=iinet_relay defer (-53): retry time not reached for any host

Full debug output is here.

A: According to the error you get, you have put the stanzas from the gmail example in the wiki in the wrong sections. The exim config is built up in distinct parts, in order:

*

*maincontains global definitions and settings

*acl

*routershow to handle an address; first hit is used so order is important

*transportsdefines ways to disposing of a message, these are referenced from the routers above; order is not important

*retryhow often to retry delivery

*rewritechanging addresses e.g. to map internal addresses to globally usable addresses

*authenticatorsdefines ways of authenticating; both as server and as client

The error message authenticator iinet_route: cannot find authenticator driver "manualroute" clearly indicates that you have put a router stanza in the authenticators section.
Put each stanza in the relevant section (i.e. the router definition after the line begin routers and before the line begin transports, taking order into account; etc.) and the error should go away.


text:
Q: Command for running integration test in flavored app I do not know what will be the command for running integration test in flavored app.
I have used flutter test --flavor app1 integration_test/test.dart but it can't load the asset image provided in the login page. And thats why it shows Some tests failed in the console. Can anyone suggest a solution?
This is my pubspec.yaml
dev_dependencies:
 flutter_test:
  sdk: flutter
 integration_test:

redpajama_set_name: RedPajamaStackExchange


text:
Q: ghci :info and haddock on type synonyms I have a type synonym like
type Events t b = Tb.T t b

The underlying type Tb.T is an instance of many typeclasses, e.g.
instance [safe] (Eq time, Eq body) => Eq (Tb.T time body)
instance [safe] Functor (Tb.T time)
..

My type synonym (of course) inherits all these instances. E.g. it is also a Functor:
λ> :t flip fmap (undefined :: Events Int String)
flip fmap (undefined :: Events Int String)
  :: (String -> b) -> Tb.T Int b

but this fact is not shown in ghci's :info command nor in the generated haddock documentation. Also, I'd rather see the return type as Events Int b instead of Tb.T Int b.
Is there a way to circumvent this?


text:
Q: how to integration test nodeJS mongo As part of setting up our continuous integration cycle we are defining standard templates for unit and integration test for our mean applications.
One basic test is to verify some settings in a mongo collection (name Setting)
We are using Mocha, Should, Require and super test
I've defined the following test

var request = require('supertest');
  describe('configuration',function(){
before(function(done) {
    // In our tests we use the test db
    mongoose.connect(config.db);
    done();
});
describe('required configuration ',function(){
     it('should return Settings Object',function(done){
        mongoose.Setting.findOne({key:'ABC'}, function(foundSetting){
            foundSetting.value.should.equal('XYZ');
            done();
        });
    })

});

})

which always errors with 'TypeError: Cannot call method 'findOne' of undefined'
can anyone point me in the right direction how to use integration test on mongo objects (also e.g. checking a collection count

A: Considering Setting is a mongoose model you would have this at the end of the model file
setting.js

...
module.exports = mongoose.model('Setting', settingSchema)

And I think if you require this model in your test file like this
test.js

var Setting = require('./setting')

Then you could call Setting.findOne instead of mongoose.Setting.findOne inside the actual test case and it should work fine. Also you should make sure you have successfully connected to your test database before you do this. It is a good practice to clean the tested collection in a before hook
before(function(done) {
    // Connect to database here

    Setting.remove({}, function(err) {
        if (err)
            throw err
        else
            done()
    })
})

and do the same thing afterEach test case.
I don't see where and how you use supertest in your snippet but I believe it is the right tool. Again, in your before hook you could first call request = request(require('./app')) where app.js exports your express application. Moreover, you could move the code that connects to the database to your app.js, which feels more environment-independent.

A: Before writing unit and integration test, you should install required libraries

*

*Install mocha framework globally
sudo npm install -g mocha

*Install chai assertion library and HTTP plug-in
npm install chai
npm install chai-http

*Add mocha command to your package.json file
"scripts": {
  "test": "mocha",
  "start": "nodemon app.js"
 }

Usage of mocha framework and chai assertion library can be seen in code below
const chai = require('chai');
const chaiHttp = require('chai-http');

chai.should();

chai.use(chaiHttp);

describe("Integration Test Case 1",() => {
it("Sign Up-In", () => {

    // Sign Up
    chai.request("localhost:5000/api/users")
        .post("/signup")
        .send(createdUser)
        .end(async (error, response) => {
            await response.should.have.status(201);

            // Sign In
            chai.request("localhost:5000/api/users")
                .get("/signin")
                .send(userCredential)
                .end(async (error, response) => {
                    await response.should.have.status(202);
}};


text:
Q: I used " time.sleep", But twitter(tweepy) crawling error 429_python twitter crawling _ python.
I used a " time.sleep ", but I get an error.
tweepy.error.TweepError: Twitter error response: status code = 429
What should I do?
import tweepy
import time
import os

search_term = 'word1'
search_term2= 'word2'
search_term3='word3'

lat = "37.6"
lon = "127.0"
radius = "100km"

API_key = "44"
API_secret = "33"
Access_token = "22"
Access_token_secret = "11"

location = "%s,%s,%s" % (lat, lon, radius)

auth = tweepy.OAuthHandler(API_key, API_secret)
auth.set_access_token(Access_token, Access_token_secret)

api = tweepy.API(auth)

c=tweepy.Cursor(api.search,
                q="{}+OR+{}".format(search_term, search_term2, search_term3),
                rpp=1000,
                geocode=location,
                include_entities=True)

data = {}
i = 1
for tweet in c.items():
    data['text'] = tweet.text
    print(i, ":", data)
    i += 1
time.sleep(300)

I have additional questions
The following is a code that stores the output results as a txt file
Does this code require " time.sleep "?
wfile = open(os.getcwd()+"/workk2.txt", mode='w')
data = {}
i = 0

for tweet in c.items():
    data['text'] = tweet.text
    wfile.write(data['text']+'\n')
    i += 1
time.sleep(300)

wfile.close()

A: A 429 means that you have sent too many requests. My guess is that because you are using for tweet in c.items(): and therefore not limiting the number of requests being sent, you are being rate limited by the Twitter API (that's what the error response is).
If you don't need to find an unlimited amount of tweets, you could set a max e.g. c.items(200).
Your time.sleep is outside the loop and therefore doesn't create a pause between each tweet request. You would want
for tweet in c.items():
    data['text'] = tweet.text
    wfile.write(data['text']+'\n')
    i += 1
    time.sleep(5)

That's a 5 second pause, which might solve your rate limiting issues. See also http://docs.tweepy.org/en/v3.5.0/cursor_tutorial.html#


text:
Q: How can i convert this sfdisk script invocation in a sequence of commands I came across this sfdisk invocation
sfdisk {device} <<EOF
label: dos
unit: sectors
4MiB,252MiB,
256MiB,,
EOF

how can i convert this "script' in a sequence of sfdisk invocation? i mean something like
sfdisk ...
sfdisk ...

A: If your question is how to run a sequence of commands in a bash script, the accepted answer to this question is good.  ie-
A; B    # Run A and then B, regardless of success of A
A && B  # Run B if and only if A succeeded
A || B  # Run B if and only if A failed
A &     # Run A in background.

If your question is more about generating scripts using thesfdisk utility in general, this question has a good answer that explains how to do that. ie-
To generate an example script, get the setup of one of your disks:

sudo sfdisk -d /dev/sda > sda.sfdisk

A: Save the following description of the device layout content to a file[example : sda.dump] and provide that as input .
label: dos
unit: sectors
4MiB,252MiB,
256MiB,,

Example :
sfdisk {device} < sda.dump


text:
Q: Error Code : 1 (SQLITE_ERROR) Caused By : SQL(query) error or missing database by click on snackbar I want to add the page to favourite list but I face this error when I click snackbar:

Error Code : 1 (SQLITE_ERROR)
                                                                           Caused By : SQL(query) error or missing database.
                                                                            (no such table: ghavaed (code 1): , while compiling: INSERT INTO
  ghavaed(saal,title) VALUES (?,?))

this is my first project please help
here is the page class I want to add to favourite lists:
public class StyleGhaede extends AppCompatActivity {

String title, tozih, sarfasl, saal;
TextView style_ghaede_content;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Bundle extras = getIntent().getExtras();
    title = extras.getString("title");
    tozih = extras.getString("tozih");
    sarfasl = extras.getString("sarfasl");
    saal = extras.getString("saal");
    setContentView(R.layout.activity_style_ghaede);

    getComponent();
    style_ghaede_content.setText(tozih);
}

private void getComponent(){
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setTitle(title);

    final DataBase db=new DataBase(this);
    final ghavaed fq=new ghavaed();

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "", Snackbar.LENGTH_LONG)
                    .setAction("برای اضافه کردن به لیست علاقه مندی کلیک کنید", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            db.addToFavourite(fq.getSaal(),fq.getTitle());
                        }
                    }).show();
        }
    });

    style_ghaede_content = (TextView) findViewById(R.id.style_ghaede_content);
}
}

my favouritelist class:
public class Favourite_List extends AppCompatActivity {

List<ghavaed> favouritelist;
DataBase db=new DataBase(this);

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_favourite__list);
    favouritelist=db.getFavouriteqavaed();
    ListView listview = (ListView) findViewById(R.id.list_view_fav);
    final Adapter_favourite adapter_fav = new Adapter_favourite(getApplicationContext(),favouritelist);
    listview.setAdapter(adapter_fav);
    ghavaed fq = new ghavaed();

    //swipelist
    SwipeLayout swipeLayout =  (SwipeLayout)findViewById(R.id.fav_item);
    swipeLayout.setShowMode(SwipeLayout.ShowMode.LayDown);
    swipeLayout.addDrag(SwipeLayout.DragEdge.Left, findViewById(R.id.bottom_wrapper));
    swipeLayout.addSwipeListener(new SwipeLayout.SwipeListener() {
        @Override
        public void onClose(SwipeLayout layout) {
            //when the SurfaceView totally cover the BottomView.
        }

        @Override
        public void onUpdate(SwipeLayout layout, int leftOffset, int topOffset) {
            //you are swiping.
        }

        @Override
        public void onStartOpen(SwipeLayout layout) {
        }

        @Override
        public void onOpen(SwipeLayout layout) {
            //when the BottomView totally show.
        }

        @Override
        public void onStartClose(SwipeLayout layout) {
        }

        @Override
        public void onHandRelease(SwipeLayout layout, float xvel, float yvel) {
            //when user's hand released.
        }
    });
}
}

my database:
public class DataBase extends SQLiteOpenHelper {

private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "Database";
private static final String TABLE_FAVOURITE_GHAVAED = "ghavaed";

private static final String Tozih = "tozih";
private static final String Saal = "saal";
private static final String Title = "title";
private static final String TAG = "DataBase";

public DataBase(Context context)
{
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {

    String CREATE_FAVOURITE_GHAVAED_TABLE = "CREATE TABLE " + TABLE_FAVOURITE_GHAVAED + "("
            + Saal + " TEXT,"
            + Title + " TEXT" + ")";
    db.execSQL(CREATE_FAVOURITE_GHAVAED_TABLE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVOURITE_GHAVAED);
    // Create tables again
    onCreate(db);
}

public void addToFavourite(String saal, String title) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(Saal, saal); // Product Name
    values.put(Title, title); // Product Number
    // Inserting Row
    db.insert(TABLE_FAVOURITE_GHAVAED, null, values);
    db.close(); // Closing database connection
    // Log.i("setUserExam", "addToFavourite : done!!");
}

public void removeFavourite(String saal, String title)
{
    SQLiteDatabase db = this.getWritableDatabase();
    db.execSQL("DELETE FROM  " + TABLE_FAVOURITE_GHAVAED + " WHERE saal ='" + saal + "' AND title = '" + title + "' ");
    db.close();
}

public List<ghavaed> getFavouriteqavaed()
{
    List<ghavaed> favouriteqavaedList = new ArrayList<>();

    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery("SELECT * FROM ghavaed", null);
    if (cursor.moveToFirst()) {
        do {
            ghavaed favouriteqavaed = new ghavaed();
            favouriteqavaed.setSaal(cursor.getString(0));
            favouriteqavaed.setTitle(cursor.getString(3));
           // favouriteqavaed.setTozih(cursor.getString(2));

            // Adding contact to list
            favouriteqavaedList.add(favouriteqavaed);
        } while (cursor.moveToNext());
    }
    db.close();
    return favouriteqavaedList;
}

public Integer getFavouritesNumber()
{
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery("SELECT * FROM ghavaed", null);
    return cursor.getCount();
}

public boolean checkIsFavourite(String saal, String title)
{
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery("SELECT * FROM ghavaed WHERE saal = '" + saal + "'" +
            "and title = '" + title + "' ", null);
    if (cursor != null && cursor.getCount() > 0) {
        cursor.moveToFirst();
        db.close();
        return true;
    } else {
        db.close();
        return false;
    }
}
}

public class ghavaed {
String saal, sarfasl, tozih, title;

public String getSaal() {
    return saal;
}

public void setSaal(String saal) {
    this.saal = saal;
}

public String getSarfasl() {
    return sarfasl;
}

public void setSarfasl(String sarfasl) {
    this.sarfasl = sarfasl;
}

public String getTozih() {
    return tozih;
}

public void setTozih(String tozih) {
    this.tozih = tozih;
}

public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}
}


text:
Q: How to create datasource in Weblogic using java I need to write a java code to create datasource in Weblogic using APIs. I found an API from Weblogic. But I am not able to find any sample implementation. Can someone please help me here? I m trying to use below API:
   DataSourceManager dsManager = DataSourceManager.getInstance();
   dsManager.createAndStartDataSource(jdbcImpl, appName, moduleName, compName, jdbcCtx, classLoader)

Thanks in advance.

A: You need use WLST script interface management for that operation as described on that snippet:
   3:  import java.net.UnknownHostException;
   4:  import org.python.util.InteractiveInterpreter;
   5:
   6:  import weblogic.management.scripting.utils.WLSTInterpreter;
   7:
   8:  public class DataSourceCreator {
   9:
  10:      static InteractiveInterpreter interpreter = null;
  11:      private String weblogicPassword;
  12:      private String weblogicUserName;
  13:      private StringBuffer wlst_script;
  14:
  15:      public DataSourceCreator(String weblogicUserName, String weblogicPassword) {
  16:          interpreter = new WLSTInterpreter();
  17:          this.weblogicUserName = weblogicUserName;
  18:          this.weblogicPassword = weblogicPassword;
  19:
  20:      }
  21:
  22:      /**
  23:       * connect to weblogic
  24:       */
  25:      private void connect() {
  26:          wlst_script.append("connect('" + this.weblogicUserName + "','" + this.weblogicPassword
  27:                  + "')");
  28:      }
  29:
  30:      /**
  31:       * creates the data source script
  32:       *
  33:       * @param dbpassword
  34:       * @param dbuser
  35:       * @param dsname
  36:       * @param jndiname
  37:       * @param dburi
  38:       * @param dbdrivername
  39:       */
  40:      private void createDataSourceScript(String dbpassword, String dbuser, String dsname,
  41:              String jndiname, String dburi, String dbdrivername) {
  42:
  43:          int timeout = 100000;
  44:          int maxcapacity = 100;
  45:
  46:          // substitute your server name here "SERVER_NAME" i.e the target.
  47:          wlst_script.append("cd('Servers/SERVER_NAME')\n");
  48:          wlst_script.append("target=cmo\n");
  49:          wlst_script.append("cd('../..')\n");
  50:          wlst_script.append("jdbcSystemResource = create('" + dsname + "','JDBCSystemResource')\n");
  51:          wlst_script.append("theJDBCResource = jdbcSystemResource.getJDBCResource()\n");
  52:          wlst_script.append("theJDBCResource.setName('" + dsname + "')\n");
  53:          wlst_script
  54:                  .append("connectionPoolParams = theJDBCResource.getJDBCConnectionPoolParams()\n");
  55:          wlst_script.append("connectionPoolParams.setConnectionReserveTimeoutSeconds(int('"
  56:                  + timeout + "'))\n");
  57:
  58:          // maximum connections that can be made
  59:          wlst_script.append("connectionPoolParams.setMaxCapacity(int('" + maxcapacity + "'))\n");
  60:          // query to execute using ds to test if its successfull
  61:          wlst_script.append("connectionPoolParams.setTestTableName('SQL SELECT 1 FROM DUAL')\n");
  62:
  63:          // update data source params
  64:          wlst_script.append("dsParams = theJDBCResource.getJDBCDataSourceParams()\n");
  65:          wlst_script.append("dsParams.addJNDIName('" + jndiname + "')\n");
  66:
  67:          wlst_script.append("driverParams = theJDBCResource.getJDBCDriverParams()\n");
  68:          wlst_script.append("driverParams.setUrl('" + dburi + "')\n");
  69:          wlst_script.append("driverParams.setDriverName('" + dbdrivername + "')\n");
  70:          wlst_script.append("driverParams.setPassword('" + dbpassword + "')\n");
  71:
  72:          wlst_script.append("driverProperties = driverParams.getProperties()\n");
  73:          wlst_script.append("proper = driverProperties.createProperty('user')\n");
  74:          wlst_script.append("proper.setValue('" + dbuser + "')\n");
  75:          wlst_script.append("proper1 = driverProperties.createProperty('DatabaseName')\n");
  76:          wlst_script.append("proper1.setValue('" + dburi + "')\n");
  77:          wlst_script.append("jdbcSystemResource.addTarget(target)\n");
  78:      }
  79:
  80:      /**
  81:       * @param wlst_script
  82:       */
  83:      private void saveActivateAndDisconnect() {
  84:          // save , activate changes and disconnect
  85:          wlst_script.append("save()\n");
  86:          wlst_script.append("activate(block='true')\n");
  87:          wlst_script.append("disconnect()\n");
  88:      }
  89:
  90:      /**
  91:       * start edit
  92:       *
  93:       * @param wlst_script
  94:       */
  95:      private void startEdit() {
  96:          wlst_script.append("edit()\n");
  97:          wlst_script.append("startEdit()\n");
  98:      }
  99:
 100:      public static void main(String args[]) throws UnknownHostException {
 101:
 102:          // weblogic related
 103:          String weblogicUserName = "username";
 104:          String weblogicPassword = "password";
 105:
 106:          DataSourceCreator dsCreator = new DataSourceCreator(weblogicUserName, weblogicPassword);
 107:
 108:          dsCreator.connect();
 109:          dsCreator.startEdit();
 110:          String sid = "sidofdb"; // sid of db
 111:          String ipaddress = "10.8.11.16"; // ip addres
 112:          String dbpassword = "password"; // database password
 113:          String dbuser = "username"; // db user name
 114:          String dsname = "datasourcename"; // your data source name
 115:          String jndiname = "jdbc/" + dsname; // jndi name for ds
 116:          String dburi = "jdbc:oracle:thin:@" + ipaddress + ":1521:" + sid;
 117:          String dbdrivername = "oracle.jdbc.driver.OracleDriver";
 118:
 119:          dsCreator.createDataSourceScript(dbpassword, dbuser, dsname, jndiname, dburi, dbdrivername);
 120:          dsCreator.saveActivateAndDisconnect();
 121:
 122:          try {
 123:              // execute the script created above
 124:              interpreter.exec(dsCreator.wlst_script.toString());
 125:          } finally {
 126:              // disconnect even if there is exception
 127:              interpreter.exec("disconnect()\n");
 128:          }
 129:
 130:      }
 131:
 132:  }


text:
Q: Faulty NMI implementation in R? #calculate NMI(c,t) c : cluster assignment , t : ground truth

NMI <- function(c,t){
n <- length(c) # = length(t)
r <- length(unique(c))
g <- length(unique(t))

N <- matrix(0,nrow = r , ncol = g)
for(i in 1:r){
    for (j in 1:g){
        N[i,j] = sum(t[c == i] == j)
    }
}

N_t <- colSums(N)
N_c <- rowSums(N)

B <- (1/n)*log(t( t( (n*N) / N_c ) / N_t))
W <- B*N
I <- sum(W,na.rm = T)

H_c <- sum((1/n)*(N_c * log(N_c/n)) , na.rm = T)
H_t <- sum((1/n)*(N_t * log(N_t/n)) , na.rm = T)

nmi <- I/sqrt(H_c * H_t)

return (nmi)
}

Running this on some clustering benchmarks here gives me a value of the  Normalized Mutual information  . But , when I compare it with values of NMI  obtained from the aricode library , I get values of NMI that generally differ in the second decimal place .
I will be grateful if someone is able to pin-point any possible error that has creeped into this code .
I am including a test case for this using a synthetic case :
library(aricode)
c <- c(1,1,2,2,2,3,3,3,3,4,4,4)
t <- c(1,2,2,2,3,4,3,3,3,4,4,2)
print(aricode::NMI(c , t))   #0.489574
print(NMI(c,t))              #0.5030771

A: This might be very late for an answer but for the sake of posterity:
The difference is in the way you and the aricode package normalise the index. You divide by sqrt() whereas aricode offers the following options:
function (c1, c2, variant = c("max", "min", "sqrt", "sum", "joint"))
so if you select variant = sqrt you should hopefully get the same answer.
The NMI package uses sum.


text:
Q: Adding picture boxes to a form from a thread I'm trying to create picture boxes in a for loop and then adding them to my main form. I create the picture boxes in another thread to decrease the loading time but my application keeps crashing over and over again.
I changed the code 10 times, the actual version looks like this.
Private letters() As PictureBox

Private Sub loadLetters()
    Dim j As Integer = 0
    letters = New PictureBox() {}
    For value As Integer = 0 To 7
        letters(value).Image = ImageList1.Images(value + 8)
        letters(value).Name = "picLetter_" & value + 8
        letters(value).Location = New Point(0, j)
        letters(value).Size = New Size(100, 100)
        letters(value).Visible = True
        j = j + 100

        Me.BeginInvoke(New MethodInvoker(AddressOf loadLetters))
    Next
End Sub

Another attempt of mine brought me to this:
If Me.InvokeRequired Then
    Dim d As New updateMain(AddressOf loadLetters)
    Me.Invoke(d, New Object() {letters(value)})
Else
    Me.Controls.Add(letters(value))
End If

Private Delegate Sub updateMain(ByVal picture As PictureBox)

How can I add picture boxes to the main form from another thread?

A: You keep invoking the same method, meaning each time you invoke you are trying to create eight additional picture boxes. The constant and continuous invocation eventually results in a StackOverflow exception, due to that you're trying to create an infinite amount of picture boxes.
You have to create a separate method for adding the picture boxes only, let your main method create them and the separate method add them to the form.
Private Delegate Sub AddPictureBoxDelegate(ByRef PBox As PictureBox)
'ByRef is better to use when not creating a copy of the PictureBox (and when you're not going to modify it as a separate one).

Private Sub AddPictureBox(ByRef PBox As PictureBox)
    If Me.InvokeRequired = True Then 'Invocation is required.
        'Call the method again, using invocation.
        Me.Invoke(New AddPictureBoxDelegate(AddressOf AddPictureBox), PBox)
    Else 'No (further) invocation required.
        Me.Controls.Add(PBox)
    End If
End Sub

Now, in your thread you just call:
AddPictureBox(letters(value))

And everything should work as expected.


text:
Q: How to add axis labels and grid to raphael bar chart I am having issues with g.raphael bar chart. Here is my example

var paper = Raphael("holder");
var chart = paper.barchart(100, 40, 480, 300, [[15,18,26,36,55,60,80]]);
Raphael.g.axis(90, 320, 280, 0, 100, 10, 1, null, "", null, paper);
//paper.path("M100 40L100 320").attr({ stroke: '#ccc' });

var paper = Raphael("holder1");
var chart = paper.barchart(100, 40, 480, 300, [[15,18,26]]);
Raphael.g.axis(90, 320, 280, 0, 100, 10, 1, null, "", null, paper);

Questions:

*

*How to stop from bars becoming smaller and bigger ? first example has 6 bars and second one has 3 bars so in the second example everything is bigger so it does not match with the label on y axis.

*How do I add gridline to bar chart? I tried drawing it with path element but it does not align as the bars get bigger and smaller compare to values being passed.
Thanks
Ved

A: I know this is a few months old, hopefully my answers help you or someone in the future.

*

*So a couple of things are happening that are causing these issues. The bars are scaled in both x and y to fill the available height and width that the chart is given when you call paper.barchart. So one way to counteract this is to pass in dummy 0 values so that the bar widths are the same.
For the height scaling, you need to set the "to" option of the barchart in order to get the bars to draw to the appropriate value.
Check out this plunker I made showing your data. Here's one of the chart creation calls:
var chart = paper1.barchart(100, 40, 480, 300,
    [[15, 18, 26, 0, 0, 0, 0]],
    {
      to: 100
    });

*What I did to solve this problem was modify the axis function to draw grid lines at the same locations as the dashes.
Hope that helps.


text:
Q: How to start Countdown timer in moment js React I am new to this using moment js, I took this sample from the internet and modified it according to my way, Here I want the countdown to start from 2 min: 00 sec to 00:00.
import React, { useEffect, useState } from "react";
import moment from "moment";

export default function CountdownMonths(){
  const [currentTime, setCurrentTime] = useState(moment());
  const timeBetween = moment.duration({
    "minutes": 2,
    "seconds":"00"
  });

  useEffect(() => {
    const interval = setInterval(() => {
      setCurrentTime(moment());
    }, 1000);

    return () => clearInterval(interval);
  }, []);

  return (
    <>

Deadline comes in

        {timeBetween.minutes()}m:
        {timeBetween.seconds()}s

    </>
  );
};

How shall I start the countdown on page render?
Any help would be much appreciated.


text:
Q: How to retain use selected option in radio buttons? I have a text form that uses a radio button of two options. For example, the 'exact match' is checked by default. However, whenever the 'submit'  is clicked, the option reverts back to the default section, which is undesired. I want to retain the radio option currently selected by users, not the default one.
<form class="search" action="{{ url_for('nlp.wbkg') }}" method="post">

        <input name="query" type="text" id="query" value="{{query}}" autocomplete="on" required>
        <button type="submit"></button>

        <input type="radio" name="options" id="exact" value="exact" checked="checked"> Exact match </input>
        <input type="radio" name="options" id="fuzzy" value="fuzzy"> Fuzzy Match </input>

    </form>

How to achieve that effect?
EDIT: add my server-side code in flask:
@bp.route('/wbkg', methods=('GET', 'POST'))
def wbkg():
    if request.method == 'POST':
        query = request.form['query']
        search_type = request.form['options']

        results, terms = search(query, search_type)

        return render_template('nlp/wbkg.html', items=results, terms=terms, query=query)

        flash(error)

    return render_template('nlp/wbkg.html')

How to handle it in server side?

A: Since you are wrapping your element in a form tag you should be sure to have your submit handler run event.preventDefault() to prevent the resetting of the form after the submit is fired.  You may be witnessing the reset of the form after the API call was sent.  You can confirm this by looking at your REQ body to see if the data sent is correct.


text:
Q: Extracting Numeric values from a text file by using Python I have a text file including some numerical values, brackets, and commas as below:
[123,5],[345,21],[1567,34],[7689,234],....

All data are in one line.
I need to extract these numbers from this text file and need to define two variables like X and Y such that all the first elements in brackets are saved in variable X and all the second elements are saved in variable Y. I also would like to have these two variables X and Y in an excel file.

A: Suppose you have a file named file.txt, you can do the following:
import ast

with open('file.txt') as f:
    values = ast.literal_eval(f.read())
    X, Y = zip(*values)


text:
Q: Relative link to stylesheet does not work on local machine, works online. Why is this? I'm trying to link my stylesheet (styles.css) to index.html.  When I do this using the Sublime Text build function for Chrome, the HTML comes out fine, but does not link to the stylesheet (the text is not blue).  When I upload this exact same code (in the same folder structure) to BitBalloon, the link works.  Why is this and how do I make the link work in both situations?
index.html:
<!DOCTYPE HTML>

    <title>I think I'm doing this right!</title>
    <link rel="stylesheet" type="text/css" href="/css/styles.css" />
</heaod>

CareerFoundry Template

This is a template for a simple marketing or informational website. It includes a large callout called a jumbotron and three supporting pieces of content. Use it as a starting point to create something more  &  unique.

Learn more »

styles.css:
body {color:blue;}
Working HTML and CSS on BitBalloon

A: Your root directory online is set to public_html (or www) on a standard setup.
The first part of this:
/css/styles.css
Tells is to look at the root of the project "/" and go from there. On your computer, it is using "/" as the root of your computer.
Using just "css/styles.css" would probably work if the css folder is the same directory that contains your html file.
Otherwise, you can run a local web server such as WAMP which will allow you to have a public_html folder as root on your local machine.

A: When you start a path with / like /css/styles.css you're telling the browser to look at the URL you're viewing, take the base part of it and append /css/styles.css
When your site is hosted on BitBalloon, the base of your URL is shopkeeper-cnythia-30345.bitballoon.com and the complete path to the stylesheet becomes http://shopkeeper-cnythia-30345.bitballoon.com/css/styles.css
When you're viewing the file locally, the URL is probably something like file:///Users/mbc/Documents/html-sites/html5up-aerial - in this case there's no base domain, so your browser ends up looking for the file: file://css/styles.css and that doesn't exist.
There's two ways around this.

*

*Use a truly relative path like css/styles.css. This tells the browser to take the directory you're on and append css/styles. The downside of this is that you'll have to take care if your on a subpage like /about/index.html - since then the browser will try to fetch /about/css/styles.css and you would need to link to ../css/styles.css to get around that

*Use an absolute path and run a local web server. Here's a really good list of one lines that
will let you start a simple web server from the command line in a directory: https://gist.github.com/willurd/5720255, this guarantees that your site will behave the same way when you're viewing it locally and when you deploy it to BitBalloon.

I would recommend getting used to running a local web server. As soon as you start playing more around with Javascript, Ajax requests, etc, it becomes a necessity anyway.


text:
Q: Why does the Ash Twin Project require rotation for artificial gravity? In Outer Wilds, the player can enter the Ash Twin Project and finds themselves in a rotating ring.
There is a switch on the ring that is marked "Artificial gravity" that stops the disk rotating. As far as I know, the artificial gravity is indeed the only reason the ring rotates.
However, everywhere else in the solar system, the Nomai used a special flooring type and crystals to create artificial gravity. Why is the Ash Twin Project different?

A: Maybe the Ash Twin Project was started by the Nomai of the Ember Twin (since they were closer than the ones in Brittle Hollow), and I don't remember any platform of gravity in Ember Twin, they only knew the rotation method you mentioned and they applied it inside the Project.
I think the Nomai in Ember Twin didn't know about the gravity platform technology, the rotational method was the way to go, and since it was started with the rotational technology it wasn't interesting to change the mechanism at all since it was working that way. I'm sure they debated the idea.

A: Neither the gravity crystals nor the special flooring are capable of being toggled off and on without being physically destroyed (at least, nowhere else in the game do we see this capability).
A toggleable floor at this location makes sense from both lore perspective - the Nomai wanted an easy way to access the reactor - and from a gameplay perspective - to allow the reactor to be in the precise center around an "interesting" area, while still allowing easy access to it.
But honestly, I think the main reason is a game development desire to generate a mysterious backdrop for when you glimpse into the Ash Twin Project from outside, and having a moving background helps that mystery. For the same reason I think the core of Timber Hearth - and consequently, the ATP - was designed to have a star-like appearance, not only for uniqueness but for generating the backdrop.

A: The Ash twin project is in the core of ash twin.  It's just an idea, but maybe a new kind of artificial gravity was needed to counteract such a strong central force.
Edit:
I have an idea that seems more logical now.  The ash twin is inside a core of rock that was designed to withstand a supernova.  While it does manage to do this, it would get very hot inside the core.  Perhaps the gravity crystal floors would melt under this temperature, and something less sophisticated was needed to create the gravity.  The main flaw in this theory, is that I don't believe anyone was meant to be inside the core during the supernova, but the nomai were obsessed with science, and the molten chrystals could possibly damage or destroy one of the masks, which would be a terrible failure, or if something on the chrystals was released due to their melting it could float and damage something.  Either way, if the crystals melted the Nomai would probably have gone with centrifugal gravity just because it would be "better" in a way.

A: The "conventional" way of generating some kind of "artificial gravity" (any kind of force that is perceived as pushing you down on the ground of some space station or whatever) in a science-fiction setting often is huge rotating rings, where the centrifugal force you would experience in a rotating reference frame pushes you away from the point the ring is rotating around, and thus pushing you on the ground of the ring-like structure.
For example in '2001: A Space Odyssey', there also is a station that consists of two huge rings.
I never played Outer Wilds myself, but this wiki article says that "The surface of the platform is made entirely of gravity pads, ensuring that the player does not fall off.". So that would mean, that it's actually the same technology the Nomai used elsewhere.
Which in turn means, I can't actually give you a game-specific answer, only the general, "out-of-universe" answer how a rotating ring would "create" something you would perceive as gravity when standing in the ring with your head pointing inwards and you feet pointing outwards.
The idea of a spinning ring acting as some kind of centrifuge is also illustrated really well in this video by the YouTube channel "Real Engineering".


text:
Q: ¿Cómo personalizar el sonido de una notificación en android 8.0? Tengo este código para las notificaciones de mi APP y funciona bien.
He intentado personalizar el sonido de la notificación, pero no he podido, sigue sonando el sonido por defecto de las notificaciones.
Me podrían decir, por favor, qué tengo mal o qué me falta en el código.
Gracias.
Este es el código del canal y de la notificación.
    Private static final String CHANNEL_ID = "tareas"

    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            CharSequence name = "Notificacion Parametros";
            String description = "Parametros";
            int importance = NotificationManager.IMPORTANCE_DEFAULT;
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
            channel.setDescription(description);
            // Register the channel with the system; you can't change the importance
            // or other notification behaviors after this
            NotificationManager notificationManager = getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
        }
    }

    private void recordatorio_tareas() {

          NotificationManager nManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

          Intent intent = new Intent(recordatorio.this, MainActivity.class);
          intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
          PendingIntent pendingIntent = PendingIntent.getActivity(recordatorio.this, 0, intent, 0);

          int color = 0x00FF00;

          String mensaje1 = "Recordatorio";
          String mensaje2 = "No olviden trabajar en la manualidad que deben presentar la proxima semana.";

          NotificationCompat.Builder notification = new NotificationCompat.Builder(
                getBaseContext(), CHANNEL_ID)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.barney_icono1))
                .setSmallIcon(R.drawable.barney_icono2)
                .setContentTitle(mensaje1)
                .setContentText(mensaje2)
                .setStyle(new NotificationCompat.BigTextStyle().bigText(mensaje2))
                .setColor(color)
                .setWhen( System.currentTimeMillis() )
                .setContentIntent(pendingIntent)
                .setAutoCancel(true)
                .setSound(Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE+ "://" + getPackageName() +"/" + R.raw.barney_sonido));

            nManager.notify(3, notification.build());

}

A: Anteriormente podìas cambiar el sonido de la notificaciòn en una aplicaciòn Android progràmaticamente sin ningùn problema, pero actualmente debes crear un canal y realizar su configuraciòn que incluye el sonido, al realizar esta configuraciòn en el canal ya no puede ser cambiada.
Lo que se debe realizar para cambiar el sonido de la notificaciòn progràmaticamente es:
Debemos eliminar el canal de notificación mediante deleteNotificationChannel() y crear uno nuevo con un nuevo id de canal de notificación definiendo la nueva ruta del archivo de sonido.
//Elimina canal de notificaciones
notificationManager.deleteNotificationChannel(OLD_CHANNEL_ID);

//Crea nueva notificaciòn con nuevo canal y nuevo sonido
      NotificationCompat.Builder notification = new NotificationCompat.Builder(
            getBaseContext(), CHANNEL_ID)
            .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.barney_icono1))
            .setSmallIcon(R.drawable.barney_icono2)
            .setContentTitle(mensaje1)
            .setContentText(mensaje2)
            .setStyle(new NotificationCompat.BigTextStyle().bigText(mensaje2))
            .setColor(color)
            .setWhen( System.currentTimeMillis() )
            .setContentIntent(pendingIntent)
            .setAutoCancel(true)
            .setSound(Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE+ "://" + getPackageName() +"/" + R.raw.barney_sonido));

A: Así quedo el código que encontre y adapte, ya no usando la propiedad setSound sino notificationChannel.setSound(soundUri,audioAttributes);
        String mensaje1 = "Recordatorio";
        String mensaje2 = "No olviden trabajar en la manualidad que deben presentar la proxima semana.";

        Uri soundUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE+ "://" + getPackageName() +"/" + R.raw.barney_sonido);

        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, "CH_ID")
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.barney_icono1))
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle(mensaje1)
                .setContentText(mensaje2)
                .setStyle(new NotificationCompat.BigTextStyle().bigText(mensaje2))
                .setColor(Color.BLUE)
                .setWhen( System.currentTimeMillis() )
                .setAutoCancel(true)
                .setSound(soundUri);

        NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {

            if(soundUri != null){
                // Changing Default mode of notification
                notificationBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
                // Creating an Audio Attribute
                AudioAttributes audioAttributes = new AudioAttributes.Builder()
                        .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                        .setUsage(AudioAttributes.USAGE_ALARM)
                        .build();

                // Creating Channel
                NotificationChannel notificationChannel = new NotificationChannel("CH_ID","Testing_Audio",NotificationManager.IMPORTANCE_HIGH);
                notificationChannel.setSound(soundUri,audioAttributes);
                mNotificationManager.createNotificationChannel(notificationChannel);
            }
        }

        mNotificationManager.notify(11, notificationBuilder.build());


text:
Q: Approximating $\pi$ with arctangent Use the fact that $\frac{\pi}{4} = \text{arctangent}(\frac{1}{2}) + \text{arctangent}(\frac{1}{3})$ to determine the number of terms summed to ensure an approximation to $\pi$ less than $10^{-3}$.
So far I've got
\begin{align*}
    \pi = 4\Bigg(\sum_{i=1}^{\infty} (-1)^{i+1}\frac{1}{2^{2i-1}(2i-1)} + \sum_{i=1}^{n} (-1)^{i+1}\frac{1}{3^{2i-1}(2i-1)}\Bigg)
\end{align*}
from the given identity. But I don't know how to proceed.

A: Rewrite the equality as:
\begin{array}{}
    \pi = 4\left[\sum\limits_{i=0}^{n-1} (-1)^{i}\left(\frac{1}{2^{2i+1}(2i+1)} +\frac{1}{3^{2i+1}(2i+1)}\right)+\sum\limits_{i=n}^{\infty} (-1)^{i}\left(\frac{1}{2^{2i+1}(2i+1)} +\frac{1}{3^{2i+1}(2i+1)}\right)\right]
\end{array}
to obtain the inequality to be solved for $n$:
$$
\begin{array}{}
 4\left|\sum\limits_{i=n}^{\infty} (-1)^{i}\left(\frac{1}{2^{2i+1}(2i+1)} +\frac{1}{3^{2i+1}(2i+1)}\right)\right|<\epsilon=10^{-3}.\tag1
\end{array}$$
Observe now that the series (1) is alternating with monotonously decreasing terms, and thus the absolute value of the series is less than that of its first term.

A: The sums are alternating and the terms decreasing in absolute value. This implies that the error is lesser or equal to the first discarded term. The error summing up to $n$ is then lesser or equal to
$$
4\Bigl(\frac{1}{2^{2n+1}(2\,n+1)}+\frac{1}{3^{2n+1}(2\,n+1)}\Bigr).
$$
Now choose $n$ so that the above is $<10^{-3}$.


text:
Q: Umbraco, how to add onChange functionality on dropdown content backoffice? I am having one document type which contains a dropdown list, I need to add a couple of things in it:

*

*I need to display the Database table names in drop-down dynamically.

*On the change of dropdown option, i need to display the selected table columns names in another drop-down.
Are above things possible by using only existing data types or it will require creating a custom template using razor syntaxes (if it is so then how the template will display directly in the back office content node?)
Can you please provide your views and any links for code/tutorials?
screen shot of content form

A: If this is for the back office, you will need to do it in HTML and Angular, with an API controller to handle the DB lookup stuff.
As far as I'm aware, there's nothing built in to do dropdowns that depend on each other, so you'd have to create a new DataType to do it.
The process is to long to detail here, but here are some useful links on creating custom DocTypes in Umbraco 7.
https://our.umbraco.org/documentation/tutorials/Creating-a-Property-Editor/
http://velstand.info/tips/umbraco/to-create-a-datatype-by-using-external-data-sources/
https://24days.in/umbraco-cms/2016/custom-property-editor-tutorial/


text:
Q: Elasticsearch backup only hot indices I have a cluster of elastiсsearch consisting of 6 nodes.
5 indexes are created per day (each index consume about 10 to 250 gigabytes)
we now have a snapshot repository (which is located on the NFS share) where these indices are backed up every day, but the fact is that in a year this snapshot repository began to weigh 40 terabytes and the fact is that these are payment logs that are required by law in my country store for 2 years, but we do not have so much space on NFS, and we had an incident when there was a bug on the NFS share and our snapshot repository was damaged and we could not restore it
and then I thought to change the backup process, make a script that will be every day

*

*create a new folder on the NFS share with the current date
(logz-backup-Year-Month-Day)

*register a snapshot repository to this folder

*take a snapshot

*delete a snapshot repository from elasticsearch

*make an archive from the folder

but the problem is that every time you take a backup to a new snapshot repository, the Elasticsearch makes a full backup of the contents, how can I make it so that elasticsearch only backs up new indexes to a new snapshot repository? I heard about https://www.elastic.co/guide/en/cloud/current/ec-getting-started-profiles-hot-warm.html, is it possible to do something that the indices are hot during the first 24 hours (for backup) and if it's older than day they switched to warm and so that they would not be backed up to a new snapshot repository?
P.S I tried to compress my elasticsearch repository folder using gzip, and got a noticeable compression (from 40 TB it turned out to be 20TB)

A: First of all, provided you use the same repository, snapshots are always incremental, i.e. a full backup is not performed every time. Only the first time, all indices are snapshotted and then only the diffs are backed up on each new snapshot operation.
The reason you're experiencing a full backup each time is because you create a new snapshot repository each time (point 2). It's a waste of resources and snapshot/restore has not been designed to be used that way. An index that has been snapshotted yesterday and to which nothing gets written anymore since the last snapshot was taken, won't be snapshotted today again. That's the whole point of incremental snapshotting.
Since snapshots are incremental, it's only useful to keep an handful of them (say the last 50 or 100 snapshots). That's what is implemented on Elastic Cloud, for instance.
To help you with this, you can leverage Snapshot Lifecycle Management (SLM for short). So, after you create your repository on NFS, you can simply set up a snapshot policy where you define an expiration time as well as the minimum and maximum number of snapshots to keep. That way you can always keep your repository size at bay, i.e. the repository size will be very close to the actual size of your cluster (a little bigger, but not 10x bigger).


text:
Q: Get an URL from text surrounded with curly braces using PHP Regular expression I have the following text (inside some more text):
{movie:http://www.film.com/films/film1}
I would like to use a regular expression to get the url based on the fact that it's wrapped inside curly braces and contains "movie:" after the first brace. How can I do this using PHP?

A: $t = "{movie:http://www.film.com/films/film1}";
preg_match(/{movie:([^}]+)}/,$t,$m);
$url = $m[1];

A: Try this:
if (preg_match('/\{movie:(.*?)}/', $text, $match))
    print "Found movie URL '".$match[1]."'\n";


text:
Q: Wordpress plugin ajax post parameter i have problem.
I don't know why but my paramters from form don't pass too aad_process_ajax().
My code from functions and jquery:
Function with my form:
function aad_render_admin() {

    ?>

<?php _e('Admin Ajax Demo', 'aad'); ?>

        <form id="aad-form" action="" method="POST">

<input type="text" name="name" />
<input type="text" name="header" />
<input type="text" name="body" />
<input type="text" name="urls" />
                <input type="submit" name="aad-submit" id="aad_submit" class="button-primary" value="<?php _e('Get Results', 'aad'); ?>"/>
                <img src="<?php echo admin_url('/images/wpspin_light.gif'); ?>" class="waiting" id="aad_loading" style="display:none;"/>

        </form>

    <?php
}

Jquery code:
jQuery(document).ready(function($) {
    $('#aad-form').submit(function() {
        $('#aad_loading').show();
        $('#aad_submit').attr('disabled', true);

      data = {
          action: 'aad_get_results',
          aad_nonce: aad_vars.aad_nonce
      };

         $.post(ajaxurl, data, function (response) {
            $('#aad_results').html(response);
            $('#aad_loading').hide();
            $('#aad_submit').attr('disabled', false);
        });

        return false;
    });
});

And this function don't get my parameters why?
function aad_process_ajax() {
    global $wpdb;

    echo $name = $_POST['name'];
    $header = $_POST['header'];
    $body = $_POST['body'];
    $urls = $_POST['urls'];
    echo 'xxxx';

        $wpdb->insert(
        'wp_myprojects',
            array(    'name' => $name,
                    'header' => $header,
                    'body' => $body,
                    'urls' => $urls,
                    ),
            array(    '%s',
                    '%s',
                    '%s',
                    '%s'
                    )
        );

    $wpdb->show_errors();
    /*EVRY PROCESS AJAX MUST DIE!!!!*/
    die();
    /*EVRY PROCESS AJAX MUST DIE!!!!*/
}
add_action('wp_ajax_aad_get_results','aad_process_ajax');

Tell my why parameters don't show in function aad_process_ajax().
Problem is in Jquery or Wordpress?

A: In your jQuery code
 data = {
      action: 'aad_get_results',
      aad_nonce: aad_vars.aad_nonce
  };

you are passing only action and aad_nonce, you are not passing form data.
If you want pass variables, you ave to pass it with ajax, use something like:
  data = {
      action: 'aad_get_results',
      aad_nonce: aad_vars.aad_nonce,
      form_data: $('#aad-form').serialize()
  };

After that, in your aad_process_ajax function use:
function aad_process_ajax() {

  parse_str($_POST['form_data'], $form_data);
  $name = isset($form_data['name']) ? : '';
  $header = isset($form_data['header']) ? : '';
  $body = isset($form_data['body']) ? : '';
  $urls = isset($form_data['urls']) ? : '';

  // the rest of your code here

}


text:
Q: Superscrollorama, TweenMax Make an Animation play and after that resume scrolling Is there a way to let the user scroll to a certain point,
an element fades in,
after that an animation (X2) is played (without user input)
and after that scrolling triggers further animations, but those can only be triggered if the animation(X2) has played through.
var controller = $.superscrollorama({
            triggerAtCenter: false
        });
            // set duration, in pixels scrolled, for pinned element
                var pinDur = 2800;

                // create animation timeline for pinned element
                var pinAnimations = new TimelineLite();
                pinAnimations
                    .append([
                        TweenMax.to($('#mouse_walk'), 5, {css:{opacity: 1},
                            onComplete: function(){
                                $( "#mouse_walk, #mouse_walk img" ).stop().animate( {height: '977px', width: '1080px', left: '49.5%', top:'370px'}, 200, function(){
                                    $( "#mouse_walk, #mouse_walk img" ).stop().animate( {height: '944px', width: '1044px', left: '50%', top:'380px'}, 200, function(){
                                        $( "#mouse_walk, #mouse_walk img" ).stop().animate( {height: '995px', width: '1100px', left: '49.3%', top:'360px'}, 200, function(){
                                            $( "#mouse_walk, #mouse_walk img" ).stop().animate( {height: '944px', width: '1044px', left: '50%', top:'380px'}, 200, function(){
                                                setTimeout(function() {
                                                      $( "#mouse_walk, #mouse_walk img" ).stop().animate( {height: '977px', width: '1080px', left: '49.5%', top:'370px'}, 200, function(){
                                                          $( "#mouse_walk, #mouse_walk img" ).stop().animate( {height: '944px', width: '1044px', left: '50%', top:'380px'}, 200, function(){
                                                              $( "#mouse_walk, #mouse_walk img" ).stop().animate( {height: '995px', width: '1100px', left: '49.3%', top:'360px'}, 200, function(){
                                                                  $( "#mouse_walk, #mouse_walk img" ).stop().animate( {height: '944px', width: '1044px', left: '50%', top:'380px'}, 200, function(){
                                                                    })
                                                                })
                                                            })
                                                        })
                                                    }, 800);
                                                    })
                                                })
                                            })
                                        });
                                    }
                                }
                            )
                        ])
                    .append([
                        TweenMax.to( $('#mouse_walk_hell'), 5, {css:{opacity: '1'}})
                    ])

A: This really seems overly complicated.
My thought process on this you have a pin that does your initial animation.
onComplete of that animation you directly add the tween you want to happen?
You can nest another timelineLight inside of the onComplete method so you can sequence those animations without having that huge nested group of JQuery animation.
I also highly recommend not to mix greensock and JQuery animations together, they have caused a nightmare for me.


text:
Q: SugarCRM/SuiteCRM Api Login redirect I am using the v4_1 Rest API from Sugar/Suite CRM to login:
http://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_6.5/Application_Framework/Web_Services/Examples/REST/PHP/Logging_In/
I have taken this php code and created a loginAuth.php script and put the credentials for a user in it...  It works and returns me a session id...
My problem now is I don't know what to do with the session id I get back...  I try to redirect the main page, but it takes me back to the login screen...
Workflow:

*

*call loginAuth.php (validate/get sessionid)

*if valid session, redirect to index.php?module=Home&action=index

But it's just taking me to the main page...
Any ideas on how I can bypass the login form when using the API?
Thanks,
Adam

A: Ok, I figured it out. There are two cookies that set:
PHPSESSID

and
MSID

but you have to send MSID to the index.php page FIRST...  So simply add this line to the bottom of the php script:
header("Location: http://{site_url}/index.php?MSID=$session_id");

and it will bypass the login.


text:
Q: Missing words when create pdf invoice with chinese character I am currently having a problem:
Currently when I create an invoice in the backend in Chinese, my font is missing some characters that cannot be created. I tried searching for different fonts on google but couldn't find the right one.
So I want to ask that in order to be able to create a pdf file, which font do I need and where do I download it.

Thank for reading and supporting me

A: I've find the right font for my question. If anyone have the same problem with me, you can download the font in this link:
https://chinesefontdesign.com/classic-song-ti-font.html


text:
Q: Sqflite Database Exception Flutter I asked a similar question yesterday, but I still couldn't solve my problem. I am sharing the problem as a photo. How can I solve this?
I also use this function with button.

A: I'd say it's because your strings aren't enclosed in ' or ": it's always better to wrap them to avoid errors. Try changing the query into [...] VALUES ("erol", "bascifci", "erolbascifci@gmail.com", "testtesttest")


text:
Q: Entity Framework Tools Errors on Reverse Engineer Code First
One or more errors occurred while processing template 'Entity.tt'.
  error : An exception was thrown while trying to compile the
  transformation code. The following Exception was thrown:
  System.ArgumentException: Empty path name is not legal.

Anyone know what might be going on?
I created a new class project in VS 2015.  Added the nuget for <package id="EntityFramework" version="6.1.3" targetFramework="net452" />.  Downloaded the VSIX file for the EF Tools and installed them.  Then I shut everything down, restarted and went to the Entity Framework tools for the project and selected Reverse Engineer.  It started going through the process of scanning the database then just stopped with this error.
I've tried running as admin, running as a normal user, rebooting the machine and nothing seems to have worked (yet).
Any suggestions?
Full Stack Trace:
One or more errors occurred while processing template 'Entity.tt'.
error : An exception was thrown while trying to compile the transformation code. The following Exception was thrown:
System.ArgumentException: Empty path name is not legal.
   at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share)
   at System.IO.File.OpenRead(String path)
   at Roslyn.Utilities.FileUtilities.OpenFileStream(String path)
   at Microsoft.CodeAnalysis.MetadataReference.CreateFromFile(String path, MetadataReferenceProperties properties, DocumentationProvider documentation)
   at Microsoft.VisualStudio.TextTemplating.CompilerBridge.<>c.<.ctor>b__15_0(String x)
   at System.Linq.Enumerable.WhereSelectListIterator`2.MoveNext()
   at System.Linq.Enumerable.<UnionIterator>d__66`1.MoveNext()
   at System.Linq.Enumerable.<UnionIterator>d__66`1.MoveNext()
   at System.Linq.Buffer`1..ctor(IEnumerable`1 source)
   at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
   at System.Collections.Immutable.ImmutableArray.CreateRange[T](IEnumerable`1 items)
   at Microsoft.CodeAnalysis.ImmutableArrayExtensions.AsImmutableOrEmpty[T](IEnumerable`1 items)
   at Microsoft.CodeAnalysis.Compilation.ValidateReferences[T](IEnumerable`1 references)
   at Microsoft.CodeAnalysis.CSharp.CSharpCompilation.WithReferences(IEnumerable`1 references)
   at Microsoft.CodeAnalysis.CSharp.CSharpCompilation.CommonWithReferences(IEnumerable`1 newReferences)
   at Microsoft.VisualStudio.TextTemplating.CompilerBridge.PrepareNewCompilation()
   at Microsoft.VisualStudio.TextTemplating.CompilerBridge.Compile()
   at Microsoft.VisualStudio.TextTemplating.TransformationRunner.Compile(String source, String inputFile, IEnumerable`1 references, Boolean debug, SupportedLanguage language, String compilerOptions)

A: You should just the official EF Tools, that are included with VS 2015, and use the "Code First from Database" feature in the "Add EDM" wizard, or use the EF Reverse POCO template - EF Power Tools reverse engineeer does not work with VS 2015 and is not supported.

A: *

*The EF Power Tools Beta do work in VS2015:  Installing EF Power Tools into VS2015

*The problem is an update in the .NET framework.  Version 4.5.1 will work.  Version 4.5.2 and later had a breaking change for the power tools.  Easiest solution is to dial your project back to the 4.5.1 framework, reverse engineer the database, dial your version back to where you need/want it.


text:
Q: How can I print to a variable instead of a file, in Perl? How can I print to a variable with Perl?
I've been working on a program for a while which logs its iterative progress in a highly verbose fashion...
print $loghandle $some_message;

However, I'd like to also selectively print some of the messages to a different file. Naturally, I could sprinkle the code with...
print $loghandle $some_message
print $otherloghandle $some_message

Or rewrite the whole business into a function. Blah.
What I want to do is do some magic when I open the $loghandle so that when I'm print'ing, I'm actually just doing a sprintfish operation against a variable(call it $current_iteration), so that when I get down to a decision point I can do something like this...
print $real_log_file $current_iteration;
print $other_real_log_file $current_iteration if($condition);

I'm fairly sure I've seen something like this somewhere, but I have no idea where it is or where to look.
edit: File::Tee solves this problem to some extent on *nix, but I run on Windows.

A: Do you mean something like IO::Scalar? Lets you write to a variable with filehandle semantics.

A: If you want to do selective logging where you can control which messages are logged and where they are logged, use Log::Log4perl. That will save you a bunch of time over messing with ties and other black magic.

A: You can treat a scalar variable as a filehandle by opening it:
open my $fh, '>', \$variable or die "Can't open variable: $!";
print $fh "Treat this filehandle like any other\n";

You can even map stdout or stderr to a scalar:
close STDOUT;
open STDOUT, '>', \$variable or die "Can't open STDOUT: $!";

If you want to split your output or set up a config file to do "interesting" things with your logging, you are better off with Log4Perl as others have suggested.

A: You can use File::Tee to split a filehandle into multiple output streams.
use File::Tee;
open my $fh, '>', 'logfile.txt' or die $!;
tee( $fh, '>', 'otherlogfile.txt' ) if $condition;

print $fh $current_iteration;   # will also go to otherlogfile.txt
                                # if $condition was true

A: Perlfaq5 recommends Tie::FileHandle::Multiplex for printing to multiple files.
The source is very simple and it should be easy to modify with a per-handle filter.

A: Sound like you want to tie your filehandle.
my $x;

# printing to $fh will update the variable $x
# when you close $fh, it will print $x to a filehandle depending
# on code in the function  Print_to_variable::CLOSE

tie $fh, "Print_to_variable", \$x, $output_fh1, $output_fh2;
print $fh "stuff";
print $fh "more stuff";
close $fh;

sub Print_to_variable::TIEHANDLE {
    my ($class, $ref, $fh1, $fh2) = @_;
    my $self = {};
    $self->{ref} = $ref;
    $self->{output_fh1} = $fh1;
    $self->{output_fh2} = $fh2;
    bless $self, "Print_to_variable";
    $self;
}
sub Print_to_variable::PRINT {
    my ($self,@list);
    ${$self->{ref}} .= join "", @list;
}
sub Print_to_variable::CLOSE {
    my $self = shift;
    my $text = ${$self->{ref}};
    if ( &myCondition1($text) ) {    # ... how you decide where to print
        print {$self->{output_fh1}} $text;
    } else {
        print {$self->{output_fh1}} $text;
    }
}

A: This is a tremendous hack, and I think mobrule's solution or(esp) Sinan's solution of Log4Perl are the way to go when I have time.
But, this is what I'm using, as a completion thing:
sub print_to_var($$) {
   my($rx_var, $scalar) = @_;
   $$rx_var .= $scalar;
}

print_to_var \$logvar, $message;

#...later on...
print $somefile $logvar;

Edit:
Since this is community wiki, it's worth nothing that Perl aliases arguments to functions.  That means you can just write this:
sub print_to_var($$) {
   $_[0] .= $_[1];
}

And then say:
my $foo = "OH HAI. ";
print_to_var $foo, "I ARE HELO KITTIE.";
say $foo; # OH HAI.  I ARE HELO KITTIE.

This is not a particularly tremendous hack, although print_to_var is a lot more typing than . is.
And here is the HELO KITTIE:
helo kittie http://blogs.philadelphiaweekly.com/style/files/2008/11/hello-kitty-color.gif


text:
Q: Parsing nested JSON values with Lift-JSON Scala 2.12 here trying to use Lift-JSON to parse a config file. I have the following myapp.json config file:
{
  "health" : {
    "checkPeriodSeconds" : 10,
    "metrics" : {
      "stores" : {
        "primary" : "INFLUX_DB",
        "fallback" : "IN_MEMORY"
      }
    }
  }
}

And the following MyAppConfig class:
case class MyAppConfig()

My myapp.json is going to evolve and potentially become very large with lots of nested JSON structures inside of it. I don't want to have to create Scala objects for each JSON object and then inject that in MyAppConfig like so:
case class Stores(primary : String, fallback : String)
case class Metrics(stores : Stores)
case class Health(checkPeriodSeconds : Int, metrics : Metrics)
case class MyAppConfig(health : Health)

etc. The reason for this is I'll end up with "config object sprawl" with dozens upon dozens of case classes that are only in existence to satisfy serialization from JSON into Scala-land.
Instead, I'd like to use Lift-JSON to read the myapp.json config file, and then have MyAppConfig just have helper functions that read/parse values out of the JSON on the fly:
import net.liftweb.json._

// Assume we instantiate MyAppConfig like so:
//
// val json = Source.fromFile(configFilePath)
// val myAppConfig : MyAppConfig = new MyAppConfig(json.mkString)
//
class MyAppConfig(json : String) {
  implicit val formats = DefaultFormats

  def primaryMetricsStore() : String = {
    // Parse "INFLUX_DB" value from health.metrics.stores.primary
  }

  def checkPeriodSeconds() : Int = {
    // Parse 10 value from health.checkPeriodSeconds
  }
}

This way I can cherry pick which configs I want to expose (make readable) to my application. I'm just not following the Lift API docs to see how this strategy is possible, they all seem to want me to go with creating tons of case classes. Any ideas?

A: Case classes are not mandatory for extracting data from JSON. You can query the parsed tree and transfrom data according to your needs. The values from the example can be extracted as follows:
import net.liftweb.json._

class MyAppConfig(json : String) {
  private implicit val formats = DefaultFormats

  private val parsed = parse(json)

  def primaryMetricsStore() : String = {
    (parsed \ "health" \ "metrics" \ "stores" \ "primary").extract[String]
  }

  def checkPeriodSeconds() : Int = {
    (parsed \ "health" \ "checkPeriodSeconds").extract[Int]
  }

}

The original doc provides all the details.


text:
Q: Integrating Piecewise with irrational exponent gives error When trying to integrate a Piecewise function with irrational exponent, I stumbled upon the following problem:
import sympy as sym

x, y = sym.symbols(['x', 'y'])
pdf = sym.Piecewise((0, x < 1),
                    (x ** -2.5, x < 2),
                    (0, True))
cdf = sym.integrate(pdf, (x, -sym.oo, y))

This gives the following error:
ValueError                                Traceback (most recent call last)
<ipython-input-3-c1f460aac84e> in <module>()
      5                     (x ** -2.5, x < 2),
      6                     (0, True))
----> 7 cdf = sym.integrate(pdf, (x, -sym.oo, y))
      8 print(cdf)

~/.local/lib/python3.6/site-packages/sympy/integrals/integrals.py in integrate(*args, **kwargs)
   1293     if isinstance(integral, Integral):
   1294         return integral.doit(deep=False, meijerg=meijerg, conds=conds,
-> 1295                              risch=risch, manual=manual)
   1296     else:
   1297         return integral

~/.local/lib/python3.6/site-packages/sympy/integrals/integrals.py in doit(self, **hints)
    551                                        for f in integrals])
    552                         try:
--> 553                             evalued = Add(*others)._eval_interval(x, a, b)
    554                             function = uneval + evalued
    555                         except NotImplementedError:

~/.local/lib/python3.6/site-packages/sympy/functions/elementary/piecewise.py in _eval_interval(self, sym, a, b)
    229                         rep = b
    230                         val = e._eval_interval(sym, mid, b)
--> 231                         val += self._eval_interval(sym, a, mid)
    232                     elif (a > upper) == True:
    233                         mid = upper

~/.local/lib/python3.6/site-packages/sympy/functions/elementary/piecewise.py in _eval_interval(self, sym, a, b)
    282                     super(Piecewise, expr)._eval_interval(sym, Max(a, int_a), Min(b, int_b)))
    283             else:
--> 284                 ret_fun += expr._eval_interval(sym, Max(a, int_a), Min(b, int_b))
    285         return mul * ret_fun
    286

~/.local/lib/python3.6/site-packages/sympy/core/expr.py in _eval_interval(self, x, a, b)
    832             else:
    833                 domain = Interval(b, a)
--> 834             singularities = list(solveset(self.cancel().as_numer_denom()[1], x, domain = domain))
    835             for s in singularities:
    836                 if a < s < b:

~/.local/lib/python3.6/site-packages/sympy/solvers/solveset.py in solveset(f, symbol, domain)
    919         return result
    920
--> 921     return _solveset(f, symbol, domain, _check=True)
    922
    923

~/.local/lib/python3.6/site-packages/sympy/solvers/solveset.py in _solveset(f, symbol, domain, _check)
    709             result += solns
    710     else:
--> 711         lhs, rhs_s = inverter(f, 0, symbol)
    712         if lhs == symbol:
    713             # do some very minimal simplification since

~/.local/lib/python3.6/site-packages/sympy/solvers/solveset.py in <lambda>(f, rhs, symbol)
    677     else:
    678         inverter_func = invert_complex
--> 679     inverter = lambda f, rhs, symbol: inverter_func(f, rhs, symbol, domain)
    680
    681     result = EmptySet()

~/.local/lib/python3.6/site-packages/sympy/solvers/solveset.py in invert_real(f_x, y, x, domain)
    116     the domain to ``S.Reals`` before inverting.
    117     """
--> 118     return _invert(f_x, y, x, domain)
    119
    120

~/.local/lib/python3.6/site-packages/sympy/solvers/solveset.py in _invert(f_x, y, x, domain)
     98
     99     if domain.is_subset(S.Reals):
--> 100         x1, s = _invert_real(f_x, FiniteSet(y), x)
    101     else:
    102         x1, s = _invert_complex(f_x, FiniteSet(y), x)

~/.local/lib/python3.6/site-packages/sympy/solvers/solveset.py in _invert_real(f, g_ys, symbol)
    184             else:
    185                 if not base.is_positive:
--> 186                     raise ValueError("x**w where w is irrational is not "
    187                                      "defined for negative x")
    188                 return _invert_real(base, res, symbol)

ValueError: x**w where w is irrational is not defined for negative x

But if I take just the part with the exponent and integrate it, it works fine:
pdf = x ** -2.5
cdf = sym.integrate(pdf, (x, -sym.oo, y))
print(cdf)

This gives:
-0.666666666666667*_y**(-1.5)

Question:
How can I integrate the first Piecewise function?
What I tried:
Specifying y to be nonnegative:
y = sym.Symbol('y', nonnegative=True)

Like this I won't get the first error, but the result becomes quite strange:
0.666666666666667*Min(1, y)**(-1.5) - 0.666666666666667*Min(2, y)**(-1.5)

which I can't use later:
eq = sym.Eq(x, cdf)
inverse_solutions = sym.solve(eq, y, rational=False)

gives:
NotImplementedError: multiple generators [Min(1, y)**1.5, Min(2, y)**1.5]
No algorithms are implemented to solve equation x - 0.666666666666667*Min(1, y)**(-1.5) + 0.666666666666667*Min(2, y)**(-1.5)

A: Looks like I found a workaround.
I just had to simplify a pdf by sympy.nsimplify and the error is gone:
import sympy as sym

x, y = sym.symbols(['x', 'y'])
pdf = sym.Piecewise((0, x < 1),
                    (x ** -2.5, x < 2),
                    (0, True))
pdf = sym.nsimplify(pdf)
print(pdf)
cdf = sym.integrate(pdf, (x, -sym.oo, y))
print(cdf)

gives:
Piecewise((0, x < 1), (x**(-5/2), x < 2), (0, True))
Piecewise((0, y < 1), (2/3 - 2/(3*y**(3/2)), y < 2), (-sqrt(2)/6 + 2/3, True))


text:
Q: What pooled data source should I use for Spring 3.1.0, Hibernate 4.0.1.Final, and MySQL 5.1? I'm using Spring 3.1.0.RELEASE, Hibernate 4.0.1.Final, and MySQL 5.1.  What is the pooled data source I should be using?  I'm currently using (snippet from application context file) ...
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName">
        <value>com.mysql.jdbc.Driver</value>
    </property>
    <property name="url">
        <value>jdbc:mysql://localhost:3306/myproj</value>
    </property>
    <property name="username">
        <value>myproj</value>
    </property>
    <property name="password">
        <value>password</value>
    </property>
</bean>

but this isn't a pooled data source, creating JDBC connections on each call.  I used to have this Hibernate config (hibernate.cfg.xml) ...
<hibernate-configuration>
<session-factory>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/myproj</property>
    <property name="hibernate.connection.username">myproj</property>
    <property name="hibernate.connection.password">password</property>
    <property name="hibernate.connection.pool_size">10</property>
    <property name="show_sql">true</property>
    <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
    ...

but because of a bug in Spring 3.1.0, I can't use a hibernate.cfg.xml file when configuring my session factory bean (which I tried to do like this -- snippet from the spring application context file ...)
<bean class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" id="sessionFactory">
    <property name="configLocation">
        <value>classpath:hibernate.cfg.xml</value>
    </property>

A: You can use Apache DBCP, which should be a drop in replacement  something like this:
<bean id="dataSource"
    class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="${jdbc.driverClassName}"/>
    <property name="url" value="${jdbc.url}"/>
    <property name="username" value="${jdbc.username}"/>
    <property name="password" value="${jdbc.password}"/>
    <property name="maxActive" value="10"/>
    <property name="minIdle" value="5"/>
    <!-- SELECT 1 is a simple query that returns 1 row in MySQL -->
    <property name="validationQuery" value="SELECT 1"/>
</bean>

a few things to note

*

*you can configure max number of connections.

*you can configure min number of idle connections.

*a query that will get executed to validate the connection is still valid.

Further options exist to configure when validation happens.

A: If you want to use something mature and performant (e.g. not Apache DBCP), use BoneCP.
Here are the options you can tweak:
<!-- BoneCP configuration -->
<bean id="dataSource" class="com.jolbox.bonecp.BoneCPDataSource" destroy-method="close">
   <property name="driverClass" value="com.mysql.jdbc.Driver" />
   <property name="jdbcUrl" value="jdbc:mysql://127.0.0.1/yourdb" />
   <property name="username" value="root"/>
   <property name="password" value="abcdefgh"/>
   <property name="idleConnectionTestPeriod" value="60"/>
   <property name="idleMaxAge" value="240"/>
   <property name="maxConnectionsPerPartition" value="30"/>
   <property name="minConnectionsPerPartition" value="10"/>
   <property name="partitionCount" value="3"/>
   <property name="acquireIncrement" value="5"/>
   <property name="statementsCacheSize" value="100"/>
   <property name="releaseHelperThreads" value="3"/>
</bean>

BoneCP forum is very active, and committers are quite responsive.
Another one you can look at (would hear about) is C3PO, although BoneCP performs a lot better.

A: Apache DBCP is a widely used pool. But do not use its option testWhileIdle. When enabled, It's background evictor thread locks all new connections serving while checking dead connections. It's unacceptable in any non-toy environment. Besides this, we have no problems with it.
You may read more about pools in this SO thread, but keep in mind, that all flames about "fastest pool" only make sense with specific tuning under specific load.

A: Basically it depends on your application.
There are below conditions(taken from here):

*

*For test or standalone environments outside of a J2EE container, use DriverManagerDataSource

*For use in a J2EE container, it is recommended to use a JNDI DataSource
provided by the container.

*For use of a connection pool datasource outside of a J2EE container, consider
Apache's Jakarta Commons DBCP or C3P0.


text:
Q: Update Package Manager failed, E:type "ain"
Possible Duplicate:
How do I fix this "E:Type '*' is not known on line * in source list …" update error?

The Update Manager failed and gave me this error:

E:Type 'ain' is not known on line 3 in source list /etc/apt/sources.list.d/scopes-packagers-ppa-precise.list

What should I do?
This message came up when I followed the editor's instructions:
$cat /etc/apt/sources.list.d/scopes-packagers-ppa-precise.list
# deb http://ppa.launchpad.net/scopes-packagers/ppa/ubuntu precise main
# deb-src http://ppa.launchpad.net/scopes-packagers/ppa/ubuntu precise main
ain$


text:
Q: C# Github API Unable to create issue Im unable to create an issue on github even though its supposed to work. I do manage to get something back out of it for some reason.
What i am trying to do is uploading a string in json format that has the same feature as POST. Apparently that is not working.
using System;
using System.Collections.Generic;
using System.Net;
using Newtonsoft.Json;

namespace TestProject
{
    class Program
    {
        static void Main(string[] args)
        {
            CreateGithubIssue("Test Issue - C#", "This is just a test to check if i can manage to create an issue from C#.");
        }
        static string username = "someUser";
        static string password = "somePassword";

        static string repoIssueLink = "http://api.github.com/repos/someUser/someRepo/issues";

        public static void CreateGithubIssue(string Title, string Description)
        {

            WebClient webClient = new WebClient();
            webClient.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
            webClient.Credentials = new NetworkCredential(username, password);

            string jsonPost = JsonConvert.SerializeObject(new Issue(Title, Description), Formatting.Indented);

            string response = webClient.UploadString(repoIssueLink, jsonPost);
            Console.WriteLine(response);
            Console.WriteLine(jsonPost);

        }
    }

    public class Issue
    {
        public string title;
        public string body;
        public List<string> assignees;
        public int milestone;
        public List<string> labels;

        public Issue(string title = "Default Title", string body = "Default Body", List<string> assignees = null, int milestone = 0, List<string> labels = null)
        {
            if (assignees == null) assignees = new List<string>();
            if (labels == null) labels = new List<string>();

            this.title = title;
            this.body = body;
            this.assignees = assignees;
            this.milestone = milestone;
            this.labels = labels;
        }
    }
}

The Output:

A: Alright, after asking some other people, i managed to find the answer.
I changed the link to HTTPS and used this code:
WebClient webClient = new WebClient();
webClient.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");

string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(username + ":" + password));

webClient.Headers[HttpRequestHeader.Authorization] = string.Format("Basic {0}", credentials);

string jsonOutput = JsonConvert.SerializeObject(new Issue(Title, Description), Formatting.Indented);

string response = webClient.UploadString(repoIssueLink, jsonOutput);
Console.WriteLine(response);
Console.WriteLine(jsonOutput);


text:
Q: Discriminant is zero iff $f\in K[X]$ has repeated roots I have to prove the statement in the title. Proving from right to left is easy. Now from left to right: $D=(\alpha_1-\alpha_2)^2(\alpha_1-\alpha_3)^2\cdots(\alpha_{n-1}-\alpha_n)^2$ where $\alpha_i$ are the roots of $f$ in the splitting field. Now $D=0$ implies that somewhere in the product we have a zero, so for some $i$ and $j$ we have that $\alpha_i=\alpha_j$. This $\alpha_i$ doesn't have to be in $K$. So we can't conclude deg(gcd($f,f'$))>0.From here I don't know what to do. Can someone give the proof?

A: As you say $\alpha_i$ and $\alpha_j$ are not in $K$, they are in
a algebraic closure $\bar{K}$ of $K$. So ${\sf gcd}_{\bar{K}}(f,f')$ is
nonconstant. But the euclidean algorithm shows that
${\sf gcd}_{\bar{K}}(f,f')={\sf gcd}_{K}(f,f')$, so you are done.


text:
Q: Access current SharePoint Online user's "Liked" & "Saved for later" docs/pages via Microsoft Graph API? At the bottom of most pages/docs in SharePoint Online modern pages, there are "Like" and "Save for later" toggles.
I would like to be able to programmatically retrieve a list of things that were either "Liked" or "Saved for later" by the currently logged in user.
Is this something I can fetch using the Microsoft Graph or does SharePoint have something more readily available for reading this data?

A: The ability to return the list of items of drive items that are followed is currently available in beta
https://learn.microsoft.com/en-us/graph/api/drive-list-following?view=graph-rest-beta
I believe that Like and save for later are different from follow. You may want to try this API to see whether they show up or not.


text:
Q: Why Android ddms not showing emulator or connected devices? This is a screenshot of my DDMS. As you can see there is nothing and I cant find any way to get the devices list or any other functional parts.

I try to reinstall android studio and new sdk but still its not solved. Is there any way to solve this problem?
Thanks

A: I encountered this problem this afternoon, after half day of annoying work, I solved it at last.
The solution is, just delete *.cfg and monitor-workspace in $HOME/.android/.
Below is how I solved the problem.
There's little information about this problem. I guess it is a rare one.
I have tried several ways. First, reinstall the build tools, simply download and replace the tools directory. But it didn't work. And then I reinstalled the Android Studio, still not work either.
But during the procedure I have found that the ddms must have saved some cache in the computer. So I find the place $HOME/.android/ in this website.
After delete all *.cfg(3 or 4) and monitor-workspace, my ddms works well again.
I guess delete all *.cfg is not necessary, just ddms.cfg. But I'm not sure.

A: Go to DDMS perspective -> Devices -> View menu(on right corner) -> Reset adb
If still not working, run this commands in command prompt/terminal
adb kill-server
adb start-server

A: It was broken after latest Android SDK sync using Android Studio. To fix it, launched SDK manager using Eclipse, and installed SDK tools versions 24.01 and 19.1, and removed intermediate results.

A: I had to right click on "DDMS" (perspective button) and click on reset to make it work.

A: I am not sure, but you can try Window menu => show preview (select your necessary window view ).

and another try minimum /Maximum window button press

Thanks

A: Delete the .android directory in user home


text:
Q: Optimization problem when demand curve is a power function A monopolist faces a demand curve $q = p^{-b}, q>0$. The cost function is $c(q) = q^2$. What restrictions must be placed on $b$ for profit maximising solution to exist? Given the restrictions what is the profit maximising output?
I tried the question , first by converting the demand function in to inverse demand function expressing $p$ in terms of $q$.

A: You want to maximize $\Pi = q p - C(q) = p^{-b+1} -p^{-2b}$. There will be a maximum if $b>1$ or $b \leq -1$. The range $b \leq -1$ may experience some economical objections.


text:
Q: Stripe payment discount for a specific Bank Credit Card I am implementing online payment app with Stripe v6.1.1.
Every thing works fine, But now I have to implement, giving certain percentage or amount Discount for specific bank credit card when user do transaction with my application.
I go through Applying  Discounts to Customers, But its doing discounts for all cards for a certain user.
Is anyone know any preferences regarding my doubt? or can anyone guide me to do this?
Thanks

A: Credit Card number contains IIN (issue identification number) WIKIPEDIA
So, you could use it to prepare a discount.
All possible ranges you could also ask from your bank.


text:
Q: Add special character folding to list filter I want to use list.js to live filter a list.
http://www.listjs.com/examples
But I need to add folding. If someone types in 'á' it should find also list items with 'a'.
Any ideas?
I could add a hidden span to ever list item without special chars and then a hidden input that contains the same string the user inputs but without special chars and use those for the list.js but that dies not seem very good...
Or maybe any similar plugins with this functionality?

A: Not super familiar with this library, but this might work (this is using code from the example you linked to):
var options = {
  valueNames: [ 'name', 'born' ],
  plugins: (function() {
      options = options || {};
      return {
        init: function(list) {
          // This method is called on initialization
          events.bind(getByClass(list.listContainer, options.searchClass), 'keyup', function(e) {
                    var target = e.target || e.srcElement; // IE have srcElement
                    list.search(target.value);
                });
        },
        name: options.name || "newsearch",
        search: function(str, columns) {
          var combining = /[\u0300-\u036F]/g;
          var new_str = str.normalize('NFKD').replace(combining, '');
          list.search(new_str, columns);

        }
      };
    })()
};

var userList = new List('users', options);


text:
Q: Issue in dependency injection while implementing Unit testing in ASP.NET MVC 6 My unit testing code is
[TestClass]
public class ProjectControllerTest
{
    Mock<IProjectService> addressRepositoryMock = new Mock<IProjectService>();
    ProjectController controller;

    [TestInitialize]
    public void TestInit()
    {
        controller = new ProjectController(addressRepositoryMock.Object);
    }

    [TestMethod]
    public void TestMethod1()
    {
        var response = controller.GetOverrides(1) as HttpResponseMessage;
    }
}

My controller code is:
[Route("GetOverrides")]
[HttpGet]
public HttpResponseMessage GetOverrides(int Project_Id)
{
        List<OverridesDto> overrides = new List<OverridesDto>();

        try
        {
            overrides = projectService.GetOverrides(Project_Id);
        }
        catch (Exception ex)
        {
            Log.Logger.Error(ex, "Exception:{Ex}", null);
            ThrowHttpExceptionOnError(ex.ToString());
        }

        return Request.CreateResponse(HttpStatusCode.OK, overrides);
 }

I am able to hit method GetOverrides in controller from  unit testing project in debug mode but the problem is I can not hit BAL method projectService.GetOverrides(Project_Id); which is returning null
Please help me out with the above issue.


text:
Q: grant ownership to everybody / remove ownership completely I had a dual boot system with Win10 and Mint 19.3 for some time and I am now in the process of adding a hackintosh to the mix.
I have a NTFS partition to which all three should have access. Between Win and Mint, I never had problems with that, but macOS is complaining about ownership issuess.
How can I remove the ownership restrictions from that partition, so that either macOS can own it or everybody owns it at the same time? And in what way would I compromise the security of my data in doing so, for example when treating with my thunderbird-profile?


text:
Q: Inconcsistent location when radius decreased in HERE Geocoding API Using the HERE geocoding API (version 6.2) to get LinkIDs from a given location(lat,long).
Example: same coordinates with different radius

*

*base-URL used for queries: https://reverse.geocoder.api.here.com/6.2/

*location: lat = 37.399643, long = -121.953085

*proximity: radius = 50 meters;

Request 1: 50m radius
With this radius the response returns the appropriate LinkIDs at location.

*

*query-param is prox=37.399643,-121.953085,50:

/reversegeocode.json?prox=37.399643,-121.953085,50&mode=retrieveAddresses&locationAttributes=linkInfo&gen=9&app_id={AppID}&app_code={AppCode}

The above query works as expected. See below:

Request 2: 5m radius
Now, if we decrease the proximity radius to 5m then HERE API's response jumps to a completely different location.

*

*query-param is prox=37.399643,-121.953085,5:

/reversegeocode.json?prox=37.399643,-121.953085,5&mode=retrieveAddresses&locationAttributes=linkInfo&gen=9&app_id={AppID}&app_code={AppCode}

The above query shows a different, unexpected location.
It's completely wrong. The spot highlighted is actually 5-6 miles away from the correct location.
See image below:

Inconsistency suspected
From observation after a few tests, this (unexpected) inconsistent location seems to be returned for proximity radius values < 30 meters.
Can anyone explain this behavior (is it a bug)?

A: Reverse Geocoder returns street results or addresses on a street only if the street geometry is within the given radius.
Otherwise it falls back to area level results and returns the center of the area, where central point of proximity is located.
Example: (37.399643,-121.953085); Proximity distance = 22m
With radius 22 the proximity still contains a street geometry.
Reverse Geocoder returns one street result which is "ReferenceId": "1121660494".

Example: (37.399643,-121.953085); Proximity distance = 21m;
With radius 21 – no one street is within the radius. Therefore the Geocoder returns the link that central point of city – Santa Clara is on it.