text:
Q: Sequelize composite unique constraint Defining model:
export default function(sequelize, DataTypes) {
   return sequelize.define('Item', {
       minor: DataTypes.INTEGER,
       major: DataTypes.INTEGER,
   });
}

Can I define the pair minor and major as a composite UNIQUE constraint?

A: I solved this by using addConstraint(...):
await queryInterface.addConstraint('Item', {
  fields: ['minor', 'major'],
  type: 'unique',
  name: 'unique_constraint_name'
});

This is as of at least v6+.

A: Recently, in V4, Sequelize has a method addConstraint on the query interface:
queryInterface.addConstraint('Items', {
  fields: ['minor', 'major'],
  type: 'unique',
  name: 'custom_unique_constraint_name'
});

A: queryInterface.createTable(
  'Item',
  {
    minor: {
      type: Sequelize.INTEGER,
    },
    major: {
      type: Sequelize.INTEGER,
    }
  },
  {
    uniqueKeys: {
      Items_unique: {
        fields: ['minor', 'major']
      }
    }
  }
);

A: Here is the simple answer:
major: { type: DataTypes.INTEGER, unique: 'compositeIndex'},
minor: { type: DataTypes.INTEGER, unique: 'compositeIndex'}

source: https://sequelize.org/master/manual/model-basics.html#column-options

// Creating two objects with the same value will throw an error. > The unique property can be either a
// boolean, or a string. If you provide the same string for > multiple columns, they will form a
// composite unique key.
uniqueOne: { type: DataTypes.STRING,  unique: 'compositeIndex' },
uniqueTwo: { type: DataTypes.INTEGER, unique: 'compositeIndex' },

You can also create a unique constraint through belongsToMany associations if it's a join table:
Major = sequelize.define('major', {})
Minor = sequelize.define('minor', {})

Major.belongsToMany(Project)
Minor.belongsToMany(User)

