text:
Q: NoClassDefFoundError while executing Android JUnit test First of all, there are similar questions like here or here but I have neither some external libs nor a lib folder nor some included jars or something, so I wonder what I'm doing wrong by running Android Junit tests.
My project structure looks like this:

As you can see I have a separate project for Android JUnit tests. The testing class looks like this:
public class PersistenceManager {
    private static final String FILENAME = "kpzwien_storage";

    public static void persist(String data, Context context) throws IOException  {
        FileOutputStream fos = context.openFileOutput(FILENAME, Context.MODE_PRIVATE);
        fos.write(data.getBytes());
        fos.close();
    }

    public static String read(Context context) throws IOException  {
        FileInputStream fis = context.openFileInput(FILENAME);
        StringBuffer fileContent = new StringBuffer("");

        byte[] buffer = new byte[1024];
        while (fis.read(buffer) != -1) {
            fileContent.append(new String(buffer));
        }

        return fileContent.toString();
    }
}

and here is its test case:
public class PersistenceManagerTest extends AndroidTestCase {

    private final String FILENAME_PREFIX = "test.";

    @Before
    public void setUp() {
        MockContentResolver resolver = new MockContentResolver();
        RenamingDelegatingContext renamingDelegatingContext = new RenamingDelegatingContext(new MockContext(), getContext(), FILENAME_PREFIX);
        Context context = new IsolatedContext(resolver, renamingDelegatingContext);

        setContext(context);
    }

    public void testPersistAndRead() throws IOException {
        String testData = "foobar";

        PersistenceManager.persist(testData, getContext());

        String result = PersistenceManager.read(getContext());

        assertEquals(testData, result);
    }
}

The manifest of the test project looks like this:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="net.devgems.android.kurzparkzonewien.androidtests"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="4" />

    <instrumentation
        android:name="android.test.InstrumentationTestRunner"
        android:targetPackage="net.devgems.android.kurzparkzonewien.activities" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <uses-library android:name="android.test.runner" />
    </application>
</manifest>

targetPackage is the application that the Instrumentation object will run against which is is identified by the package name assigned in its manifest file by the  element. (Source: http://developer.android.com/guide/topics/manifest/instrumentation-element.html
The name of the package in my main project is

package="net.devgems.android.kurzparkzonewien.activities"

So it is exactly where targetPackage points to. If I run as "Android JUnit test", I always get a NoClassDefFoundError but why? Any ideas? I'm using ADT 20.0.3, Eclipse Juno.
At last here is the logcat output:

09-22 16:00:12.745: I/TestRunner(1528):
  java.lang.NoClassDefFoundError:
  net.devgems.android.kurzparkzonewien.controller.PersistenceManager
  09-22 16:00:12.745: I/TestRunner(1528):   at
  net.devgems.android.kurzparkzonewien.androidtests.PersistenceManagerTest.testPersistAndRead(PersistenceManagerTest.java:32)
  09-22 16:00:12.745: I/TestRunner(1528):   at
  java.lang.reflect.Method.invokeNative(Native Method) 09-22
  16:00:12.745: I/TestRunner(1528):     at
  java.lang.reflect.Method.invoke(Method.java:521) 09-22 16:00:12.745:
  I/TestRunner(1528):   at
  junit.framework.TestCase.runTest(TestCase.java:154) 09-22
  16:00:12.745: I/TestRunner(1528):     at
  junit.framework.TestCase.runBare(TestCase.java:127) 09-22
  16:00:12.745: I/TestRunner(1528):     at
  junit.framework.TestResult$1.protect(TestResult.java:106) 09-22
  16:00:12.745: I/TestRunner(1528):     at
  junit.framework.TestResult.runProtected(TestResult.java:124) 09-22
  16:00:12.745: I/TestRunner(1528):     at
  junit.framework.TestResult.run(TestResult.java:109) 09-22
  16:00:12.745: I/TestRunner(1528):     at
  junit.framework.TestCase.run(TestCase.java:118) 09-22 16:00:12.745:
  I/TestRunner(1528):   at
  android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:169)
  09-22 16:00:12.745: I/TestRunner(1528):   at
  android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:154)
  09-22 16:00:12.745: I/TestRunner(1528):   at
  android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:430)
  09-22 16:00:12.745: I/TestRunner(1528):   at
  android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1447)
  09-22 16:00:12.745: I/TestRunner(1528): ----- end exception -----

A: I found the solution. But it's actually some kind of workaround because I can't image that I usually need to tinker like this (maybe someone knows a better solution?):
My main project is a Maven project, in this project I have to set configured the output folders from /bin... to /target/classes, target/test-classes and target/generated-sources. I've done that because otherwise my JUnit tests from main project would not find the latest code changes as long as I do not run mvn install.. If the output folders are target/..., I don't need to run mvn install to have the latest changes in my tests.
The problem is now that the Android test project doesn't find the compiled sources when they are stored in main project's target. When I set the output folder in main project to bin and run mvn install, the Android test project can find the classes now. I have to do this just once. When I set it back to target, both my Android tests still run and my main JUnit tests run. When I change the methods in the main project, the test project immediately recognize the changes, so that means it doesn't use binary jar or something (which is indeed very good, although I don't understand why it finds it now, although I set it back to target?).
[UPDATE]
Adding these two lines to main project's pom to build section solves the issue, so I don't need a workaround anymore.
    <outputDirectory>bin/classes</outputDirectory>
    <testOutputDirectory>bin/test-classes</testOutputDirectory>


text:
Q: Send UDP on specific connection in µIP I'm using uIP on a Tiva C Launchpad board and want to send UDP Packages. But it seems that the uip_buf is not filled when i call the uip_udp_periodic function.
The code looks like this:
uint8_t my_udp_buf = {0x00, 0xAA, 0xBB, 0xCC};
uint32_t my_udp_buf_len = 4;

void main(main){
[...]
    uip_ipaddr_t addr;
    struct uip_udp_conn *c;

    uip_ipaddr(&addr, 172,16,23,1);
    c = uip_udp_new(&addr, HTONS(12345)); // setting up a new UDP connection to 172.16.23.1:12345 here

    [...]
    while(42==42){
        uip_udp_conn = c; // set the current connection to our udp connection
        uip_appdata = my_udp_buf; // asssign the uip_appdata pointer to our data pointer
        uip_send(uip_appdata, my_udp_buf_len); // sending the data

        [...]
        // call the periodic function for all UDP connections
        for(ui32Temp = 0; ui32Temp < UIP_UDP_CONNS; ui32Temp++)
        {
            uip_udp_periodic(ui32Temp);
            // --> The uip_len is always 0! why?

            //
            // If the above function invocation resulted in data that
            // should be sent out on the network, the global variable
            // uip_len is set to a value > 0.
            //
            if(uip_len > 0)
            {
                uip_arp_out();
                PacketTransmit(EMAC0_BASE, uip_buf, uip_len);
                uip_len = 0;
            }
        }
    }
}

The question is, do i set the connection correctly? In the header file i cannot find any macro or function to control on which connection i send out the data, so i assume that i need to set the connection pointer. Also do i need to save the data? probably the pointer to uip_appdata is overwritten somewhere else afterwards.

A: It seems like UDP is not well implemented in the bare uIP version. you need to do a lot of manual stuff:
        uip_udp_conn = c; // set your connection
        uip_slen = len; // set the length of data to send
        memcpy(&uip_buf[UIP_LLH_LEN + UIP_IPUDPH_LEN], data, len > UIP_BUFSIZE? UIP_BUFSIZE: len); // copy to the buffer
        uip_process(UIP_UDP_SEND_CONN); // tell uip to construct the package

        uip_arp_out(); // attack Ethernet header
        PacketTransmit(EMAC0_BASE, uip_buf, uip_len); // send the package with the Tiva C function
        uip_len = 0; // reset length to 0

in the contiki version of uIP is a lot more UDP convenient functionality.

A: When working with udp and the tiva, I have found that having a seperate function to handle the udp instances works much better. when you run it out of your main function, you will end up having multiple instances and that will cause instability

redpajama_set_name: RedPajamaStackExchange


text:
Q: "\n" is not being recognized properly in Windows command line I'm trying to issue a command that requires a line break due to a formatting restriction.
I need to commit a file to a CVS repository, but the repository has a restriction that requires a message to be included in the following format.
Change #: <number>
Description: <description>

The command used to commit the file is:
cvs commit -m "Change #: <number>\nDescription: <description>" <filename>

However when I issue the command it doesn't seem to be properly recognizing the line break and it fails saying that I gave it an invalid Change # and no Description.
How can I make it recognize the new line without it trying to issue two separate commands?

A: Try powershell in this format:

start-process -FilePath cvs.exe -ArgumentList "commit -m `"Change #:123 `nDescription:my description`""

A: I'm actually attempting to call this command from a Perl script and found an acceptable workaround.  For some reason calling the command as a system command seems to fail, but if you call it using backticks it works fine.
# Fails
system 'cvs commit -m "Change #: <number>\nDescription: <description>" <filename>'

# Works
my $output = `cvs commit -m "Change #: <number>\nDescription: <description>" <filename>`

Whats funny is this difference in handling "\n" between using system commands and backticks doesn't seem to be documented anywhere.


text:
Q: How to learn programming GPS applications in Android A few weeks ago, I began learning to write Android applications, that must use GPS (getting position and saving it to a database). But I found so much information; I don't know where to start!
Question:
Please help me make my studying comprehensive and complete!
What help was most useful for you (or most understandable) when you were learning this topic?
(Please provide links to useful topics or video lessons)

A: If you are looking for useful book I can suggest you "Professional Android Sensor Programming" (G. Milette, A. Stroud).
I can also suggest this link:
http://www.vogella.com/articles/AndroidLocationAPI/article.html
or a basic presentation:
http://www.slideshare.net/androidstream/android-gps-tutorial
finally, I think you should always refer to developer.android.com web site:
http://developer.android.com/guide/topics/location/strategies.html


text:
Q: Rsync contents of tar with remote server I've got a number of backups as tar archives, and to do checking/testing of them I restore to some test machines using:
cat archive.tar.gz | ssh server2 "cd /path/to/dir; tar zxvf -"

Most of the target machine is the same, so this ssh/tar piping is overkill in bandwidth, time and disk access.  Is there any way of piping through rsync to compare the contents of the tar file with the target server?
Edit: Forgot to say, I'm Using RHEL6

A: Well, the only answer I can find is to mount the archive using ArchiveMount, then rsync against that.  I had to manually install it using an RPM as it's not in the Redhat 6 repositories.
No wasted space on the backup or test machines to unpack, though it does take a good few minutes to mount a 30gb archive, I guess because it has to read all the files in the archive and create a directory structure - not looking forward to the 200gb archive I've got!
Anyway, seems to run fast enough, though not done any real stats.
Thank Tom!


