text:
Q: TfIdfVectorizer with grouped tokens I've vectorized ~1million of textual documents with TfIdfVectorizer.
vect1 = TfIdfVectorizer()
vect1.fit_transform(data)

Now I need to group some (semantically similar) tokens and repeat vectorization.
Replacing all tokens in the raw data with the new ones seems tedious and time consuming for me, since I intend to repeat the process for multiple grouping strategies.
I've tried
voc = vect1.vocabulary_
voc['cabman'] = voc['driver']
# grouping similar tokens to have the same ids ...
vect2 = TfIdfVectorizer(vocabulary=voc)
vect2.fit_transform(data)

ValueError: Vocabulary contains repeated indices.

Is there an efficient way to accomplish it without touching the input data?


text:
Q: "Half an hour" versus "half hour"
*

*I'll be back in half an hour.

*I'll be back in half hour.
Which is the correct sentence? Are there any differences between British English and American English?

A: In Australia we say 'half an hour'. You might hear 'a half hour', but it would sound stilted. This is probably changing with the influence of American television.

A: You could say "a half hour" or "half an hour". The article choice depends on where in a phrase you place it.
Would you ever say "I'll be back in hour"? No, because while possibly legal, the use of the article "an" would be needed to make it sound like a native English speaker.

A: The top one is correct.

* I'll be back in half hour

would be OK if it said

I'll be back in a half hour

Note that "a half hour" is an American usage, British people only use "half an hour".

A: The very same question puzzles me these days. The title should be "half an hour" versus "a half hour" I used to apply the former. I notice it is an issue when I read the entry in electronic dictionary of Longman contemporary English version 5.  It offers examples like, 1. half a mile/pound/hour etc  half a pound of butter; It's about half a mile down the road. She drank half a bottle of wine. half a million  dollars; 2. a half hour/mile etc
You can't just waltz in a half hour late. It's about a half mile down the road. a half day excursion to the island; He demanded a half share of the money. Both items belong to entry of half with the meaning of  "exactly or about 50% (½) of an amount, time, distance, number etc" The dictionary does not explain the difference. I infer it is the same and both are correct. Maybe the only difference lies in habit or region. For instance, many mention on this page, British people and Americans apply this in different ways.

A: "half-hour" is commonly written with a dash (hyphen) and is a distinct word in the dictionary. So, "a half-hour" = 30 minutes = "half an hour".

redpajama_set_name: RedPajamaStackExchange


text:
Q: select latest comments for multiple objects at once Say I have a Comment Model like this:
class Comment(models.Model):
    user = models.ForeignKey(User)
    content = models.CharField(max_length=200)
    create_time = models.DateTimeField(blank=True, default=datetime.datetime.now)

    content_type = models.ForeignKey(ContentType, verbose_name=_('content type'))
    object_id    = models.PositiveIntegerField(_('object id'), db_index=True)
    object       = generic.GenericForeignKey('content_type', 'object_id')

If it's possible for me to select latest several comments for multiple objects in the same content_type (say Posts, giving ids of those Posts) in one query?
If that's possible, how about select the oldest comment and latest 4 comments for those objects all in one query?
Thx!

A: I've had trouble with the greatest-n-per-group problem. I had to drop to raw SQL to get my results (top X questions per question category in my FAQ). There's no easy way to do this through the ORM.
This post: uses an interesting solution with SQL
SQL join: selecting the last records in a one-to-many relationship
My solution involved subqueries. Since you're using generic keys, it may involve a little more head scratching.
I ended up just going back to the ORM with aggressive caching on this specific view, so I might recommend that. It's juts too much pain to keep up the SQL.
Foo.objects.raw('''
    SELECT ...
    FROM foo
    LEFT OUTER JOIN bar
    ON (foo.bar_id = bar.id )
    WHERE foo.id
    IN (
        SELECT subquery.id
        FROM foo subquery
        WHERE foo.bar_id = subquery.bar_id
        ORDER BY score DESC
        LIMIT %s
        )
    ORDER BY "baz" DESC;''', [5])

A: You mention "giving ids of those Posts", but don't actually have any Post model defined (in your question at least). But, as you're asking to get all comments with the same content_type, I'm not sure how the Posts are needed.
The following query gets all Comment items that match a ContentType with a certain primary key (1), orders them by create_time and selects the first 4 items:
Comment.objects.filter(content_type__pk=1).order_by('-create_time')[:4]


text:
Q: closure of rationalsmin topology Why is the closure of the rationals Q,  the reals R ?
Is it because the irrational numbers are only considered part of the set of rationals Q in its closure?
Aside: Good thorough website to learn Latex?


text:
Q: Sunmi V1s device - Java callback doesn't work when the printer is done printing I'm using Sunmi V1s device and want to show a Dialog once the printer finished printing the whole receipt. I now can get a message once the query is done processing, but I cannot get the message the exact moment when the printer is done the whole printing.
I used demo app to create a Callback which I then send to an AidlUtil class.
TextActivity
final PrinterCallback printerCallback = new PrinterCallback() {
          @Override
          public void onReturnString(String result) {
                System.out.println("Finished: " + result); //never prints out, expecting this line to work when Sunmi printer finishes printing
          }

          @Override
          public void onRunResult(boolean success) {
                System.out.println("Success: " + success); //prints out immediately after query is sent
          }
          @Override
          public void onRaiseException(String msg) {

          }
};
AidlUtil.getInstance().printText(content, size, isBold, isUnderLine, printerCallback);