Source: http://docs.sequelizejs.com/en/v3/docs/associations/
In my case, I wanted to find a way to enforce this with my migration. I did this by appending a raw sql query at the end of my up function:
  up: function(queryInterface, Sequelize) {
return queryInterface.createTable('Item', {
  major: {
    allowNull: false,
    type: Sequelize.INTEGER
  },
  minor: {
    allowNull: false,
    type: Sequelize.INTEGER
  },
})
.then(function() {
  return queryInterface.sequelize.query(
    'ALTER TABLE `Item` ADD UNIQUE `unique_index`(`major`, `minor`)'
  );
});

Related Questions:
Sequelize, foreign keys as composite primary key
Unique constraint across foreign keys in Sequelize model

A: You can use something like this:
module.exports = {
  up: (queryInterface, Sequelize) => {
    return queryInterface.sequelize.transaction(t => {
      return queryInterface.createTable('item',
        {
          minor: {
            type: Sequelize.INTEGER,
          },
          major: {
            type: Sequelize.INTEGER,
          }
        }, { transaction: t }
      ).then(() => {
        return queryInterface.addConstraint(
          'item',
          ['minor', 'major'],
          {
            type: 'unique',
            name: 'Items_unique'
          },
          {
            transaction: t
          }
        );
      });
    });
  },
  down: (queryInterface, Sequelize) => {
    return queryInterface.dropTable('item');
  }
}

A: For ES6 Migrations
const item = {
  up: (queryInterface, Sequelize) => queryInterface.createTable('Items', {
    minor: {
      type: Sequelize.INTEGER,
      allowNull: false,
    },
    major: {
      type: Sequelize.INTEGER,
      allowNull: false,
    },
  }).then(() => queryInterface.addConstraint('Items', ['minor', 'major'], {
    type: 'unique',
    name: 'composite_key_name'
  })),
  down: queryInterface => queryInterface.dropTable('Items')
};

export default item;

A: sequelize.define('', {}, {indexes: [ { unique: true
Another way besides Jake's answer:
const Item = sequelize.define('Item', {
    minor: DataTypes.INTEGER,
    major: DataTypes.INTEGER,
  }, {
    indexes: [
      {
        fields: ['minor', 'major'],
        unique: true,
      }
    ]
  }
)

which automatically creates the name based on the fields, SQLite query:
CREATE TABLE IF NOT EXISTS `Items` (
  `id` INTEGER PRIMARY KEY AUTOINCREMENT,
  `minor` INTEGER,
  `major` INTEGER,
  `createdAt` DATETIME NOT NULL,
  `updatedAt` DATETIME NOT NULL
);
PRAGMA INDEX_LIST(`Items`)
CREATE UNIQUE INDEX `items_minor_major` ON `Items` (`minor`, `major`)

Documented at: https://sequelize.org/master/class/lib/model.js~Model.html#static-method-init

options.indexes[].unique:
Should the index by unique? Can also be triggered by setting type to UNIQUE

The approach on Jake's answer:
const Item = sequelize.define('Item', {
  minor: { type: DataTypes.INTEGER, unique: 'asdf' },
  major: { type: DataTypes.INTEGER, unique: 'asdf' },
})

produces instead an anonymous UNIQUE constraint (which automatically implies an index I believe), so both are very similar except for the name:
CREATE TABLE IF NOT EXISTS `Items` (
  `id` INTEGER PRIMARY KEY AUTOINCREMENT,
  `minor` INTEGER,
  `major` INTEGER,
  `createdAt` DATETIME NOT NULL,
  `updatedAt` DATETIME NOT NULL,
  UNIQUE (`minor`, `major`)
);
PRAGMA INDEX_LIST(`Items`)
PRAGMA INDEX_INFO(`sqlite_autoindex_Items_1`)

PostgreSQL queries are analogous.
Full runnable example:
main.js
#!/usr/bin/env node
const assert = require('assert')
const path = require('path')
const { DataTypes, Sequelize } = require('sequelize')
let sequelize
if (process.argv[2] === 'p') {
  sequelize = new Sequelize('tmp', undefined, undefined, {
    dialect: 'postgres',
    host: '/var/run/postgresql',
  })
} else {
  sequelize = new Sequelize({
    dialect: 'sqlite',
    storage: 'tmp.sqlite'
  })
}
;(async () => {
const Item = sequelize.define('Item', {
    minor: DataTypes.INTEGER,
    major: DataTypes.INTEGER,
  }, {
    indexes: [
      {
        fields: ['minor', 'major'],
        unique: true,
      }
    ]
  }
)
await Item.sync({ force: true })
await Item.create({ minor: 1, major: 1 })
await Item.create({ minor: 1, major: 2 })
let threw = false
try {
  await Item.create({ minor: 1, major: 2 })
} catch (e) {
  threw = true
}
assert(threw)
})().finally(() => { return sequelize.close() })

package.json
{
  "name": "tmp",
  "private": true,
  "version": "1.0.0",
  "dependencies": {
    "pg": "8.5.1",
    "pg-hstore": "2.3.3",
    "sequelize": "6.14.0",
    "sql-formatter": "4.0.2",
    "sqlite3": "5.0.2"
  }
}

tested on PostgreSQL 13.5.


text:
Q: Get value of selected value in listbox after submit I have a listbox and a submit button, which fires an event when clicked. In the event handler I need the information which element in listbox is now selected. The problem is that every time the index is -1??
<form id="form1" runat="server">
    <div>

        <asp:ListBox ID="ListBox1" runat="server" Height="400px" Width="200px"></asp:ListBox>

    </div>
        <asp:Button ID="Button1" runat="server" Height="60px" Text="Send"  Width="100px" OnClick="send"/>

    </form>

This is the code in the .aspx file.

A: You can use GetSelectedIndices() method to get the selected indexes.
int[] selectedItemsIndexes = myListbox.GetSelectedIndices();

or you can use
foreach(Object selecteditem in listBox1.SelectedItems)
{

}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Dynamic versus explicit querys in sql-server 2005 Can anybody explain this?
Theoretically both are the same query but they give different answers.
a)
declare @date varchar(10)

set date = '03/02/2013'

select count(*) from table1 where (from <= @date) and (@date <= to)

b)
declare @date varchar(10)

set date = '03/02/2013'

set @sqlstring = 'select count(*) from table1 where (from <= ' + @date + ') and (' + @date + ' <= to)'

exec sp_executeSql @sqlstring

The first set of sentences gives '2' as a result, and this is the correct answer, but in the second set of sentences, I have the same query executed dynamically through a string, but the answer is '0'.

A: In the first, the effective SQL is
select count(*) from table1 where (from <= '03/02/2013') and ('03/02/2013' <= to)

In the second one, the effective SQL is
select count(*) from table1 where (from <= 03/02/2013) and (03/02/2013 <= to)

That is, the first one uses variables that do not require delimiters. In the second one, you have an expression of integer constants which has "constant folding" applied. Integer 3 divided by 2 divided by 2013 = 0 = 01 Jan 1900 when changed to a date
You'd need this:
set @sqlstring = 'select count(*) from table1
    where (from <= ''' + @date + ''') and (''' + @date + ''' <= to)'

Note that you should use yyyymmdd or ISO 8601 dates for consistency and clarity

*

*How to prevent out-of-range datetime value error?


text:
Q: Why is it bad practice to call System.gc()? After answering a question about how to force-free objects in Java (the guy was clearing a 1.5GB HashMap) with System.gc(), I was told it's bad practice to call System.gc() manually, but the comments were not entirely convincing. In addition, no one seemed to dare to upvote, nor downvote my answer.
I was told there that it's bad practice, but then I was also told that garbage collector runs don't systematically stop the world anymore, and that it could also effectively be used by the JVM only as a hint, so I'm kind of at loss.
I do understand that the JVM usually knows better than you when it needs to reclaim memory. I also understand that worrying about a few kilobytes of data is silly. I also understand that even megabytes of data isn't what it was a few years back. But still, 1.5 gigabytes? And you know there's like 1.5 GB of data hanging around in memory; it's not like it's a shot in the dark. Is System.gc() systematically bad, or is there some point at which it becomes okay?
So the question is actually double:

*

*Why is or isn't it bad practice to call System.gc()? Is it really merely a hint to the JVM under certain implementations, or is it always a full collection cycle? Are there really garbage collector implementations that can do their work without stopping the world? Please shed some light over the various assertions people have made in the comments to my answer.

*Where's the threshold? Is it never a good idea to call System.gc(), or are there times when it's acceptable? If so, what are those times?

A: GC efficiency relies on a number of heuristics. For instance, a common heuristic is that write accesses to objects usually occur on objects which were created not long ago. Another is that many objects are very short-lived (some objects will be used for a long time, but many will be discarded a few microseconds after their creation).
Calling System.gc() is like kicking the GC. It means: "all those carefully tuned parameters, those smart organizations, all the effort you just put into allocating and managing the objects such that things go smoothly, well, just drop the whole lot, and start from scratch". It may improve performance, but most of the time it just degrades performance.
To use System.gc() reliably(*) you need to know how the GC operates in all its fine details. Such details tend to change quite a bit if you use a JVM from another vendor, or the next version from the same vendor, or the same JVM but with slightly different command-line options. So it is rarely a good idea, unless you want to address a specific issue in which you control all those parameters. Hence the notion of "bad practice": that's not forbidden, the method exists, but it rarely pays off.
(*) I am talking about efficiency here. System.gc() will never break a correct Java program. It will neither conjure extra memory that the JVM could not have obtained otherwise: before throwing an OutOfMemoryError, the JVM does the job of System.gc(), even if as a last resort.

A: Lots of people seem to be telling you not to do this. I disagree. If, after a large loading process like loading a level, you believe that:

*

*You have a lot of objects that are unreachable and may not have been gc'ed. and

*You think the user could put up with a small slowdown at this point

there is no harm in calling System.gc().  I look at it like the c/c++ inline keyword. It's just a hint to the gc that you, the developer, have decided that time/performance is not as important as it usually is and that some of it could be used reclaiming memory.
Advice to not rely on it doing anything is correct. Don't rely on it working, but giving the hint that now is an acceptable time to collect is perfectly fine. I'd rather waste time at a point in the code where it doesn't matter (loading screen) than when the user is  actively interacting with the program (like during a level of a game.)
There is one time when i will force collection: when attempting to find out is a particular object leaks (either native code or large, complex callback interaction. Oh and any UI component that so much as glances at Matlab.) This should never be used in production code.

A: Maybe I write crappy code, but I've come to realize that clicking the trash-can icon on eclipse and netbeans IDEs is a 'good practice'.

A: People have been doing a good job explaining why NOT to use, so I will tell you a couple situations where you should use it:
(The following comments apply to Hotspot running on Linux with the CMS collector, where I feel confident saying that System.gc() does in fact always invoke a full garbage collection).

*

*After the initial work of starting up your application, you may be a terrible state of memory usage. Half your tenured generation could be full of garbage, meaning that you are that much closer to your first CMS. In applications where that matters, it is not a bad idea to call System.gc() to "reset" your heap to the starting state of live data.

*Along the same lines as #1, if you monitor your heap usage closely, you want to have an accurate reading of what your baseline memory usage is. If the first 2 minutes of your application's uptime is all initialization, your data is going to be messed up unless you force (ahem... "suggest") the full gc up front.

*You may have an application that is designed to never promote anything to the tenured generation while it is running. But maybe you need to initialize some data up-front that is not-so-huge as to automatically get moved to the tenured generation. Unless you call System.gc() after everything is set up, your data could sit in the new generation until the time comes for it to get promoted. All of a sudden your super-duper low-latency, low-GC application gets hit with a HUGE (relatively speaking, of course) latency penalty for promoting those objects during normal operations.

*It is sometimes useful to have a System.gc call available in a production application for verifying the existence of a memory leak. If you know that the set of live data at time X should exist in a certain ratio to the set of live data at time Y, then it could be useful to call System.gc() a time X and time Y and compare memory usage.

A: The reason everyone always says to avoid System.gc() is that it is a pretty good indicator of fundamentally broken code.  Any code that depends on it for correctness is certainly broken; any that rely on it for performance are most likely broken.
You don't know what sort of garbage collector you are running under.  There are certainly some that do not "stop the world" as you assert, but some JVMs aren't that smart or for various reasons (perhaps they are on a phone?) don't do it.  You don't know what it's going to do.
Also, it's not guaranteed to do anything.  The JVM may just entirely ignore your request.
The combination of "you don't know what it will do," "you don't know if it will even help," and "you shouldn't need to call it anyway" are why people are so forceful in saying that generally you shouldn't call it.  I think it's a case of "if you need to ask whether you should be using this, you shouldn't"

EDIT to address a few concerns from the other thread:
After reading the thread you linked, there's a few more things I'd like to point out.
First, someone suggested that calling gc() may return memory to the system.  That's certainly not necessarily true - the Java heap itself grows independently of Java allocations.
As in, the JVM will hold memory (many tens of megabytes) and grow the heap as necessary.  It doesn't necessarily return that memory to the system even when you free Java objects; it is perfectly free to hold on to the allocated memory to use for future Java allocations.
To show that it's possible that System.gc() does nothing, view
JDK bug 6668279
and in particular that there's a -XX:DisableExplicitGC VM option:

By default calls to System.gc() are enabled (-XX:-DisableExplicitGC). Use -XX:+DisableExplicitGC to disable calls to System.gc(). Note that the JVM still performs garbage collection when necessary.

A: Some of what I am about to write is simply a summarization of what has already been written in other answers, and some is new.
The question "Why is it bad practice to call System.gc()?" does not compute. It assumes that it is bad practice, while it is not. It greatly depends on what you are trying to accomplish.
The vast majority of programmers out there have no need for System.gc(), and it will never do anything useful to them in the vast majority of use cases. So, for the majority, calling it is bad practice because it will not do whatever it is that they think it will do, it will only add overhead.
However, there are a few rare cases where invoking System.gc() is actually beneficial:

*

*When you are absolutely sure that you have some CPU time to spare now, and you want to improve the throughput of code that will run later. For example, a web server that discovers that there are no pending web requests at the moment can initiate garbage collection now, so as to reduce the chances that garbage collection will be needed during the processing of a barrage of web requests later on. (Of course this can hurt if a web request arrives during collection, but the web server could be smart about it and abandon collection if a request comes in.) Desktop GUIs are another example: on the idle event (or, more broadly, after a period of inactivity,) you can give the JVM a hint that if it has any garbage collection to do, now is better than later.

*When you want to detect memory leaks. This is often done in combination with a debug-mode-only finalizer, or with the java.lang.ref.Cleaner class from Java 9 onwards. The idea is that by forcing garbage collection now, and thus discovering memory leaks now as opposed to some random point in time in the future, you can detect the memory leaks as soon as possible after they have happened, and therefore be in a better position to tell precisely which piece of code has leaked memory and why. (Incidentally, this is also one of, or perhaps the only, legitimate use cases for finalizers or the Cleaner. The practice of using finalization for recycling of unmanaged resources is flawed, despite being very widespread and even officially recommended, because it is non-deterministic. For more on this topic, read this: https://blog.michael.gr/2021/01/object-lifetime-awareness.html)

*When you are measuring the performance of code, (benchmarking,) in order to reduce/minimize the chances of garbage collection occurring during the benchmark, or in order to guarantee that whatever overhead is suffered due to garbage collection during the benchmark is due to garbage generated by the code under benchmark, and not by unrelated code. A good benchmark always starts with an as thorough as possible garbage collection.

*When you are measuring the memory consumption of code, in order to determine how much garbage is generated by a piece of code. The idea is to perform a full garbage collection so as to start in a clean state, run the code under measurement, obtain the heap size, then do another full garbage collection, obtain the heap size again, and take the difference.  (Incidentally, the ability to temporarily suppress garbage collection while running the code under measurement would be useful here, alas, the JVM does not support that. This is deplorable.)
Note that of the above use cases, only one is in a production scenario; the rest are in testing / diagnostics scenarios.
This means that System.gc() can be quite useful under some circumstances, which in turn means that it being "only a hint" is problematic.
(For as long as the JVM is not offering some deterministic and guaranteed means of controlling garbage collection, the JVM is broken in this respect.)
Here is how you can turn System.gc() into a bit less of a hint:
private static void runGarbageCollection()
{
    for( WeakReference<Object> ref = new WeakReference<>( new Object() ); ; )
    {
        System.gc(); //optional
        Runtime.getRuntime().runFinalization(); //optional
        if( ref.get() == null )
            break;
        Thread.yield();
    }
}

This still does not guarantee that you will get a full GC, but it gets a lot closer. Specifically, it will give you some amount of garbage collection even if the -XX:DisableExplicitGC VM option has been used. (So, it truly uses System.gc() as a hint; it does not rely on it.)

A: It has already been explained that calling system.gc() may do nothing, and that any code that "needs" the garbage collector to run is broken.
However, the pragmatic reason that it is bad practice to call System.gc() is that it is inefficient.  And in the worst case, it is horribly inefficient!  Let me explain.
A typical GC algorithm identifies garbage by traversing all non-garbage objects in the heap, and inferring that any object not visited must be garbage.  From this, we can model the total work of a garbage collection consists of one part that is proportional to the amount of live data, and another part that is proportional to the amount of garbage; i.e. work = (live * W1 + garbage * W2).
Now suppose that you do the following in a single-threaded application.
System.gc(); System.gc();

The first call will (we predict) do (live * W1 + garbage * W2) work, and get rid of the outstanding garbage.
The second call will do (live* W1 + 0 * W2) work and reclaim nothing.  In other words we have done (live * W1) work and achieved absolutely nothing.
We can model the efficiency of the collector as the amount of work needed to collect a unit of garbage; i.e. efficiency = (live * W1 + garbage * W2) / garbage.  So to make the GC as efficient as possible, we need to maximize the value of garbage when we run the GC; i.e. wait until the heap is full.  (And also, make the heap as big as possible.  But that is a separate topic.)
If the application does not interfere (by calling System.gc()), the GC will wait until the heap is full before running, resulting in efficient collection of garbage1.  But if the application forces the GC to run, the chances are that the heap won't be full, and the result will be that garbage is collected inefficiently.  And the more often the application forces GC, the more inefficient the GC becomes.
Note: the above explanation glosses over the fact that a typical modern GC partitions the heap into "spaces", the GC may dynamically expand the heap, the application's working set of non-garbage objects may vary and so on.  Even so, the same basic principal applies across the board to all true garbage collectors2.  It is inefficient to force the GC to run.

1 - This is how the "throughput" collector works.  Concurrent collectors such as CMS and G1 use different criteria to decide when to start the garbage collector.
2 - I'm also excluding memory managers that use reference counting exclusively, but no current Java implementation uses that approach ... for good reason.

A: This is a very bothersome question, and I feel contributes to many being opposed to Java despite how useful of a language it is.
The fact that you can't trust "System.gc" to do anything is incredibly daunting and can easily invoke "Fear, Uncertainty, Doubt" feel to the language.
In many cases, it is nice to deal with memory spikes that you cause on purpose before an important event occurs, which would cause users to think your program is badly designed/unresponsive.
Having ability to control the garbage collection would be very a great education tool, in turn improving people's understanding how the garbage collection works and how to make programs exploit it's default behavior as well as controlled behavior.
Let me review the arguments of this thread.

*

*It is inefficient:

Often, the program may not be doing anything and you know it's not doing anything because of the way it was designed. For instance, it might be doing some kind of long wait with a large wait message box, and at the end it may as well add a call to collect garbage because the time to run it will take a really small fraction of the time of the long wait but will avoid gc from acting up in the middle of a more important operation.

*It is always a bad practice and indicates broken code.

I disagree, it doesn't matter what garbage collector you have. Its' job is to track garbage and clean it.
By calling the gc during times where usage is less critical, you reduce odds of it running when your life relies on the specific code being run but instead it decides to collect garbage.
Sure, it might not behave the way you want or expect, but when you do want to call it, you know nothing is happening, and user is willing to tolerate slowness/downtime. If the System.gc works, great! If it doesn't, at least you tried. There's simply no down side unless the garbage collector has inherent side effects that do something horribly unexpected to how a garbage collector is suppose to behave if invoked manually, and this by itself causes distrust.

*It is not a common use case:

It is a use case that cannot be achieved reliably, but could be if the system was designed that way. It's like making a traffic light and making it so that some/all of the traffic lights' buttons don't do anything, it makes you question why the button is there to begin with, javascript doesn't have garbage collection function so we don't scrutinize it as much for it.

*The spec says that System.gc() is a hint that GC should run and the VM is free to ignore it.

what is a "hint"? what is "ignore"? a computer cannot simply take hints or ignore something, there are strict behavior paths it takes that may be dynamic that are guided by the intent of the system. A proper answer would include what the garbage collector is actually doing, at implementation level, that causes it to not perform collection when you request it. Is the feature simply a nop? Is there some kind of conditions that must me met? What are these conditions?
As it stands, Java's GC often seems like a monster that you just don't trust. You don't know when it's going to come or go, you don't know what it's going to do, how it's going to do it. I can imagine some experts having better idea of how  their Garbage Collection works on per-instruction basis, but vast majority simply hopes it "just works", and having to trust an opaque-seeming algorithm to do work for you is frustrating.
There is a big gap between reading about something or being taught something, and actually seeing the implementation of it, the differences across systems, and being able to play with it without having to look at the source code. This creates confidence and feeling of mastery/understanding/control.
To summarize, there is an inherent problem with the answers "this feature might not do anything, and I won't go into details how to tell when it does do something and when it doesn't and why it won't or will, often implying that it is simply against the philosophy to try to do it, even if the intent behind it is reasonable".
It might be okay for Java GC to behave the way it does, or it might not, but to understand it, it is difficult to truly follow in which direction to go to get a comprehensive overview of what you can trust the GC to do and not to do, so it's too easy simply distrust the language, because the purpose of a language is to have controlled behavior up to philosophical extent(it's easy for a programmer, especially novices to fall into existential crisis from certain system/language behaviors) you are capable of tolerating(and if you can't, you just won't use the language until you have to), and more things you can't control for no known reason why you can't control them is inherently harmful.

A: Sometimes (not often!) you do truly know more about past, current and future memory usage then the run time does.   This does not happen very often, and I would claim never in a web application while normal pages are being served.
Many year ago I work on a report generator, that

*

*Had a single thread

*Read the "report request" from a queue

*Loaded the data needed for the report from the database

*Generated the report and emailed it out.

*Repeated forever, sleeping when there were no outstanding requests.

*It did not reuse any data between reports and did not do any cashing.

Firstly as it was not real time and the users expected to wait for a report, a delay while the GC run was not an issue, but we needed to produce reports at a rate that was faster than they were requested.
Looking at the above outline of the process, it is clear that.

*

*We know there would be very few live objects just after a report had been emailed out, as the next request had not started being processed yet.

*It is well known that the cost of running a garbage collection cycle is depending on the number of live objects, the amount of garbage has little effect on the cost of a GC run.

*That when the queue is empty there is nothing better to do then run the GC.

Therefore clearly it was well worth while doing a GC run whenever the request queue was empty; there was no downside to this.
It may be worth doing a GC run after each report is emailed, as we know this is a good time for a GC run.   However if the computer had enough ram, better results would be obtained by delaying the GC run.
This behaviour was configured on a per installation bases, for some customers enabling a forced GC after each report greatly speeded up the production of reports.   (I expect this was due to low memory on their server and it running lots of other processes, so hence a well time forced GC reduced paging.)
We never detected an installation that did not benefit from a forced GC run every time the work queue was empty.
But, let be clear, the above is not a common case.
These days I would be more inclined to run each report in a seperate process leaving the operating system to clear up memory rather then the garbage collector and having the custom queue manager service use mulple working processes on large servers.

A: Yes, calling System.gc() doesn't guarantee that it will run, it's a request to the JVM that may be ignored. From the docs:

Calling the gc method suggests that the Java Virtual Machine expend effort toward recycling unused objects

It's almost always a bad idea to call it because the automatic memory management usually knows better than you when to gc. It will do so when its internal pool of free memory is low, or if the OS requests some memory be handed back.
It might be acceptable to call System.gc() if you know that it helps. By that I mean you've thoroughly tested and measured the behaviour of both scenarios on the deployment platform, and you can show it helps. Be aware though that the gc isn't easily predictable - it may help on one run and hurt on another.

A: First, there is a difference between spec and reality. The spec says that System.gc() is a hint that GC should run and the VM is free to ignore it. The reality is, the VM will never ignore a call to System.gc().
Calling GC comes with a non-trivial overhead to the call and if you do this at some random point in time it's likely you'll see no reward for your efforts. On the other hand, a naturally triggered collection is very likely to recoup the costs of the call. If you have information that indicates that a GC should be run than you can make the call to System.gc() and you should see benefits. However, it's my experience that this happens only in a few edge cases as it's very unlikely that you'll have enough information to understand if and when System.gc() should be called.
One example listed here, hitting the garbage can in your IDE. If you're off to a meeting why not hit it. The overhead isn't going to affect you and heap might be cleaned up for when you get back. Do this in a production system and frequent calls to collect will bring it to a grinding halt! Even occasional calls such as those made by RMI can be disruptive to performance.

A: In my experience, using System.gc() is effectively a platform-specific form of optimization (where "platform" is the combination of hardware architecture, OS, JVM version and possible more runtime parameters such as RAM available), because its behaviour, while roughly predictable on a specific platform, can (and will) vary considerably between platforms.
Yes, there are situations where System.gc() will improve (perceived) performance. On example is if delays are tolerable in some parts of your app, but not in others (the game example cited above, where you want GC to happen at the start of a level, not during the level).
However, whether it will help or hurt (or do nothing) is highly dependent on the platform (as defined above).
So I think it is valid as a last-resort platform-specific optimization (i.e. if other performance optimizations are not enough). But you should never call it just because you believe it might help(without specific benchmarks), because chances are it will not.

A: *

*Since objects are dynamically allocated by using the new operator,
you might be wondering how such objects are destroyed and their
memory released for later reallocation.

*In some languages, such as C++, dynamically allocated objects must
be manually released by use of a delete operator.

*Java takes a different approach; it handles deallocation for you
automatically.

*The technique that accomplishes this is called garbage collection.
It works like this: when no references to an object exist, that object is assumed to be no longer needed, and the memory occupied by the object can be reclaimed. There is no explicit need to destroy objects as in C++.

*Garbage collection only occurs sporadically (if at all) during the
execution of your program.

*It will not occur simply because one or more objects exist that are
no longer used.

*Furthermore, different Java run-time implementations will take
varying approaches to garbage collection, but for the most part, you
should not have to think about it while writing your programs.


text:
Q: Incrementing days in two different rows I have two rows with date fields and I want to increment the days according to the entry I gave in the textbox field in the both rows on one go. And want to save that values in databse. I have tried the following code.
code

    <input type="text" class="form-control" name="lt" id="lt" value="" placeholder="" autocomplete="off">

    <input type="date" class="form-control" name="actual_engg[]" id="actual_engg" onchange="getdate()" value="<?php echo $subshow['actual_engg'];?>">
    <input type="text" class="form-control" name="ipd[]" id="ipd" value="<?php echo $subshow['indus_plan'];?>">

                         <input type="submit" class="btn btn-primary" name="tasksub" id="tasksub"  placeholder="Assign"/>


text:
Q: Jstl error (array display) I'm following a video about web development jee. The programmer used the "jstl" library to do the array display (img1)the image from the video
But i get this one if i run my application ! (img 2)
my page
code:
            <c:forEach items="${model.produits}" var="p">

                    ${p.reference}
                    ${p.designation}
                    ${p.prix}
                    ${p.quantite}

            </c:forEach>

A: The EL (Expression Language) is set to be ignored in your deployment descriptor or JSP.
You can look:

*

*In the JSP for <%@ page isELIgnored="true" %> and/or

*In the deployment descriptor web.xml for <el-ignored>true</el-ignored>
If you find this. Turn it to false.
The Documentation say:

Each JSP page has a default mode for EL expression evaluation. The
  default value varies depending on the version of the web application
  deployment descriptor. The default mode for JSP pages delivered with a
  Servlet 2.4 descriptor is to evaluate EL expressions; this
  automatically provides the default that most applications want. The
  default mode for JSP pages delivered using a descriptor from Servlet
  2.3 or before is to ignore EL expressions; this provides backward compatibility.

So can check at the top of web.xml, if you can find web-app_2_3.xsd or less, you have to add this in the deployment descriptor:
<jsp-config>
  <jsp-property-group>
      <url-pattern>*.jsp</url-pattern>
      <el-ignored>false</el-ignored>
   </jsp-property-group>
</jsp-config>


text:
Q: Select Tag Helper with grouping elements Does Select tag helper in ASP.NET MVC Core have grouping option such as the one shown below. I'm using latest versions of ASP.NET Core and VS2015:
<select>
  <optgroup label="Swedish Cars">
    <option value="volvo">Volvo</option>
    <option value="saab">Saab</option>
  </optgroup>
  <optgroup label="German Cars">
    <option value="mercedes">Mercedes</option>
    <option value="audi">Audi</option>
  </optgroup>
</select>

Display:

A: Yes. The SELECT tag helper can render opt groups for the options. All you have to do is to provide a Group property value when you create a new SelectListItem object.
var swedish = new SelectListGroup { Name="Swedish" };
var german = new SelectListGroup { Name="German" };

var optionItems = new List<SelectListItem>
{
  new SelectListItem { Value="vovlo", Text = "Volvo", Group = swedish },
  new SelectListItem { Value="saab", Text="Saab", Group = swedish },
  new SelectListItem { Value="mercedes", Text="Mercedes", Group = german } ,
  new SelectListItem { Value="audi", Text ="Audi", Group = german }
};
// use optionItems for asp-items when using SELECT tag helper

A: The select tag helper has an items param, where you pass an IEnumerable<SelectListItem>. SelectListItem has a property, Group, which is an instance of SelectListGroup. In other words, this is really about how you set up your list of SelectListItems. The tag helper should generate optgroups if you have them defined.


text:
Q: How to get data from Firestore data on a website hosted on secure HTTPS protocol using Javascript I am using Firestore to save some customer data, and I populate it on my website. When I use "HTTP" protocol, I receive data from Firestore effortlessly. However, as soon as I switch over to the secure protocol, "HTTPS," I stop receiving the documents saved in Firestore.
Please help me understand how do I receive data in my secure "HTTPS" based website.
I have tried running my code on a Non-Secure "HTTP" based website, and the entire code is working just fine in that case. The issue appears when I switch to "HTTPS."
My Firestore Config File (I copied this exactly from GCP setup guide):
const config = {
    apiKey: "API-KEY",
    authDomain: "MY-DOMAIN.firebaseapp.com",
    databaseURL: "https://MY-DOMAIN.firebaseio.com",
    projectId: "MY-DOMAIN",
    storageBucket: "MY-DOMAIN.appspot.com",
    messagingSenderId: "SENDER-ID"
};
const default_app = firebase.initializeApp(config);
const db = firebase.firestore();
const settings = {/* your settings... */ timestampsInSnapshots: true };
db.settings(settings);

Here is the code I am using to populate my results:
var doc_ref = db.collection(collection).doc(document)

doc_ref.get().then(function(doc){
    if (doc.exists) {
        // do something
    } else {
        console.log('Document not Found')
    }
}

I expect to get data from Firestore on HTTPS secure website


text:
Q: \pause not working properly, going backwards So I would like to use \pause in its normal way, but it is revealing stuff backwards and I don't know why!!!!
\documentclass[usenames, dvipsnames]{beamer}
\usepackage{amsmath, amssymb, amsthm, mathtools, commath, array, tcolorbox, cancel, caption, subcaption, graphicx, multicol,beamerthemesplit,stmaryrd,comment, color,movie15,animate}

\usepackage[latin1]{inputenc}

\usetheme{Madrid}

\begin{document}
    %6 slide
\begin{frame}{Introducción: La función gamma}
\begin{align*}
\Gamma(x) = \int_0^\infty e^{-t}t^{x-1} dt \\\pause
\text{Integrando por partes, obtenemos:}\\
\Gamma(x+1) &= \int_0^\infty e^{-t}t^{x}dt\\ \pause
&= \lim_{B \rightarrow \infty} \int_0^B e^{-t}t^{x}dt\\ \pause
&=\lim_{B \rightarrow \infty} \Big[-e^{-t}t^x \Big|_0^B + x \int_0^B e^{-t}t^{x-1}dt \Big] \\ \pause
&= x \lim_{B \rightarrow \infty} \int_0^B e^{-t}t^{x-1}dt\\ \pause
&= x\Gamma(x)
\end{align*}
\end{frame}
\end{document}

A: align gets executed twice and you need to make \pause keep out of the way of the first run:
\documentclass[usenames, dvipsnames]{beamer}
\usepackage{amsmath, amssymb, amsthm, mathtools, commath, array, tcolorbox, cancel, caption, subcaption, graphicx, multicol,beamerthemesplit,stmaryrd,comment, color,movie15,animate}

\usepackage[latin1]{inputenc}

\usetheme{Madrid}

\makeatletter
\def\zzpause{\ifmeasuring@\else\expandafter\pause\fi}
\makeatother
\begin{document}
    %6 slide
\begin{frame}{Introducción: La función gamma}
\begin{align*}
\Gamma(x) = \int_0^\infty e^{-t}t^{x-1} dt \\\zzpause
\text{Integrando por partes, obtenemos:}\\
\Gamma(x+1) &= \int_0^\infty e^{-t}t^{x}dt\\ \zzpause
&= \lim_{B \rightarrow \infty} \int_0^B e^{-t}t^{x}dt\\ \zzpause
&=\lim_{B \rightarrow \infty} \Big[-e^{-t}t^x \Big|_0^B + x \int_0^B e^{-t}t^{x-1}dt \Big] \\ \zzpause
&= x \lim_{B \rightarrow \infty} \int_0^B e^{-t}t^{x-1}dt\\ \zzpause
&= x\Gamma(x)
\end{align*}
\end{frame}
\end{document}

A: As a workaround:
\documentclass[usenames, dvipsnames]{beamer}
\usepackage{amsmath, amssymb, amsthm, mathtools, commath, array, tcolorbox, cancel, caption, subcaption, stmaryrd,comment, media9,animate}

\usepackage[utf8]{inputenc}
\useoutertheme{split}
\usetheme{Madrid}

\begin{document}

%6 slide
\begin{frame}{Introducción: La función gamma}
\begin{align*}
\visible<+->{\Gamma(x) = \int_0^\infty e^{-t}t^{x-1} dt} \\
\visible<+->{\text{Integrando por partes, obtenemos:}}\\
\visible<.->{\Gamma(x+1) &= \int_0^\infty e^{-t}t^{x}dt}\\
\visible<+->{&= \lim_{B \rightarrow \infty} \int_0^B e^{-t}t^{x}dt}\\
\visible<+->{&=\lim_{B \rightarrow \infty} \Big[-e^{-t}t^x \Big|_0^B + x \int_0^B e^{-t}t^{x-1}dt \Big]} \\
\visible<+->{&= x \lim_{B \rightarrow \infty} \int_0^B e^{-t}t^{x-1}dt}\\
\visible<+->{&= x\Gamma(x)}
\end{align*}
\end{frame}

\end{document}


text:
Q: Can't log in to Microsoft account on Windows 10 Today I installed Windows 10, everything went well and I can now use it normally. But I can't sign in to any applications that use the Microsoft account (Store, Mail, Calendar, ...) which causes some problems because I can't use those applications. Whenever I try to sign in to Microsoft account by clicking the option in a menu (be it selection of the service in Mail, connecting the User from Settings or downloading in Store), a window pops up for about a millisecond (where I presume I'd be asked for the account information) and then it instantly disappears. Can anyone help me?
I have tried looking elsewhere (even second page of Google) but they always talked about forgetting one's password or being blocked, but they didn't talk about not even having the chance to sing in.


text:
Q: One year young - young If somebody says my baby is one year young rather than one year old,is it grammatically acceptable?

A: I would understand it; some people use it to try to be cute or something. I wouldn't use it formally, though.

A: The way we speak of our age is based on the established fact and physical reality that all beings, from conception to birth, grow older with time. No exceptions.
We say: "The foetus is 10 weeks old."
But statements such as "I'm 60 years young" may be acceptable in informal conversations, but might become acceptable over time with respect to older individuals, who hate to think or say they're getting old.

A: It may depend on what it is they are trying to emphasize. Both terms are relative so it might be used euphemistically.

A: It is grammatically correct as a parallel to "one year old" but it is - in my own view - a nauseating and simpering attempt at a cute parody of the truth.


text:
Q: how to using localStorageService in $translateProvider module config I used angular-translate and angular-local-storage with MEANjs, all is add to module dependencies,
in app config.js:
  var service = {
    applicationEnvironment: window.env,
    applicationModuleName: applicationModuleName,
    applicationModuleVendorDependencies: ['ngResource', 'ngAnimate', 'ngMessages', 'ui.router', 'ui.bootstrap', 'ngFileUpload', 'ui-notification',
      'LocalStorageModule', 'pascalprecht.translate', 'angularMoment', 'ngFileSaver', 'ngSanitize', 'uiCropper', 'hc.marked'],
    registerModule: registerModule
  };

and in init.js:
  angular
    .module(app.applicationModuleName)
    .config(localStorageModuleConfig)
    .config(transConfig);

  localStorageModuleConfig.$inject = ['localStorageServiceProvider'];
  function localStorageModuleConfig(localStorageServiceProvider) {
    console.log('localStorageModuleConfig');
    localStorageServiceProvider
      .setPrefix('meanTorrent')
      .setStorageType('localStorage')
      .setDefaultToCookie(true)
      .setNotify(true, true);
  }

  transConfig.$inject = ['$translateProvider', 'localStorageService'];
  function transConfig($translateProvider, localStorageService) {
    $translateProvider.useSanitizeValueStrategy(null);

    var user_lang = navigator.language || navigator.userLanguage;
    user_lang = user_lang.substr(0, 2) || 'en';

    var storage_lang = localStorageService.get('storage_user_lang');
    user_lang = storage_lang || user_lang;

    $translateProvider.preferredLanguage(user_lang);
  }

I already include all .js files in html, when runing, I got error Unknown provider: localStorageService,I know in config part, must used provider, but if i used localStorageServiceProvider in transConfig, it can not to  .get('storage_user_lang')
any way to used service in config? or how to use provider to call self service`s method?

A: You can't inject service to configuration block (only providers and constants),
I used window.localStorage to solve this issue localStorage.


text:
Q: How to make the array initialize only the first time function is called? class Class
  def attr_accessor_with_history(attr_name)
    attr_name = attr_name.to_s
    # make sure it's a string
    attr_reader attr_name
    # create the attribute's

    attr_reader attr_name+"_history" # create bar_history

    class_eval %Q{

      def #{attr_name}=(val)
        @#{attr_name+"_history"}=[]
        @#{attr_name+"_history"}.push(val)
        @#{attr_name}=val
      end
    }
  end
end

class Foo

  attr_accessor_with_history :bar
end

i want to make attr accessor which would record the history of all writes in an array but the problem is in the class_eval the array is initialized every time so it doesnt hold the old values.
what changes should i do?

A: Use ||=:
@#{attr_name+"_history"} ||= []


text:
Q: Bash Script Command Line Argument Batch Stdin (heredocs) I have a program that asks for stdin a few seconds after it startups. I would like to send it the stdin from the command line instead of manually typing it out. I've done the following:
./program.sh << EOF
./program.sh <<< EOF
./program.sh << 'input'
./program.sh <<< 'input'

but none work. Why aren't heredocs working in this case?

A: The program probably thinks itself more interactive than it really is and ignores input that doesn't arrive at the right time. telnet is notorious for this. The options are:

*

*The good way: Use expect to interactively wait for a prompt and input a response.

*The bad way: Try to time responses and hope it works,
e.g.
{ sleep 5; echo "foo"; sleep 5; } | ./program.sh

A: << denotes a here document
./program.sh <<END
hello
world
END

<<< denotes a here string
./program.sh <<< "hello world"

If the input is generated somehow, use a pipe or redirect from a process substitution
helloWorldGenerator.sh | ./program.sh
./program.sh < <(helloWorldGenerator.sh)


text:
Q: MathType and Word Automation Programmatically Is there a way to extract MathJax Tex (using MathType) programmatically from documents?
I can only extract it through manually running the conversion over the whole document.  It would be more convenient to be able to run it programmatically.

A: Created a simple AutoIt script to make it more automatic.
In my case, manual labor was still opted for, and for some reason the choice was made to manually process the data into a certain form that the team at the time had chosen.  So making it fully automatic and programmatic ended up not being necessary.


text:
Q: Complex Task, LAG and RETAIN functions may not be good enough Probably the most complicated task I encountered.
Could really use your help here...
Let's say I have a data set similar to  this:
data have;
rk = 1;
version = 0;
treatment_ind = 1;
start_date_1 = "01jan2013"d;
end_date_1 = "01feb2013"d;
start_date_2 = "21jan2013"d;
end_date_2 = "18feb2013"d;
money_field = 32;
OUTPUT;

rk = 1;
version = 1;
treatment_ind = 1;
start_date_1 = "01feb2013"d;
end_date_1 = "01apr2013"d;
start_date_2 = "3jan2013"d;
end_date_2 = "9feb2013"d;
money_field = 1;
OUTPUT;

rk = 1;
version = 2;
treatment_ind = 2;
start_date_1 = "01jan2013"d;
end_date_1 = "01feb2013"d;
start_date_2 = "21jan2013"d;
end_date_2 = "18feb2013"d;
money_field = 65;
OUTPUT;

rk = 1;
version = 3;
treatment_ind = 3;
start_date_1 = "01jan2013"d;
end_date_1 = "01jun2013"d;
start_date_2 = "21jul2013"d;
end_date_2 = "18aug2013"d;
money_field = 6;
OUTPUT;

rk = 1;
version = 0;
treatment_ind = 7;
start_date_1 = "11mar2013"d;
end_date_1 = "22may2013"d;
start_date_2 = "21feb2013"d;
end_date_2 = "24feb2013"d;
money_field = 34;
OUTPUT;

FORMAT start_date_1 end_date_1 start_date_2 end_date_2 DATE9.;
run;

if treatment_ind = 1  - That's an easy one. A regular case, All calculations work just fine  for me.
The trickier ones are below:
If treatment_ind = 2,
I need to do few things:

*

*First of all, the easier task: to update few fields in existing rows (where treatment_ind = 2)

*Every rk owns somewhere a treatment_ind = 2, should act in certain way.
If treatment_ind = 3,

*

*First of all, the easier task: to update few fields in existing rows (where treatment_ind = 3)

*Every rk owns somewhere a treatment_ind = 3, should act in certain way. Different way.
And so on....
I have 8 different indicators that act in different ways, not just for the current row,
but EVERY row , by RK, owns the indicator somewhere...
Some of them actually cancels behaviors of other indicators.
For example,
if a certain RK has somewhere an Indicator_ind = 7,
than treatment_ind = 3 should not be calculated.
When all of this is done,
I should use Retain in order to accumulate numbers from one row to another...
Main problem is,
I can't upload the table I work with to explain better the situation I'm facing,
and the Data Set I did upload is REALLY simple and do not represent the complexity of that task...
If for example,
indicator_ind = 1 , then difference between dates should be according to first set of dates.
In other indicator it should be calculated according to the second set.
The same goes to lots and lots of other calculations...
I know it would be probably tough to answer this...
But, for a start, I'm asking for a direction...
as Retain/Lag  alone won't help me, I'm afraid...

A: This might help you with your problem, but since I can't see your data set it's hard to predict. You can play around with the RETURN and SELECT statements. RETURN skips the current data step iteration and moves on to the next iteration. SELECT works like a "switch" statement in other programming languages. Once a condition is fulfilled, it will only execute that condition's consequent statement.
data work.test;
set work.sample;
if indicator_ind=7 and treatment_ind=3 then return;

select;
    when(treatment_ind = 1 and version = 0) do;

    rk = 1;
    start_date_1 = "01jan2013"d;
    end_date_1 = "01feb2013"d;
    start_date_2 = "21jan2013"d;
    end_date_2 = "18feb2013"d;
    money_field = 32;
    OUTPUT;
    end;

    when(treatment_ind = 1 and version = 1) do;

    rk = 1;
    start_date_1 = "01feb2013"d;
    end_date_1 = "01apr2013"d;
    start_date_2 = "3jan2013"d;
    end_date_2 = "9feb2013"d;
    money_field = 1;
    OUTPUT;
    end;

    when(treatment_ind = 2 and version = 2) do;

    rk = 1;
    start_date_1 = "01jan2013"d;
    end_date_1 = "01feb2013"d;
    start_date_2 = "21jan2013"d;
    end_date_2 = "18feb2013"d;
    money_field = 65;
    OUTPUT;
    end;

    when(treatment_ind = 3 and version = 3) do;

    rk = 1;
    start_date_1 = "01jan2013"d;
    end_date_1 = "01jun2013"d;
    start_date_2 = "21jul2013"d;
    end_date_2 = "18aug2013"d;
    money_field = 6;
    OUTPUT;
    end;

    when(treatment_ind = 7 and version = 0) do;

    rk = 1;
    start_date_1 = "11mar2013"d;
    end_date_1 = "22may2013"d;
    start_date_2 = "21feb2013"d;
    end_date_2 = "24feb2013"d;
    money_field = 34;
    OUTPUT;
    end;

    otherwise;
end;

FORMAT start_date_1 end_date_1 start_date_2 end_date_2 DATE9.;
run;


text:
Q: In which cases is calling bind() necessary?
Possible Duplicate:
What client-side situations need bind()?

I saw the server program binding to a port. Why is this not necessary for a client program?
After all client program will also be sending and receiving data.
Anyway, in which cases is calling bind() necessary? And W-H-Y?

A:
Why is this not necessary for a client program?

Because it happens automatically when you connect the socket. Usually you don't care about which local outbound port you are using in client software, in fact the only times you do care are when your netadmin has mistakenly implemented an outbound port numbering rule, which just causes problems and doesn't solve anything.

A: *

*You need to perform binding regardless of socket family for server sockets.

*For client sockets it depends. For AF_INET type of sockets underlying stack (TCP) performs binding for client sockets. However for AF_UNIX type of sockets client needs to perform binding with code. So for clients sockets it depends on socket family type.

A: For TCP server socket you must specify the IP and port number: this enables the client to know the address of the host(via IP) and the process of the server(via port number),
after the server socket accepts a new connection from a client it creates a new socket dedicate for that client, and the server differentiate between the clients by these new sockets, so you can create a client/server application without binding the client socket to a port number


text:
Q: Calculating weighted average in Pandas using NumPy function Assume we have a pandas dataframe like this:
a    b    id
36   25   2
40   25   3
46   23   2
40   22   5
42   20   5
56   39   3

I would like to perform a operation (a div b), then group by id and finally calculate a weighted average, using "a" as weights. It work's when I only calculate the mean.
import pandas as pd
import numpy as np

df = pd.read_csv('file', sep='\s+')
a = (df['a'].div(df['b'])).groupby(df['id']).mean()           # work fine
b = (df['a'].div(df['b'])).groupby(df['dd']).apply(lambda x: np.average(x ??? ), weights=x['a']))

Don't know how to parse the values of df['a'].div(df['b'] to the first parameter of the numpy average function. Any ideas?
Expected Output:

   id  Weighted Average
0   2          1.754146
1   3          1.504274
2   5          1.962528

A: Are you looking to group the weighted average by id ?
df.groupby('id').apply(lambda x: np.average(x['b'],weights=x['a'])).reset_index(name='Weighted Average')
Out[1]:
   id  Weighted Average
0   2         23.878049
1   3         33.166667
2   5         20.975610

Or if you want to do the weighted average of a / b:
(df.groupby('id').apply(lambda x: np.average(x['a']/x['b'],weights=x['a']))
 .reset_index(name='Weighted Average'))
Out[2]:
   id  Weighted Average
0   2          1.754146
1   3          1.504274
2   5          1.962528


text:
Q: Cannot connect Remote MSSQL through sql alchemy in Mac import sqlalchemy as sa
import pyodbc
from sqlalchemy.sql import select

engine = sa.create_engine('mssql+pyodbc://user:password@ipaddress.domain.name/database')

con = engine.connect()

It is throwing me an error:

sqlalchemy.exc.DBAPIError: (pyodbc.Error) ('01000', "[01000]
  [unixODBC][Driver Manager]Can't open lib 'SQL Server Native Client
  10.0' : file not found (0) (SQLDriverConnect)")

Can any one please help me on this ?

A: Please check the below settings and try
1) Search for a file named libsqlncli* in your filesystem .Then check its :
A)permissions
B) rows reporting "NOT FOUND" in the output of the ldd command executed against this file;
C )If all seems to be ok check for/ddd the following entry in your odncinst.ini file:
*

[SQL Server Native Client 1[0|1].0]  Description=Microsoft SQL Server
  ODBC Driver V1.0 for Linux
  Driver=/opt/microsoft/sqlncli/lib64/libsqlncli-11.0.so.1790.0
  UsageCount=1

*


text:
Q: How do I increase height of an input field so that placeholder text fully appears in input box HTML5 I want to increase height of input box so my placeholder text wraps and is fully viewable to read.  However, my css does not seem to be working!  Any ideas??
Here's the hmtl5 for the screen name

    Screen Name*
    <input class="large_width tall_height" id="screen_name" type="text" name="screenname" value="{{screenname}}" placeholder="Put in a name others can understand if you don't want to use your actual name."/>

Here's the CSS:
.large_width {
    width:250px;
    height: 25px;
}

.tall_height {
    height: 50px;
}

input {
    font-size: 14px;
    font-family: "Helvetica Neue";
}

input[placeholder] {
    font-size: 11px;
}

A: Make height of input and line-height of placeholder same.
For Example
CSS:
.input-class
{
  height:30px;
}

.input-class[placeholder]
{
  line-height:30px;
  font-size:22px;
}

A: maybe something like this?
http://jsfiddle.net/nXWfM/
.place {
    height:30px; }

.place[placeholder] {
    font-size:22px; }

just set the height of input

A: You can set the height of the input box.
That should do it.

#screen_name{
   height: 30px;
}

    Screen Name*
    <input class="large_width tall_height" id="screen_name" type="text" name="screenname" value="{{screenname}}" placeholder="Put in a name others can understand if you don't want to use your actual name."/>

A: How to Increase Placeholder/Input Field Height and width in CSS3
   I have also same problem came now i solved this Question to follows simple code to increase height&width of placeholder/input field
input{
height: 25 p x;
width: 180 p x;

padding:0 10px;
}
 The above code 100% will works
    thank u have a nice day


text:
Q: an interesting combination question when i work over combination problems , i run into two questions.Both of them were talking about same concept ,but their solutions were different.
Fist question:A student write these letters to whiteboard a,b,b,c,c,c,d,d,d,d.After that, his teacher wants to erase some letters in order that there left only four letters which are distinct from each other.How many ways are there to do it?
Solution: C(2,1)*C(3,2)*C(4,3)=24 ways .We chose one b from two bs and two c from three cs and three d from four ds.
Second question: Suppose a shipment of 100 computers contains four defective computers. We choose a sample of six computers. How many different samples are there if the defective computers are distinct from each other and the unfaulty ones are identical?
Solution: no defective computer = 1 since all unfaulty computers are identical
When we choose same objects in the former question , we used combination.For example , we selected 3 ds among 4 ds , and all of ds were same.On the other hand, in the second question, we said that all of them are the same of each other.Because of this, there is only one way to select.
My question is that which one is true solution.Are not both of them same question type.Why didnt we say that all of ds are same and there is only one selection in the first.Otherwise, why didnt we  we make use of C(94,6) to select 6 identical computer in the second question?

A: No, the questions are not of the same type. In the first question all ten letters are distinct. For instance, erasing the first $d$ on the whiteboard is different from erasing the third $d$, and we can see that it is different. In the other problem we are asked to assume that the $94$ computers that are not defective really are indistinguishable, so that we cannot tell one set of $6$ of them from another. This is not an entirely realistic assumption, but we're asked to make it for the sake of the problem.


text:
Q: using entsp in GSA - making no difference to the results I was hoping someone had some experience using the entsp flag in GSA and was able to point out what I am doing wrong.  I've read the documentation but can't figure it out.
The query string I am passing through is:
?as_sitesearch=examplesite.com&callback=angular.callbacks._1&collection=hybrid_site_colection&entsp=a__di_site_biasing&frontend=jsonp&num=10&query=test&start=0

I've set up the biasing in the GSA, and when I apply it to the frontend itself, it behaves.  But I was hoping to pass it in dynamically, as I believed you could (we are likely to want to dynamically pass through one of a few biasing, depending on where the user is coming from), it makes no difference.
Am I missing a tag, or can someone see anything else wrong?

A: Sorry, peoples, I've seen now that the problem is that we are going through a JSON bridge that isn't passing through my variables.
When I go directly to the GSA with a frontend, it works.


text:
Q: Add border to UIButtons frame A UIButton, created in the Interface Builder, has a frame with the size: 240×40.
When trying to add a single line border around it, the border appears around the text instead of the UIButtons frame.
ViewController.m
#import <QuartzCore/QuartzCore.h>

- (void)viewDidLoad
{
    [[LoginButton layer] setCornerRadius:20.0f];
    [[LoginButton layer] setMasksToBounds:YES];
    [[LoginButton layer] setBorderWidth:1.0f];
}

No additional changes to the UIButton were made. Logging its size will result in: 240×40
Result:

A: Do you use auto layout? Make sure that the width constraint matches the frame width you've set.

A: I have created a custom View that has a UIButton as a subview. The containing view will act as the border and you can handle all sizing and etc. in detail as you want.


text:
Q: Angularjs value service & factory service In angular DOC

Register a value service with the $injector, such as a string, a number, an array, an object or a function. This is short for registering a service where its provider's $get property is a factory function that takes no arguments and returns the value service.

In the bold text, that says $get property is a factory function that takes no arguments, I know about the $get function in a angular providers which will be invoked using $injector.invoke() when an instance needs to be created and it is must have a $get function in a provider.
my question is about what is the underlying meaning of function that takes no arguments?
much appreciate if someone can describe the inner pieces of the angular values service & factory service with comparing both with the above doc quote. Thanks.

A: It means angular is creating a provider, like any other, that returns the value you're passing to it with module.value('name', value);. This type of provider is appropriate when there is no logic involved in building the value, and no dependency on some other service.
Comparison, yielding same result:

angular.module('myApp')
    .value('baseUrl', 'http://localhost:8080/');

angular.module('myApp')
    .factory('baseUrl', baseUrlFactory);

function baseUrlFactory(){
    return 'http://localhost:8080/';
}


text:
Q: Sorting a list alphabetically before sorting by length? I want to sort a list of strings alphabetically and by length so it gets sorted like this:
["a", "b", "ba", "ab", "cccc", "cccef", "c"]

to
["a", "ab", "b", "ba", "c", "cccc", "cccef"]

It's probably a duplicate question and the solution is probably quite simple but i can't seem to figure it out.

A: The first argument is just x which sorting by alphabetically(default) and the second is len(x) which sort by the length.
s = ["a", "b", "ba", "ab", "cccc", "cccef", "c"]
s = sorted(s, key = lambda x: (x,len(x)))
print (s)
>>>['a', 'ab', 'b', 'ba', 'c', 'cccc', 'cccef']


text:
Q: How to clone Andengine files? I have seen many tutorials which suggest cloning of andengine and its extensions by using Mercurial.
The url is https://code.google.com/p/andengine. However when I clone using this URL I get a single README file telling me that everything has moved to https://github.com/nicolasgramlich/AndEngine
However I am not able to clone from here. How should I clone the files
Any help will be appreciated.

A: They moved to Github so you need to use Git to get the files. See Installing Git for more info.
git clone git://github.com/nicolasgramlich/AndEngine.git


text:
Q: XSL : display text between two milestone, show milestone value elsewhere I'm working with a XML file that must be TEI-compilant. The problem is about the pb (page break) milestone. It's not a new problem, but the existing solutions are so complicated and heavy that I was wondering if there was a more simple way in my case.
Let's have this XML file part :

<pb n="2"/>
Some random text is put here

Another
paragraph starts here, and in the
middle of it<pb n="3"/> a page break occurred.
<pb n="4"/

the next paragraph begins
on a new page

But in the next paragraph, after<pb n="5"/>another page break, something else
 happend : a note<note
 type=glossary">the note content</note> and so everything
 failing <pb n="6"/> because of this note.

I would like to transform the XML into this HTML :

Some random text is put here

Another paragraph starts here, and in the
middle of it
	2

a page break occurred.
	3

the next par graph begins on a new page
	4

But in the next paragraph, after	5

another page break, something else happend : a note
<note type=glossary">the note content</note> and so everything's failing	6

because of this note.

It seems to me that it should be possible to achieve quite simply with a for-each-group. So, basically, I was trying something like that :
<xsl:stylesheet
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="2.0">

    <xsl:template match="/body">

        <xsl:for-each-group select="descendant::*" group-starting-with="pb">

<xsl:value-of select="current-group()"/>
        	<xsl:value-of select="current-group()[1]/@n"/>

        </xsl:for-each-group>

    </xsl:template>

</xsl:stylesheet>

Obviously, it doesn't work… the result is :

 Some random text is put here Another paragraph starts here, and in the
middle of it a page break occurred.	2

3

the next paragraph begins on
a new page	4

Am I going in a totally wrong direction ?
Many thanks for your help !
Christophe

A: I think you are not in wrong direction with for-each-group. Sometimes it is useful (for me) to make some "preprocessing" of input document and save it into variable for further transformation.
I have this xslt
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:fn="http://www.w3.org/2005/xpath-functions" exclude-result-prefixes="fn xs fo">
    <xsl:output method="html" />

    <xsl:variable name="preprocess">

        <xsl:element name="{/node()[1]/name()}">
            <xsl:apply-templates select="/node()[1]/node() | @*" mode="preprocess"/>
        </xsl:element>
    </xsl:variable>

    <xsl:template match="node() | @*" mode="preprocess">
        <xsl:copy>
            <xsl:apply-templates select="node() | @*" mode="preprocess"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="*[pb]" mode="preprocess">

        <xsl:variable name="nodeName" select="name()" />
        <xsl:element name="{$nodeName}">

            <xsl:apply-templates select="pb[1]/preceding-sibling::node()" mode="preprocess" />
        </xsl:element>
        <xsl:copy-of select="pb[1]" />

        <xsl:variable name="restOfElement">
            <xsl:element name="{$nodeName}">
                <xsl:copy-of select="pb[1]/following-sibling::node()" />
            </xsl:element>
        </xsl:variable>
        <xsl:apply-templates select="$restOfElement" mode="preprocess" />
    </xsl:template>

    <xsl:template match="/">

                <title></title>

                    <xsl:for-each-group select="$preprocess/body/descendant::*" group-starting-with="pb">

                                <xsl:copy-of select="current-group()[position() > 1]" />

                            <xsl:value-of select="current-grouping-key()/@n"/>

                    </xsl:for-each-group>

    </xsl:template>

</xsl:stylesheet>

In first step I split all elements containing <pb>. The variable then looks like following

    <pb n="2"/>

Some random text is put here

Another
paragraph starts here, and in the
middle of it

    <pb n="3"/>

 a page break occurred.

    <pb n="4"/>

the next paragraph begins
on a new page

But in the next paragraph, after

    <pb n="5"/>

another page break, something else
 happend : a note<note type="glossary">the note content</note> and so everything
 failing

    <pb n="6"/>

 because of this note

On this I apply your for-each-group statement. It produced following output

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title></title>

Some random text is put here

Another
paragraph starts here, and in the
middle of it

                2

 a page break occurred.

                3

the next paragraph begins
on a new page

But in the next paragraph, after

                4

another page break, something else
 happend : a note
                        <note type="glossary">the note content</note> and so everything
 failing

                    <note type="glossary">the note content</note>

                5

 because of this note

                6


text:
Q: Debian does not detect serial PCI card after reboot I have installed a PCI card with two serial and one parallel port on it. the chipset is MCS9865. I downloaded the latest driver(V1.0.12) from here. I ran make and make install. now the two serial ports are /dev/ttyD0 and /dev/ttyD1. I have tested them with picocom and it is working perfectly. the problem is that when I reboot the system there is no /dev/ttyD0 and /dev/ttyD1. I need to do another make install. Is there any solution?
output of lspci -v shows this:
03:01.0 Serial controller: NetMos Technology PCI 9865 Multi-I/O Controller (prog-if 02 [16550])
    Subsystem: Device a000:1000
    Flags: bus master, medium devsel, latency 32, IRQ 19
    I/O ports at df00 [size=8]
    Memory at fbeff000 (32-bit, non-prefetchable) [size=4K]
    Memory at fbefe000 (32-bit, non-prefetchable) [size=4K]
    Capabilities: [48] Power Management version 2
    Kernel driver in use: mcs9865-serial

03:01.1 Serial controller: NetMos Technology PCI 9865 Multi-I/O Controller (prog-if 02 [16550])
    Subsystem: Device a000:1000
    Flags: bus master, medium devsel, latency 32, IRQ 18
    I/O ports at de00 [size=8]
    Memory at fbefd000 (32-bit, non-prefetchable) [size=4K]
    Memory at fbefc000 (32-bit, non-prefetchable) [size=4K]
    Capabilities: [48] Power Management version 2
    Kernel driver in use: mcs9865-serial

03:01.2 Parallel controller: NetMos Technology PCI 9865 Multi-I/O Controller (prog-if 03 [IEEE1284])
    Subsystem: Device a000:2000
    Flags: bus master, medium devsel, latency 32, IRQ 7
    I/O ports at dd00 [size=8]
    I/O ports at dc00 [size=8]
    Memory at fbefb000 (32-bit, non-prefetchable) [size=4K]
    Memory at fbefa000 (32-bit, non-prefetchable) [size=4K]
    Capabilities: [48] Power Management version 2

make install shows this:
cp mcs9865.ko mcs9865-isa.ko /lib/modules/2.6.32-5-amd64/kernel/drivers/serial/
depmod -A
chmod +x mcs9865
cp mcs9865 /etc/init.d/
ln -s /etc/init.d/mcs9865 /etc/rcS.d/S99mcs9865 || true
ln: creating symbolic link `/etc/rcS.d/S99mcs9865': File exists
modprobe mcs9865
modprobe mcs9865-isa

I'm running debian 6.0.5 with most updated packages.

A: The way this normally works is:

*

*The module source code contains calls to the MODULE_DEVICE_TABLE macro to declare a table of device identifiers that this module supports.

*In the compiled module, the aliases are stored as values of symbols called __mod_alias_NNN where the NNN are integers. The value encodes the bus identification for the device, e.g. pci:v00009710d00009865sv*sd*bc*sc*i* for the PCI device identified as vendor 0x9710, device 0x9865.
 They are also stored under the name __mod_pci_device_table for PCI devices, __mod_usb_device_table for USB devices, etc.

*The depmod program creates an alias table mapping __mod_alias_NNN values to the module name. This table is stored in the file modules.alias at the root of the kernel modules directory, e.g. /lib/modules/2.6.32-5-amd64/modules.alias.
 It also creates files like modules.pcimap, modules.usbmap, …, which are used by the obsolete hotplug infrastructure which has been subsumed back into modprobe.

*When the kernel detects a device for which no driver is present, it tries to load a module by calling the program indicated by the kernel.modprobe sysctl, which is /sbin/modprobe by default. The kernel passes an argument to modprobe that indicates what driver is requested. For a PCI device, this is a name like pci:v00009710d00009865sv*sd*bc*sc*i*.

*modprobe searches for a module with the given name. If it finds a module with the requested name (after following the alias defined in its configuration files, which include /etc/modprobe.d/*.conf and /lib/modules/$(uname -r)/modules.alias), it loads that module.
modprobe will not load a module that has been blacklisted by a blacklist directive in its configuration files.

Run lspci -n to see the PCI ids of your device, and check the chain above to see where something went wrong.
Sometimes a driver works for a device that is very similar to the device it is intended for, but has a different PCI id. In that case, it's possible that the driver will work, but won't be loaded automatically because it doesn't declare the PCI id for your device. You can add the alias manually in /etc/modprobe/my_aliases.conf.
You can force a module to be loaded automatically at boot time by adding its name to /etc/modules.

A: A quick fix would be to run after every reboot
modprobe mcs9865
modprobe mcs9865-isa

to me it seems as if the kernel modules are not auto inserting.
there is an init script so you might just have to add it to the default run level with this
sudo update-rc.d mcs9865 defaults


text:
Q: How can i delete firebase child node with the same name?Get the key to be delited from one node and delete those node with same key from the other I want to delete all the child nodes form different nodes with the same names. I used the following code to get the keys of the child nodes to be deleted and pass it to the other node but it is deleting them from both nodes(completedSurveys and surveyList).
DatabaseReference dr_completedSurveys = firebaseDatabase.getReference("users").child(userId).child("completedSurveys");
    dr_completedSurveys.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            StringBuilder stringBuilder = new StringBuilder();
            for(DataSnapshot ds : dataSnapshot.getChildren()) {
                stringBuilder.append(ds.getKey()).append("\n");
                String completedSurveys = stringBuilder.toString();
                String[] lines = completedSurveys.split("\n");
                for (String line : lines) {
                    //Toast.makeText(HomePage.this, line, Toast.LENGTH_SHORT).show();
                    String compSurList = line;
                    DatabaseReference dr_completed = FirebaseDatabase.getInstance().getReference("users").child(userId);
                    dr_completed.child("surveyList").child(compSurList).removeValue();
                }
            }
        }
        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });

Attached below is the firebase realtime database structure.

A:
It could be deleted one by one or once; I just want to delete all the names which are found on both DB from surveyList.

String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference completedSurveysRef = rootRef.child("users").child(uid).child("completedSurveys");

Now to remove all values within the completedSurveys node at once, you should use the following line of code:
completedSurveysRef.removeValue();

If you want to delete each child separately, please use the following lines of code:
completedSurveysRef.child("sld0000001").removeValue();
completedSurveysRef.child("sld0000002").removeValue();

Edit:
According to your comment:

Dear Alex, I want to remove all child nodes from surveyList, that are in completedList. sld0000001 and sld0000002 are both in completedList and surveyList, so I want to remove these values from surveyList not from comletedList.

Please use the following lines of code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference completedSurveysRef = rootRef.child("users").child(uid).child("completedSurveys");
DatabaseReference surveyListRef = rootRef.child("users").child(uid).child("surveyList");
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String surveyId = ds.getKey();;
            surveyListRef.child(surveyId).removeValue();
        }
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
        Log.d("TAG", databaseError.getMessage()); //Don't ignore errors!
    }
};
completedSurveysRef.addListenerForSingleValueEvent(valueEventListener);


text:
Q: How to delete a table that is corrupted when copying another table in Access Web App? This question is specific to an Access Web App, hosted on my institutional Sharepoint / Office 365 account. I copied a table, "Equipment" by dragging and dropping it using the Navigation Pane in the Access 2013 editor. After doing so, Access crashed. When I open my application for design now, the other tables are still there, and apparently their data, views and relationships are intact. They are also working on the client side in the browser.
However, I have a "broken" table with a name of "Copy of Equipment." The table does not have any views. Here are the symptoms when I try options on the table in Access 2013 editor:

*

*"edit table" -> no response at all (no error message)

*"view data" -> A new tab appears that is blank with two buttons (a plus sign and trash can). An error window pops up that says Access Services The record source Copy of Equipment specified on this view does not exist. TECHNICAL DETAILS OK.

*

*When I click on TECHNICAL DETAILS I get a Correlation ID: <long hex code> and a date and time.

*When I right click on the new tab and choose "design view" Access 2013 crashes.

Does anyone know how I can delete this table? If you're familiar with Access Web Apps, at least at this point, you'll know that the options available in Access 2013 editor are far more limited than with a desktop database. I am wondering if there is possibly a trick for deleting this table, although I suspect that any method would require a different application to connect to the database, and probably some privileges that I don't have with my user account to our Office 365 site.  Thank you for any ideas!


text:
Q: WebSocket closes immediately after opening/send I'm making a simple chat using websockets on client and flask + flask_sockets on server.
When the client gets their token, connects to a websocket and sends a message, websockets.exceptions.ConnectionClosed appears
Client code:
async def main(token):
    async with websockets.connect(f'ws://localhost:5000/ws?token={token}') as ws:
        await ws.send(input('> '))
        print(await ws.recv())

if __name__ == '__main__':
    username = input('Your username >>> ').strip()
    token = get(f'http://localhost:5000/getToken?username={username}').text
    print(f"Got token: {token}")

    while True:
        asyncio.get_event_loop().run_until_complete(main(token))

Server WebSocket handler:
class User:
    ws = None

    def __init__(self, username):
        self.username = username

@sockets.route('/ws')
def alert(ws):
    token = request.args.get('token')
    if token in users:
        user = users[token]
        user.ws = ws
        print(f'Connected user {token}')
    print(users[token].username, '>>>', ws.receive())

I expect the connection to stay open so when a new message appears server would send it to all clients using something like
for user in users:
    user.ws.send(message)

P.S. this is my first post on StackOverflow, so any corrections are welcome :)

A: For anyone else with the same problem, the answer is to use a for loop to continually read in messages as described in the docs here.
Adjusted for the question:
async def main(token):
    async with websockets.connect(f'ws://localhost:5000/ws?token={token}') as ws:
        async for message in ws:
            # note: message can be a string or bytes
            print(message)
...


text:
Q: How to run a javascript file with node.js I have just started learning node.js and i am trying to open a local .js file. The file is stored on desktop and its location is something like C:\Users\Jim\Desktop\hello.js.
I use the following command:
node C:\Users\Jim\Desktop\hello.js
Now i use this command but all i get is ... and nothing happens. I have installed node.js and use its own terminal. Other commands also work well without any problem but i am stuck at this very beginning step.

A: I created a cmd file in nodjs-folder. The cmd-file has only one line:

node %1

Then I told windows to always open js files with this cmd file.


text:
Q: How to update RecycleView Kivy This is my first question, so sorry if butcher it.
I'm making an application, that will allow for a more efficient protocol creation for other people at my job.
The problem is, that I'm trying to update created RecycleView, but for some reason it doesn't work. Some solutions on the web advise using .refresh_from_data() method, but it did not work, and all the other solutions are too complicated (or I'm too dumb).
I have this function - add_entry that adds information from two TextInputs as a dictionary inside protocol list.
At the current moment my RecycleView just shows numbers, because no solution have worked, and I actually really struggled to even make a Recycle View.
Here is relevant part of Python code:
class DrillingInfoPage(Screen):
    rod = 1
    dist = 3
    protocol = ListProperty() # {Rod:_,Distance:_,Proc:_,Depth:_}

    def add_entry(self, proc, depth):
        self.protocol.append({'Rod': 0, 'Distance': 0, 'Proc': 0, 'Depth': 0})
        self.protocol[self.rod-1]['Proc'] = proc
        self.protocol[self.rod-1]['Depth'] = depth
        self.protocol[self.rod-1]['Rod'] = self.rod
        self.protocol[self.rod-1]['Distance'] = self.dist
        self.rod += 1
        self.dist += 3
        print(self.protocol)
        return self.protocol

class Profile(Screen):
    pass

class WindowManager(ScreenManager):
    pass

class ColorsPopup(Screen):
    popupWindow = None

class Recycle(RecycleView):
    def __init__(self, **kwargs):
        super(Recycle, self).__init__(**kwargs)
        self.data = [{'text': str(x)} for x in range(50)]

kv = Builder.load_file("my.kv")

class MyApp(App):
    def build(self):
        return kv

if __name__ == '__main__':
    MyApp().run()

And here is a relevant part of KV file:
<DrillingInfoPage>:
    name: 'third'
    BoxLayout:
        orientation: 'vertical'
        Label:
            size_hint: 1, .4
            text: 'Drilling Info Page'
        GridLayout:
            size_hint: 1, .1
            cols:3
            GridLayout:
                cols:2
                Label:
                    text: 'BG'
                TextInput:
                    id: start
                    multiline: False
            GridLayout:
                cols:2
                Label:
                    text: 'BG'
                TextInput:
                    id: end
                    multiline: False
            Button:
                text: 'Confirm'
                on_release: drilling_holes.text = 'BG' + start.text + ' -----> ' + 'BG' + end.text

        GridLayout:
            size_hint: 1, .1
            cols:3
            GridLayout:
                cols:2
                Label:
                    text: '%:'
                TextInput:
                    id: proc
                    multiline: False
            GridLayout:
                cols:2
                Label:
                    text: 'Depth:'
                TextInput:
                    id: depth
                    multiline: False
            Button:
                text: 'Add'
                on_release: root.add_entry(proc.text, depth.text)

        Label:
            id: drilling_holes
            size_hint: 1, .2
            text: ''

        Recycle:
            id: drilling_data
            data: self.data
            viewclass: 'Label'
            RecycleBoxLayout:
                default_size: None, '25dp'
                default_size_hint: 1, None
                size_hint_y: None
                height: self.minimum_height
                orientation: 'vertical'

        Label:
            size_hint: 1, .2
            text: ''
        GridLayout:
            size_hint: 1, .17
            cols:2
            Button:
                text: 'Go Back'
                on_release:
                    app.root.current = 'second'
                    root.manager.transition.direction = 'down'
            Button:
                text: 'Confirm'
                on_release:
                    app.root.current = 'last'
                    root.manager.transition.direction = 'up'

I've tried creating some functions inside RecycleView class that would refresh the data, as well as inside the DrillingInfoPage class, but nothing seems to work.
I'm new to Python and especially Kivy, therefore hoping someone wise can guide me in the right direction :)
Here how the screen itself looks right now, ideally it should be empty at first and pressing 'Add' button should add a new line

A: You just have to add the new information to the data list of the RecycleView. It's not clear exactly what you want to add to the RecycleView, but you can just add a line to your add_entry() method like this:
    self.ids.drilling_data.data.append({'text': proc})  # add new entry to data list

And that method does not need a return statement


text:
Q: Do not maintain session i have one website and i have added it in bookmark.
the situation is:
i opened the browser and website loaded from bookmarked location now the tab1 contains the website next i am logging it now it is in home page.
then i opened new tab but i didnt loaded any site. then i closed the tab1 then i opening the site from bookmark location. here instead of loginpage its directly loading the page which was in tab2.
when i can close the logged in tab then it should ask for login page in next tab
please help me guys how to achieve this
thanks

A: Login cookie is shared in same browser tabs (sometimes even in same type of browser).
In other words, if you login in a tab in IE, you do not have to login in different tabs. Login cookie is still valid, and you are automatically login.
However, if you open same page in FireFox or Chrome, you'll still have to login even if you have logged-in in IE.
Updated: Please do not ask user to re-login if a tab is closed and reopen in different tab (in same browser). Even banking websites won't do that. (Of course, user'll need to relogin if the browser is closed.)

A: You need to logged out the user when page is closing.
You can use onbeforeunload event to manually logged out the active user.
Have a look at this article about Save Changes on Close of Browser or When Exiting the Page


text:
Q: Number of ways of selection from a mixed group For example I want to know number of ways I can select $2$ items from $AAABBC$ i,e $3$ of one group,$2$ of other and $1$ of last.

A: AA, AB, AC, BB, BC
There are 5 options if you want this.
I think there is not general formula for it.


text:
Q: how to sync two related projects with each other preferably with git? We have two separate webshop projects Webshop A and Webshop B. They are both in a repository on github. Webshop B is basically a copy of Webshop A with few changes, but a lot of functionality stays the same.
Right now when we change something in Websop A needed in Webshop B also, we just copy+paste the necessary code to the other project. Is there a way to do it through Git?
We basically want to pick changes from Webshop A to Webshop B, in some cases from Webshop B to Webshop A but not everything.

A: One possible approach:
Have one git repository with two branches shop A and shop B. (You can further extend on this according to your git workflow, e.g. shop A develop and shop A master etc.)
When a new feature shall be used for both shops, make a new branch feature xyz, develop the feature and make a pull request / merge of feature xyz into both branches shop A and shop B.
If you only make tiny adjustments, e.g. bugfixes, you can use cherry pick to select certain commits to go into your branches.


text:
Q: Java: picocli: How to provide argument to command without naming it? Is it possible to provide argument to @CommandLine.Command without explicitly naming the argument in picocli?
As example the following command can be invoked as: open n 1. However, I would like to be able to invoke the command as open 1.
@CommandLine.Command(name = "open",
    mixinStandardHelpOptions = true,
    version = "1.0",
    description = "Open note")
@Getter
@ToString
public class OpenCommand implements Runnable {
    @CommandLine.ParentCommand TopLevelCommand parent;

    @CommandLine.Option(names = {"number", "n"}, description = "Number of note to open")
    private Integer number;

    public void run() {

        System.out.println(String.format("Number of note that will be opened: " + number));
    }
}

A: Picocli offers the @Parameters annotation for positional parameters, in addition to the @Option annotation, which is for named parameters.
If you use the @Parameters annotation for the number, instead of @Option(names = "n"), then end users can invoke the command as open 1.
That is a fairly minimal change, the resulting code could look like this:
@CommandLine.Command(name = "open",
    mixinStandardHelpOptions = true,
    version = "1.0",
    description = "Open note")
@Getter
@ToString
public class OpenCommand implements Runnable {
    @CommandLine.ParentCommand TopLevelCommand parent;

    @CommandLine.Parameters(description = "Number of notes to open")
    private Integer number;

    public void run() {
        System.out.printf("Number of notes that will be opened: %s%n", number);
    }
}


text:
Q: Reset a PCI Device in Linux Is there a generic way to reset a PCI device in Linux from the command line? That is, cause the PCI bus to issue a reset command.

A: according to http://www.kernel.org/doc/Documentation/ABI/testing/sysfs-bus-pci you can reset individual functions of the device if that's supported:
What:       /sys/bus/pci/devices/.../reset
Description:
            Some devices allow an individual function to be reset
            without affecting other functions in the same device.
            For devices that have this support, a file named reset
            will be present in sysfs.  Writing 1 to this file
            will perform reset.

A: The closest thing the PCI bus has to a device level reset is changing the power state to D3 and back to D0.  After unloading the driver ( it would be bad to reset the hardware out from under the driver ), you can use setpci to write to the control registers to change the power state, but I believe this happens automatically when you unload the driver.

A: The problem with the solutions above is that they require the cooperativity of the device; however in most scenarios the reason to reset it is exactly its non-cooperativity.
However, as it is described here, there is another, "harder" way to reset it on the PCI level: we remove it from the PCI bus and then re-insert it by a rescan.
The steps:

*

*echo 1 >/sys/bus/pci/<pci-id-of-device>/remove. We can find its PCI ID with an lspci command.

*echo 1 >/sys/bus/pci/rescan
I have here a buggy pci device, sometimes PCI-level reset, sometimes this removal-readd trick fixes it. I am about to write a script to do it automagically. :-)

A: Since a generic PCI device is not hotpluggable there won't be a way to reset it and have the kernel re-enumerate it.
Whatever kind of problems you are trying to solve, there surely is a better way than to just reset it.


text:
Q: Finding all possible simple path in an undirected graph is NP hard/ NP complete The proof is needed:
Finding all possible simple path in an undirected graph is NP hard/ NP complete. The graph may contain multiple edges between same pair of nodes, and loops.
I have searched over, got some idea or discussion. But I need a direct proof/link stating the complexity is NPC/ NP-Hard.

A: Problems of the form "find all objects of some type" aren't NP-complete, because NP consists purely of decision problems, questions that have a yes/no answer. So this problem can't be NP-complete.
If you specifically have to list the paths in descending order of size, then the problem would be NP-hard. If you can list all paths in descending size order, then you can just check the first path to see if it passes through all nodes. If so, great! Your graph has a Hamiltonian path, and finding Hamiltonian paths is NP-hard.
On the other hand, if you listed the paths in ascending order of length, then assuming you're working with Turing machines the cost of simply reading all the paths to get to the last one would take more than polynomial time, so this reduction wouldn't work. A similar argument shows that this reduction won't work if the paths come back in arbitrary order. I suspect, but am not fully sure, that it's unknown whether that version of the problem is NP-hard, but I'm open to being corrected on that.
This is all the more interesting given that the number of simple paths in a graph can be O(n!), which happens when the graph is a complete graph (all pairs of nodes are linked by edges). The fact that something takes a long time to complete doesn't immediately mean that it's NP-hard or NP-complete.
Hope this helps!

A: The complexity of this problem appears to be O(n!) which is worse than the O(2^n) of the NP-Hard / NP-Complete series. Additionally, this is not NP-Hard / NP-Complete because it isn't even in NP.
Requirement for NP:
"A problem is called NP (nondeterministic polynomial) if its solution can be guessed and verified in polynomial time"[1]
Your problem is not in NP, since checking your solution has a complexity of O(n!) just like calculating your results, because in an (n-1)-Simplex (fully interconnected graph with n vertices)[2] the solution of all possible simple paths will be for(i = {1 to n}){sum(n!/(n-i)!)} + 1 for the empty set paths (please look at templatetypedef's comment[3] for proof), which is O(n!) and more specifically does not fall into polynomial time solution.
In the image above[4] you have an example of a 3 simplex.
 Full enumeration will consist of for(i = {1 to 4}){sum(4!/(4-i)!)}+1 = (4!÷3!)+(4!÷2!)+(4!÷1!)+(4!÷0!)+1 = 65 paths:
{}

{A}
{A->B}
{A->B->C}
{A->B->D}
{A->B->C->D}
{A->B->D->C}
{A->C}
{A->C->B}
{A->C->D}
{A->C->B->D}
{A->C->D->B}
{A->D}
{A->D->B}
{A->D->C}
{A->D->B->C}
{A->D->C->B}

{B}
{B->A}
{B->A->C}
{B->A->D}
{B->A->C->D}
{B->A->D->C}
{B->C}
{B->C->A}
{B->C->D}
{B->C->A->D}
{B->C->D->A}
{B->D}
{B->D->A}
{B->D->C}
{B->D->A->C}
{B->D->C->A}

{C}
{C->B}
{C->B->A}
{C->B->D}
{C->B->A->D}
{C->B->D->A}
{C->A}
{C->A->B}
{C->A->D}
{C->A->B->D}
{C->A->D->B}
{C->D}
{C->D->B}
{C->D->A}
{C->D->B->A}
{C->D->A->B}

{D}
{D->B}
{D->B->C}
{D->B->A}
{D->B->C->A}
{D->B->A->C}
{D->C}
{D->C->B}
{D->C->A}
{D->C->B->A}
{D->C->A->B}
{D->A}
{D->A->B}
{D->A->C}
{D->A->B->C}
{D->A->C->B}

Hope this helps and good luck with solving this problem.