text:
Q: Diazo / XSLT - replace class of content in one of two places in theme Using Plone 4.3.x
Basically: How can I copy one set of elements from the content to place a and place b in a theme and in place b change an attribute of the copied elements?
Specifically: In my rules.xml file I am <replace>ing two .replace-main-nav in the theme.html with the children of #navigation from the content:
rules.xml:
<replace css:theme=".replace-main-nav"
         css:content-children="#navigation" />

examples of places in theme.html:

example of nav in content

            Item 1

            Item 2

            Item 3

I want to replace the attribute class="foo" with class="baa" ONLY when the
 replaces .replace-main-nav in .place-b.
Is this possible?
If so how can I do it?
What I want out

            Item 1

            Item 2

            Item 3

            Item 1

            Item 2

            Item 3

A: Perhaps this helps?
So something like this? (which is not tested)
<replace css:content-children=".place-b">

  <xsl:for-each select="//*[@id='navigation']/*">

      <xsl:copy-of select="./text()" />

  </xsl:for-each>

</replace>


text:
Q: CFSCRIPT - For Loop - How to increment by 50 or 100? I am using ColdFusion 9.  I am not interested in non-CFSCRIPT answers.
I am trying to loop from 0 to 100 by increments of 5.
Here's my normal loop:
for (i = 0; i < 100; i + 5) {
    writeOutput(i);
}

Why isn't this working for me?

A: You need to do
i = i +5

instead of
    i + 5


text:
Q: Quaternion algebras over a non-Archimedean local field $K$, up to isomorphism I want to know the number of non-isomorphic quaternion algebras over a non-Archimedean local field $K$. What is the number of non-isomorphic central simple algebras of dimension $n^2$ over a non-Archimedean local field $K$?
I know the Brauer group of $K$ is isomorphic to $\dfrac{\mathbb{Q}}{\mathbb{Z}}$. I know the structure of the group $\dfrac{\mathbb{Q}}{\mathbb{Z}}$ very well, and it has only one element of order $2$.
Let $n \in \mathbb{N}$ be arbitrary. Is there any relation between the elements of order $n$ (or elements of order dividing $n$) in the group $\dfrac{\mathbb{Q}}{\mathbb{Z}}$, and the central simple algebras of dimension $n^2$?

A: The elements of order $n$ in $\frac{\mathbb{Q}}{\mathbb{Z}}$ correspond bijectively  to the isomorphism classes of central simple algebras over $K$ of dimension $n^2$. In particular there is a unique isomorphism class of (non-split) quaternion algebra. See Remark 4.4 on p. 110 here for an explicit construction.
https://www.jmilne.org/math/CourseNotes/CFT310.pdf


text:
Q: Netography for managing links To manage my links used in my thesis, I wanted to use a netography so that I can cite links that are listed (with time stamp of the last visit!) at the end, like a bibliography. I couldn't find any package or similar questions. Does anyone know a package or a work-around?

A: You could use the glossaries package. It serves not only to make glossaries and acronyms, but also to make lists of things
The following should be put in the preamble after the hyperref package (if it is called, and I think you do call it)
\usepackage{hyperref} % Optional
...
\usepackage[toc]{glossaries} % toc option puts an entry in the table of contents
\newglossary{links}{sym}{sbl}{Netography}
\makeglossaries
\loadglsentries{listofurls}
\begin{document}
...

The following should be put where you want the netography to appear
\glsaddall[types={links}] % This adds all of the defined acronyms without needing to call them in the body of the document
\printglossary[style=super,type=links,nonumberlist] % Prints the acronyms