AidlUtil class:
public void printText(String content, float size, boolean isBold, boolean isUnderLine, PrinterCallback printerCallback) {
        if (woyouService == null) {
            Toast.makeText(context, R.string.toast_2, Toast.LENGTH_LONG).show();
            return;
        }

        try {
            if (isBold) {
                woyouService.sendRAWData(ESCUtil.boldOn(), null);
            } else {
                woyouService.sendRAWData(ESCUtil.boldOff(), null);
            }

            if (isUnderLine) {
                woyouService.sendRAWData(ESCUtil.underlineWithOneDotWidthOn(), null);
            } else {
                woyouService.sendRAWData(ESCUtil.underlineOff(), null);
            }

            woyouService.printTextWithFont(content, null, size, generateCB(printerCallback)); //generating ICallback and sending it to printTextWithFont method
            woyouService.lineWrap(3, null);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
}

generateCB method:
public ICallback generateCB(final PrinterCallback printerCallback){
        return new ICallback.Stub(){
            @Override
            public void onRunResult(boolean isSuccess) throws RemoteException {
                printerCallback.onRunResult(isSuccess);
            }

            @Override
            public void onReturnString(String result) throws RemoteException {
                printerCallback.onReturnString(result);
            }

            @Override
            public void onRaiseException(int code, String msg) throws RemoteException {
                printerCallback.onRaiseException(msg);
            }

            @Override
            public void onPrintResult(int code, String msg) throws RemoteException {
            }
        };
}

What can be an issue? I expect to get a System.out.println onReturnString method, but the method is not called anytime


text:
Q: sbt 1.3.8 displaying a lot of useless messages After I upgrade sbt to 1.3.8, I see a lot of unuseful messages in the sbt console, which is very annoying. I searched online but didn't find a good key word. Does anyone know how to disable the messages showing like below?
  | => Zero / checkBuildSources / dynamicInputs 0s

  | => Zero / checkBuildSources / dynamicInputs 0s

  | => Global / previousCache 0s

  | => Zero / checkBuildSources / dynamicInputs 0s

  | => Global / previousCache 0s

A: These messages are progress logging from the sbt "super-shell". You can disable it using the sbt.supershell option, e.g.
sbt -Dsbt.supershell=false

Or by adding it to your .sbtopts file or SBT_OPTS env var (check sbt -help for details on how to use them). See also Command Line Options for the reference.


text:
Q: appearance phrase question My student wrote in his essay

it gives her face a peculiar charm?

I tried all the dictionaries at hand (hard-copy and electronic ones) but did not find a definite answer whether this phrase sounds English. Could you please help me?

A: The sentence is correct in both grammar and meaning.
A peculiar charm is basically a charm that you can't place.
In other words, it has a charm, but you don't know why.
Peculiar means unusual.
You don't understand what the charm about it is, but it has something.
I doubt you've never had the feeling :)


text:
Q: Using my package throws ModuleNotFoundError: No module named 'my-package' in Travis I am trying to use Travis CI for continuous integration but have been dealing with a lot of issues since it is my first time with Travis. Lately, I am running in to the following build fail:
ModuleNotFoundError: No module named 'my-package'

Which happens when in the following line of code in my db.py file:
import importlib
db_conf = importlib.import_module("my-package.conf.db_conf")

I should mention that I am using importlib since my repository has dashes in its name and based on suggestion in this post, I started using that package.
Right now, my project structure looks like the following:
my-project
├── conf
├───── db_conf.py
├── lib
└───── db.py

So as you can see I am trying to import db_conf.py from conf directory and running into no module named issue. I have been stuck with this for the past couple of days and have found the following posts on it: this one and this one. Problem is that I have tried all those methods and none of them seems to be working for me. Here is how my .travis.yml and setup.py files look like:
.travis.yml
language: python
python:
  - 3.7
env:
  global:
    # TRAVIS TESTING CONFIGURATION
    - COMMIT=${TRAVIS_COMMIT::8}
    - CGO_ENABLED=0
    - GOOS=linux
    - GOARCH=amd64
before_script:
  - export PYTHONPATH=$PYTHONPATH:$(pwd)
before_install:
  - python --version
  - pip install -U pip
  - python setup.py install
  - pip install -U pytest
  - pip install codecov
install:
  - pip install ".[test]" . # install package + test dependencies
script:
  - pytest
  - codecov
after_success:
  - codecov

And setup.py:
from setuptools import setup, find_packages

INSTALL_REQUIRES = [
    'pandas',
    'pyspark',
    'pyhdfs',
    'sqlalchemy',
    'configparser',
    'python-dotenv',
    'mysqlclient'
]
TEST_REQUIRES = [
    # testing and coverage
    'pytest', 'coverage', 'pytest-cov',
    # to be able to run `python setup.py checkdocs`
    'collective.checkdocs', 'pygments',
]

with open('README.md') as f:
    README = f.read()

setup(
    author="John Doe",
    author_email="john.doe@gmail.com",
    name='my-package',
    license="MIT",
    description='Supports my processes',
    version='1.0.0',
    long_description=README,
    url='https://github.com/my-user-name/my-package',
    packages=find_packages(),
    include_package_data=True,
    python_requires=">=3.5",
    install_requires=INSTALL_REQUIRES,
    extras_require={
        'test': TEST_REQUIRES + INSTALL_REQUIRES,
    },
    classifiers=[
        'Development Status :: 3 - Alpha',
        'Programming Language :: Python',
        'Programming Language :: Python :: 3.7',
        'Topic :: Software Development :: Build Tools',
        'Intended Audience :: Developers',
    ],
)

Is there anything that I am missing here? Am I doing something wrong? Any help or any lead to the right direction is much appreciated because this is driving me nuts.


text:
Q: What says JAXB specification: XmlAnyAttribute collision with explicit mapped attribute Scenario
Consider the following class (imports omitted):
@XmlAccessorType(XmlAccessType.NONE)
@XmlRootElement
public class Test {

    @XmlAttribute
    public int id;

    @XmlAnyAttribute
    public Map<QName,String> any;

}

What is the behaviour when I do the following:
Test t = new Test();
t.id = 5;
t.any = new HashMap<QName,String>();
t.any.put(new QName("id"), "10");
JAXBContext jc = JAXBContext.newInstance(Test.class);
Marshaller m = jc.createMarshaller();
m.setEventHandler(myEventHandler);
m.marshal(t, System.out);

The obvious problem:
An XML element should be generated for the instance of Test. But the obvious problem is: With which attributes? <test id="5"/>? Or <test id="10"/>? Or an invalid XML <test id="5" id="10"/>?
Please answer:

*

*Will the marshalling be successful (or will there be an exception?)

*Will handleEvent(ValidationEvent) of myEventHandler be called? If yes, with what?

*What can be expected on System.out, i.e. what is the output XML? (If 1. is answered positive)

*Will a (standard conforming) JAXB marshaller always generate well-formed XML? (No schema involved)

*Is the behaviour of the reference implementation in the standard library, which outputs <test id="5" id="10"/> and reports absolutely no error, conforming to the JAXB specification?
Please base your answer on solid fundaments:
Of course one can just try it out. But one should be able to predict the exact behaviour with studying the Javadoc and JAXB specification documents. So, if possible, back your answer with citing the relevant part of a documentation source.

A: Note:  I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB (JSR-222) expert group.
Where to Find the JAXB Specification
For reference the JAXB (JSR-222) specification can be downloaded from the following location:  https://jcp.org/en/jsr/detail?id=222
Answers to Your Questions

*

*Will the marshalling be successful (or will there be an exception?)
The JAXB 2.2 specification does not cover what will happen for this use case.  Only the unmarshalling use case is defined (see B.3.6.2).

*Will handleEvent(ValidationEvent) of myEventHandler be called? If yes, with what?
There is nothing in the JAXB 2.2 spec requiring this.

*What can be expected on System.out, i.e. what is the output XML? (If 1. is answered positive)
The behaviour for this is undefined.  As you pointed out both the reference and MOXy implementations of JAXB will output two attributes with the same name.

*Will a (standard conforming) JAXB marshaller always generate well-formed XML? (No schema involved)
You have identified one case where this is not true.

*Is the behaviour of the reference implementation in the standard library, which outputs  and reports absolutely no error, conforming to the JAXB specification?
The marshalling behviour is undefined in the specification, therefore the behaviour of the reference (and MOXy) implementations of JAXB don't conflict with the specification.
Where to Report Issues

A seriously developed software should, IMHO, leave no doubts about
  behaviour in edge cases.

You can raise issues like this either through Jira or the mailing lists.

*

*https://java.net/jira/browse/JAXB/ (Issue Tracker)

*https://java.net/projects/jaxb/lists/ (Mailing Lists)


text:
Q: nginx invalid URL prefix in "" with map proxy_pass worked if I keep default http://127.0.0.1:9200 uncomment,
 but with the below code map to ~^/kibana-dev the proxy_pass doesn't worked and I get 500 if I go to http://my.domain.com/kibana-dev
user www-data;
worker_processes auto;
pid /run/nginx.pid;

events {
        worker_connections 768;
        # multi_accept on;
}

http {

    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';
    access_log  /var/log/nginx/access.log  main;
    sendfile        on;
    keepalive_timeout  65;

    map $request_uri $target {
        #default http://127.0.0.1:9200;
        ~^/kibana-dev http://127.0.0.1:9200;
        ~^/kibana-test http://127.0.0.1:9100;
    }

    server {

        listen 80 default_server;
        listen [::]:80 default_server ipv6only=on;

        if ( $request_uri ~* ^/kibana-test ) {
        return 301 http://my.domain.com/_plugin/kibana;
        }

        if ( $request_uri ~* ^/kibana-dev ) {
        return 301 http://my.domain.com/_plugin/kibana;
        }

        location / {
        proxy_set_header X-Real-IP 1.2.3.4;
        proxy_http_version 1.1;
        proxy_set_header Connect "Keep-Alive";
        proxy_set_header Proxy-Connection "Keep-Alive";
        proxy_set_header Authorization "";
        proxy_pass $target;
        }

    }
}

I also tried :
map $uri $target {
        /kibana-dev http://127.0.0.1:9200;
    }

Any idea why ?
Thanks

A: Your configuration file does not make sense.
If you present the URI http://my.domain.com/kibana-dev, the server block will execute:
return 301 http://my.domain.com/_plugin/kibana;

This causes the URI to be represented as /_plugin/kibana. The new URI is processed by the location / block and executes:
proxy_pass $target;

At this point, the map is consulted to determine the value of $target which is the default value as /_plugin/kibana does not match any of the other values.


text:
Q: R - Interpreting the multinom output using the iris dataset I got a simple question.
I built a prediction model using multinom from the nnet package to predict the species of the flowers from the iris dataset. However, when I look at the output of the model, it shows the coefficients of versicolor and virginica, but not for setosa (check the picture). So my question is, where is the information related to the setosa type? Am I missing something? Or if there something I am not seeing?
This is my code.
   index <- sample(2, nrow(iris), replace=TRUE, prob=c(0.7, 0.3))
   train.data <- iris[index == 1, ]
   test.data <- iris[index == 2, ]
   multinom.model <- multinom(Species ~ ., data = train.data)
   print(multinom.model)

And this is the output of the previous line.

A: I had exactly the same question using statsmodels.
I've found the explanation (for SPSS but it's the same answer for R or Statsmodels) here.

These are the estimated multinomial logistic regression coefficients for the models. An important feature of the multinomial logit model is that it estimates k-1 models, where k is the number of levels of the outcome variable. In this instance, SPSS is treating the vanilla as the referent group and therefore estimated a model for chocolate relative to vanilla  and a model for strawberry relative to vanilla. Therefore, since the parameter estimates are relative to the referent group, the standard interpretation of the multinomial logit is that for a unit change in the predictor variable, the logit of outcome m relative to the referent group is expected to change by its respective parameter estimate (which is in log-odds units) given the variables in the model are held constant.


text:
Q: Find an item and change value in custom object array - Swift I have this class
class InboxInterests {

    var title = ""
    var eventID = 0
    var count = ""
    var added = 0

    init(title : String, eventID : NSInteger, count: String, added : NSInteger) {
        self.title = title
        self.eventID = eventID
        self.count = count
        self.added = added

    }
}

And i use it like this
var array: [InboxInterests] = [InboxInterests]()

Add item
let post = InboxInterests(title: "test",eventID : 1, count: "test", added: 0)
self.array.append(post)

I want to find the index by eventID key and change the value of added key in the same index
How is that possible?

A: Since you are using a class, use filter and first to find the value:
array.filter({$0.eventID == id}).first?.added = value

In this you:

*

*filter the array down to elements that match the event ID

*pick the first result, if any

*then set the value

This works since classes are pass by reference. When you edit the return value from array.filter({$0.eventID == id}).first?, you edit the underlying value. You'll need to see the answers below if you are using a struct
EDIT: In Swift 3 you can save yourself a couple of characters
array.first({$0.eventID == id})?.added = value

EDIT: Swift 4.2:
array.first(where: { $0.eventID == id })?.added = value
array.filter {$0.eventID == id}.first?.added = value

A: array = array.map { $0.eventID == id ? newValue : $0 }

A: The filter operator is not the best in this case, it works for some of you because classes are passed by reference.
Explanation: (You can copy the following code in a playground if you want to verify it).
class Book {
    let id: Int
    var title = "default"

    init (id: Int) {
        self.id = id
    }
}
var arrayBook = [Book]()
arrayBook.append(Book(id: 0))
arrayBook.append(Book(id:1))
arrayBook.forEach { book in
    print(book.title)
}

arrayBook.filter{ $0.id == 1 }.first?.title = "modified"

arrayBook.forEach { book in
    print(book.title)
}

Arrays are copied by value not reference, so when you are using filter you are creating a new array (different than the initial), but when you modify the new one, the initial one gets modified too because both are pointing to the same class (classed are passed by reference), so after the filter your array will have changed and the new one gets deallocated. So in this case it will print "default", "default" and then "default, "modified".
What happens if you change class for struct, the value will be passed by value not reference so you will have 2 arrays in memory with different values, so if you go through arrayBooks again it will print before the filter "default","default", and then "default", "default" again. Because when you are using the filter you are creating and modifying a new array that will get deallocated if you do not store it).
The solution is using map, creating a new array with all the values but with the modified items or fields that we want and then replace our array with the new one. This will print "default", "default" before the map, and then "default", "modified"
This will work with structs, classes and everything that you want :).
struct Book {
    let id: Int
    var title = "default"

    init (id: Int) {
        self.id = id
    }
}
var arrayBook = [Book]()
arrayBook.append(Book(id: 0))
arrayBook.append(Book(id:1))
arrayBook.forEach { book in
    print(book.title)
}

arrayBook = arrayBook.map{
    var mutableBook = $0
    if $0.id == 1 {
        mutableBook.title = "modified"
    }
    return mutableBook
}

arrayBook.forEach { book in
    print(book.title)
}

A: If you conform your class to Equatable then this would work:
extension Array where Element: Equatable {
    @discardableResult
    public mutating func replace(_ element: Element, with new: Element) -> Bool {
        if let f = self.firstIndex(where: { $0 == element}) {
            self[f] = new
            return true
        }
        return false
    }
}

Use like this:
array.replace(prev, with: new)

A: For me, the above answer did not work. So, what I did was first find the index of the object that I want to replace then using the index replace it with the new value
if let row = self.upcoming.index(where: {$0.eventID == id}) {
       array[row] = newValue
}

In Swift 5.0:
if let row = self.upcoming.firstIndex(where: {$0.eventID == id}) {
       array[row] = newValue
}


text:
Q: Retrieving storage volume info from tree URI I'm adapting an application to Android, that allows backup to external storage (USB pen drives).
I'm currently using Intent.ACTION_OPEN_DOCUMENT_TREE to get the tree Uri to the selected provider.
public void chooseDrive(View view) {
    Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);

    startActivityForResult(intent, READ_REQUEST_CODE);
}

I get the URI, can create files, etc, but what I need is some way to programmatically identify the chosen provider, or, in other words, I want the info of the Usb device/Storage Volume, as it shows on the selection window, like the description and the size.
I should refer that minimal API is 19, so many TreeUri methods (Like DocumentFile.fromTreeUri, or DocumentsContract.buildDocumentUriUsingTree) are unusable.


text:
Q: How to make my Python module visible by Cython? I have typical Cython code (.pyx) with an exception that it needs to access the variable from Python module:
helloworld.pyx:
from hellotest import label

def say_hello():
    print('Hello world!' + label)

And hellotest.py
from helloworld import say_hello

label = 'some label'
say_hello()

When I try to compile it with usual python setup.py build_ext --inplace, I get an error:
Traceback (most recent call last):
  File "hellotest.py", line 1, in
    from helloworld import say_hello
  File "helloworld.pyx", line 2, in init helloworld (helloworld.c:967)
    from hellotest import label
  File "/home/dusan/projects/temp/hellotest.py", line 1, in
    from helloworld import say_hello
ImportError: cannot import name say_hello
However, when I just remove label dependency (the very first line in helloworld.pyx and label in print statemet), code compiles and runs fine.
Can someone please tell me, how to access other module from within pyx code?
Thanks!

A: The problem was that you tried to import hellotest into helloworld and to import helloworld into hellotest. This is called a circular import, which means that the dependency-graph, where the nodes are the files to import and the vertices are the import statements, so, this graph has a circle, therefore it will never be a forest. This means that you need to read hellotest to be able to read helloworld, but you need to read helloworld to read hellotest. If you imagine something which tries to analyze the dependencies, then you will quickly realize that the circle creates an infinite loop. Try to not form circles with your import statements in the future and you will be safe against this kind of problem.


text:
Q: In tm package, remove all numbers except alphanumeric characters In r, I'm trying to keep words like 3g, 4g, 4s, etc. in my corpus when removing numbers while using the tm package.
When using removeNumbers how can I preserve alphanumeric characters like 3g, 4g, 4s, etc.? In other words, any digits that is together with another letter is to be preserved. Does anyone know of an alternative function that I could use if a custom function needs to be used instead?
examp1 <- "When 222 discussing performance 4g with colleagues, teaching, sending a bug report or searching for 55 guidance on mailing lists and here on SO, a reproducible example is often asked and 3g always helpful. What are your tips for creating an 333 excellent 444 example? How do you paste data structures from r in a text format? What other 443 galaxy 4s information should you include? Are there other tricks in addition to using dput(), dump() or structure()? When should you include library() or require() statements? Which reserved words should one avoid, in addition to c, df, data, etc? How does one make a great r reproducible example?"
examp2 <- "Sometimes the problem 24K really isn't reproducible with a smaller piece of data, no matter how hard you try, and doesn't happen with synthetic data (although it's useful to show how you produced synthetic data sets that did not reproduce the problem, because it rules out some hypotheses). Posting the data t 8888 the web somewhere and providing a URL may be necessary. If the data can't be released to the public at large but could be shared at all, then you may be able to offer to e-mail it to interested parties (although this will cut down the number of people who will bother to work on it). I haven't actually seen this 4444 done, because people who can't release their data are sensitive about releasing it any form, but it would seem plausible that in some cases one could still post data if it were sufficiently anonymized/scrambled/corrupted slightly in some way. If you can't do either of these then you probably need to hire a consultant to solve your problem"
examp3 <- "You are 888 most 1g likely to get good 5g help with your R problem if you provide a reproducible example. A reproducible example allows someone else to recreate your problem by just copying and pasting R code. There are four things you need to include to make your example reproducible: required packages, data, code, and a description of your R environment. Packages should be loaded at the top of the script, so it's easy to see which ones the example needs. The easiest way to include data in an email is to use dput() to generate the R code to recreate it. For example, to recreate the mtcars dataset in R, I'd perform the following steps: Run dput(mtcars) in R Copy the output In my reproducible script, type mtcars <- then paste. Spend a little bit of time ensuring that your code is easy for others to read: make sure you've used spaces and your variable names are concise, but informative, use comments to indicate where your problem lies, do your best to remove everything that is not related to the problem. The shorter your code is, the easier it is to understand. Include the output of sessionInfo() as a comment. This summarises your R environment and makes it easy to check if you're using an out-of-date package. You can check you have actually made a reproducible example by starting up a fresh R session and pasting your script in. Before putting all of your code in an email, consider putting it on http://gist.github.com/. It will give your code nice syntax highlighting, and you don't have to worry about anything getting mangled by the email system."
examp4 <- "Do your homework before posting: If it is clear that you have done basic background research, you are far more likely to get an informative response. See also Further Resources further down this page. Do help.search(keyword) and apropos(keyword) with different keywords (type this at the R prompt). Do RSiteSearch(keyword) with different keywords (at the R prompt) to search R functions, contributed packages and R-Help postings. See ?RSiteSearch for further options and to restrict searches. Read the online help for relevant functions (type ?functionname, e.g., ?prod, at the R prompt) If something seems to have changed in R, look in the latest NEWS file on CRAN for information about it. Search the R-faq and the R-windows-faq if it might be relevant (http://cran.r-project.org/faqs.html) Read at least the relevant section in An Introduction to R If the function is from a package accompanying a book, e.g., the MASS package, consult the book before posting. The R Wiki has a section on finding functions and documentation"
examp5 <- "Before 6g asking a technical question by e-mail, or in a newsgroup, or on a website chat board, do the following:  Try to find an answer by searching the archives of the forum you plan to post to. Try to find an answer by searching the Web. Try to find an answer by reading the manual. Try to find an answer by reading a FAQ. Try to find an answer by inspection or experimentation. Try to find an answer by asking a skilled friend. If you're a programmer, try to find an answer by reading the source code. When you ask your question, display the fact that you have done these things first; this will help establish that you're not being a lazy sponge and wasting people's time. Better yet, display what you have learned from doing these things. We like answering questions for people who have demonstrated they can learn from the answers. Use tactics like doing a Google search on the text of whatever error message you get (searching Google groups as well as Web pages). This might well take you straight to fix documentation or a mailing list thread answering your question. Even if it doesn't, saying "I googled on the following phrase but didn't get anything that looked promising" is a good thing to do in e-mail or news postings requesting help, if only because it records what searches won't help. It will also help to direct other people with similar problems to your thread by linking the search terms to what will hopefully be your problem and resolution thread. Take your time. Do not expect to be able to solve a complicated problem with a few seconds of Googling. Read and understand the FAQs, sit back, relax and give the problem some thought before approaching experts. Trust us, they will be able to tell from your questions how much reading and thinking you did, and will be more willing to help if you come prepared. Don't instantly fire your whole arsenal of questions just because your first search turned up no answers (or too many). Prepare your question. Think it through. Hasty-sounding questions get hasty answers, or none at all. The more you do to demonstrate that having put thought and effort into solving your problem before seeking help, the more likely you are to actually get help. Beware of asking the wrong question. If you ask one that is based on faulty assumptions, J. Random Hacker is quite likely to reply with a uselessly literal answer while thinking Stupid question..., and hoping the experience of getting what you asked for rather than what you needed will teach you a lesson."

corpus <- Corpus(VectorSource(c(examp1, examp2, examp3, examp4)))

# How can I remove numbers except for numbers with words (1g, 4g, etc.) so after doing so it would look like...

inspect(corpus)

    [1] "When discussing performance 4g with colleagues, teaching, sending a bug report or searching for guidance on mailing lists and here on SO, a reproducible example is often asked and 3g always helpful. What are your tips for creating an excellent example? How do you paste data structures from r in a text format? What other galaxy 4s information should you include? Are there other tricks in addition to using dput(), dump() or structure()? When should you include library() or require() statements? Which reserved words should one avoid, in addition to c, df, data, etc? How does one make a great r reproducible example?"
    [2] "Sometimes the problem 24K really isn't reproducible with a smaller piece of data, no matter how hard you try, and doesn't happen with synthetic data (although it's useful to show how you produced synthetic data sets that did not reproduce the problem, because it rules out some hypotheses). Posting the data t 8888 the web somewhere and providing a URL may be necessary. If the data can't be released to the public at large but could be shared at all, then you may be able to offer to e-mail it to interested parties (although this will cut down the number of people who will bother to work on it). I haven't actually seen this done, because people who can't release their data are sensitive about releasing it any form, but it would seem plausible that in some cases one could still post data if it were sufficiently anonymized/scrambled/corrupted slightly in some way. If you can't do either of these then you probably need to hire a consultant to solve your problem"
    [3] "You are most 1g likely to get good 5g help with your R problem if you provide a reproducible example. A reproducible example allows someone else to recreate your problem by just copying and pasting R code. There are four things you need to include to make your example reproducible: required packages, data, code, and a description of your R environment. Packages should be loaded at the top of the script, so it's easy to see which ones the example needs. The easiest way to include data in an email is to use dput() to generate the R code to recreate it. For example, to recreate the mtcars dataset in R, I'd perform the following steps: Run dput(mtcars) in R Copy the output In my reproducible script, type mtcars <- then paste. Spend a little bit of time ensuring that your code is easy for others to read: make sure you've used spaces and your variable names are concise, but informative, use comments to indicate where your problem lies, do your best to remove everything that is not related to the problem. The shorter your code is, the easier it is to understand. Include the output of sessionInfo() as a comment. This summarises your R environment and makes it easy to check if you're using an out-of-date package. You can check you have actually made a reproducible example by starting up a fresh R session and pasting your script in. Before putting all of your code in an email, consider putting it on http://gist.github.com/. It will give your code nice syntax highlighting, and you don't have to worry about anything getting mangled by the email system."
    [4] "Do your homework before posting: If it is clear that you have done basic background research, you are far more likely to get an informative response. See also Further Resources further down this page. Do help.search(keyword) and apropos(keyword) with different keywords (type this at the R prompt). Do RSiteSearch(keyword) with different keywords (at the R prompt) to search R functions, contributed packages and R-Help postings. See ?RSiteSearch for further options and to restrict searches. Read the online help for relevant functions (type ?functionname, e.g., ?prod, at the R prompt) If something seems to have changed in R, look in the latest NEWS file on CRAN for information about it. Search the R-faq and the R-windows-faq if it might be relevant (http://cran.r-project.org/faqs.html) Read at least the relevant section in An Introduction to R If the function is from a package accompanying a book, e.g., the MASS package, consult the book before posting. The R Wiki has a section on finding functions and documentation"
    [5] "Before 6g asking a technical question by e-mail, or in a newsgroup, or on a website chat board, do the following:  Try to find an answer by searching the archives of the forum you plan to post to. Try to find an answer by searching the Web. Try to find an answer by reading the manual. Try to find an answer by reading a FAQ. Try to find an answer by inspection or experimentation. Try to find an answer by asking a skilled friend. If you're a programmer, try to find an answer by reading the source code. When you ask your question, display the fact that you have done these things first; this will help establish that you're not being a lazy sponge and wasting people's time. Better yet, display what you have learned from doing these things. We like answering questions for people who have demonstrated they can learn from the answers. Use tactics like doing a Google search on the text of whatever error message you get (searching Google groups as well as Web pages). This might well take you straight to fix documentation or a mailing list thread answering your question. Even if it doesn't, saying "I googled on the following phrase but didn't get anything that looked promising" is a good thing to do in e-mail or news postings requesting help, if only because it records what searches won't help. It will also help to direct other people with similar problems to your thread by linking the search terms to what will hopefully be your problem and resolution thread. Take your time. Do not expect to be able to solve a complicated problem with a few seconds of Googling. Read and understand the FAQs, sit back, relax and give the problem some thought before approaching experts. Trust us, they will be able to tell from your questions how much reading and thinking you did, and will be more willing to help if you come prepared. Don't instantly fire your whole arsenal of questions just because your first search turned up no answers (or too many). Prepare your question. Think it through. Hasty-sounding questions get hasty answers, or none at all. The more you do to demonstrate that having put thought and effort into solving your problem before seeking help, the more likely you are to actually get help. Beware of asking the wrong question. If you ask one that is based on faulty assumptions, J. Random Hacker is quite likely to reply with a uselessly literal answer while thinking Stupid question..., and hoping the experience of getting what you asked for rather than what you needed will teach you a lesson."