Then, you create a file (named listofurls in this case) that contains the declarations as follows:
\newglossaryentry{url1}
{
    type=links,
    name={2012/10/10},
    sort=20121010, % Use what ever form you want to sort your list
    description={\url{www.google.com}}
}
\newglossaryentry{url2}
{
    type=links,
    name={2012/05/06},
    sort=20120506,  % Use what ever form you want to sort your list
    description={\url{http://tex.stackexchange.com}}
}

Run pdflatex jobname then makeglossaries jobname then pdflatex jobname
MWE:
\documentclass{article}

\usepackage{hyperref} % Optional

\usepackage[toc]{glossaries} % toc option puts an entry in the table of contents
\newglossary{links}{sym}{sbl}{Netography}
\makeglossaries
%\loadglsentries{listofurls}

\newglossaryentry{url1}
{
    type=links,
    name={2012/10/10},
    sort=20121010, % Use what ever form you want to sort your list
    description={\url{www.google.com}}
}
\newglossaryentry{url2}
{
    type=links,
    name={2012/05/06},
    sort=20120506,  % Use what ever form you want to sort your list
    description={\url{http://tex.stackexchange.com}}
}
\begin{document}

\glsaddall[types={links}] % This adds all of the defined acronyms without needing to call them in the body of the document
\printglossary[style=super,type=links,nonumberlist]

\end{document}

Output

Update 1
Oliver asks if you can reference the links in the body. Actually, there is a problem that I don't know how to handle with the \urlcommand, here is a MWE:
\documentclass{article}

\usepackage{hyperref} % Optional

\usepackage[toc]{glossaries} % toc option puts an entry in the table of contents
\newglossary{links}{sym}{sbl}{Netography}
\makeglossaries
%\loadglsentries{listofurls}

\newglossaryentry{url1}
{
    type=links,
    name={2012/10/10},
    sort=20121010, % Use what ever form you want to sort your list
    description={\url{www.google.com}}
}
\newglossaryentry{url2}
{
    type=links,
    name={2012/05/06},
    sort=20120506,  % Use what ever form you want to sort your list
    description={\url{http://tex.stackexchange.com}}
}
\begin{document}

For more information visit \glsdesc{url1}\footnote{This site was last visited in \gls{url1}} Notice that there is a problem with the url command...

Workaround \glslink{url1}{\url{www.google.com}}

\glsaddall[types={links}] % This adds all of the defined acronyms without needing to call them in the body of the document
\printglossary[style=super,type=links,nonumberlist]
\end{document}

Output:


text:
Q: How to add a project to already existing repository I am using codeigniter framework. I want to upload my project to github. I have username and password. In github i have a repository. I want to upload my project to that repository. I tried with git desktop. My system is 32-bit. So I tried with git bash using command promt. My project folder is on my desktop. I don't know how connect to that already existing repository to my local folder. I tried with lot of commands like
git init
git remote add origin https://github.com/yourusername/your-repo-name.git
git commit -m "adding files"

but my files are not upload to github. I am using codeigniter so, there are lot of files like applications, assets, Systems folder. I need to upload those folders with files. Please help me.

A: This is a very nice description how to add an existing project to github.
For your issue that files are not added:
What I could see from your trial you maybe forgot to use git add on the files you want to add. To be sure you could post the output of git status

A: I guess what you want to do is to "download" the existing repository and then add files to it.
You should first clone your GitHub repository, and then add the files to it.
After this, you can commit (and push) your files to the repo.
I recommend reading the Git basics:

*

*Getting a Git Repository

*Recording Changes to the Repository


text:
Q: Template specialization for unspecialized template arguments Given I can do this:
template <class T>
struct foo {
    typedef T   type;
};

template <template <size_t> class B>
struct foo2 {
    typedef B<0>    type;
};

struct bar1 {};

template <size_t N = 1>
struct bar2 {};

// usage
foo<bar1>::type // ok, = bar1
foo<bar2<> >::type // ok, = bar2<1>
foo2<bar2>::type // ok, = bar2<0>

Can I partially specialize foo to accept unspecialized class argument bar2?
Like:
foo<bar2>::type  // should give me bar2<0>

I've tried something below, but it doesn't work:
// compile error
template <template <size_t> class B>
struct foo<B> {
    typedef B<0>    type;
};

A: Using decltype with an overloaded template function, I came up with this:
#include <type_traits>

struct bar;

template <size_t> struct baz;

template <typename T>
struct foo_type
{
  typedef T type;
};

template <template <size_t> class C>
struct foo_class_template
{
  typedef C<0> type;
};

template <typename T>
foo_type<T> doit();

template <template <size_t> class C>
foo_class_template<C> doit();

void stackoverflow()
{
  typedef decltype(doit<bar>()) Ret;
  static_assert(std::is_same<Ret::type, bar>::value, "oops");

  typedef decltype(doit<baz>()) Ret2;
  static_assert(std::is_same<Ret2::type, baz<0>>::value, "oops");
}

You need C++11-support for this to work, though.


text:
Q: Gradle: Run subproject task also on dependency projects I am stuck on the following Problem:
I have a main project with multiple sub-projects, each dependent on each other. For example:
+---Main
    +- Shared
       +- Variant1
          +- Variant1A

If I run the build task on project 3 with the Variant1A:build command, all other projects get built too.
I now added a deploy task to every sub-project, and if I deploy one of my projects, I want to deploy every project it depends upon as well, like so:
+---Main:deploy
    +- Shared:deploy
       +- Variant1:deploy
          +- Variant1A:deploy

However running Variant1A:deploy only runs the task for the Variant1A project:
+---Main:build
    +- Shared:build
       +- Variant1:build
          +- Variant1A:deploy

As I have a lot of subprojects and many complicated dependencies, I don't want to specify each project with dependsOn.
So I am searching for a way to run the task on all local projects like build does, however I don't want to add the logic to the build task, as it should not be deployed in the normal building process...

A: from your root project's build.gradle you might be able to do something like this
// look for deploy as a task argument sent via command line
def isDeploy
// could be many tasks supplied via command line
for (def taskExecutionRequest : gradle.startParameter.taskRequests) {
    // we only want to make sure deploy was specified as a task request
    if (taskExecutionRequest.args.contains('deploy')) {
        isDeploy = true
    }
}
// if deploy task was specified then setup dependant tasks
if (isDeploy) {
    // add the task to all subprojects of the `rootProject`
    subprojects.each {
        // get all projects that depend on this subproject
        def projectDependencies = project.configurations.runtime.getAllDependencies().withType(ProjectDependency)
        // the subproject's dependant projects may also have project dependencies
        def dependentProjects = projectDependencies*.dependencyProject
        // now we have a list of all dependency projects of this subproject
        // start setting up the dependsOn task logic
        dependentProjects.each {
            // find the deploy task then make our dependant
            // project's deploy task a dependant of the deploy task
            tasks.findByName('deploy').dependsOn project(it.name).tasks.findByName('deploy')
        }
    }
}


text:
Q: append list within classes (python) I've run into a problem with inheritance in python that I know how to avoid, but don't completely understand. The problem occured while making a menu but I've stripped down the code to only the real problem.
code:
class menu:
    buttonlist=[]

>>> class av(menu):
    def __init__(self, num):
        self.buttonlist.append(num)
        print self.buttonlist

>>> AV=av(12)
[12]
>>> class main(menu):
    def __init__(self, num):
        self.buttonlist.append(num)
        print self.buttonlist

>>> Main=main(14)
[12, 14]
>>> AV.buttonlist
[12, 14]

I'd expect to get [14] in return by the 'Main=main(14)', and [12] with the 'AV.buttonlist' but instead it seems append has appended the list in all classes and objects :S
can anyone explain to me why this is?
thanks in advance!

A: @Cat beat me to it, but here is some working code
class Menu(object):
    def __init__(self):
        self.buttonlist = []

class AV(Menu):
    def __init__(self, num):
        Menu.__init__(self)
        self.buttonlist.append(num)
        print self.buttonlist

class Main(Menu):
    def __init__(self, num):
        Menu.__init__(self)
        self.buttonlist.append(num)
        print self.buttonlist

>>> av = AV(12)
>>> main = Main(14)

Note that the convention is to name python classes with CamelCase so your av class would be AV and menu would be Menu. This is by no means required though.

A: Because buttonlist is a class variable, not an instance variable. You need to assign it in the constructor if you want it to be local to the instance.
class menu:
    def __init__(self):
        self.buttonlist = []

And then, of course, remember to call the base constructor in derived classes.

A: buttonlist is a class attribute and is also mutable(lists)
since buttonlist was not defined in the  __ init__ in the base class, it's a class variable and not instance variable, thus all changes from all inheritances will affect it. Meaning that it doesn't belong to any class inheriting from it but to all instances. The first instance appended 12 and the second, 14
#Main and AV.buttonlist are actually different,
print Main
print AV
#you should get something similar to this pointing to different locations
<__main__.main object at 0x02B753F>
<__main__.av object at 0x02B6B910>

#obviouly different objects but inheriting from the same class. Thus,the class variable changes, keeps appending
class menu:
    buttonlist=""

class av(menu):
    def __init__(self, num):
        self.buttonlist = num

class main(menu):
    def __init__(self, num):
        self.buttonlist = num

a=av("food")
b=main("menu")

print(menu.buttonlist)
print(a.buttonlist)
print(b.buttonlist)

##won't work for strings as they are immutable and can't be changed after delared in the base class

A: class av:
    def __init__(self, num):
        self.num = num

lst = []
lst.append(av(14))
lst.append(av(12))
print(str(lst[0]) + str(lst[1]))


text:
Q: jquery add element then select (for overwriting) added text I have a simple bit of code for adding new bullet points to a list. New bullet points have the generic text of 'Your new bullet' which the user then edits. Is there any way that once the new bullet point is added the generic text is selected ready for overwriting.
My code looks like this....

$(document).on("click", "#addNewBullet", function(){
    $('
Your new bullet
').insertBefore('#addNewBullet')
    })

Bullet1

Bullet2

Bullet3

+ Add

Thanks

A: use focus and i have added functon selectText to select the all the text, so easy to edit the text.

jQuery.fn.selectText = function(){
   var doc = document;
   var element = this[0];
   console.log(this, element);
   if (doc.body.createTextRange) {
       var range = document.body.createTextRange();
       range.moveToElementText(element);
       range.select();
   } else if (window.getSelection) {
       var selection = window.getSelection();
       var range = document.createRange();
       range.selectNodeContents(element);
       selection.removeAllRanges();
       selection.addRange(range);
   }
};

$(document).on("click", "#addNewBullet", function() {
  $('
Your new bullet
').insertBefore('#addNewBullet').focus().selectText();
});

Bullet1

Bullet2

Bullet3

+ Add

A: You can use .focus() and then select all the text:

$(document).on("click", "#addNewBullet", function() {
  $('
Your new bullet
').insertBefore('#addNewBullet').focus();
  document.execCommand('selectAll', false, null);
})

Bullet1

Bullet2

Bullet3

+ Add


text:
Q: How does java resolve hidden methods at runtime Given the following class hierarchy
package pack1;

public class A
{
    private int methodOne(int i)
    {
        return ++i;
    }

    public int methodTwo(int i)
    {
        return methodOne(++i);
    }
}

package pack2;

import pack1.A;

class B extends A
{
    int methodOne(int i)
    {
        return methodTwo(++i);
    }
}

public class MainClass
{
    public static void main(String[] args)
    {
        System.out.println(new B().methodOne(101));
    }
}

The output of the above program is 104.  Class Bcreates its own version of methodOn() because methodOne() is private in Class A.  However, during runtime, when inside methodTwo(), the runtime object is of type Class B.  Why would java use the methodOne() in class A as oppose of class B.

A: This is because, despite the name, the two methods are entirely different. methodOne in class B does not override the method with the same name in class A. As you said, B can't see the private methodOne, so it can't possibly override it. So Java creates two separate methods that are not related in any way. Then A's methodTwo calls the methodOne that's defined in A. If it were public or protected, then other classes might have overridden it, resulting in the late binding we know all too well from Java. However, the methodOne that it sees has never been overridden because B didn't know to do so.
tl;dr: Internally, they're two different and unrelated methods, even though the names are the same.

A: At very first your code starts executing the code
public static void main(String[] args)
    {
        System.out.println(new B().methodOne(101)); // it invokes methodOne() of class B.
    }

Above code calls methodOne() of class B. Now, MethodOne() is private so it won't override in Class B
Now definition of methodOne() in Class B
int methodOne(int i)
    {
        return methodTwo(++i);  // calling methodTwo() from class A which is a super class of class B.
    }

this code is increase the value of i by 1. So, Now i = 102. Now again the methodTwo calling the methodOne() of class B in below code.
public int methodTwo(int i) //methodTwo in class A. part of object due to public access modifier.
    {
        return methodOne(++i); // it increase the value of i by 1. Now i =103.
    }

Now the value of i = 103. Now it calls methodOne() of class A , because methodOne() is private in Class A
private int methodOne(int i)
    {
        return ++i; //again this increase the value of i by 1. Now i =104.
    }

increased the value of i by 1. So, variable i = 104. So, Final value of i is 104 Now.

So, The Final Output is 104.


text:
Q: Can't vertically drag a view in Android I'm working in Titanium SDK 3.1.1 and deploying to an Android 4.0 device. I'm trying to drag a View in any direction, but while the touchmove event is being fired, something goes wrong and the event is interrupted. The touchmove event works as long as I try a horizontal drag, if I try to drag the view in the y axis, the event is interrupted. The application doesn't crash nor the touchend event is fired. While looking at logcat I get the following:
D/InputEventConsistencyVerifier(11897): TouchEvent: ACTION_MOVE contained 1 pointers but there are currently 0 pointers down.
D/InputEventConsistencyVerifier(11897):   in android.view.ScaleGestureDetector@41223570
D/InputEventConsistencyVerifier(11897):   0: sent at 199051208557000, MotionEvent { action=ACTION_MOVE, id[0]=0, x[0]=214.55301, y[0]=163.79526, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=1, eventTime=199051208, downTime=199051042, deviceId=2, source=0x1002 }
D/InputEventConsistencyVerifier(11897):   -- recent events --
D/InputEventConsistencyVerifier(11897):   1: sent at 199050732492000, MotionEvent { action=ACTION_UP, id[0]=0, x[0]=186.61124, y[0]=73.907616, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x80000000, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=199050732, downTime=199049818, deviceId=2, source=0x1002 }
D/InputEventConsistencyVerifier(11897):   2: sent at 199050713565000, MotionEvent { action=ACTION_MOVE, id[0]=0, x[0]=186.61124, y[0]=73.907616, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x80000000, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=199050713, downTime=199049818, deviceId=2, source=0x1002 }
D/InputEventConsistencyVerifier(11897):   3: sent at 199050693173000, MotionEvent { action=ACTION_MOVE, id[0]=0, x[0]=205.57172, y[0]=81.89763, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x80000000, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=199050693, downTime=199049818, deviceId=2, source=0x1002 }
D/InputEventConsistencyVerifier(11897):   4: sent at 199050683204000, MotionEvent { action=ACTION_MOVE, id[0]=0, x[0]=233.51352, y[0]=96.87891, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x80000000, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=199050683, downTime=199049818, deviceId=2, source=0x1002 }
D/InputEventConsistencyVerifier(11897):   5: sent at 199050669151000, MotionEvent { action=ACTION_MOVE, id[0]=0, x[0]=264.44907, y[0]=115.85519, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x80000000, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=199050669, downTime=199049818, deviceId=2, source=0x1002 }

I don't understand why is this happening, I've done drag & drops behaviours before in Android using Titanium and had not encountered this problem.
This is the code for the touchstart, touchmove and touchend events:
var draggedView = Titanium.UI.createView({
        backgroundColor : 'transparent',
        width : circleWidth + 'dp',
        widthNumber : circleWidth,
        height : circleWidth + 'dp',
        heightNumber : circleWidth,
        left : '10dp',
        top : '10dp',
        leftNumber : 10,
        topNumber : 10,
        zIndex : 4,
    });
    var dragView = Titanium.UI.createView({
        backgroundColor : 'transparent',
        opacity : 1,
        width : circleWidth + 'dp',
        height : circleWidth + 'dp',
        widthNumber : circleWidth,
        heightNumber : circleWidth,
        left : '10dp',
        top : '20dp',
        leftNumber : 10,
        topNumber : 20,
        zIndex : 4
    });
    var targetView = Ti.UI.createImageView({
        image : imagesPath + "KineduPaperPlane.png",
        width : '100dp',
        widthNumber : 100,
        height : '100dp',
        heightNumber : 100,
        bottom : '-120dp',
        bottomNumber : -120
    });
    dragView.addEventListener('touchstart', function(e) {
        if (dragEnabled == true) {
            curX = e.x;
            curY = e.y;
        }
    });

    dragView.addEventListener('touchmove', function(e) {
        if (dragEnabled == true) {
            if (targetViewDisplayed == false) {
                targetView.animate({
                    bottom : '20dp',
                    duration : 200
                });
                targetView.bottomNumber = 20;
                targetViewDisplayed = true;
            }

            deltaX = e.x - curX;
            deltaY = e.y - curY;
            currentPositionX = initialViewX + deltaX;
            currentPositionY = initialViewY + deltaY;

            draggedView.setLeft(currentPositionX + 'dp');
            draggedView.leftNumber = currentPositionX;
            draggedView.setTop(currentPositionY + 'dp');
            draggedView.topNumber = currentPositionY;

        }
    });

    function recallControl() {
        var animateControlToOrigin = Ti.UI.createAnimation({
            left : initialViewX,
            top : initialViewY,
            duration : 300,
        });
        animateControlToOrigin.addEventListener("complete", function(e) {

            draggedView.setLeft(initialViewX + 'dp');
            draggedView.leftNumber = initialViewX;
            draggedView.setTop(initialViewY + 'dp');
            draggedView.topNumber = initialViewY;

            dragView.setLeft(initialViewX + 'dp');
            dragView.leftNumber = initialViewX;
            dragView.setTop(initialViewY + 'dp');
            dragView.topNumber = initialViewY;

        });

        draggedView.animate(animateControlToOrigin);
    }

    dragView.addEventListener("touchend", function(e) {
        if (dragEnabled == true) {

            if (targetViewDisplayed == true) {
                var leftLimit = true;
                var rightLimit = true;
                var topLimit = false;
                var lowerLimit = false;

                if (currentPositionY > (Ti.Platform.displayCaps.platformHeight - circleWidth - 100)) {
                    topLimit = true;
                }

                if (currentPositionY < Ti.Platform.displayCaps.platformHeight) {
                    lowerLimit = true;
                }

                if (leftLimit && rightLimit && topLimit && lowerLimit) {
                    var circleWidthAnimated = 20;

                    var animationLeft = (Ti.Platform.displayCaps.platformWidth / 2) - (circleWidth / 2);
                    var draggedViewAwayAnimation = Ti.UI.createAnimation({
                        left : animationLeft + 'dp',
                        height : circleWidthAnimated + 'dp',
                        width : circleWidthAnimated + 'dp',
                        borderRadius : circleWidthAnimated / 2,
                        opacity : 0,
                        duration : 400
                    })
                    draggedView.animate(draggedViewAwayAnimation);

                    var targetViewAwayAnimationPart2 = Ti.UI.createAnimation({
                        top : '10dp',
                        left : '-150dp',
                        duration : 1200,
                        opacity : 0,
                    });
                    draggedViewAwayAnimation.addEventListener("complete", function(e) {
                        targetView.animate(targetViewAwayAnimationPart1);
                        targetView.leftNumber = animationLeft;
                        targetView.heightNumber = circleWidthAnimated;
                        targetView.widthNumber = circleWidthAnimated;
                    });

                    var animationLeftPart1 = (Ti.Platform.displayCaps.platformWidth / 2) - circleWidthAnimated - (2) + 30;
                    var targetViewAwayAnimationPart1 = Ti.UI.createAnimation({
                        bottom : 0,
                        left : animationLeftPart1 + 'dp',
                        duration : 600,
                    });

                    targetViewAwayAnimationPart1.addEventListener("complete", function(e) {
                        targetView.animate(targetViewAwayAnimationPart2);
                        targetView.bottomNumber = 0;
                        targetView.leftNumber = animationLeftPart1;
                    });

                    targetViewAwayAnimationPart2.addEventListener("complete", function(e) {
                        dragEnabled = false;
                        targetView.leftNumber = -150;
                        targetView.top = 10;
                    });

                } else {

                    targetView.animate({
                        bottom : '-20dp',
                        duration : 200
                    });
                    targetView.bottomNumber = -20;
                    targetViewDisplayed = false;

                    recallControl();
                }
            }
        }
    });

The dragView is a transparent view I use to detect the touch events and the draggedView is the one being moved by the changes detected on those events. The targetView is the final destination for the draggedView.
Since I display views using dpi, I added some properties that contains the numerical values for properties like top, left, width, etc. If there's a way to work with dpi and arithmetical operations, I would be glad to be told how to do it.
Returning to my problem, I don't understand the reason for the touchmove event to stop. The message ACTION_MOVE contained 1 pointers but there are currently 0 pointers down gives me the impression that the finger tracking is lost during my try at vertically dragging the view.
Can someone direct in the issue at hand? What's is causing this behavior? Thanks for any help in advance.

A: did targetView stack on any view with horizontal scroll behavior?
i had the same issue before, mine is because i have a scrollview nested inside a scrollableview. i solve it via switching the scrollingEnabled to be true once at a time only, other to be false.
so i make a guess, it might because one of the view in the stack u have include inside the window have an horizontal scrolling enabled and causes when u scroll horizontally, the pointer doesnt know which view's event should goes to. check from window to targetView.
just a guess, hope it helps!


text:
Q: ¿ Cómo hacer que se muestren toast en CalendarView en Fragment? El problema es que tengo un Fragment y no funciona... :
He probado esto pero no funciona :
public class FragmentoPerfil extends Fragment {

    CalendarView calendar;
    public FragmentoPerfil() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        calendar = (CalendarView) getActivity().findViewById(R.id.calendarView);
        calendar.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
            @Override
            public void onSelectedDayChange(CalendarView view, int year, int month, int dayOfMonth) {
                // display the selected date by using a toast
                Toast.makeText(getActivity().getApplicationContext(), dayOfMonth + "/" + month + "/" + year, Toast.LENGTH_LONG).show();
            }
        });
        return inflater.inflate(R.layout.fragmento_perfil, container, false);
    }

}

XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#dee4ee"
    android:orientation="vertical"
    android:padding="@dimen/espacio_norma_1"
    android:weightSum="1">

    <CalendarView
        android:layout_width="match_parent"
        android:layout_height="371dp"
        android:id="@+id/calendarView"
        android:layout_weight="0.40" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/float_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        android:src="@android:drawable/ic_dialog_email" />

</LinearLayout>

Parte donde llamo a los Fragment en el MainActivity:
private void seleccionarItem (MenuItem itemDrawer)
{

        Fragment fragmentoGenerico = null;
        FragmentManager fragmentManager = getSupportFragmentManager();

        switch (itemDrawer.getItemId()) {

            case R.id.CALENDARIO:

                fragmentoGenerico = new FragmentoPerfil();

                break;

            case R.id.PRIMERO:
                fragmentoGenerico = new FragmentPrimero();
                break;

            case R.id.SEGUNDO:
                fragmentoGenerico = new FragmentSegundo();
                break;

            case R.id.TERCERO:
                fragmentoGenerico = new FragmentTercero();
                break;

            case R.id.CUARTO:
                fragmentoGenerico = new FragmentCuarto();
                break;

            case R.id.nav_share:
                Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
                sharingIntent.setType("text/plain");
                sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "AndroidSolved");
                sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, "si que funciona");
                startActivity(Intent.createChooser(sharingIntent, "Share via"));
                break;
    }

A: Asegura que en el layout que carga la Activity en realidad se encuentre el CalendarView ya que haces referencia a este en el layout de la Activity no en el Fragment:
 calendar = (CalendarView) getActivity().findViewById(R.id.calendarView);

Para mostrar el Toast debe ser suficiente usar el contexto de la Activity:
 Toast.makeText(getActivity(), dayOfMonth + "/" + month + "/" + year, Toast.LENGTH_LONG).show();


text:
Q: Why am I not able to run swirl in Rstudio? I am on Windows 8.1 and am running R 3.2.2 in RStudio and am trying to install the package swirl.  I used the command install.packages("swirl") and it installs successfully, but when I enter library(swirl), Rstudio fails to take any further action and eventually crashes.
What is causing this issue and can I fix it?
I have already tried deleting and reinstalling R, Rstudio and swirl several times without any success, nor did I find better ideas online.


text:
Q: Computing orientation of a square and displaying an object with the same orientation I wrote an application which detects a square within an image. To give you a good understanding of how such an image containing such a square, in this case a marker, could look like:

What I get, after the detection, are the coordinates of the four corners of my marker. Now I don't know how to display an object on my marker. The object should have the same rotation/angle/direction as the marker.
Are there any papers on how to achieve that, any algorithms that I can use that proofed to be pretty solid/working?
It doesn't need to be a working solution, it could be a simple description on how to achieve that or something similar. If you point me at a library or something, it should work under linux, windows is not needed but would be great in case I need to port the application at some point.
I already looked at the ARToolkit but they you camera parameter files and more complex matrices while I only got the four corner points and a single image instead of a whole video / camera stream.

A: I believe you can use OpenCV's cvGetPerspectiveTransform to find the transform that can warp a square to the marker's corners, and then cvWarpPerspective to warp the image.

A: It's a square. It's supposed to lye in a plane that has normal and we need to find it because it's the way we should place our object. We can suppose that all y cooridnates are 0 and now we are dealing with aspect problem. Maybe we could start by mapping it into 0-1 range. Most left point gets 0 on x, most right 1, same will be on z - nearest get's 0 and farest 1.
we can determine this by checking length of diagonals. shorter one connects front and back point and next the other 2.
so we get something like
       x z
left:  0 ?
right: 1 ?
front: ? 0
back:  ? 1

I think these ? could be computed by aspect of sides. Using square simplifies problem. If 2 lines connecting front-right and front-left are same, z values of left and right are 0.5 . Well and this way you could get all 3 dimensions and using vector cross product compute normal. You could then take your models having y axis as height, compute matrix used to rotate 0,1,0 vector into normal you get, then draw position 2D image and scale it properly. Well I don't know if I helped you maybe it's not the way it even works but I hope I wrote something that can be useful.


text:
Q: Elasticsearch: Unable to import logger (answer applies to other imports) Objective
To use Elasticsearch's logger functionality to better debug server-side Groovy script code.
Problem Summary
Unable to import org.elasticsearch.common.logging.*
Details

*

*Using Elasticsearch 2.3

*Scripts stored in /etc/elasticsearch/scripts and Java client has been able to access them successfully via Client.update(). That is, the folder location should be correct. I've seen suggestions to place code in elasticsearch/config/scripts, which actually didn't work for me)

*Tried this solution, that is:
import org.elasticsearch.common.logging.*
ESLogger logger = ESLoggerFactory.getLogger('myscript')
But the Elasticsearch log shows a compiler complaint:
unable to resolve class org.elasticsearch.common.logging.ESLogger
I checked the source code on GitHub here and the ESLogger class is there. So I don't know why this is happening.
Does anyone have advice on getting the import to work?

A: The reason for this is the Java Security Manager that has been enabled in Elasticsearch 2.2 for scripting. Which means you need to follow the rules and configure which classes you want your script to be able to access.
To be able to make logging work in scripts I have defined my own policy file and set it JAVA_OPTS or even in the startup command as -Djava.security.policy=file:///D:/ES/elasticsearch-2.3.1/my.policy. The minimum content of the my.policy file should be:
grant {
    permission org.elasticsearch.script.ClassPermission "org.elasticsearch.common.logging.*";
    permission org.elasticsearch.script.ClassPermission "org.apache.log4j.*";
};

Of course, you need to restart ES for the changes to be effective.


text:
Q: Setting a ReadOnly TextBox default BackColor I have a TextBox which is set to be ReadOnly.
At some point that TextBox is being available for editing, and it's BackColor changes (It is indicating if the value is valid).
If I want to set the TexBox back to ReadOnly, the TextBox doesn't get back the original BackColor that a ReadOnly TextBox gets.
What should I do in order to get the original color again?
I realize I can set the color manually to SystemColors.Control, but is this the "right way"?
Code Sample
This is a simple code for demonstration.
If SystemColors.Control is the way to go, I will change it in the ReadOnlyChanged event...
private void button1_Click(object sender, EventArgs e)
{
    //At this point this.textBox1 is ReadOnly
    this.textBox1.ReadOnly = false;
    this.textBox1.BackColor = Color.Orange;

    /*this.textBox1.BackColor = SystemColors.Control;*/ //Is this the right way?
    this.textBox1.ReadOnly = true; //Textbox remains orange...
}

A: I know this is an old question, but for posterity sake:
TextBox as well as many other controls rely on Color.Empty to decide whether or not to display its default color.
To set a TextBox back to the system default (irregardless of state):
textBox1.BackColor = Color.Empty;

A: Yes, that's fine. There's no reason you can't use the SystemColors to specify the desired color for the control. I've never heard of anything in WinForms that would cause a control to automatically revert to its default color upon setting ReadOnly = true.
I suppose one alternative is to create a class-level variable called textBox1OriginalColor or something and set it in the form's Load event. Then you know exactly what it was when the form was originally displayed, if you think someone might in the future set the text box's default background color to, say, blue in the designer or something.

A: You have to set BackColor to the look of a ReadOnly TextBox's BackColor, that is Color.FromKnownColor(KnownColor.Control):
//this is the ReadOnlyChanged event handler for your textbox
private void textBox1_ReadOnlyChanged(object sender, EventArgs e){
   if(textBox1.ReadOnly) textBox1.BackColor = Color.FromKnownColor(KnownColor.Control);
}

You may need a variable to store the current BackColor every time your TextBox's BackColor changes:
Color currentBackColor;
bool suppressBackColorChanged;
private void textBox1_BackColorChanged(object sender,EventArgs e){
   if(suppressBackColorChanged) return;
   currentBackColor = textBox1.BackColor;
}
private void textBox1_ReadOnlyChanged(object sender, EventArgs e){
   suppressBackColorChanged = true;
   textBox1.BackColor = textBox1.ReadOnly ? Color.FromKnownColor(KnownColor.Control) : currentBackColor;
   suppressBackColorChanged = false;
}


text:
Q: Generating Fibonacci Numbers Using variable-Length Arrays Code Compiler Error Compile error in vs2010(Win32 Console Application Template) for the code below. How can I fix it.
unsigned long long int Fibonacci[numFibs]; // error occurred here

error C2057: expected constant expression
error C2466: cannot allocate an array of constant size 0
error C2133: 'Fibonacci' : unknown size
Complete code attached(It's a sample code from programming In c -3E book. No any modify)
int main()
{

 int i, numFibs;

 printf("How may Fibonacci numbers do you want (between 1 to 75)? ");
 scanf("%i", &numFibs);

 if ( numFibs < 1 || numFibs > 75){
  printf("Bad number, sorry!\n");
  return 1;
 }

 unsigned long long int Fibonacci[numFibs];

 Fibonacci[0] = 0; // by definition
 Fibonacci[1] = 1; // ditto

 for ( i = 2; i < numFibs; ++i)
  Fibonacci[i] = Fibonacci[i-2] + Fibonacci[i-1];

 for ( i = 0; i < numFibs; ++i)
  printf("%11u",Fibonacci[i]);

 printf("\n");

 return 0;

}

A: VS2010 is a C++ compiler by default, and C++ does not support variable length arrays. You can change your project to compile code as C code, but VS2010 still doesn't really support C99.
I would recommend you use gcc for C code, it's much more conformant.

A: You cannot have an array of variable length. Use dynamic allocation returning pointer (malloc)

A: Either dynamically allocate the array or use a constant array size.
#define kMaxFibs 75
...
if ( numFibs < 1 || numFibs > kMaxFibs){
...
unsigned long long int Fibonacci[kMaxFibs];

A: Which compiler are you using? And are you compiling as C or C++?
Variable-length arrays are legal in C since C99, but if you're using an older compiler (or compiling as C++) they won't work.
As a workaround, you can switch to using dynamic allocation:
typedef unsigned long long uint64; // just for convenience
uint64* Fibonacci = (uint64*)malloc(sizeof(uint64)*numFibs);
// {code here}
// then at the end:
free(Fibonacci);
return 0;


text:
Q: Método Paint do Jframe não mostra os desenhos na tela Eu sobrecarreguei o método paint do Jframe e estou utilizando a classe Graphics2D para tentar fazer os desenhos, mas nada está sendo desenhado na tela, pude ver com o debugger que o método é executado constantemente mas os desenhos não aparecem na tela, esse é o método:
@Override
public void paint(Graphics g) {
    super.paint(g);

    Graphics2D g2d = (Graphics2D)g.create();

    g2d.setColor(Color.yellow);
    g2d.drawLine(0, 0, WIDTH, HEIGHT);

    g2d.dispose();
}

A classe principal implementa a interface Runnable, disparo uma thread e dentro do método run eu chamo o método repaint() do JFrame:
public void run(){
     repaint();
     try {
        Thread.sleep(100);
     } catch (InterruptedException ex) {
        Logger.getLogger(Game.class.getName()).log(Level.SEVERE, null, ex);
     }

Aqui é o método main onde a thread é disparada:
public static void main(String[] args) {
    Game game = new Game();
    game.createGameWindow("Game");
    new Thread(game, "Game").start();
}

Já procurei por vários tutoriais atrás de um solução, no YouTube, sites de tutoriais etc, todos fazem exatamente o que estou fazendo mas nenhum funcionou,  qual pode ser o problema?

A: O problema é que você está criando um novo objeto ao fazer:

Graphics2D g2d = (Graphics2D)g.create();

Por isso seu desenho não aparece na tela (ele está ocorrendo nesse outro Graphics2D que você criou).
Você deve simplesmente converter g em um objeto Graphics2D, via um type cast:
Graphics2D g2d = (Graphics2D)g;

De acordo com essa outra resposta, esse type cast é sempre válido desde o Java 1.2.
Lembrando que ao fazer esse type cast, deve-se remover o g2d.dispose(); do final.


text:
Q: Java Client Update Strategy I'm having some trouble deciding on the best way to distribute and update my Java application.
My Java application is launched on Windows via an executable that was created from a shell script (Bat_To_EXE_Converter) and launched on Mac via the Mac's handy App system (that basically just runs a shell script).  I can happily update all of my CLASS files and all of my JARs.  The problem arises when I need to modify the shell script that launched the program.
I can't reliably rename the running executable in Windows.  This is essentially the crux of the problem.
Should my shell script use the start /b command to start another upgrader app?  With this approach I'd need some form of IPC to allow the master program to let the upgrader program know it was shutting down.
As I've been sitting here thinking through this, my spidey-sense has been telling me this is a solved problem that people surely will have opinions on.  But Google doesn't have any answers, so I turn to you, Stack Overflow java gurus. :)
I'm open to all forms of answers.  Should I be using WebStart or something similar to solve these problems for me?  Is there something else I should know about?  Is my only option to have another process running and doing the upgrading, if so how do I start this other process so it exists beyond the life of the main process?
Thanks!

A: You may want to check out Getdown. It's billed as "a replacement for Java Web Start due to limitations in Java Web Start's architecture".


text:
Q: How to cache the function that is returned by scipy interpolation Trying to speed up a potential flow aerodynamic solver. Instead of calculating velocity at an arbitrary point using a relatively expensive formula I tried to precalculate a velocity field so that I could interpolate the values and (hopefully) speed up the code. Result was a slow-down due (I think) to the scipy.interpolate.RegularGridInterpolator method running on every call. How can I cache the function that is the result of this call? Everything I tried gets me hashing errors.
I have a method that implements the interpolator and a second 'factory' method to reduce the argument list so that it can be used in an ODE solver.
x_panels and y_panels are 1D arrays/tuples, vels is a 2D array/tuple, x and y are floats.
def _vol_vel_factory(x_panels, y_panels, vels):
# Function factory method
def _vol_vel(x, y, t=0):
    return _volume_velocity(x, y, x_panels, y_panels, vels)
return _vol_vel

def _volume_velocity(x, y, x_panels, y_panels, vels):
velfunc = sp_int.RegularGridInterpolator(
        (x_panels, y_panels), vels
        )
return velfunc(np.array([x, y])).reshape(2)

By passing tuples instead of arrays as inputs I was able to get a bit further but converting the method output to a tuple did not make a difference; I still got the hashing error.
In any case, caching the result of the _volume_velocity method is not really what I want to do, I really want to somehow cache the result of _vol_vel_factory, whose result is a function. I am not sure if this is even a valid concept.

A: scipy.interpolate.RegularGridInterpolator returns a numpy array. This is not cacheable because it doesn't implement hash.
You can store other representations of the numpy array and cache that and then convert it back to a numpy array though. For details on how to do that look at the following.
How to hash a large object (dataset) in Python?


text:
Q: Google Oauth2.0 authentication in a console application I am trying to use Google shopping API. In order to use the API,  my application should be authenticated using OAuth2.0. Looks like this method involves user interaction (where user allows the application to access the resource)
Is it possible to do OAuth authorization in non web applications with no user interaction?

A: This may be a good case for using a Service Account. This would mean that your application isn't running as a user but as itself. That is, as a made up account corresponding to your APIs Console project.
Various official client libraries support the Service Account flow as described in the link above, but C# is not listed among them, so you may have to write it yourself. (Though this issue claims it's supported in the google-api-dotnet-client library, I couldn't find the source for this feature after a minute or two of looking).


text:
Q: Code stop working after I added nested views Code stop working after I added nested views - AngularJS
Hi guys,
I have a simple page that checks a text input against an set word. In my original code the page works the following (original code)

*

*If the user does not enter a text the code will prompt them not to leave the text field empty.

*The text will be compared, if wrong the number of guesses diminishes and then the user will have another chance to enter the right answer.

*If the user gets the right answer and alert will prompt them of the right answer.

*If the user runs out tries the page will pop an alert letting the user knows that they run out of guesses and will let them know what the correct word was.

I added nested views to my code and now my code broke, because it is always telling the user that the text field is empty (nested view code)
I am not certain if it is an issue with my controllers, but I gone up and down my code and I can't find the issue.
Here is the controller for the game
  gameApp.controller('wordController', function($scope)
    {
    $scope.guess = '';
    $scope.guesses = [];
    $scope.guessed= '';
    $scope.allowed = 6;
    $scope.wordToGuess = "Just";
    $scope.guestGuess = "";

    $scope.pushGuess = function () {
        $scope.guesses.push($scope.guestGuess);
        $scope.guessed = $scope.guesses.length;
        $scope.resetGuess();
        $scope.$apply();
    };

    $scope.resetGuess = function() {
        $scope.guestGuess = '';
    };

    $scope.addGuess = function()
        {
        if ($scope.guestGuess === null || $scope.guestGuess === '')
            {
                $("input[type=text]").ready(function () { $("#guessEntry").addClass("has-error"); });
                $("#guessStatus").removeClass("glyphicon glyphicon-thumbs-down form-control-feedback");
                $("#guessStatus").addClass("glyphicon glyphicon-remove form-control-feedback");
                $scope.result = "   Please enter a guess\n\nDon't leave the box empty.";
                alert($scope.result);
            }
        else if ($scope.guestGuess.toLowerCase() == $scope.wordToGuess.toLowerCase())
            {
                $("input[type=text]").ready(function () { $("#guessEntry").removeClass("has-warning").removeClass("has-error").addClass("has-success has-feedback"); });
                $("#guessStatus").removeClass("glyphicon glyphicon-thumbs-down form-control-feedback").removeClass("glyphicon glyphicon-remove form-control-feedback");
                $("#guessStatus").addClass("glyphicon glyphicon-thumbs-up form-control-feedback");
                $scope.pushGuess(guestGuess);
                $scope.result = "You have guessed the correct word. Way to go!\n\n\t\t       The word was: ";
                alert($scope.result + $scope.wordToGuess);
                $scope.resetGuess();
            }
        else if ($scope.guestGuess != $scope.wordToGuess & ($scope.allowed - $scope.guessed) > 1)
            {
                $("input[type=text]").ready(function () { $("#guessEntry").removeClass("has-error").addClass("has-warning"); });
                $("#guessStatus").removeClass("glyphicon glyphicon-remove form-control-feedback").addClass("glyphicon glyphicon-thumbs-down form-control-feedback");
                $scope.pushGuess(guestGuess);
                $scope.result = "Please try again!";
                alert($scope.result);
            }
        else if (($scope.allowed - $scope.guessed) <= 1)
            {
                $("input[type=text]").ready(function () { $("#guessEntry").removeClass("has-warning").addClass("has-error"); });
                $("#guessStatus").removeClass("glyphicon glyphicon-thumbs-down form-control-feedback");
                $("#guessStatus").addClass("glyphicon glyphicon-remove form-control-feedback");
                $scope.guesses.push($scope.guestGuess);
                $scope.guessed = $scope.guesses.length;
                $scope.result = "Game over! The word was: ";
                alert($scope.result + $scope.wordToGuess);
            }
        $scope.guess = '';
        };
    });

A: Seems like it's the way that ui-router handles the creation of scopes when it loads views. I don't use it so i don't know what it does (i use and recommend http://angular-route-segment.com/ )
So i put your wordController inside of game.html and it worked
http://plnkr.co/edit/8ZSyuNAXiC9JX4vBcwtr
I do also kindly recommend you to re-write your app using more directives and factories than controllers, having factories control the checking of the guesses, so you'd have an api with a factory and use GuessService.checkInput($scope.guestGuess) that would make your app more modular and easier to debug and test.

A: $scope.addGuess = function()
{
    $scope.guestGuess = $("#guessEntry").val();
    if ($scope.guestGuess === null || $scope.guestGuess === '')
        {

        ........ //rest of code

I think a reference to the user input was missing.


text:
Q: Problem looping through array of coordinates from database I can parse data from the database but having a hard time looping through all the coordinates in the database and plotting them on the mapview. Can someone please help.
-(void)scanDatabase{

  UIDevice *device = [UIDevice currentDevice];
  NSString *uid = [device uniqueIdentifier];
  NSString *myUrl = [NSString stringWithFormat:@"http://address.php?uid=%@",uid];
  NSData *dataURL =  [NSData dataWithContentsOfURL: [ NSURL URLWithString: myUrl ]];

  // to receive the returend value
  NSString *serverOutput =[[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];
  NSArray *components = [serverOutput componentsSeparatedByString:@"\n"];

  for (NSString *line in components) {
    NSArray *fields = [line componentsSeparatedByString:@"\t"];
    [eventPoints addObjectsFromArray:fields];

    int count = [fields count];
    for(int i=0;i < count; i++) {
      int myindex0 = i*count;
      int myindex1 = (i*count)+1;
      int myindex2 = (i*count)+2;

      NSString *mytitle = [eventPoints objectAtIndex:myindex0];
      NSNumber *myLat = [eventPoints objectAtIndex:myindex1];
      NSNumber *myLon = [eventPoints objectAtIndex:myindex2];

      CLLocationCoordinate2D loc;

      loc.latitude = myLat.doubleValue;
      loc.longitude = myLon.doubleValue;

      customAnnotation *event = [[customAnnotation alloc] initWithCoordinate:loc];
      event.title = mytitle;

      MKPinAnnotationView *newAnnotationPin = [[MKPinAnnotationView alloc] initWithAnnotation:event reuseIdentifier:@"simpleAnnotation"];
      newAnnotationPin.pinColor = MKPinAnnotationColorRed;

      [map addAnnotation:event];
    }
  }
}

A: you need to use the delegate method to add the annotation view
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation

otherwise it will never appear see here
http://developer.apple.com/library/ios/#documentation/MapKit/Reference/MKMapViewDelegate_Protocol/MKMapViewDelegate/MKMapViewDelegate.html
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
    MKPinAnnotationView *newAnnotationPin = [[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"simpleAnnotation"] autorelease];
        newAnnotationPin.pinColor = MKPinAnnotationColorRed;
    return newAnnotationPin;
}

A: Not really sure what problems you are experiencing since "having a hard time..." doesn't describe them very well :-)
Looking at your code I like to make the following comments:

*

*The inner loop doesn't seem to make any sense.

*Why don't you access the fields directly?

*myLat and myLon should be NSString object references.

Maybe something like this works better:
-(void)scanDatabase{

  UIDevice *device = [UIDevice currentDevice];
  NSString *uid = [device uniqueIdentifier];
  NSString *myUrl = [NSString stringWithFormat:@"http://address.php?uid=%@",uid];
  NSData *dataURL =  [NSData dataWithContentsOfURL: [ NSURL URLWithString: myUrl ]];

  // to receive the returend value
  NSString *serverOutput =[[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];
  NSArray *components = [serverOutput componentsSeparatedByString:@"\n"];

  for (NSString *line in components) {
    NSArray *fields = [line componentsSeparatedByString:@"\t"];
    [eventPoints addObjectsFromArray:fields];

    if ( [fields count] != 3 ) {
      // something is wrong/unexpected here, act appropriately
    }
    else {
      NSString *mytitle = [fields objectAtIndex:0];
      NSString *myLat = [fields objectAtIndex:1];
      NSString *myLon = [fields objectAtIndex:2];

      CLLocationCoordinate2D loc;

      loc.latitude = myLat.doubleValue;
      loc.longitude = myLon.doubleValue;

      customAnnotation *event = [[customAnnotation alloc] initWithCoordinate:loc];
      event.title = mytitle;

      MKPinAnnotationView *newAnnotationPin = [[MKPinAnnotationView alloc] initWithAnnotation:event reuseIdentifier:@"simpleAnnotation"];
      newAnnotationPin.pinColor = MKPinAnnotationColorRed;

      [map addAnnotation:event];
    }
  }
}


text:
Q: wysiwyg редактор с кастомными блоками для сайта Подскажите, есть ли wysiwyg редактор, в котором можно добавить свой блок с выбором параметров. Это должно работать так:

*

*перетаскиваем блок "Список новостей" в область редактирования

*в этой области щелкаем по блоку "Список новостей" и выбираем параметры: категория "Новости компании" (выпадающий список), количество новостей: 10

*при сохранении получается примерно такая разметка

Новости компании

<component>
  <type>news</type>
  <params>
    <category>17</category>
    <count>10</count>
  </params>
</component>

Эту разметку будет парсить PHP (это я смогу сделать сам) и в результате получится страница с заголовком и подгруженными новостями.
Нечто подобное есть в Битриксе:

A: Сложно ответить однозначно, т.к. не понятно какую цель вы преследуете. Следует отталкиваться от конкретных требований.
Дело в том что wysiwyg не обладают функционалом "Список новостей". Из коробки их функционал не превышает минимум редактора Word.
В битриксе используется "Setka Editor" Но сам он с новостями не работает, это уже его целевая заточка под конкретное решение в виде битрикс.
Таким образом "Параметры" дорабатываются программистом отдельно на базе wysiwyg под конкретную CMS.
В пример для Wordpress'а есть Unyson, который позволяет работать с блочной сеткой 5 колонок. В нем есть базовый набор элементов для контента, вроде текстового блока, таблицы, видео или картинки. Но программист может доработать дополнительные элементы вроде "списка новостей с переключателем 10|20|50".
Основной Момент в том что сами Новости как таковые берутся из CMS, а wysiwyg это просто редактор текста который превращает текст в html-тэги.
Дополнительный функционал поддерживают почти все актуальные WYSIWYG. Например вот тут для tinymce добавляется кнопочка которая вставляет текущую дату(а далее и параметрическую шестеренку). Если разобраться в коде можно создавать довольно мощный кастомный функционал.


text: Q: Stopping objekt when reach 200z I would like to freeze my cube when it reach 200z. I want to use it for a tutorial level. So the player/cube will stand stil and there can come up a text that explains the game. If you got some idears to do it a better way, ill be open for all of it.


text:
Q: $n!$ as product of consecutive numbers Let $n$ be a positive integer.
In how many ways can one write $n!$ as a product of consecutive integers?
For example: $4!=1\times2\times3\times4=2\times3\times4$. Here, $2$ possibilities exist.
$5!=1\times2\times3\times4\times5=2\times3\times4\times5=4\times5\times6$. Here, $3$ possibilities exist.

A: The products of consecutive integers, $(m+1)\cdot (m+2)\cdot(m+3)\cdots n$ is a factorial from which you have removed the first factors, i.e $\dfrac{n!}{m!}$. To make this equal another factorial, you need to discard the largest factors of $n!$, i.e. $n\cdot(n-1)\cdot(n-2)\cdots$.
It is always possible to discard $n$ itself. This yields
$$\frac{(m!)!}{m!}=(m!-1)!$$
For instance
$$5\cdot6\cdots24=1\cdot2\cdots23.$$
and there are infinitely many solutions, extremely large.
Other solutions are accidental and rare.

A: There are infinitely many $n$ for which $n!$ can be written in 3 ways. All you have to do is set $n_k = 2 \cdot 3 \cdot 4 \ldots \cdot k$. Then whenever $n = n_k - 1$ for some $k$, you can remove the first $k$ numbers in the product and add $n_k$ to the end. It seems much more complicated to prove that you can add, say, two extra consecutive numbers to the end of the product for infinitely many $n$ (and determine for which $n$ when you can, in analytic or fast computational form). If you add two numbers to the end, $n+1$ and $n+2$, then $GCD(n+1,n+2) = 1$ so somehow $n+1$ and $n+2$ must partition the prime factors of $n_k!$. I'm currently running a computer search to find the first $n$ (if any) where this is possible. I'll update if I find anything.

A: It exists at least 2 trivial combinations (1*2*...*n and 2*3*...*n).
It will also exist a third combination if n+1 is the potencial of other number, although it is not an enough condition.
For example:
while 23! = 1*2*3*...*23 = 2*3*4*5*...*23 = 5*6*...*23*24
To get a fourth combination continuing this method, it would have to be a number that reach next conditions:

*

*n+1 = m!

*n+2 = p!/m!

but as soon as p!/m! is always an even number (p>m+1), the difference between it and m! (also even) cannot be one.
For that reason, it is not possible to have 4 combinations.


text:
Q: Distance measure in word2vec I am currently learning about word embedding and word2vec, and I am having a hard time understanding how the similarity between words is measured in that representation.
I have often read that the cosine distance, ergo the angle between vectors, is used for calculate similarity.
I'll illustrate my problem with this example, which shows a simplified representation in the latent word2vec space and discriminates between farm animals and pets:

Here the vector for "Dog" has approximately the same direction as the vector for "Cow", thereby they would be classified as very similar in terms of cosine distance. Also, the distance between "Cat, Dog" would be way bigger than ""Cow, Horse", since they are closer to the origin.
Considering this example, how is cosine distance a valid distance measure in word2vec?

A: The cosine measure is a similarity measure, not a distance measure.
The cosine similarity between two vectors $x,y$ is
$$\mathrm{S}_{\cos}(x,y) = \dfrac{\langle x,y\rangle}{\lVert x \rVert\lVert y \rVert  }.$$
In fact, the actual angle $\theta$ between $x$ and $y$ is equal to the similarity up to a bijection:
$$\theta(x,y) = \cos^{-1}\mathrm{S}_{\cos}(x,y)$$
If you want a distance, use the normalised distance
$$ \mathrm{S}_{\cos}(x,x) +\mathrm{S}_{\cos}(y,y) - 2\mathrm{S}_{\cos}(x,y)$$
Which is equal to the Euclidean distance between the normalised vectors $x/\lVert x\rVert$ and $y/\lVert y\rVert$.
This distance is equal to
$ 2(1 - \mathrm{S}_{\cos}(x,y)) $
Indeed:

*

*Large angle, very dissimilar

*Small angle, very similar


text:
Q: Sprite Kit Collision without bouncing I setup a hero and some platforms that are moving from the top downwards.
With these I have collisionBitMasks that detect when the hero lands on a platform if the hero comes from above (to let the hero jump through the platforms)
if (_hero.physicsBody.velocity.dy > 0) {
                            _hero.physicsBody.collisionBitMask = 0;
                        }
                        else {_hero.physicsBody.collisionBitMask = platformCategory;
                                }

Everything works fine, except that the hero keeps bouncing on the platform.
Is there a way to let him sit on it, while the platform is moving down?
I tried using physicsBody.resting and physicsBody.friction, but without any success.
Thanks for help Guys

A: Had the same issue just a minute ago. It works with setting the restitution but you need to set both restitutions. The one of the hero AND the one of the platform (or in my case the scene boundaries).
so:
hero.physicsBody.collisionBitMask = platformCategory
hero.physicsBody.restitution = 0.0
platform.physicsBody.restitution = 0.0
any_other_object_that_should_still_bounce.physicsBody.restitution = 1.0

will do it. All other objects on the screen still bounce on the platform as long as you set their restitution > 0

A: The trick is to avoid any physics behavior while the hero is on the platform by resetting the hero body's velocity and setting the hero's position to a fixed vertical offset from the platform's position.
In semi-pseudo-code:
-(void) didSimulatePhysics
{
    if (<hero on platform>)
    {
        hero.physicsBody.velocity = CGPointZero;
        hero.position = CGPointMake(hero.position.x,
                                    platform.position.y + <offset as needed>);
    }
}

A: Have you tried altering the restitution property of the nodes' physics bodies?
_hero.physicsbody.restitution = 0;

It controls the bounciness...

A: You can use the Collision category:
When the velocity.dy is < 0 the hero is falling.
func collisionWithPlayer(player: SKNode) {
    // 1
    if player.physicsBody?.velocity.dy < 0 && (player.position.y - player.frame.size.height / 2.0) >= (self.position.y){
        // 2
        player.physicsBody?.collisionBitMask = CollisionCategoryBitMask.Platform

    }


text:
Q: Google Cloud Vision API "cannot use connPool" I'm learning Google Cloud Vision API, but facing some issues. I have completely repeated all the steps from the 'Getting Started' Guide.

*

*download/install google cloud SDK

*activate login credentials using gcloud

*Set the environment variable GOOGLE_APPLICATION_CREDENTIALS

*Install the client library

After that I ran this code and got this error when compiling:
..\cloud.google.com\go\longrunning\autogen\operations_client.go:166:54: cannot use connPool (type "google.golang.org/api/internal".ConnPool) as type *"google.golang.org/grpc".ClientConn in argument to longrunning.NewOperationsClient

Compilation finished with exit code 2

I repeated all the steps over and over and still get this error. Windows 10 is installed on my pc with the latest software updates.
I have NOT changed the code from the tutorial.
Can anyone please tell me why I'm getting this error?

A: Issue has been fixed.
I just needed to remove conflicting custom imports and re-install Google Vision library.
Well that was a dumb mistake, sorry to bother you.


text:
Q: How to select the time between NOW() and last row inserted? What i basically need is a query that will allow me to display the time that has passed between last row inserted and the current time.
The specific table uses the timestamp field type.
I know that DATE_SUB must be used here, but i have no idea how to in this particular problem

A: Assuming that table has a timestamp field which records the time-of-insertion for each record, then
SELECT TIMEDIFF(now(), max(timestampfield))
FROM yourtable

A: select min(now() - timestamp) from table


text:
Q: Mongo DB Version 5 Access Control With Two Read Replicas I have three ubuntu 20.04 servers:

*

*db-master

*db-node1

*db-node2

I would like to know how to enable access control.
The servers work fine except when the following configuration is added to /etc/mongod.conf Thanks in advance:
$ mongo --version
    MongoDB shell version v5.0.1
$ sudo vim /etc/mongod.conf
    security:
     keyFile: "/home/ubuntu/security.keyFile"
     authorization: enabled
$ sudo systemctl status mongod
● mongod.service - MongoDB Database Server
     Loaded: loaded (/lib/systemd/system/mongod.service; disabled; vendor preset: enabled)
     Active: active (running)
$ sudo systemctl restart mongod
ubuntu@db-node2:~$ sudo systemctl status mongod
● mongod.service - MongoDB Database Server
     Loaded: loaded (/lib/systemd/system/mongod.service; disabled; vendor preset: enabled)
     Active: failed

# mongod.conf
# for documentation of all options, see:
#   http://docs.mongodb.org/manual/reference/configuration-options/

# Where and how to store data.
storage:
  dbPath: /var/lib/mongodb
  journal:
    enabled: true
#  engine:
#  wiredTiger:

# where to write logging data.
systemLog:
  destination: file
  logAppend: true
  path: /var/log/mongodb/mongod.log

# network interfaces
net:
  port: 27017
  bindIp: 0.0.0.0

# how the process runs
processManagement:
  timeZoneInfo: /usr/share/zoneinfo

#security:

#operationProfiling:

replication:
  replSetName: "rs0"
#sharding:

## Enterprise-Only Options:

#auditLog:

security:
 keyFile: "/home/ubuntu/security.keyFile"
 authorization: enabled
#snmp:

A: Solution
ubuntu@:~$ sudo chown mongodb [PATH TO KEY FILE]

ubuntu@:~$ sudo chgrp root [PATH TO KEY FILE]

ubuntu@:~$ sudo chmod 400 [PATH TO KEY FILE]


text:
Q: Blocking certain public packages with AWS CodeArtifact I'm hoping to create a private CodeArtifact PyPI repo with an upstream that connects to the public PyPI repo. The private repo will store packages with a certain prefix.
Examples:

*

*foo.databases

*foo.logging
I want to avoid pulling the packages above from the public PyPI repo if a version is requested from the private repo is not available. Any package request with a foo prefix should be blocked from the upstream repo.
Per the repository policy docs...

The codeartifact:ReadFromRepository action can only be used on a repository resource. You cannot put a package's Amazon Resource Name (ARN) as a resource with codeartifact:ReadFromRepository as the action to allow read access to a subset of packages in a repository. A given principal can either read all the packages in a repository or none of them.

...I get the impression that this is not possible. Is there any way to make this work? Artifactory uses an include / exclude pattern to solve this. I was hoping for something similar in CodeArtifact.

A: CodeArtifact does not support blocking packages from upstream based on package name prefix. But CodeArtifact now offers package origin controls that can be used to block individual packages from upstreams.
If you create a private CodeArtifact PyPI repo with an upstream that connects to the public PyPI repo and then publish versions of the packages foo.databases and foo.logging to your private repo, then those packages will be initialized in your private repo with settings to block versions of those package from upstream repositories, which will prevent pulling any versions of those packages from the public PyPI repo.
Since the feature doesn't work on prefixes, if you later request something like foo.networking, it won't be blocked from pulling from public PyPI unless you first  published a version of foo.networking to your private repository or manually configured package origin control on package foo.networking to set Upstream: BLOCK.


text:
Q: How to add JLabel to JPanel public void mouseClicked(MouseEvent e){
        JLabel label = ((JLabel)e.getSource());
        //searches for the label in the label arrayList
        for(int i = 0; i < labels.size(); i++)
            if(labels.get(i) == label){
                JLabel newLabel = new JLabel();
                newLabel.setIcon(label.getIcon());
                newLabel.addMouseMotionListener(motionListener);
                modelPanel.add(newLabel);
                newLabel.setLocation(150, 160);
                newLabel.setVisible(true);
                modelPanel.revalidate();
                modelPanel.repaint();
                System.out.println("added" +modelPanel.getX()+ " " + modelPanel.getY());
                System.out.println(newLabel.getX() + " " + newLabel.getY());
            return;
            }
    }

the above code is supposed to create a new JLabel  and add it to the JPanel modelPanel. the System.out.println shows the object has been added but it fails to show on the screen during runtime.
modelPanel doesn't have a layoutManager as I am building an application that allows a user to drag and drop the created labels in any part of the modelPanel.
How do I make the JLabels show on the modelPanel?

A: Using a null LayoutManager means you need to do the job of the absent LayoutManager, this includes setting both the location and size of the child Component (the latter of which is not done in your code). A very simple example which dynamically adds JLabels to a null layout JPanel:
JFrame frame = new JFrame();
final JPanel panel = new JPanel();
panel.setLayout(null);
final int size = 400;
javax.swing.Timer timer = new javax.swing.Timer(500, new ActionListener(){
    @Override
    public void actionPerformed(ActionEvent e) {
        JLabel lab = new JLabel("HERE");
        lab.setLocation((int)(size * Math.random()), (int)(size * Math.random()));
        lab.setSize(new Dimension(40,20));
        panel.add(lab);
        panel.repaint();
    }
});

frame.add(panel);
frame.setSize(size, size);
frame.setVisible(true);
timer.start();


text:
Q: Copy only new or modified files/directories in C# I am trying to create a simple "directory/file copy" console application in C#. What I need is to copy all folders and files (keeping the original hierarchy) from one drive to another, like from drive C:\Data to drive E:\Data.
However, I only want it to copy any NEW or MODIFIED files from the source to the destination.
If the file on the destination drive is newer than the one on the source drive, then it does not copy.
(the problem)
In the code I have, it's comparing file "abc.pdf" in the source with file "xyz.pdf" in the destination and thus is overwriting the destination file with whatever is in the source even though the destination file is newer. I am trying to figure out how to make it compare "abc.pdf" in the source to "abc.pdf" in the destination.
This works if I drill the source and destination down to a specific file, but when I back out to the folder level, it overwrites the destination file with the source file, even though the destination file is newer.
(my solutions – that didn't work)
I thought by putting the "if (file.LastWriteTime > destination.LastWriteTime)" after the "foreach" command, that it would compare the files in the two folders, File1 source to File1 destination, but it's not.
It seems I'm missing something in either the "FileInfo[]", "foreach" or "if" statements to make this a one-to-one comparison. I think maybe some reference to the "Path.Combine" statement or a "SearchOption.AllDirectories", but I'm not sure.
Any suggestions?
As you can see from my basic code sample, I'm new to C# so please put your answer in simple terms.
Thank you.
Here is the code I have tried, but it's not working.

class Copy
{
    public static void CopyDirectory(DirectoryInfo source, DirectoryInfo destination)
    {
        if (!destination.Exists)
        {
            destination.Create();
        }
        // Copy files.
        FileInfo[] files = source.GetFiles();
        FileInfo[] destFiles = destination.GetFiles();
        foreach (FileInfo file in files)
            foreach (FileInfo fileD in destFiles)
                // Copy only modified files
                    if (file.LastWriteTime > fileD.LastWriteTime)
                    {
                        file.CopyTo(Path.Combine(destination.FullName,
                        file.Name), true);
                    }

                // Copy all new files
                else
                if (!fileD.Exists)
                {
                    file.CopyTo(Path.Combine(destination.FullName, file.Name), true);
                }
        // Process subdirectories.
        DirectoryInfo[] dirs = source.GetDirectories();
        foreach (DirectoryInfo dir in dirs)
        {
            // Get destination directory.
            string destinationDir = Path.Combine(destination.FullName, dir.Name);
            // Call CopyDirectory() recursively.
            CopyDirectory(dir, new DirectoryInfo(destinationDir));
        }
    }
}

A: You can just take the array of files in "source" and check for a matching name in "destination"
/// <summary>
    /// checks whether the target file needs an update (if it doesn't exist: it needs one)
    /// </summary>
    public static bool NeedsUpdate(FileInfo localFile, DirectoryInfo localDir, DirectoryInfo backUpDir)
    {
        bool needsUpdate = false;

        if (!File.Exists(Path.Combine(backUpDir.FullName, localFile.Name)))
        {
            needsUpdate = true;
        }
        else
        {
            FileInfo backUpFile = new FileInfo(Path.Combine(backUpDir.FullName, localFile.Name));

            DateTime lastBackUp = backUpFile.LastWriteTimeUtc;
            DateTime lastChange = localFile.LastWriteTimeUtc;

            if (lastChange != lastBackUp)
            {
                needsUpdate = true;
            }
            else
            {/*no change*/}
        }
        return needsUpdate;
    }

A: Update:
I modified my code with the suggestions above and all went well. It did exactly as I expected.
However, the problem I ran into was the amount of time it took run the application on a large folder. (containing 6,000 files and 5 sub-folders)
On a small folder, (28 files in 5 sub-folders) it only took a few seconds to run. But, on the larger folder it took 35 minutes to process only 1,300 files.
Solution:
The code below will do the same thing but much faster. This new version processed 6,000 files in about 10 seconds. It processed 40,000 files in about 1 minute and 50 seconds.
What this new code does (and doesn't do)
If the destination folder is empty, copy all from the source to the destination.
If the destination has some or all of the same files / folders as the source, compare and copy any new or modified files from the source to the destination.
If the destination file is newer than the source, don't copy.
So, here's the code to make it happen. Enjoy and share.
Thanks to everyone who helped me get a better understanding of this.

    using System;
    using System.IO;

    namespace VSU1vFileCopy
    {
        class Program
        {
            static void Main(string[] args)
            {
                const string Src_FOLDER = @"C:\Data";
                const string Dest_FOLDER = @"E:\Data";
                string[] originalFiles = Directory.GetFiles(Src_FOLDER, "*", SearchOption.AllDirectories);

                Array.ForEach(originalFiles, (originalFileLocation) =>
                {
                    FileInfo originalFile = new FileInfo(originalFileLocation);
                    FileInfo destFile = new FileInfo(originalFileLocation.Replace(Src_FOLDER, Dest_FOLDER));

                    if (destFile.Exists)
                    {
                        if (originalFile.Length > destFile.Length)
                        {
                            originalFile.CopyTo(destFile.FullName, true);
                        }
                    }
                    else
                    {
                        Directory.CreateDirectory(destFile.DirectoryName);
                        originalFile.CopyTo(destFile.FullName, false);
                    }
                });
            }
        }
    }


text:
Q: Postgresql add values to a column with a for loop (on Python) I've added a new column to my postgresql table.
Now I want to add values to this new added column.
The only commands I found allow adding values but not in chosen rows of the column.
What I'm tryin to have is:
cursor.execute('SELECT Column_name FROM Table_name')
rows = cursor.fetchall()
cursor.execute('ALTER TABLE Table_name ADD NewColumn_name type')
for row in rows:
     #Here I want to have a commands that adds a value (result of a function: func(row)) to every row of the new column, one by one something like:

     NewColumn_name[i] = func(row)
     i = i+1

A: Are you looking for update?
update table_name
    set column_name = ?;

Fill in the ? with the value you want (using a parameter is much preferred to munging the query string).

A: You need to execute UPDATE statements in your loop's body. Instead of this:
 NewColumn_name[i] = func(row)

try something like this (documentation):
cursor.execute('UPDATE Table_name SET NewColumn_name = %s WHERE id = %s', (func(row),row[0]);

Assuming the Table_name's first row is a primary index.


text:
Q: Creating a boost::posix_time::ptime object from a 64 bit integer second count I have a 32 bit Linux system in which I have to record data that is timestamped with a UINT32 second offset from an epoch of 1901-01-01 00:00:00.
Calculating the timestamp is ok for me as I can use the 64 bit ticks() counter and ticks_per_second() functions to generate the seconds since epoch as follows (I only require second level resolution)
const ptime ptime_origin(time_from_string("1901-01-01 00:00:00"));
time_duration my_utc = microsec_clock::universal_time() - ptime_origin;
boost::int64_t tick_per_sec = my_utc.ticks_per_second();
boost::int64_t tick_count = my_utc.ticks();
boost::int64_t sec_since_epoch = tick_count/tick_per_sec;

This works for me since I know that as an unsigned integer, the seconds count will not exceed the maximum UINT32 value (well not for many years anyway).
The problem I have is that my application can receive a modbus message containing a UINT32 value for which I have to set the hardware and system clock with an ioctl call using RTC_SET_TIME. This UINT32 is again the offset in seconds since my epoch 1901-01-01 00:00:00.
My problem now is that I have no way to create a ptime object using 64 bit integers - the ticks part of the time_duration objects is private and I am restricted to using long which on my 32 bit system is just a 4-byte signed integer not large enough to store the seconds offset from my epoch.
I have no control over the value of the epoch and so I am really stumped as to how I can create my required boost::posix_time::ptime object from the data I have.
I can probably obtain a dirty solution by calculating hard second counts to particular time intervals and using an additional epoch to make a bridge to allow this but I was wondering if there is something in the boost code that will allow me to solve the problem entirely using the boost datetime library.
I have read all the documentation I can find but I cannot see any obvious way to do this.
EDIT: I found this related question Convert int64_t to time_duration but the accepted answer there does NOT work for my epoch

A: Although boost::posix_time::seconds cannot be used if the seconds represent a number greater than 32 bits (as of Oct 2014), it turns out that boost::posix_time::milliseconds can easily be used (without workarounds), as follows:
inline std::string convertMsSinceEpochToString(std::int64_t const ms)
{
    boost::posix_time::ptime time_epoch(boost::gregorian::date(1970, 1, 1));
    boost::posix_time::ptime t = time_epoch + boost::posix_time::milliseconds(ms);
    return boost::posix_time::to_simple_string(t);
}

So, just convert your 64-bit seconds to (64-bit) milliseconds, and you're good to go!

Note Be /very/ aware of compiler dependent behaviour with the capacity of builting integral types:
uint64_t offset = 113ul*365ul*24ul*60ul*60ul*1000ul; // 113 years give or take some leap seconds/days etc.?

would work on GCC or Clang, but it would simply overflow the calculations in MSVC2013. You'd need to explicitly coerce the calulation to 64 bits:
uint64_t offset = uint64_t(113ul)*365*24*60*60*1000;

A: You could apply time_durations in the maximum allowable increments (which is std::numeric_limits<long>::max()) since the total_seconds field is limited to long (signed).
Note: I worded it as int32_t below so that it will still work correctly if compiled on a 64-bit platform.
Here's a small demonstration:
#include "boost/date_time.hpp"
#include <iostream>

using namespace boost::gregorian;
using namespace boost::posix_time;

int main()
{
    uint64_t offset = 113ul*365ul*24ul*60ul*60ul; // 113 years give or take some leap seconds/days etc.?

    static const ptime time_t_epoch(date(1901,1,1));
    static const uint32_t max_long = std::numeric_limits<int32_t>::max();
    std::cout << "epoch: " << time_t_epoch << "\n";

    ptime accum = time_t_epoch;
    while (offset > max_long)
    {
        accum  += seconds(max_long);
        offset -= max_long;
        std::cout << "accumulating: " << accum << "\n";
    }

    accum += seconds(offset);
    std::cout << "final: " << accum << "\n";
}

Prints:
epoch: 1901-Jan-01 00:00:00
accumulating: 1969-Jan-19 03:14:07
final: 2013-Dec-04 00:00:00

See it Live on Coliru


text:
Q: Beamer theme customization: modifying frankfurt I personally like the Beamer theme `Frankfurt', however for longer presentations with a lot of slides/sections I'm finding that the header space where the sections and the slide dots are listed is not large enough.
My preference would be that rather than listing all sections, the header space only showed the current section plus the navigation dots, either left-justified or centered.
Here is a MWE of what you get by default:
\documentclass[pdf]{beamer}
\mode<presentation>{\usetheme{Frankfurt}}

\title{The title}
\author{A name}
\begin{document}

\begin{frame}
\titlepage
\end{frame}

\begin{frame}
\tableofcontents
\end{frame}

\section{Section 1}
\subsection{}
\begin{frame}{stuff}
some stuff
\end{frame}

\begin{frame}{stuff}
some stuff
\end{frame}

\section{Section 2}
\subsection{}
\begin{frame}{stuff}
some stuff
\end{frame}

\begin{frame}{stuff}
some stuff
\end{frame}

\end{document}

You can see in the MWE result that both section 1 and 2 are listed in the header for all slides.
I don't know the first thing about modifying beamer layouts - anyone have advice? thanks!