A: Here's a simple gsub with a regex pattern. I suspect that it may fail with real data, but since you provided basically nothing to test this on, this seems a reasonable place to start
> gsub("([ ,.])([[:digit:]. ]+)([ ,.])", "\\1\\3", c('3g 44 999 4g 4s 555 42.') )
[1] "3g  4g 4s ."

This applies that strategy to a Corpus:
> modcorp <- lapply(corpus, function(cp) { cp[['content']] <- gsub("([ ,.])([[:digit:]. ]+)([ ,.])", "\\1\\3", cp[['content']] ); return(cp) }
+ )
> str(modcorp)
List of 4
 $ 1:List of 2
  ..$ content: chr "When  discussing performance 4g with colleagues, teaching, sending a bug report or searching for  guidance on mailing lists and"| __truncated__
  ..$ meta   :List of 7
  .. ..$ author       : chr(0)
  .. ..$ datetimestamp: POSIXlt[1:1], format: "2015-11-09 18:05:27"
  .. ..$ description  : chr(0)
  .. ..$ heading      : chr(0)
  .. ..$ id           : chr "1"
  .. ..$ language     : chr "en"
  .. ..$ origin       : chr(0)
  .. ..- attr(*, "class")= chr "TextDocumentMeta"
  ..- attr(*, "class")= chr [1:2] "PlainTextDocument" "TextDocument"
 $ 2:List of 2
  ..$ content: chr "Sometimes the problem 24K really isn't reproducible with a smaller piece of data, no matter how hard you try, and doesn't happe"| __truncated__
  ..$ meta   :List of 7
  .. ..$ author       : chr(0)
  .. ..$ datetimestamp: POSIXlt[1:1], format: "2015-11-09 18:05:27"
  .. ..$ description  : chr(0)
  .. ..$ heading      : chr(0)
  .. ..$ id           : chr "2"
  .. ..$ language     : chr "en"
  .. ..$ origin       : chr(0)
  .. ..- attr(*, "class")= chr "TextDocumentMeta"
  ..- attr(*, "class")= chr [1:2] "PlainTextDocument" "TextDocument"
 $ 3:List of 2
  ..$ content: chr "You are  most 1g likely to get good 5g help with your R problem if you provide a reproducible example. A reproducible example a"| __truncated__
  ..$ meta   :List of 7
  .. ..$ author       : chr(0)
  .. ..$ datetimestamp: POSIXlt[1:1], format: "2015-11-09 18:05:27"
  .. ..$ description  : chr(0)
  .. ..$ heading      : chr(0)
  .. ..$ id           : chr "3"
  .. ..$ language     : chr "en"
  .. ..$ origin       : chr(0)
  .. ..- attr(*, "class")= chr "TextDocumentMeta"
  ..- attr(*, "class")= chr [1:2] "PlainTextDocument" "TextDocument"
 $ 4:List of 2
  ..$ content: chr "Do your homework before posting: If it is clear that you have done basic background research, you are far more likely to get an"| __truncated__
  ..$ meta   :List of 7
  .. ..$ author       : chr(0)
  .. ..$ datetimestamp: POSIXlt[1:1], format: "2015-11-09 18:05:27"
  .. ..$ description  : chr(0)
  .. ..$ heading      : chr(0)
  .. ..$ id           : chr "4"
  .. ..$ language     : chr "en"
  .. ..$ origin       : chr(0)
  .. ..- attr(*, "class")= chr "TextDocumentMeta"
  ..- attr(*, "class")= chr [1:2] "PlainTextDocument" "TextDocument"

A: Try the quanteda package, it knows the difference between alphanumeric and numeric.  E.g.
> quanteda::tokenize("You are 888 most 1g likely to get gr8 help with your 24K R problem.",
+                    removePunct = TRUE, removeNumbers = TRUE)
tokenizedText object from 1 document.
Component 1 :
 [1] "You"     "are"     "most"    "1g"      "likely"  "to"      "get"     "gr8"     "help"
[10] "with"    "your"    "24K"     "R"       "problem"

removeNumbers only removes numbers, not digits.  You can create a corpus directly from texts using quanteda::corpus(), or from a tm VCorpus or, as in the example above, tokenise directly on a character (vector) object.
Added:
If you want to return a tm TermDocumentMatrix, wrap it up like this:
examp <-  c("When 222 discussing performance 4g with colleagues, teaching, sending a bug report or searching for 55 guidance on mailing lists and here on SO, a reproducible example is often asked and 3g always helpful. What are your tips for creating an 333 excellent 444 example? How do you paste data structures from r in a text format? What other 443 galaxy 4s information should you include? Are there other tricks in addition to using dput(), dump() or structure()? When should you include library() or require() statements? Which reserved words should one avoid, in addition to c, df, data, etc? How does one make a great r reproducible example?",
            "Sometimes the problem 24K really isn't reproducible with a smaller piece of data, no matter how hard you try, and doesn't happen with synthetic data (although it's useful to show how you produced synthetic data sets that did not reproduce the problem, because it rules out some hypotheses). Posting the data t 8888 the web somewhere and providing a URL may be necessary. If the data can't be released to the public at large but could be shared at all, then you may be able to offer to e-mail it to interested parties (although this will cut down the number of people who will bother to work on it). I haven't actually seen this 4444 done, because people who can't release their data are sensitive about releasing it any form, but it would seem plausible that in some cases one could still post data if it were sufficiently anonymized/scrambled/corrupted slightly in some way. If you can't do either of these then you probably need to hire a consultant to solve your problem",
            "You are 888 most 1g likely to get good 5g help with your R problem if you provide a reproducible example. A reproducible example allows someone else to recreate your problem by just copying and pasting R code. There are four things you need to include to make your example reproducible: required packages, data, code, and a description of your R environment. Packages should be loaded at the top of the script, so it's easy to see which ones the example needs. The easiest way to include data in an email is to use dput() to generate the R code to recreate it. For example, to recreate the mtcars dataset in R, I'd perform the following steps: Run dput(mtcars) in R Copy the output In my reproducible script, type mtcars <- then paste. Spend a little bit of time ensuring that your code is easy for others to read: make sure you've used spaces and your variable names are concise, but informative, use comments to indicate where your problem lies, do your best to remove everything that is not related to the problem. The shorter your code is, the easier it is to understand. Include the output of sessionInfo() as a comment. This summarises your R environment and makes it easy to check if you're using an out-of-date package. You can check you have actually made a reproducible example by starting up a fresh R session and pasting your script in. Before putting all of your code in an email, consider putting it on http://gist.github.com/. It will give your code nice syntax highlighting, and you don't have to worry about anything getting mangled by the email system.",
            "Do your homework before posting: If it is clear that you have done basic background research, you are far more likely to get an informative response. See also Further Resources further down this page. Do help.search(keyword) and apropos(keyword) with different keywords (type this at the R prompt). Do RSiteSearch(keyword) with different keywords (at the R prompt) to search R functions, contributed packages and R-Help postings. See ?RSiteSearch for further options and to restrict searches. Read the online help for relevant functions (type ?functionname, e.g., ?prod, at the R prompt) If something seems to have changed in R, look in the latest NEWS file on CRAN for information about it. Search the R-faq and the R-windows-faq if it might be relevant (http://cran.r-project.org/faqs.html) Read at least the relevant section in An Introduction to R If the function is from a package accompanying a book, e.g., the MASS package, consult the book before posting. The R Wiki has a section on finding functions and documentation",
            "Before 6g asking a technical question by e-mail, or in a newsgroup, or on a website chat board, do the following:  Try to find an answer by searching the archives of the forum you plan to post to. Try to find an answer by searching the Web. Try to find an answer by reading the manual. Try to find an answer by reading a FAQ. Try to find an answer by inspection or experimentation. Try to find an answer by asking a skilled friend. If you're a programmer, try to find an answer by reading the source code. When you ask your question, display the fact that you have done these things first; this will help establish that you're not being a lazy sponge and wasting people's time. Better yet, display what you have learned from doing these things. We like answering questions for people who have demonstrated they can learn from the answers. Use tactics like doing a Google search on the text of whatever error message you get (searching Google groups as well as Web pages). This might well take you straight to fix documentation or a mailing list thread answering your question. Even if it doesn't, saying "I googled on the following phrase but didn't get anything that looked promising" is a good thing to do in e-mail or news postings requesting help, if only because it records what searches won't help. It will also help to direct other people with similar problems to your thread by linking the search terms to what will hopefully be your problem and resolution thread. Take your time. Do not expect to be able to solve a complicated problem with a few seconds of Googling. Read and understand the FAQs, sit back, relax and give the problem some thought before approaching experts. Trust us, they will be able to tell from your questions how much reading and thinking you did, and will be more willing to help if you come prepared. Don't instantly fire your whole arsenal of questions just because your first search turned up no answers (or too many). Prepare your question. Think it through. Hasty-sounding questions get hasty answers, or none at all. The more you do to demonstrate that having put thought and effort into solving your problem before seeking help, the more likely you are to actually get help. Beware of asking the wrong question. If you ask one that is based on faulty assumptions, J. Random Hacker is quite likely to reply with a uselessly literal answer while thinking Stupid question..., and hoping the experience of getting what you asked for rather than what you needed will teach you a lesson.")
dtm <- dfm(examp, removePunct = TRUE, removeNumbers = TRUE)
as.TermDocumentMatrix(as.DocumentTermMatrix(dtm))
# <<TermDocumentMatrix (terms: 469, documents: 5)>>
# Non-/sparse entries: 652/1693
# Sparsity           : 72%
# Maximal term length: 18
# Weighting          : term frequency (tf)


text:
Q: How do I make line breaks in a Javascript countdown timer? I have a countdown timer in an inline JS element.
As of now they are all in one line, I would like days/hours/mins/secs to appear under each number, as shown here: http://prnt.sc/b8le72 - also, is it possible to style the text and numbers individually in CSS? (like making the text orange but keep numbers white)
https://jsfiddle.net/eyd8fd4x/
HTML:
<!doctype html>

<meta charset="utf-8">
<title>onepageskiw</title>
<link href="styles.css" rel="stylesheet" type="text/css">

CSS:
@charset "utf-8";

body {
margin:0;
}

#countdowner {
color:white;
position:absolute;
margin:0;
margin-top:5em;
padding:0;
text-align:center;
width:100%;
font-size:1em;
font-family:Helvetica;
}

#forsidediv {
position:fixed;
left: 0;
right: 0;
top: 0;
bottom: 0;
text-align: center;
}

#forsidepic {
width: 100%;
}

A: Approach #1: Involving no change to the current div layout:
Use nbsp or such equivalent whitespace characters to pad the text. This is pure hard coding of the text content and shall break for many situations.
Working fiddle here.
Approach #2: Splitting the current div (that holds the whole data) into four separate divs - one each for days, hours, etc.
Ensure these fours divs are laid out "side-by-side" rather than "one above another". The easiest approach I am aware of for solving this 'side-by-side' problem is the old school table layout. So, put all the divs in a single
 of the table, to render them as a single row. That'll do the trick.
Also, I found this answer helpful, although I could not get it to work here.
Working fiddle with the table layout here.
Working fiddle with the table layout and color formatting :
Used the answer here for guidance:
span in JS: here
span in the HTML: here

A: My working suggestion which also pads the numbers and handles plural day/days hour/hours in Danish

CountDownTimer('06/25/2016 10:00 AM', 'countdown');

function pad(num) {
  return String("0" + num).slice(-2);
}

function CountDownTimer(dt, id) {
  var end = new Date(dt);

  var _second = 1000;
  var _minute = _second * 60;
  var _hour = _minute * 60;
  var _day = _hour * 24;
  var timer;
  document.getElementById(id).innerHTML = '

' +
    '

' +
    '

' +
    '

';

  function showRemaining() {
    var now = new Date();
    var distance = end - now;
    if (distance < 0) {

      clearInterval(timer);
      document.getElementById(id).innerHTML = 'EXPIRED!';

      return;
    }
    var days = Math.floor(distance / _day);
    var hours = Math.floor((distance % _day) / _hour);
    var minutes = Math.floor((distance % _hour) / _minute);
    var seconds = Math.floor((distance % _minute) / _second);

    document.getElementById(id + "days").innerHTML = days + '
dag' + (days == 1 ? "" : "e");
    document.getElementById(id + "hours").innerHTML = pad(hours) + '
time' + (hours == 1 ? "" : "r");
    document.getElementById(id + "mins").innerHTML = pad(minutes) + '
 minut' + (minutes == 1 ? "" : "ter");
    document.getElementById(id + "secs").innerHTML = pad(seconds) + '
sekund' + (seconds == 1 ? "" : "er");
  }

  timer = setInterval(showRemaining, 1000);
}
@charset "utf-8";
body {
  margin: 0;
}

#countdowner {
  color: red;
  position: absolute;
  margin: 0;
  margin-top: 5em;
  padding: 0;
  text-align: center;
  width: 100%;
  font-size: 1em;
  font-family: Helvetica;
}

#forsidediv {
  position: fixed;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  text-align: center;
}

#forsidepic {
  width: 100%;
}

#countdown {
  width: 100%
}

.tm {
  text-align: center;
  display: inline-block;
  padding-left: 20px
}


text:
Q: How do I set default value for a foreign key column in mysql                        table1

            bookid     bookname         author
             0         No book           no author
             1         Engg Maths        Greiwal
             2         Java Basics       James Gosling
             3         Mahabharata       Ved Vyasa
             4         Ramayana          Valmiki
             5         Harry Potter      JK Rowling

                    table2

           userid       name           bookid
            1          Arjun             2
            2          Charles           2
            3          Babbage           3

Am having table1 and table2. In the table1 bookid is primary key and the table2 bookid is foreign key. I want to set table2 bookid default value to 0.
Is there any possibilities?
We tried with default value as zero.
It throws an exceptions "Cannot add or update child row: a foreign key constaint fails"

A: why do you have a row called "no book"? all you need in a table are books, not a "no book"
first delete that useless row from table1, then in table2:
allow the foreign key to be null, if the foreign key is null then that means "no book"
basically, now "null" is the default value, and null means "no book"
that is what you want

A: I just ran this on mysql...
create table table1 (
    bookid int not null primary key,
    bookname varchar(100) not null,
    author varchar(100) not null
);

create table table2 (
    userid int not null,
    username varchar(100) not null,
    bookid int not null default 0
);
alter table table2 add constraint fk1 foreign key (bookid) references table1(bookid);

insert into table1(bookid,bookname,author) values (0,'None','none');

insert into table2(userid, username) values (1,'bob');

select * from table2;

Result
1    bob    0

You could also make the fk column table2.bookid nullable (bookid int null,). The choice to allow foreign keys to be null or use 'sentinel values' is a design choice best made consciously, if you're going to build a lot of code.

A: If I understood your problem,Possible two solution

*

*Either table1 should have default row ,and table 2's default value will be referring to it

*Allow NULL values to be foreign key
Allowing null values or default values-SQL fiddle


text:
Q: @ManyToOne is fetching all columns of join table while inserting new record I am using JPA 2.0 with EclipseLink persistence provider and Hibernate entity manager 4.3.10.Final. I have a @ManyToOne relationship between Employee and Office entities. I'm inserting a new Employee using EntityManagerFactory. The employee instance refers to an existing Office.The code works but the queries show that it is fetching all columns of Office instead of just officeId. How can I fine tune the queries to avoid fetching all columns of Office while inserting a new employee? I tried using FetchType.LAZY on @ManyToOne but it does not work.
Employee.java
@Entity
public class Employee {

    @Id
    @SequenceGenerator(name="employeeSequence",allocationSize=1, sequenceName="EMP_SEQ")
    @GeneratedValue(strategy=GenerationType.SEQUENCE,generator="employeeSequence")
    private int empId;

    @Column(name="FIRST_NAME")
    private String firstName;

    @Column(name="LAST_NAME")
    private String lastName;

    @Column(name="DOB")
    private Date dateOfBirth;

    private Date hireDate;

    @ManyToOne
    @JoinColumn(name="location")
    private int location;

Office.java
@Entity
public class Office {
    @Id
    private int officeId;

    private String location;
    private String address1;
    private String address2;
    private String city;
    private String state;
    private String country;
    private String zipcode;

Code which creates Employee object
Employee emp = new Employee();
emp.setFirstName(firstName);
emp.setLastName(lastName);
emp.setDateOfBirth(dob);
emp.setHireDate(hiredate);

Office office = new Office();
office.setOfficeId(officeId);
emp.setLocation(office);

SQL queries
Hibernate:
select
     EMP_SEQ.nextval
 from
    dual

Hibernate:
select
     office_.officeId,
    office_.address1 as address2_1_,
    office_.address2 as address3_1_,
    office_.city as city4_1_,
    office_.country as country5_1_,
    office_.location as location6_1_,
    office_.state as state7_1_,
    office_.zipcode as zipcode8_1_
from
   Office office_
 where
   office_.officeId=?

Hibernate:
insert
 into
   Emp
     (DOB, FIRST_NAME, hireDate, LAST_NAME, location, empId)
 values (?, ?, ?, ?, ?, ?)

A: It is pretty common for developers to query their database based on some foreign-key value to get a persistent instances of a relationship when they are saving a new object, something like the following:
@Entity
public class Employee {
  // other stuff removed for breavity
  @ManyToOne
  private Office office;
}

@Entity
public class Office {
  // no relationship back to Employee
}

// some repository method
public Employee save(String employeeName, Long officeId) {
  final Office office = entityManager.find( Office.class, offceId );
  final Employee employee = new Employee( employeeName, officeId );
  entityManager.persist( employee );
  return employee;
}

In this case, the persistence provider will query the database to construct an Office entity all for the purpose of associating the identifier with the Employee when persisted.  As you've noticed, this is not only unnecessary, but can impact performance.
Another solution to avoid the database fetch would be to leverage either Session#load in terms of the native Hibernate API or EntityManager#getReference for JPA.  For all intents and purposes, they're synonymous in that they accept a class-type and primary key value and construct a proxy that represents the class-type whose internal state will be loaded lazily if accessed.
So by changing the repository method above to:
// some repository method
public Employee save(String employeeName, Long officeId) {
  final Office office = entityManager.getReference( Office.class, offceId );
  final Employee employee = new Employee( employeeName, officeId );
  entityManager.persist( employee );
  return employee;
}

There should no longer be a fetch against the data store for Office.


text:
Q: How do I programatically control a Chrome instance from the command line? How do I control a running Google Chrome instance from the command line?  I'm hoping there's something like a -remote flag that will allow me to send in some javascript or somesuch.  In particular, I would like to reload the topmost document on the foremost window.
I'm especially interested in Linux/MacOS solutions.

A: Take a look at http://code.google.com/p/chromedevtools/ . It might be you can use the Debugging Protocol to do the job.
There is also an Ruby Client.
There is also chromix.

A: You can use this command line tool if you're on a Mac - it uses the Chrome Scripting API, I guess
https://github.com/prasmussen/chrome-cli


text:
Q: Is there a c# IDE for Android tablet? This might be a silly question, but I'll ask it anyway.
I'm on the road a lot or otherwise away from my computer, and i don't own a laptop sadly, and I'm still a beginner in programming.
I'm wondering if there is a c# IDE that would run on an android tablet, or will i have to stick to text editors while away from my PC?
Thanks in advance!

A: A C# IDE doesn't exist on Android as far as i know, but you could have a look at Touchqode, which is a great code editor.

Touchqode is a true mobile code editor that comes with syntax
  highlighting, autocomplete and other features found in a desktop IDE


text:
Q: CustomShadowVariable not calling listener methods in optaplanner java     @Getter
    @Setter
    @PlanningEntity
    public class Match {

        private SimpleScore score;
        private int  id;
        @CustomShadowVariable(variableListenerClass = MatchVariableListner.class, sources = @PlanningVariableReference(entityClass = Team.class ,variableName = "match"))
        private List<Team> team;
        private Court court;
        private Date available;

    }

this is the Match class
    @Getter
    @Setter
    @PlanningEntity
    public class Team {

        private Grade grade;
        private Court court;
        @PlanningVariable(valueRangeProviderRefs = {"matches"})
        private Match match;
        private Club club;
        private Divison divison ;
        private List<Date> availableDates;
        private String name;
        private String id;
        private List<Sequence> sequence;

    }

this is team class
    public class MatchVariableListner implements VariableListener<Team> {

        protected void updateMatch(ScoreDirector scoreDirector, Team team) {

            System.out.println("hello");

        }

        @Override
        public void beforeEntityAdded(ScoreDirector scoreDirector, Team team) {

        }

        @Override
        public void afterEntityAdded(ScoreDirector scoreDirector, Team team) {

            updateMatch(scoreDirector,team);
        }

        @Override
        public void beforeVariableChanged(ScoreDirector scoreDirector, Team team) {
            System.out.println("hehhe");

        }

        @Override
        public void afterVariableChanged(ScoreDirector scoreDirector, Team team) {
            updateMatch(scoreDirector,team);
        }

        @Override
        public void beforeEntityRemoved(ScoreDirector scoreDirector, Team team) {
            System.out.println("hehhe");

        }

        @Override
        public void afterEntityRemoved(ScoreDirector scoreDirector, Team team) {
            System.out.println("hehhe");

        }
    }

this is the listner
    @Getter
    @Setter
    @NoArgsConstructor
    @AllArgsConstructor
    @PlanningSolution
    public class WSASolution {

        @PlanningEntityCollectionProperty
        List<Team> teams;
        @ProblemFactCollectionProperty
        @ValueRangeProvider(id = "matches")
        List<Match> matches;
        @ProblemFactCollectionProperty
        List<Court> courts;

        public WSASolution(List<Team> teams, List<Match> matches, List<Court> courts) {
            this.teams = teams;
            this.matches = matches;
            this.courts = courts;
        }
        @PlanningScore
        private HardSoftScore score;

    }

this is the planning solution entity  it runs good by adding matches to every team but the inverse shadow variable not calling the listener methods through which i want to have some operations.but the listener is not getting calls to the interface overridden methods.
please help thanks in advance


text:
Q: Calling luabind derived member as a coroutine The luabind documentation says to call a Lua-derived virtual member from C++, you create a wrapper class derived from luabind::wrap_base and call the function like so:
class BaseWrapper : public Base, public luabind::wrap_base
{
    public:
        virtual void foo()
        {
            call<void>("foo");
        }
};

So far so good - I have this much working.
But how do I implement BaseWrapper::foo() to call the overridden foo (on the Lua side) as a coroutine (using resume_function) instead of calling it directly with call?
This is how it's done with non-member functions:
luabind::object func = luabind::globals(L)["bar"];
luabind::resume_function<void>(func);

I think what I need to know is how to get func for foo (as implemented by the Lua-derived class), and then my existing resume_function logic should work as-is.

A: So I've figured out the answer to this problem. It seems that the simplest solution is to pass self from Lua when you construct the object and then look up the function from its table:
On the C++ side:
BaseWrapper::BaseWrapper(luabind::object self) : _self(self)
{ }

virtual void BaseWrapper::foo()
{
  luabind::object func = _self["foo"];

  /* now put func in coroutine scheduler queue and when appropriate call:

     luabind::resume_function<void>(func, _self);
  */
}

And in Lua:
class 'Derived' (Base)
  function Derived:__init()
    Base.__init(self, self)     -- the second self is param to BaseWrapper()
  end

  function Derived:foo()
    -- here is the target function
  end
end


text:
Q: Async task is not triggered I have an app which should send locations once the app is stopped,
i override onstop method and it run the service perfect
but when it reached location sender nothing happened here is my service code:
    @Override
    public void onCreate() {
        super.onCreate();
        dbHelper = new DBHelper(this);
        warnniSharedPreference = new WarnniSharedPreference(this);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        LocationSender locationSender = new LocationSender();
        locationSender.execute();
        return android.app.Service.START_NOT_STICKY;
    }
    private class LocationSender extends AsyncTask<Void, Void, Void> {
        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            if (null != response) {
           dbHelper.deleteAllRecords(DBHelper.LOCATION_TRACKER_TABLE_NAME);
                dbHelper.deleteAllRecords(DBHelper.IMAGES_TABLE_NAME);
            }
        }
        @Override
        protected Void doInBackground(Void... voids) {
            try {
                int start = 0;
                int end = 0;
                ArrayList<WarnniLocation> locationArrayList = dbHelper.getAllLocationRecords();
                int locationGroupSize = (int) Math.ceil((double) locationArrayList.size() / (double) 60);
                for (int i = 0; i < locationGroupSize; i++) {
                    MultipartUtility multipartUtility = new MultipartUtility(Constants.ADD_LOCATION_DATA, "UTF-8");
                    multipartUtility.addFilePart("image", new File(imagesPaths.get(i)));
                    multipartUtility.addFormField("driverId", String.valueOf(warnniSharedPreference.getKey("id")));
                    if (i == 0) {
                        end = 59;
                    } else {
                        end = i * 60 + 59;
                        if (end >= locationArrayList.size()) {
                            end = locationArrayList.size() - 1;
                        }
                    }
                    multipartUtility.addFormField("locations", new Gson().toJson(locationArrayList.subList(start, end)));
                    response = multipartUtility.finish();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
    }

Please advise
thanks in advance and any help will be appreciated

A: Hi there is no problem usind asynctask in services . All you need to do is to use doin background method only because that runs in the background . But onPostExecute method runs on ui thread. So remove onPostExecute method.


text:
Q: Override max graphics dimensions in latex? So, I'm writing a report on powerautomate flow code. I'm attaching screenshots in the appendix of code (because it's visual code blocks), but these are VERY large images. (3500x21094) with a really tight ratio.
I'm using code inspired by this post to split the images into pages :
\documentclass[11pt,a4paper]{article}
\usepackage{adjustbox}
\usepackage{fp}
\usepackage{graphicx}
\graphicspath{ {./Assets/} }
\newcommand{\cropImg}[3]{
    \FPeval{\top}{#2 / #3}
    \FPeval{\bot}{(#3-#2-1) / #3}

    \adjincludegraphics[
            width=\textwidth,
            trim={0 {\bot\height} 0 {\top\height}},
            clip, % needed for trim to work
        ]{#1}
}

\begin{document}
  \cropImg{LargePowerFlowImage}{1}{10}

\end{document}

I'm running into "dimensions too large" when running this on some of my tallest screenshots when building though.
This link suggests this is because I'm going beyond the capacity of latex, and the images wouldn't fit.HOWEVER it's only too big as an actual image, and the result of \cropimage is well within reason.
ABD: EveryShipout initializing macros ( FP-EVAL ( FP-UPN ( FP-DIV ) ) )
( FP-EVAL ( FP-UPN ( FP-SUB ) ( FP-SUB ) ( FP-DIV ) ) )
! Dimension too large.
<argument> \ht \@tempboxa

l.19   \cropImg{FlowCompute}{1}{10}

Is there a way to override Latex's limits on graphics size so I can import those screenshots into the code, where they are broken down ?
(also posted on Reddit


text:
Q: How can I run a node.js server I'm new to node and have many things unclear.
Like, for php, I just need a index.php file on server's root dir and it can work by itself.
However, for a node.js file, we need to "node" command it in terminal right?
So what if we close that terminal? How can I keep it running to accept my requests?

A: You are correct in saying that the 'node' command will start a node process with whatever script you supply to it.
As far as keeping it running, there are several ways to do it.  There are plenty of CLI libraries that will help you.  For example, this one is called Forever
If you are using linux, you can simply run the node process as a background task:
node server.js &

A: To run node without terminal, you might want to check out one of these modules depending on your platform:
node-mac
node-windows
node-linux


text:
Q: Почему vue не связывает html атрибуты <template lang="pug">
  div(:class="internalClass")
    | text
</template>

<style lang="sass">
  .classname
    color: red
</style>

<script>
  export default {
    data () { return { internalClass: 'classname' } }
  }
</script>

При использовании компонента
<v-component class="otheClass" />

otherClass - игнорируется (список классов перезаписывается внутри компонента)

Приведенный пример упрощен, но решение проблемы для него, решит проблему для ниже приведенного кода (оригинала)

Оригинал
<style lang="sass" module>
  @import '../../assets/sass/elements/link.sass'
</style>

<script>
  const state = ctx => ({
    staticClass: ctx.$style.link
  })

  export default {
    name: 'v-lnk',
    props: {
      to: { type: String, required: false }
    },
    functional: true,
    render (h, ctx) {
      return ctx.props.to === undefined
        ? <a {...state(ctx)}> { ctx.children } </a>
        : <nuxt-link to={ctx.props.to} {...state(ctx)}> { ctx.children } </nuxt-link>
    }
  }
</script>

<style lang="sass" module>

Не влияет на ошибку (проверял)
Добавление ключа 'class' в props тоже не помогает, вижу лишь один выход, завести prop 'className' и проксировать классы извне во внутрь компонента через него
<v-lnk className="otherClass"> Link </v-lnk>

Смена staticClass на 'class' тоже не влияет


text:
Q: Old network login passed to IIS Let me start by saying that I am not a server guy - I am a developer. But I develop and manage an ASP.NET application that uses Windows authentication. I've run into the problem I am about to describe before, and I would just like to understand how to remedy it since I am the one who always gets the original support request.
A user, let's call her JaneDoe, has just gotten married and her login has been changed to JaneJones. We have an application that uses Windows authentication to store the user's login name to a table and then redirects the user to another non-Windows authenticated site with a GUID which points to the table entry we just made. When the user reaches the second site, we read in the login name from the database using the GUID that was passed. Then, we look up the login name in another database where we track application permissions.
The problem is that the user is logging into her workstation as JaneJones, but the Windows authenticated site is still receiving a login name of JaneDoe. Is this a domain controller issue? Is it a workstation issue? What's the best way to resolve this?

A: Are you sure Login name was changed and not the display name? You can check her log on name on her pc by
Start -> Run -> cmd  ->OK
In the CMD window type
  set username

This shows her windows userid. If normal Windows authenication is used with IE, this is the user id being presented to Webserver. If you IIS logging, this is the same ID you will see in the log.

A: If you've confirmed that the username really was changed (see ggonsalv's suggestion), double check to make sure the user didn't check the IE box to save the password.  Follow these steps:

*

*Control Panel

*User Accounts

*Click the Advanced Tab

*Manage Passwords

If you see the server address you're trying to connect to in there, select it, and click remove.

A: Yep, I've seen this before with IIS 6. Turns out there's a token cache external to the W3WP instance, so restarting that (i.e. recycling) doesn't help; I can't remember the details, but either an IISReset or a whole-server restart is required to clear it.


text:
Q: How to have different types in Multi dimensional array Java Question from my Java class that I don't understand:
Declare a multi-dimensional array of type Person that can be used to store a chore list for a group of people for every day of the week and every week of the year.
How do I declare this? It would be Dimension1 person D2 String D3 int d4 int.
I thought you couldnt have different types so maybe im misunderstanding question?
Thanks for any help.
Here's person class:
package ProvidedClasses;

public class Person
{
private String name;

public Person()
{
    name = "John Doe";
}

public String getName()
{
    return name;
}

}

A: The beauty of Java is that (almost) everything is an Object. So you may have multidimensional array of Objects and just remember that first index is Person, second is String and third is Integer.
However arrays are lower level and they are rarely used for dynamic data storing. Use Collections and their advantages. It's not clear what you want to achieve but here is one possible solution:
HashMap<String,HashMap<String,HashMap<String,Person>>> chore;
//So, access could be like
chore.get("Friday").get("25").get("Andy"); // get Andy on Friday of 25-th week.

Or
HashMap<String,HashMap<String,ArrayList<Person>>> choreN;
chore.get("Friday").get("25").get(12); // 12-th person on Friday 25-th week.

A: A multidimensional array of type person (unless I'm missing something), and given that you will have 7 days in any given week (and there are 52 weeks in a year) and assuming you have x people (10 for the sake of argument) in your group that might look something like
int x = 10;
Person[][][] multidimensionalArrayOfPersons = new Person[x][7][52];

Then, your Person class should have some Chore(s).


text:
Q: How to convert RSS pubDate string to DateTime in flutter? I'm kei, this is my first question in stackoverflow.
I want to convert RSS pubDate string(like this → "Tue, 28 Jul 2020 22:00:00 +0900") to DateTime
in Flutter.
I spent 5 hours on this problem...please help me.

A: In Dart, you can change it to the DateTime data using the parse method.
var parsedDate = DateTime.parse('2020-07-28 22:00:00.000');

NOTE
The parse method has its own input rules. Based on the documentation :

The accepted inputs are currently:

*

*A date: A signed four-to-six digit year, two digit month and two    digit day, optionally separated by - characters. Examples:
"19700101", "-0004-12-24", "81030-04-01".

*An optional time part, separated from the date by either T or a    space. The time part is a two digit hour, then optionally a two digit
minutes value, then optionally a two digit seconds value, and then
optionally a '.' or ',' followed by at least a one digit second
fraction. The minutes and seconds may be separated from the previous
parts by a ':'. Examples: "12", "12:30:24.124", "12:30:24,124",
"123010.50".

*An optional time-zone offset part, possibly separated from the    previous by a space. The time zone is either 'z' or 'Z', or it is a
signed two digit hour part and an optional two digit minute part. The
sign must be either "+" or "-", and can not be omitted. The minutes
may be separated from the hours by a ':'. Examples: "Z", "-10",
"+01:30", "+1130".

So you need to rearrange the input based on the rules above.
Here's the examples of accepted String
2012-02-27 13:27:00
2012-02-27 13:27:00.123456789z
2012-02-27 13:27:00,123456789z
20120227 13:27:00
20120227T132700
20120227
+20120227
2012-02-27T14Z
2012-02-27T14+00:00
-123450101 00:00:00 Z: in the year -12345.
2002-02-27T14:00:00-0500: Same as 2002-02-27T19:00:00Z


text:
Q: How can I change the color of the reorder accessory in a UITableViewCell? There's a great answer on how to move the reorder accessory in a UITableViewCell.  I'd like to keep it where it is but change its color because the background color of my table isn't white.  It looks like I could follow the same basic approach shown below, but I'm not sure if there's a more efficient way to change the color of this programmatically drawn control than just replacing it with a programmatically drawn control of my own?
- (void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    for(UIView* view in cell.subviews)
    {
        if([[[view class] description] isEqualToString:@"UITableViewCellReorderControl"])
        {
            // the problem: change view color
        }
    }
}

A: You are better off implementing the custom reorder accessory on your own, as a custom view that slides in when the UITableView enters editing mode.
The answer you mention navigates the internal UITableViewCell view hierarchy and makes assumptions about class names like UITableViewCellReorderControl which could change in future versions of iOS and break your code.

A: Although I agree with Antonis's concerns about possible future changes to iOS, I ended up following the approach I describe in the question, simply redrawing the accessory in a different color over the system accessory.  The reason is that this view comes with the interaction for dragging the cell; if I tried to remove it and draw my own, I became unable to move the cell.  I extended the MSCellAccessory library.  Here's my willDisplayCell method:
- (void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    for(UIView* view in cell.subviews)
    {
        if([[[view class] description] isEqualToString:@"UITableViewCellReorderControl"])
        {
            MSCellAccessory *overlayControl = [MSCellAccessory accessoryWithType:FLAT_REORDER_CONTROL color:[UIColor colorWithRed:0.353 green:0.153 blue:0.035 alpha:1.0]];
            [overlayControl setFrame:CGRectMake(0, 0, view.bounds.size.width, view.bounds.size.height)];
            [view addSubview:overlayControl];
        }
    }
}

and here's my extension to MSCellAccessory.m:
#define FLAT_REORDER_CONTROL_START_X                        CGRectGetMinX(self.bounds)+15
#define FLAT_REORDER_CONTROL_END_X                          CGRectGetMaxX(self.bounds)-15
#define FLAT_REORDER_CONTROL_STROKE_1_Y                     19
#define FLAT_REORDER_CONTROL_STROKE_2_Y                     22.5
#define FLAT_REORDER_CONTROL_STROKE_3_Y                     26
#define FLAT_REORDER_CONTROL_STROKE_WIDTH                   2

and
} else if(_accType == FLAT_REORDER_CONTROL) {
    CGContextRef ctx = UIGraphicsGetCurrentContext();

CGContextMoveToPoint(ctx, FLAT_REORDER_CONTROL_START_X, FLAT_REORDER_CONTROL_STROKE_1_Y);
CGContextAddLineToPoint(ctx, FLAT_REORDER_CONTROL_END_X, FLAT_REORDER_CONTROL_STROKE_1_Y);
CGContextMoveToPoint(ctx, FLAT_REORDER_CONTROL_START_X, FLAT_REORDER_CONTROL_STROKE_2_Y);
CGContextAddLineToPoint(ctx, FLAT_REORDER_CONTROL_END_X, FLAT_REORDER_CONTROL_STROKE_2_Y);
CGContextMoveToPoint(ctx, FLAT_REORDER_CONTROL_START_X, FLAT_REORDER_CONTROL_STROKE_3_Y);
CGContextAddLineToPoint(ctx, FLAT_REORDER_CONTROL_END_X, FLAT_REORDER_CONTROL_STROKE_3_Y);
CGContextSetLineWidth(ctx, FLAT_REORDER_CONTROL_STROKE_WIDTH);

[self.accessoryColor setStroke];

CGContextStrokePath(ctx);
}


text:
Q: Can I use Foreground Service to monitor new app installation by registering ACTION_PACKAGE_ADDED broadcast dynamically in service for Oreo and above I am successfully able to monitor new app installation by dynamically registering broadcast in foreground service for Oreo and above version. But for this I always have to show a persistent notification of my app.
Is there any alternative to
Google in documentation says:
You should only use a foreground service when your app needs to perform a task that is noticeable by the user even when they're not directly interacting with the app. For this reason, foreground services must show a status bar notification with a priority of PRIORITY_LOW or higher, which helps ensure that the user is aware of what your app is doing. If the action is of low enough importance that you want to use a minimum-priority notification, you probably shouldn't be using a service; instead, consider using a scheduled job.
So can I use foreground service for this purpose. If not than what is its alternative.

A: As said in the doc you posted, consider using a scheduled job.
if you use a foreground service you will need a constant notification and that would be annoying for the user (plus you don't install new package every five minutes so ...)
Instead you should schedule a job to check if a new package is installed.
Look at the accepted answer in this question

You can also use polling, setting up a JobScheduler job to check every so often, asking PackageManager for what has changed in the roster of installed apps via getChangedPackages().


text:
Q: Eigen 3.3.4 compilation error on MIPS Compiler (C++98) I compile Eigen 3.3.4 under Multi-2000 (Green Hill) MIPS C++ compiler.
After I solved some align macro issue in Macros.h, I met a problem again for some template expression.
Find the Error Details as below. I know it should be some issue for my old C++ compiler, but anyone whom can propose an work around it will be greatly appreciated.
"C:\Eigen/Eigen/src/Core/util/Meta.h", line 389
: error:
          expression must have pointer-to-class type
    template <typename C> static meta_yes testFunctor(C const *,typename enable_if<(sizeof(return_ptr<C>()->operator()())>0)>::type * =
 0);
                                                                                ^

"C:\Eigen/Eigen/src/Core/util/Meta.h", line 389
: error:
          incomplete type is not allowed
    template <typename C> static meta_yes testFunctor(C const *,typename enable_if<(sizeof(return_ptr<C>()->operator()())>0)>::type * =
 0);
                                                                     ^

So The Problem must be inside expression as below. But I really can not figure it out.
  template <typename C> static meta_yes testFunctor(C const *,typename enable_if<(sizeof(return_ptr<C>()->operator()())>0)>::type * = 0);

Update 8/25-> whether "typename enable_if" cause this?


text:
Q: Getting LazyInitializationException "could not initialize proxy - no Session" when running a transaction in a background thread I have a strange problem:
Say I have two Entity classes, e.g. Container and ContainedObject. Container has a @OneToMany relationship to ContainedObject.
When getting the contained objects directly, everything works fine, but when running from a background thread, I get "could not initialize proxy - no Session".
Example:
@Component
public class Something {

    @Autowired
    private ContainerRepository _repo;

    public void doInForeground() {
        Container container = _repo.findOne(42L); // suppose 42 exists
        container.getContainedObjects().size(); // succeeds
    }

    public void submitToBackground() {
        CompletableFuture<Void> f = CompletableFuture.supplyAsync(() -> doInBackground());
    }

    private Void doInBackground() {
        Container container = _repo.findOne(42L);
        container.getContainedObjects().size(); // throws LazyInitializationException
    }
}

The ContainerRepository is a PagingAndSortingRepository. Running doInForegroundsucceeds, but submitToBackground throws the well-known LazyInitializationException "could not initialize proxy - no Session"
It seems as if no transaction is started or it is closed too fast. Annotating any of the methods with @Transactional does not help either.
Is it simply not possible to use Spring-JPA in background threads or is any additional magic needed?

A: 1) You need a readOnly transaction to get lazy collections.
2) I suppose that @Transactional doesn't work on your local methods because when you call a local method you call the implementation directly, not a proxy object created by Spring.
If it's the case there are at least 2 choices:
1) Switch to Aspectj
<tx:annotation-driven mode="aspectj" proxy-target-class="true"/>

2) Create a transaction manually using TransactionTemplate inside doInForeground():
http://simplespringtutorial.com/springProgrammaticTransactions.html


text:
Q: Query over text column takes ages to run I'm not used to querying text columns with a large amount of data as I've always used NVARCHAR(MAX) and VARCHAR(MAX) but this is not my Database that I'm querying.
myTable has 305,000 rows.
myDescriptionField is a text column and allows nulls & has loads of data in it.
When I run the following query, it returns a row instantly.
SELECT TOP 1 userid
FROM myTable
WHERE ISNULL(userID,0) > 0
AND TRIM(SUBSTRING(myDescriptionField,1,1)) is not null

However, when I add this line to the where clause, the query just sits for over a minute (not sure how long it actually takes to finish as I always end up stopping the execution).
AND myDescriptionField NOT LIKE ''

I thought it might be because I'm forced to do a not like as it's a text column and also that it may be where a lot of rows have blanks or null so I tried different combinations of the following :-
AND ISNULL(TRIM(SUBSTRING(myDescriptionField,1,1)),'') <> ''

None of this worked.
So now a quick explanation as to what I need to achieve :-
I just need to find out if at least one row has data in the column myDescriptionField and if so, I can move on to the next table.
Is there a quick way of returning just one row once it's hit one?

A: Not sure if you added another predicate, or if you changed the existing one, but you could try like:
SELECT TOP 1 userid
FROM myTable
WHERE ISNULL(userID,0) > 0
  AND NULLIF(SUBSTRING(myDescriptionField,1,1),'') is not null;

A: Can you use DATALENGTH?
SELECT TOP 1
    userID
FROM
    myTable
WHERE
    DATALENGTH(myDescriptionField) >= 1


text:
Q: How rigorous are pictorial proofs? The standard proof that $|\mathbb{Q}| = \mathbb{|N|}$ is pictorial. I am sure everyone here has seen it. The "zig-zag".  I must admit, however, that, although I was "intuitively" convinced by it, I was never entirely satisfied with it because it is not an explicit bijection $f:\mathbb{N} \to \mathbb{Q}$ given by an actual formula. The fact that the proof is correct seems "clear" to us, but this is, again, merely an appeal to intuition. One should note that some of these "proofs by picture" are simply incorrect: see Russell O'Connor's answer here .
I have two questions

Is the pictorial proof that $|\mathbb{Q}| = \mathbb{|N|}$ rigorous by the standards of modern pure mathematics?

For the sake of this question, suppose that there isn't an explicit formla, or that it's too unwieldy to use in practice. After all, even if there is a formula, most of the people who've seen the pictorial argument do not know of it.

Is there an explicit formula for the "pictorial" proof?

There's some minor issues, of course, namely the inclusion of $0$ and variations of the "zig-zag" path, but these are no big deal. A bijection $f:\mathbb{N} \to \mathbb{N} \times \mathbb{N}$ suffices; dealing with negatives, equivalent fractions, etc is trivial.

A: I suppose if you really wanted to, you could come up with an explicit bijection associated with the "zig-zag" proof. If that turns out to be difficult, you could come up with a different "zig-zag" that may have a simpler bijection. Although, the "zig-zag" proof is really just providing some intuitive backing to this theorem:

The union of a countable number of finite sets is countable.

Thinking of each diagonal of the "zig-zag" as one of your finite sets, and noting that every rational number has to be in one of those diagonals is sufficient to prove that $|\mathbb{Q}| = |\mathbb{N}|$.

On a more general note, the whole point of a proof is to clearly and correctly convey why a theorem is true. Sometimes it is easiest to convey why through written words, especially when the proof is long, relies on lemmas or the theorems of others, or just has lots of cases. But if there is a clever reason why a theorem is true, some clever "ah-HA" that you just have to see, a "proof by picture" can be much more clear than a formal write-up of a proof. The hope is, though, that after a reader sees a pictorial proof, they should have enough intuition into why the theorem is true to write up a formal proof if they really needed.
After seeing the "zig-zag" proof, do you think you can prove that the union of a countable number of finite sets is countable?

A: Munkres' "Topology" gives both the zig-zag intuition, and the actual formula for the bijection, as a good reference.
I read in an article (cannot remember the author, sadly) that proofs are not supposed to be 'entirely' rigorous. 'Proofs' try to convince the reader that it is possible to construct a completely rigorous proof. As in this case, although I too was not satisfied with the zig-zag-proof, it conveys the idea that the bijection does exists (without explicitly writing it out), and thus it is countable.

A: The point of something like the zig-zag proof is not to be rigorous in itself but instead to convince a mathematician that he or she could easily make the proof rigorous if pressed to do so by the gods of rigour.
Also, you can come up with very succinct surjections from N to Q. For example, map every natural number of the form $2^p 3^q 5^r $ to $(-1)^r p/q$. It's extremely easy now to see that if you give me a rational, there is a natural number which is mapped to it.
The downside with this is that if you are teaching countability you would need to check that "surjection from" is the same as "bijection with", which sometimes hasn't been proved by this stage.

A: I had the same question with the same proof (the zig-zag proof you are mentioning). At some point I decided to produce a formal proof.
Define a bijective function $f\colon \mathbb N \times \mathbb N \to \mathbb N$.
First of all you notice that going zig and then zag only helps intuition. In fact you don't need a "continuous" curve, so it is easier to go zig and the zig again... (so to speak). Then it is easy to count how many points you need to fill the first $k$ diagonals (sum of a arithmetic series: $k(k+1)/2$). The couple $(n,m)$ lies on the diagonal number $k=n+m$ so you easily find:
$$
   f(n,m) = \frac{(n+m)(n+m+1)}{2} + m = \frac{n^2+m^2+2nm+3m+n}{2}.
$$
This was a little bit shocking to me! The function I was looking for is as simple as a polynomial... I would have expected some modulus, or some strange discontinuous function.
Nevertheless the algebraic proof that $f$ is bijective is not so simple... but following the intuition of the construction it is easy to write it.
What can we learn from this? The pictorial proof is for sure the best to understand a result and to remember it. Then it might happen that the abstract mathematics is even simpler than our intuition. Not always simple mathematics corresponds to simple pictures.

A: Pictures have their strengths and weaknesses, but they're just as rigorous as any other informal type of proof — that is, they may or may not be depending on how well written it is.
And the zig-zag proof is a rather clear depiction of an explicit algorithm for enumerating the rationals.
Regarding your particular doubts, I don't think it's really the picture that's the issue — it's that the function was defined by an algorithm for producing its values, rather than as an arithmetic formula.
Formal proofs can be 'pictures' too; you can develop formal logic in a way where the basic 'data type' is something other than strings of symbols. e.g. graphs of various sorts are often useful.

A: This doesn't directly address the proof of $|\mathbb{N}|=|\mathbb{Q}|$, but the more abstract notion of pictorial proofs as found in elementary geometry:
Avigad, Dean & Mumma A Formal System for Euclid's Elements:
http://repository.cmu.edu/philosophy/61/
They show that certain types of pictorial arguments that occur in Euclid's Elements, while apparently un-rigorous, can be described in a precise manner using formal rules, in a way that the conclusion follows directly from the pictorial "special case". In essence, a particular diagram can be in "general enough position" to allow rigorous conclusions to be drawn from it.

A: So... take the ordered pair $(n,m) $.
The pictorial and non rigorous concept of the "diagonal"  is simply {$(j,k) | j+k=n+m; j\ge 0;k \ge 0$}. Note: there are $(n+m)+1$ terms in this diagonal
The previous diagonals had 1 term, two terms ... so on to $(n+m)$ terms.  So the previous diagonals account for $\sum_{i=1}^{n+m} i  = \frac {(n+m)(n+m+1)}{2} $ items.
Starting at $(0,n+m) $ end of the diagonal $(n,m) $ is the $n +1$th item of the current diagonal.
So the bijection you want is $(n,m)\rightarrow \frac {(n+m)(n+m+1)}2 + n $.
$(0,0)\implies 0$
$(0,1)\implies 1$
$(1,0) \implies 2$
$(2,0) \implies 3$
$(1,1)\implies 4$
Etc. Algebraically it's probably easy to show this is injective .  Suppose (a,b) and (c,d) both map to t.
Case 1: a+b = c+d= K.
Then $\frac {K (K+1)}{2} + a = \frac {K (K+1)}2 + b$.  So $a = c $.  So $b = c =K -a $.
Case 2:  Wolog a+b < c+d
$\frac {(a+b)(a+b+1)}2 + a \le \frac {(a+b)(a+b+1)}2 + (a+b)$
$=\frac {(a+b)(a+b+3)}2 $
$\le \frac {((c+d)-1)((c+d+1)+1)}2$
$=\frac {(c+d)(c+d +1) +(c+d) -(c+d+1)-1}2 $
$=\frac{(c+d)(c+d+1)}2 -1$
$< \frac{(c+d)(c+d+1)}2 + c $
Which is a contradiction.
So (a,b)=(c,d).
Proving it's surjective isn't nescessary though it is.
For each t there exist, k, so that $\frac {k (k+1)}2 \le t < \frac{(k+1)(k+2)}2$.
Let $n = t -\frac {k (k+1)}2 \ge 0$.  Let $m=k-n = k - t + \frac {k (k+1)}2 > k - \frac {(k+1)(k+2)}2 + \frac {k (k+1)}2=k +\frac {k+1}2 (k-(k+2))=k - (k+1)=-1$.  So $m \ge 0$
Then $(n,m)\rightarrow t$.
===
Anyway....
I don't think such an intensive arithmetic is nescessary.  What matters is the argument that it can be done.  As the diagonals increase by one each iteration, and as we can group the natural numbers into sequences of groups each increasing in terms by one, each group of natural numbers coresponds to a diagonal, and each of there natural numbers in the group corresponds to a term in the diagonal.  Thus must be shown but it needn't be shown by convoluted arithmetic.


text:
Q: How to place abstract text in front of abstract key? I want to place my abstract text behind the abstract-key(which is used in all article), and left-aligned rather than centered on the page. How do I do this in LaTeX?
I want the following format:
Abstract: some text is here.

The default abstract format (which I want to change it) is:
                           Abstract

Some text is here

A: Here's an example how you could redefine the abstract environment:
\documentclass{article}
\renewenvironment{abstract}{%
  \noindent\bfseries\abstractname:\normalfont}{}
\begin{document}
\begin{abstract}
  some text is here.
\end{abstract}
\section{First section}
\end{document}

You could also customize the end code of the new abstract for making a paragraph break etc. However, I guess a \section would follow, so it would be ok.

A: You can use the abstract package to customise the abstract block as you want it by using the runin option:
\documentclass{article}
\usepackage{lipsum}
\usepackage[runin]{abstract}
\setlength{\abstitleskip}{-\parindent}
\begin{document}
\begin{abstract}
  \lipsum[1]
\end{abstract}
\section{First section}
\lipsum[1-2]
\end{document}


text:
Q: move mouse with python on windows 7 How can I move the mouse cursor in python 2.7 on Windows 7?
def MoveMouse(x,y):
    #move mouse cursor

A: what you need is Win32api.

import win32api
def move_to(x,y):
    win32api.SetCursorPos((x,y))