text:
Q: In Python with a nested dictionary should I check the type? What other approach can I use? Disclaimer: Hello all Python masters and fans. I would like to thank everyone for their caring support and dear advises which helped me so much. I am a Python newbie who is trying to learn and advance whilst keeping in mind the importance of best practices. Here's a question in which I am seeking a swift way to avoid type checking as if there's one thing I learnt here, that it's not a good thing to do and there must be another way of doing it.
I am constructing a data-object to represent a site map.
I want this in memory so I can quickly map URLs before querying the DB.
Each node must have 2 elements. A name (of website's section) and an ID (its ID in the DB) (4 to 8 digits normally but here represented with one digit only).
If this node has children (on the page), it has Name, ID and another dictionary representing the children.
I have decided to use the following for performance, ease of iteration and memory reasons:
I tried in the past only lists [name, id, [name, id, ..]], dictionaries and I think this is a not-such a bad way.
sitemap = {'section_one': 0,
           'section_two': [1, {'c_sect_2_1': 10,
                         'c_sect_2_2': [11, {'c_sect_2_2_1': 110,
                                           'c_sect_2_2_2': 111,
                                           'c_sect_2_2_3': 112}],
                          'c_sect_2_3': 12,
                          'c_sect_2_4': 13}],
           'section_three': 2,
           'section_four': 3,
           'section_five': 4}

I opted for lists because I might need to modify them (hence no tuples)
I am using dictionaries (hashable) and I can easily check if they contain a section.
Using this data-set, with below function, I map a URL (e.g. /section_two/c_sect_2_2/c_sect_2_2_3) and see if it exists or not to fetch the data from the DB. My function for this:
def map_url(url): #url here is a list e.g. ['section_two', 'c_sect_2_2', 'c_sect_2_2_3']
    sm = sitemap
    for e in url:
        if e in sm:
            if isinstance(sm[e], int):
                return sm[e] #e = where it stops matching due to no children
            sm = sm[e][1] #if not INT it's a list. list[1] has another dict to go-through
    return False #the URL could not be matched-mapped

My questions are:

*

*Instead of checking if value of an item in the dictionary is an
integer to see whether it has children or not, what should I do?
What can I do?

*What might be an alternative to this whole thing? (the way data-structure is built and/or the iteration through it)

I need this way of url mapping as my website can have a lot of nested sections and I don't want to query the DB multiple times just to see if it exists or not.
Finally, I thank you all for your precious times and advises.

A:
Instead of checking if value of an item in the dictionary is an integer to see whether it has children or not, what should I do? What can I do?

The problem seems to be that you use different representations for sections with children and for sections without children. A section without children should really just be a section with an empty list of children:
sitemap = {'section_one': [0, {}],
           'section_two': [1, {'c_sect_2_1': [10, {}],
                               'c_sect_2_2': [11, {'c_sect_2_2_1': [110, {}],
                                                   'c_sect_2_2_2': [111, {}],
                                                   'c_sect_2_2_3': [112, {}]}],
                               'c_sect_2_3': [12, {}],
                               'c_sect_2_4': [13, {}]}],
           'section_three': [2, {}],
           'section_four': [3, {}],
           'section_five': [4, {}]}

Now your code should become a bit simpler.

What might be an alternative to this whole thing? (the way data-structure is built and/or the iteration through it)

You could transform the sitemap into a flat dictionary at the start of your program, so that it becomes something like
flat_sitemap = {
    'section_one': 0,
    'section_two': 1,
    'section_two/c_sect_2_1': 10,
       # ...
    'section_two/c_sect_2_2/c_sect_2_2_1': 110
       # ...
    }

That way your queries would work in expected O(1) time at the cost of a higher space usage.
As for processing the original structure in a different way, you could use recursion. I often find it easier to formulate an algorithm on a tree-like structure in a recursive way, but it depends a bit on your way of thinking. Here's an example (I'm assuming the format of sitemap that is shown in my first sample):
def map_url(url, sm=[None, sitemap]):
    if not url: return sm[0]
    if url[0] not in sm[1]: return False
    return map_url(url[1:], sm[1][url[0]])

print map_url(['section_two', 'c_sect_2_2', 'c_sect_2_2_3']) # => 112
print map_url(['section_two', 'c_sect_2_2'])                 # => 10
print map_url(['section_two', 'notexisting'])                # => False
print map_url([])                                            # => None

As you can see, this makes the special case explicit where you pass an empty URL. You should definitely think about what should happen in that particular case.
You can even leave the second line of the function away. In that case a KeyError would be thrown if an URL cannot be matched (which seems sensible as well).

A: A more consistent approach would be to always use the combination of id and dict, but use an empty dict if there are no children.
sitemap = {'section_one': [0, {}],
           'section_two': [1, {'c_sect_2_1': [10,{}],
                         'c_sect_2_2': [11, {'c_sect_2_2_1': [110,{}],
                                           'c_sect_2_2_2': [111,{}],
                                           'c_sect_2_2_3': [112,{}]}],
                          'c_sect_2_3': [12,{}],
                          'c_sect_2_4': [0,{}]}],
           'section_three':[2,{}],
           'section_four': [3,{}],
           'section_five': [4,{}]}

That way you can always check if a remaining url part is in the child dict.

A: For your first question: a pythonic way isn't to check the type, but to try and catch an exception:
sm = sitemap
for e in url:
    if e in sm:
        try:
            sm = sm[e][1]
        except TypeError:
            return sm[e]
return False

Here, if sm[e] is an integer, it cannot be indexed and a TypeError exception is raised: you can then return your item. If sm[e] can be indexed, you update your sm. Should indexing fail (for example, because there's only one element), another exception would be raised that you could also catch.


text:
Q: can't return motionEvent.action_up please see my code
public boolean onTouchEvent(MotionEvent event) {
         Log.e("mainClass",""+ event.getY( ));
     manager.setNewX((int)event.getX());
     manager.setNewY((int)event.getY());
     log("action = "+event.getAction());
     manager.doTouchEvent(event.getAction());
     return false;

}

when i pressed on field - i see coordinates and  action ( event.getAction()). I see what log returned me 0 (action.down). But when i leave my finger from screen i not see event.action_up. Can any one explain me why i can't get actio_up
p.s. doTouchEvent - function which used in other class.  doTouchEvent(int event);
p.s2 hello everyone :) can't set this to first line

A: Just return true. do not return false.

A: If you define onTouchEvent() for your custom view try calling it for the super view.
return super.onTouchEvent(event);.

A: After I insert return super.onTouchEvent(event); at the end of the method (onTouchEvent must return a value) your code works for me, when I put it in a blank main activity.
You should probably return true instead of breaking in those cases because you are responding to the event.
Android ACTION_UP even never called

redpajama_set_name: RedPajamaStackExchange


text:
Q: I wait for Vs I'm waiting for A friend of mine, who's a ESL intermediate student, wrote in a letter "I wait for your answer" and I found it very weird. I know it's wrong but I can't explain what is exactly wrong. I would have said "I'm waiting for your answer".
So my question is, why is it wrong? Thanks!

A: The verb wait is a dynamic verb which is also known as action verb or activity verb and it is opposite of stative verb.
One of the biggest differences between the Simple Present tense and Present Progressive (Continuous) for a dynamic verb is the former has a habitual aspect and the latter expresses incomplete action or state in progress at a specific time.
For example, let's contrast "I run" with "I am running". The former has a habitual (repetition) aspect and could be an answer to a question, "what kind of (physical) exercise do you do". "I run" means I run habitually to stay healthy. However, the latter means I am running now which is still in progress but we expect the action to finish soon and it could be an answer to "What are you doing (now)?". There is a huge difference.
Going back to your question, "I wait for your answer" can't express your progressive action you are performing at this moment. Nobody waits for an answer habitually or repeatedly. It happens only from time to time and doesn't happen on a regular basis. Therefore, it is more appropriate to use "I am waiting for your answer".
Present tense also has other aspects and it can mean a future action when you use the verbs like leave, start and depart, etc. For further information, please read the linked Wikipedia article.

A: It's wrong because that would state it as a permanent action. (You don't actually wait you whole life for an answer.)
For instance, I wait for your arrival every day.
It's a temporary action, that's why you need the continuous form.


text:
Q: How to add corners to a view I added a full border around a view but I need to add just the corner as shown image below :

I mean the red corner only .
I tried to adjust the below border xml , but it didn't work :
<shape xmlns:android="http://schemas.android.com/apk/res/android"
  android:shape="rectangle">
    <stroke android:width="10dp" android:height="10dp" android:color="#B22222" />
    <solid android:color="#FCE6C9" />
    <corners android:radius="20dp"  />
</shape>

Any help will be appreciated

A: I don't think it's possible to do this using a ShapeDrawable, as it would require you to use some sort of margin or padding on the drawable itself. There actually is a padding attribute, but unfortunately that only has effect on the content of the View, and not the drawable itself.
That being said, an easy solution would be to create a 9-patch in stead and apply that as background to the TextView. Just for demonstration purposes: make the 9-patch look somewhat like this:

Edit:
On second thought, there's actually another option that relies on using a LayerDrawable to create the desired effect. It's a bit tedious to create and I have my doubts it'll be more efficient than using a 9-patch, but at least you don't have to render out images, which means that if you need to make e.g. a change in colours, it's more straightforward.
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/rounded" />
    <item android:drawable="@android:color/white" android:left="30dp"
        android:right="30dp" />
    <item android:bottom="30dp" android:drawable="@android:color/white"
        android:top="30dp" />
    <item android:bottom="30dp" android:left="10dp" android:right="10dp"
        android:drawable="@color/pink" android:top="30dp" />
    <item android:bottom="10dp" android:left="30dp" android:right="30dp"
        android:drawable="@color/pink" android:top="10dp" />

</layer-list>

Some details: @drawable/rounded is the code snippet you posted yourself. The following two items are simply white rectangles with an offset, to create the white edges. Now, since these will also overlay the pink surface, we need two more pink rectangles (again with specific offsets) to counter that. The result is a background that looks exactly like what you're showing in your question.
Note that you might want to see if you can optimise this a bit. At the least I'd recommend not hardcoding the offsets (like I did for simplicity), but store them in a dimens.xml file so you can keep these values centralized and consistent by referencing them from both the ShapeDrawable and LayerDrawable.
Addendum: On pre-ICS (or perhaps pre-Honeycomb) devices, there appears to be an issue with directly referencing colours with the android:drawable attribute. You can however easily get around this by setting up another drawable (be it either a 9-patch or ShapeDrawable) to represent this colour. For example, in the snippet above, you would replace android:drawable="@color/pink" with android:drawable="@drawable/color_pink", where color_pink can simply be an xml file containing:
<shape xmlns:android="http://schemas.android.com/apk/res/android"
  android:shape="rectangle">
    <solid android:color="#FCE6C9" />
</shape>

Obviously you will need to do the same for all other colours referenced in the LayerDrawable. Tested on Gingerbread 2.3.7.

A: I would create a 9-patch file and set it to be the background of the main container. The steps to do that would be.

*

*You create the background you would like roughly in fireworks, illustrator, or whatever image editing software you prefer.

*Then crop the artwork so that there is only a 1 pixel border around the artwork. Save it as a png.

*Open the draw9patch.bat file in your android sdk folder on your computer C:\Program Files (x86)\Android\android-sdk\tools.

*Open your png file. You can then use your mouse to click on the outer 1 pixel border which will turn the clicked pixels black. The areas that you have black pixels on both the top and bottom or on the left and right will be the area that is stretched. In your case you just want to have the middle area where there is no red stretched.

*My personal preference is to just open the file above and save it as a 9 patch file. Then open it in my photo editing software to create a 1 pixel thick line in the same fashion as above. It is quicker and more precise.

*Finally add the file to your drawable folder. Then set the background of your main view container to the drawable.

That should be it. Hope that helps.


text:
Q: How to make a live search bar from replicated divs in MVC? I'm trying to create a live search bar which filters out results as the user is typing. My home page shows a list of employees which is being received from my EmployeeModel.cs via the HomeController.cs.
Below is my index.cshtml code which is repeating the div for every employee in the database:

        @foreach (var e in Model)
        {

@e.FirstName @e.LastName

@e.SubDivision.Name

@e.Role.Description

                Details

        }


text:
Q: 3D image in MATLAB using different images I have a set of images of a scene at different angles and the camera intrinsic parameters. I was able to generate the 3D points using point correspondences and triangulation. Is there a built-in method or a way to produce 3D images in MATLAB? From the given set of images, a 3D image as such? By 3D image, I mean a 3D view of the scene based on the colors, depth, etc.?

A: There was a recent MathWorks blog post on 3D surface rendering, which showed methods using built-in functions and using contributed code.
The built-in method uses isosurface and patch. To display multiple surfaces, the trick is to set the 'FaceAlpha' patch property to get transparency.
The post also highlighted the "vol_3d v2" File Exchange submission, which provides the vol3d function to render the surface. It allows explicit definition of voxel colors and alpha values.

A: Some file exchange from mathworks:
3D CT/MRI images interactive sliding viewer, 3D imshow, image3, and viewer3D.
If your images matrix I has the dimension of x*y*z, you can try surface as well:
[X,Y] = meshgrid(1:size(I,2), 1:size(I,1));
Z = ones(size(I,1),size(I,2));
for z=1:size(I,3)
   k=z*sliceInterval;
   surface('XData',X, 'YData',Y, 'ZData',Z*k,'CData',I(:,:,z), 'CDataMapping','direct', 'EdgeColor','none', 'FaceColor','texturemap')
end

A: The Computer Vision System Toolbox for MATLAB includes a function called estimateUncalibratedRectification, which you can use to rectify a pair of stereo images. Check out this example of how to create a 3-D image, which can be viewed with a pair of red-cyan stereo glasses.


text:
Q: smarty , how to solve smarty incompatible
unrecognized tag: $ncache['tab']="gallery_cat" (Smarty_Compiler.class.php, line 455)

i got this error, when i type the following code
{$ncache[tab]="gallery_cat"}
{$ncache.tab="gallery_cat"}

anyway to assign an array in smarty?

A: You can assign arrays in smarty with the php tag like this:
{php}
$this->assign("array", array('1','2','3'));
{/php}

Or if you are using version 3 you can also use it directly from smarty
{$array = ['1','2','3']}


text:
Q: DeltaSpike @Transactional is not called Well, i'm trying to use @Transactional by DeltaSpike but TransactionalInterceptor is never called.
This is my EntityManagerProducer:
public class EntityManagerProducer implements Serializable {

    private static final long serialVersionUID = 1L;

    private static EntityManagerFactory emf = Persistence.createEntityManagerFactory("generalPU");

    @Produces
    @TransactionScoped
    // is a bit better than @RequestScoped because it won't allow perform injection outside transaction context
    public EntityManager createEntityManager() {
        return emf.createEntityManager();
    }

    public void close(@Disposes EntityManager em) {
        if (em.isOpen()) {
            em.close();
        }
    }

    public EntityManagerFactory getEmf() {
        return emf;
    }

    public void setEmf(EntityManagerFactory emf) {
        this.emf = emf;
    }

}

I have a class that inject EntityManager and use @Transactional, see:
@Named
@RequestScoped
public class BasicDAOImpl implements BasicDAO, Serializable {
    @Inject
    private EntityManager entityManager;

    @Transactional
    public void save(AbstractBean bean) {
    try {
        entityManager.merge(bean);
    } catch (Exception e) {
        logger.error("Erro ao tentar salvar. \n " + e);
    }
    }
}

And i have a beans.xml with interceptor, look:
<?xml version="1.0"?>
<beans xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://jboss.org/schema/cdi/beans_1_0.xsd">
     <interceptors>
        <class>org.apache.deltaspike.jpa.impl.transaction.TransactionalInterceptor</class>
    </interceptors>
</beans>

How can i fix this problem ? I'm following exactly the same example in the apache page (https://deltaspike.apache.org/documentation/jpa.html).
I'm using Tomcat7 + JDK 1.8 + CDI 1.2 (Weld 2.3.0 final implementation)
Edit 1:
This is my persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
    xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd ">

    <persistence-unit name="generalPU">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <non-jta-data-source>java:/comp/env/jdbc/cedDS</non-jta-data-source>
        <properties>
            <property name="hibernate.show_sql" value="true" />
            <property name="hibernate.format_sql" value="false" />
            <property name="hibernate.hbm2ddl.auto" value="update" />
            <property name="hibernate.cache.use_second_level_cache"
                value="false" />
            <property name="hibernate.cache.use_query_cache" value="false" />
            <property name="hibernate.jdbc.batch_size" value="50" />
            <property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect" />
        </properties>
    </persistence-unit>

</persistence>

Edit 2: My dependencies in pom.xml
<dependency>
            <groupId>org.facebook4j</groupId>
            <artifactId>facebook4j-core</artifactId>
            <version>2.3.1</version>
        </dependency>

        <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>mail</artifactId>
            <version>1.4</version>
        </dependency>

        <dependency>
            <groupId>org.apache.deltaspike.modules</groupId>
            <artifactId>deltaspike-jpa-module-api</artifactId>
            <version>1.7.1</version>
        </dependency>

        <dependency>
            <groupId>org.apache.deltaspike.modules</groupId>
            <artifactId>deltaspike-jpa-module-impl</artifactId>
            <version>1.7.1</version>
        </dependency>

        <!-- JASPER REPORT IMPORTS -->

        <dependency>
            <groupId>net.sourceforge.barbecue</groupId>
            <artifactId>barbecue</artifactId>
            <version>1.5-beta1</version>
        </dependency>

        <dependency>
            <groupId>net.sf.jasperreports</groupId>
            <artifactId>jasperreports</artifactId>
            <version>5.0.1</version>
        </dependency>

        <dependency>
            <groupId>net.sf.jasperreports</groupId>
            <artifactId>jasperreports-fonts</artifactId>
            <version>4.0.0</version>
        </dependency>

        <dependency>
            <groupId>xml-apis</groupId>
            <artifactId>xml-apis</artifactId>
            <version>1.4.01</version>
        </dependency>
        <dependency>
            <groupId>xerces</groupId>
            <artifactId>xercesImpl</artifactId>
            <version>2.10.0</version>
        </dependency>

        <!-- FIM JASPER RESPORT IMPORTS -->

        <dependency>
            <groupId>com.sun.faces</groupId>
            <artifactId>jsf-api</artifactId>
            <version>2.1.6</version>
        </dependency>

        <dependency>
            <groupId>com.sun.faces</groupId>
            <artifactId>jsf-impl</artifactId>
            <version>2.1.6</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>

        <dependency>
            <groupId>javax.persistence</groupId>
            <artifactId>persistence-api</artifactId>
            <version>1.0</version>
        </dependency>

        <!-- CDI -->
        <dependency>
            <groupId>org.jboss.weld.servlet</groupId>
            <artifactId>weld-servlet</artifactId>
            <version>2.3.0.Final</version>
        </dependency>

        <dependency>
            <groupId>javax.inject</groupId>
            <artifactId>javax.inject</artifactId>
            <version>1</version>
        </dependency>

        <!-- HIBERNATE -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>3.6.10.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>3.6.10.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>5.1.0.Final</version>
        </dependency>
        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib-nodep</artifactId>
            <version>2.2.2</version>
        </dependency>

        <dependency>
            <groupId>javassist</groupId>
            <artifactId>javassist</artifactId>
            <version>3.12.1.GA</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.6.1</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>1.6.1</version>
        </dependency>
        <dependency>
            <groupId>asm</groupId>
            <artifactId>asm-commons</artifactId>
            <version>3.1</version>
        </dependency>

        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

        <dependency>
            <groupId>commons-collections</groupId>
            <artifactId>commons-collections</artifactId>
            <version>20040616</version>
        </dependency>

        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>

        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3</version>
        </dependency>

        <dependency>
            <groupId>org.primefaces</groupId>
            <artifactId>primefaces</artifactId>
            <version>3.5</version>
        </dependency>

        <dependency>
            <groupId>javax.annotation</groupId>
            <artifactId>jsr250-api</artifactId>
            <version>1.0</version>
        </dependency>

A: This works by me, with breakpoint into TransactionalInterceptor. Manuelly register the TransactionalInterceptor is no need.
public class EntityManagerProducer implements Serializable {

    @Inject
    @PersistenceUnitName(value="generalPU")
    private EntityManagerFactory entityManagerFactory;

    @Produces
    @TransactionScoped
    protected EntityManager createTranEntityManager() {
        return this.entityManagerFactory.createEntityManager();
    }

    protected void closeEntityManager(@Disposes EntityManager entityManager){
        if (entityManager.isOpen()) {
            entityManager.close();
        }
    }
}


text:
Q: Cannot read MP4 files with openCV (3.2.0) - Python (2.7.13) I am (unfortunately) absolutely new to both Python and OpenCV, but I'd like to use OpenCV (3.2.0) with Python (2.7.13) bindings to extract specific frames from .mp4 files.
I tried to follow the "Getting Started with Videos" tutorial to learn how to play video files (http://docs.opencv.org/3.0-beta/doc/py_tutorials/py_gui/py_video_display/py_video_display.html), but even though I was able to VideoCapture(0) (i.e. stream the web cam), I was not able to play a video file (mp4): I used the following code named "Untitled.py":
import numpy as np
import cv2

cap = cv2.VideoCapture('PathToVideoFile\film.mp4')
while(cap.isOpened()):
    ret, frame = cap.read()
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    cv2.imshow('frame',gray)
    if cv2.waitKey(25) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

And this is all I get:
================== RESTART: C:\Python27\Scripts\Untitled.py ==================

(and nothing else...)
I downloaded ffmpeg and copied the opencv_ffmpeg320_64.dll from opencv\build\x64\vc14\bin into C:\Python27 but it did not help... Can you please help me with this issue?
Plese let me know if you need more information about the issue and sorry if my question is due to me missing something trivial.
Thank you very much in advance!
Adrien

A: Video camera capture output is in RGB, not the same format as video file for playback. Video file is usually compressed and need a correct codec to decode.
If opencv_ffmpeg320_64.dll is not in %OPENCV_DIR%\bin, video playback won't work. For OPENCV_DIR environment variable setup, below is the example and subjects to your installation.

*

*OPENCV_DIR=C:\Program Files\OpenCV 3.2.0\x64\vc14

*Path=%OPENCV_DIR%\bin;%Path%
Also check the properties of your opencv_ffmpeg320_64.dll file. Its size is about 16.5 MB (17,397,760 bytes) if compiled by VS2015 on Win10 64-bit platform for Python 2.7.
Your Python code works in my PC. From the question above, seems you incorrectly copied the FFMPEG DLL to Python's directory.


text:
Q: Cloning Git repository locally I have just create a git repository on my iMac under the user git account and am now want to clone it from my main user account on the same computer. I have created my SSH key and added it to the .ssh/authorized_keys file. However when I log back in with my main account I get the following error message:

Permission denied (publickey)
  fatal: The remote end hung up unexpectedly

Now to me, and while searching on the web it seems like my public key is incorrect. I have created it twice and still get the same issue.

A: You shouldn't need an ssh key at all.  Make all of the files world readable and just clone the full path.  In other words, do

$ git clone /path/to/repo

A: git clone /path/to_repository  /path/to_where_you_want_it_cloned

Make sure that your main user account has permissions to copy to/from your accounts directories.

A: One additional point is that if you created the git repo and did a git init -bare, you use a .git extension, but you do not need this on the folder name (when cloning it on the same machine).


text:
Q: How to commit edit or end edit on selection confirmed for datagridview combobox cell? Problem: I want to commit an edit for when the user has a datagridview combobox cell, i.e. it would be the regular combo box cell's "Selection Committed"
What I've Tried: So based off a lot of stackflow questions (like Datagridview comboBox not selecting on click/edit ) where they look at the event called such as selected index changed, the cell value changed, cell content click, and edit control showing.
  In these event handlers I have tried to commit the edit, but it instead calls this event after another cell has clicked, not once the selected item has been chosen in the cell. I've already tried making a "selected index changed" handler and definition, but since the combobox cell doesn't have that event, I get an error in vb.net
Here's a sample code snippet:
 Private Sub editingComboBox_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs)

    editCameraTable.CommitEdit(DataGridViewDataErrorContexts.Commit)
    editCameraTable.EndEdit()
End Sub

This isn't called until another cell is clicked or otherwise. Any suggestions on how to flag this event for a datagridviewcomboboxcell?

A: Handel the CellEndEdit action. Yes it only fires after the person clicks elsewhere; but combine it with a keydown preview..  People naturally click return at the end of a text edit and you can use this to trigger the update. A Cell in a gridview can't determine when a person is done typing in it, so it needs the person to click out of it before the edit commit occurs. The only other way around this is perhaps using a timer that resets on each keydown event and updates if the typing goes idle.
Private Sub datagridview1_CellEndEdit(ByVal sender As Object, _
               ByVal e As System.EventArgs) HAndels datagridview1.CellEndEdit

   '  If InLoad = True Then Exit Sub ' may want to suppress if you are programmatically changing this

   datagridview1.CommitEdit(DataGridViewDataErrorContexts.CurrentCellChange)
   ' Do your saves...

End Sub

Private Sub datagridview1_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) _
     Handles datagridview1.KeyDown

    If e.KeyCode = Keys.Return Then
        datagridview1.CommitEdit(DataGridViewDataErrorContexts.CurrentCellChange)
    End If

End Sub


text:
Q: GHC 8 and still the error "Multiple declarations of myDataField123" I have 2 data's with the fields named the same:
data Data1 = Data1 { var1 :: String }
data Data2 = Data2 { var1 :: String }

Also in my 'stack.yaml' I have this:
resolver: lts-7.11

which makes it to use GHC 8.01 which must  deal with this issue. However, it still doesn't and the error is:
 Multiple declarations of 'var1''


text:
Q: MpMovieplayer crash during reminder alert popup I am having this strange issue. When I am playing any video using MpMoviePlayerController, if I get any reminder alert and I choose Close, then my application is crashing with Log :

"An AVPlayerItem cannot be associated with more than one instance of
  AVPlayer".

I am using only one instance of MpPlayerController.
I googled on this issue and found that this can be avoided if I set the property useApplicationAudioSession = NO  of MpMoviePlayerController, then I am not having any crashes.
But the thing is this property is deprecated after IOS6 and apple doesn't recommend to use this property.

A: I would guess that the issue is that your audio session is being interrupted by the audio ping of the alert message. Try using the shared instance to get your audio session. Then set a notification listener to handle the interruption properly. See apples guidelines here Handle Audio Interruptions
NSError *setCategoryError = nil;
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:      &setCategoryError];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(interruptionHandler:) name:AVAudioSessionInterruptionNotification object:nil];

A: I think what you want is : AVAudioSessionCategoryAmbient
See descriptions of all the "Audio Session Categories".
This should Work for you :
NSError *setCategoryError = nil;
BOOL success = [[AVAudioSession sharedInstance]
                 setCategory: AVAudioSessionCategoryAmbient
                 error: &setCategoryError];

as Described In : Setting the Category.


text:
Q: Need to get a list of all scheduled reports/dashboards that belong to my organization, each with its running user As we have a massive number of scheduled reports in our organization this information will be very useful in maintaining the report schedule. Some users are inactive and some reports are failing due to this.

A: List of reports can be obtained by running SOQL: SELECT CreatedDate,Description,DeveloperName,Id FROM Report
same thing with dashboard
To find list of all scheduled reports, easiest way is to find them is in scheduled jobs


text:
Q: Sonar - Always use curly braces for if/else/for/while/do statements So, I've analyzed my project with Sonar and I get this weird error: Always use curly braces for if/else/for/while/do statements I know normally what this mean (and I don't create blocks without curly braces) but in this case it's weird: The errors appears mostly at this types of code (when using && or ||) and I was wondering why:
if (isCreate && latitude && longitude) {
    ...some code here...
}

EDIT:
The entire code:
var map = Ext.getCmp('map_canvas').getMap();

    var latitude = Ext.getCmp('latitudeCmp').getValue();
    var longitude = Ext.getCmp('longitudeCmp').getValue();

    if (isCreate && latitude && longitude) {
        var center = new google.maps.LatLng(latitude, longitude);
        map.setCenter(center);
        var marker = new google.maps.Marker({ position: center, map: map,icon: staticPath+'/images/residence_gMap.png'});
        markersArray.push(marker);
    } else if (latitude && longitude) {
        var center = new google.maps.LatLng(latitude, longitude);
        map.setCenter(center);
    } else if (!latitude && !longitude) {
        var siteEditAction = Seam.Component.getInstance('siteEditAction');
        siteEditAction.getGeolocalizationParameters(fillMapParamsCallback, exceptionHandler);
    }

A: This may be a bug in the Sonar Javascript Plugin. Can you please report your case on the user@sonar.codhaus.org mailing list: our language team will have a look at it and maybe fill an issue on our JIRA.

A: As I answered in Sonar Mailing List ( http://markmail.org/message/dva7u5pxtggsiz7x ): you face with following two issues, which
will be fixed in next release -
http://jira.codehaus.org/browse/SONARPLUGINS-2079 and
http://jira.codehaus.org/browse/SONARPLUGINS-2200


text:
Q: Redux Saga Twice call in async I am building react-native app with redux saga. I think I am doing something wrong. This may be because I don't know much about how saga works. But the part I'm trying to understand is why you need to call twice.
My button for first call.
    <Button
                loading={pending}
                onPress={this.handleLogin}
                containerStyle={styles.margin}
              />

My function for button.
 handleLogin = () => {
    const { screenProps: {t} } = this.props;
    const {email, password} = this.state;
    this.props.dispatch(signInWithEmail({email, password}));

My actions
import * as Actions from './constants';

export function signInWithEmail({email, password}) {
  return {
    email,
    password,
    type: Actions.SIGN_IN_WITH_EMAIL,
  };
}

My Saga Listeners
export default function* authSaga() {
  yield takeEvery(Actions.SIGN_IN_WITH_EMAIL, signInWithEmailSaga);
  yield takeEvery(Actions.SIGN_IN_WITH_MOBILE, signInWithMobileSaga);
  yield takeEvery(Actions.SIGN_UP_WITH_EMAIL, signUpWithEmailSaga);
  yield takeEvery(Actions.SIGN_IN_WITH_GOOGLE, signInWithGoogleSaga);
  ...
}

My saga function
function* signInWithEmailSaga({email, password}) {
  try {
    const language = yield select(languageSelector);
    let loginRequest = {
      email,
      password,
    };
    const token = globalConfig.getToken();
    const responseLogin = yield call(loginWithEmail, loginRequest);

    if (!responseLogin.user) {
      console.log('if not user', responseLogin);
      yield put({
        type: Actions.SIGN_IN_WITH_EMAIL_ERROR,
        payload: {
          message: responseLogin.message,
        },
      });
    } else {
      yield call(setUser, responseLogin);
    }
  } catch (e) {
    // yield call(handleError, e)
    yield put({
      type: Actions.SIGN_IN_WITH_EMAIL_ERROR,
      payload: {
        message: e.message,
      },
    });
  }
}

I send an email and password to the server to get a response. I making this via
yield call(loginWithEmail, loginRequest);
if signInWithEmailSaga function contains only console log line only trigger twice.
This is a big mistake for me. I am spend 20 hours but I didnt.
I used takeLatest, takeEvery and changed actions name. Same result.
This is my redux store and saga middleware setup.
import {composeWithDevTools} from 'redux-devtools-extension';
import {createStore, applyMiddleware, compose} from 'redux';
import createSagaMiddleware from 'redux-saga';
import {persistStore, persistReducer} from 'redux-persist';
import AsyncStorage from '@react-native-community/async-storage';
import immutableTransform from 'redux-persist-transform-immutable';
import rootReducer from './reducers';
import rootSaga from './sagas';

const persistConfig = {
  key: 'root',
  transforms: [immutableTransform()],
  storage: AsyncStorage,
  whitelist: [
    // 'test',
    'common',
    'category',
    'classified',
    //'auth',
  ],
};

const composeEnhancers =
  process.env.NODE_ENV === 'development'
    ? composeWithDevTools({realtime: true})
    : compose;
const sagaMiddleware = createSagaMiddleware();
const persistedReducer = persistReducer(persistConfig, rootReducer);

export default () => {
  const enhancer = composeEnhancers(applyMiddleware(sagaMiddleware));
  const store = createStore(persistedReducer, enhancer);
  let persistor = persistStore(store);
  // then run the saga
  sagaMiddleware.run(rootSaga);
  return {store, persistor};
};

I will be very glad if you give information about where the problem is. Thank you.

A: It could be possible that your saga listeners are getting registered again when you change route and land back on the same page
Solution would be to de-register the saga when the container corresponding to that particular route is un-mounted


text:
Q: String to lists Java I am doing XML unmarshalling using java jaxb and converting them into strings and calling the function that stores the string in a sql table.
Now I want to store all of string in a list and  insert them in a sql table. Based on the length of list, I ll do them bulk insert I don't want to call the table insert function
everytime.I need help on modifying the code accordingly
    XMLInputFactory xif = XMLInputFactory.newFactory();
    Reader reader = new StringReader(response.toString());
    XMLStreamReader xsr = xif.createXMLStreamReader(reader);
     while(xsr.hasNext()) {
        if(xsr.isStartElement() && xsr.getLocalName().equals("customer")) {
          JAXBContext jc = JAXBContext.newInstance(Customer.class);
          Unmarshaller unmarshaller = jc.createUnmarshaller();
          Customer jb = unmarshaller.unmarshal(xsr,Customer.class).getValue();
         String  customer_name=jb.getNAME();
         String customer_id=jb.getCUSTOMERID();
         String entity_id=jb.getENTITY();
         System.out.println("Customer Name" +customer_name);
         System.out.println("Customer ID" +customer_id);
         System.out.println("Entity ID" +entity_id);
         String insertStatement = "TABLEINSERT (customer_id, customer_name, entity_id)";
             insertStatements.add(insertStatement);
         }

          xsr.next();

     }

      if(insertStatements.size() > 10){
          TABLEINSERT (customer_id, customer_name, entity_id);
        } else {
          System.out.println("Nothing");
        }

private static void TABLEINSERT (String CustomerID,String CustomerName, String EntityID)
{
  try
  {
    System.out.println("Inserting....");
    PreparedStatement statement = con.prepareStatement("INSERT INTO intacct_customer (customer_id,customer_name,entity_id) VALUES ( ?, ?,?)");
    statement.setString(1, CustomerID);
    statement.setString(2, CustomerName);
    statement.setString(3, EntityID);
    statement.execute();
  }
  catch (Exception e)
  {
    System.out.println(e.getMessage());
    System.exit(0);
  }
    }

A: You can create insert statements and store it in a list. Finally based on the size of the list you can choose to perform a insert in a loop or a bulk one.
XMLInputFactory xif = XMLInputFactory.newFactory();
Reader reader = new StringReader(response.toString());
XMLStreamReader xsr = xif.createXMLStreamReader(reader);
List<String> insertStatements = new ArrayList<>();
 while(xsr.hasNext()) {
    if(xsr.isStartElement() && xsr.getLocalName().equals("customer")) {
      JAXBContext jc = JAXBContext.newInstance(Customer.class);
      Unmarshaller unmarshaller = jc.createUnmarshaller();
      Customer jb = unmarshaller.unmarshal(xsr,Customer.class).getValue();
     String  customer_name=jb.getNAME();
     String customer_id=jb.getCUSTOMERID();
     String entity_id=jb.getENTITY();
     System.out.println("Customer Name" +customer_name);
     System.out.println("Customer ID" +customer_id);
     System.out.println("Entity ID" +entity_id);
     String insertStatement = INSERTTABLE(customer_id, customer_name, entity_id); -> I dont want to call them everytime. I need to store them into strings and i need to bulk based on the length of the list.
     insertStatements.add(insertStatement);

    }

     xsr.next();

}

if(insertStatements.size > 10){
  // perform bulk insert
} else {
  // usual insert
}


text:
Q: problem restricting deletion of a django model value I have a foreign key, that when the object it references gets deleted will be filled with a default value via a callable on_delete=models.SET(callable)..   However, I have problem with that because in the Django admin site I'm able to delete the callable value that it has passed to the foreign key and since my foreign key can't be null this is going to raise a server error which I don't like.. so I want to handle that error through the Django admin site itself if that is possible and I know it is.. also if you have better thoughts on this, I really appreciate your help.
As a temporary solution I had overrode the QuerySet > delete() method of the referenced model to skip deleting the object through the Django admin site bulk deletion. I'm sure that there is a better way than this.
The foreign key:
class Product(models.Model):
    marektplace_tag = models.ForeignKey('tags.MarketplaceTag', on_delete=models.SET(default_marketplace_tag))

the callable:
# Model: Product
def default_marketplace_tag():
    from tags.models import MarketplaceTag
    tag = MarketplaceTag.objects.get_or_create(name='None')
    return tag[0].id

The referenced model:
class MarketplaceTag(models.Model):
    name = models.CharField(max_length=32, validators=[only_letters])


text:
Q: how to open a file in python in google app engine?  new_file = open('../pages/pdf/test.PDF', 'rb').read()

keeps giving me file/directory not found
I also tried this in my app.yaml :
 - url: /test.((pdf)|(PDF))
   static_files: pages/pdf/test.PDF
   upload: pages/pdf/test.PDF

File structure
 -app.yaml
 pages
   -index.html
   -page1.html
   pdf
     -test.PDF
 entities
   -booking.py (file that im writing the above code)

how to properly open a file in google app engine?
Here are the app.yaml handlers
 - url: /sitemap.xml
   script: sitemap.app

 - url: /test.((pdf)|(PDF))
   static_files: pages/pdf/test.PDF
   upload: pages/pdf/test.PDF
   application_readable: true

 - url: /images
   static_dir: pages/images

 - url: /fonts
   static_dir: pages/fonts

 - url: /css
   static_dir: pages/css
   expiration: 1s

Trying to attach the above file as below using EmailMessage :
 new_file = open(os.path.dirname(__file__) +'/../pages/pdf/test.PDF').read()

 message = mail.EmailMessage( sender=EMAIL_SENDER,
 subject=subject,body=theBody,to=['myemail@gmail.com'],attachments=
 [('test',new_file)])

 message.send()

In debuggin it says : Invalid attachment type

A: By default files included in your app's static content (i.e. matching a static_files or static_dir handler configuration pattern) aren't accessible to your application code. If you want such access you need to set the application_readable: true option for the respective app.yaml handler configurations. See GAE: file_get_contents() and static files
Once you do that the file will be accessible using a path relative to your application/service root directory (i.e. where the app.yaml file is located), in your case it'll be pages/pdf/test.PDF.


text:
Q: Explanation of generalization of Newton's Method for multiple dimensions I've been following the CS 229 lecture videos for machine learning, and in lecture 4 (~14:00), Ng explains Newton's Method for optimization to maximize an objective function ($f$), but doesn't clearly explain the derivation of the higher dimension generalization:
$$
\theta := H^{-1} \nabla_{\theta}\ f(\theta)
$$
I've read that the Hessian matrix ($H$) is a multiple dimension generalization of the second order derivative, but other than that I'm not sure I understand the formulation of the Hessian or why we multiply by its inverse; perhaps I need to brush up on linear algebra.
What's an intuitive explanation of the Hessian and its inverse in this formula?

A: Overview
Suppose we want to minimize an objective function $f$ that maps a parameter vector $x \in \mathbb{R}^d$ to a scalar value. The idea behind Newton's method is to locally approximate $f$ with a quadratic function, then solve for the point that minimizes this approximation. We then jump to this new point, where we build a new approximation, and repeat the process until convergence.
Local quadratic approximation
Say our current location in parameter space is the vector $x_0$. We can approximate $f$ in the vicinity of $x_0$ using the second order Taylor series expansion:
$$f(x) \approx f_T(x) =
f(x_0) + (x-x_0)^T \nabla f(x_0) + \frac{1}{2}(x-x_0)^T H(x_0) (x-x_0)$$
This is a quadratic function whose value at $x_0$, as well as its first and second partial derivatives, match those of $f$. $\nabla f(x_0)$ is the gradient of $f$ evaluated at $x_0$. This is a vector containing the partial derivatives of $f$, and is analogous to the derivative for functions of single variables. Similarly, $H(x_0)$ is the Hessian of $f$ evaluated at $x_0$. It's a matrix containing second partial derivatives of $f$, and is analogous to the second derivative for functions of single variables.
$$\nabla f(x_0) = \left [ \matrix{
    \frac{\partial f}{\partial x_1} (x_0) \\
    \vdots \\
    \frac{\partial f}{\partial x_d} (x_0) \\
} \right ]
\quad
H(x_0) = \left [ \matrix{
    \frac{\partial^2 f}{\partial x_1^2} (x_0) &
    \cdots &
    \frac{\partial^2 f}{\partial x_1 \partial x_d} (x_0) \\
    \vdots & \ddots & \vdots \\
    \frac{\partial^2 f}{\partial x_d \partial x_1} (x_0) &
    \cdots &
    \frac{\partial^2 f}{\partial x_d^2} (x_0) \\
} \right ]$$
Minimizing the local approximation
Given the local approximation $f_T$ at the current point $x_0$, we want to find a new point $x$ that minimizes $f_T$. This can be done in closed form by taking the gradient of $f_T$ with respect to $x$, setting it to zero, then solving for $x$.
The gradient of $f_T$ can be found by differentiating the expression above (keeping in mind that $\nabla f(x_0)$ is just a fixed vector and $H(x_0)$ is just a fixed matrix):
$$\nabla f_T(x) = \nabla f(x_0) + H(x_0) (x - x_0)$$
Setting it to zero, we have:
$$H(x_0) (x - x_0) = -\nabla f(x_0)$$
We need to isolate $x$, so multiply both sides by the inverse of the Hessian, then move $x_0$ to the righthand side:
$$x = x_0 - \Big( H(x_0) \Big)^{-1} \nabla f(x_0)$$


text:
Q: MySQL - Select all rows which not exist or a field equal to value I have two tables:
g1 :
id |  name  |
1  |  G1    |
2  |  G2    |
3  |  G3    |
4  |  G4    |
5  |  G5    |

g_u_groups :
id | group_id | action |
1  |    2     |  view  |
2  |    3     |  add   |
3  |    2     |  view  |
4  |    3     |  view  |
5  |    1     |  add   |

I have a problem with the following query:
SELECT *
FROM g1
LEFT JOIN g_u_groups ON
    g_u_groups.group_id = g1.id
    AND (g_u_groups.action = 'add' OR g_u_groups.id is null)
ORDER BY g_u_groups.id DESC
LIMIT 10

Now it selects only the groups which have rows in g_u_groups.
I want to order all groups by latest 'add' action but I also want to select the groups which don't have actions.
The expected results :
id |  name  |
1  |  G1    |
3  |  G3    |
2  |  G2    |
4  |  G4    |
5  |  G5    |

A: Does this return the expected?
    SELECT g1.id, g1.name
    FROM g1
    LEFT JOIN g_u_groups
     ON g_u_groups.group_id = g1.id
      AND g_u_groups.action = 'add' or g_u_groups.id is null
    ORDER BY g_u_groups.id DESC, g1.id DESC
    LIMIT 10

this POST talk about sorting multiple columns, it could help you

A: Here is the SQL returning by latest add action also showing items without action:
SELECT *
FROM g1
LEFT JOIN g_u_groups ON
g_u_groups.group_id = g1.id
where (g_u_groups.action = 'add' OR g_u_groups.id is null)
ORDER BY g_u_groups.id DESC
LIMIT 10;


text:
Q: Problemas para crea un callback Hola estoy realizando una prueba sobre el uso de funciones asincronas y estamos viendo Callback, me dan el siguiente enunciado:

Implementa la función "callback" para que reciba un número y lo
  imprima por consola. Utiliza esa función para iterar sobre el array
  utilizando el método forEach que tienen los mismos.

y me dan el siguiente codigo:
var miArray = [1, 2, 3, 4];

function callback(/*...*/) {
}

miArray./*...*/

He intentado darle solucion de multiples maneras pero no he podido, espero poder recibir ayuda, ya que me exigen una manera en particular.

A: Solo te pide que completes la función callback y el forEach que es una funcion propia de los array.

var miArray = [1, 2, 3, 4];

//Esta funcion recive un parametro, en nuestro caso un numero.
function callback(a) {
  //Lo imprimimos en pantalla.
  console.log( a);
}
//Con el forEach, en este caso no es necesario definir los parametros.
miArray.forEach(callback);

// Esto tambien se puede hacer

miArray.forEach( x => { callback(x) });

//Tambien puedes definir el callback dentro del for each.

miArray.forEach( x =>{ console.log(x) });

En esta linea miArray.forEach(callback); no es necesario llamar los parametros puesto que el forEach ya entrega uno por defecto, asi de manera interna completa la funcion :callback(x).


text:
Q: Can JavaScript be used as a general scripting language? I've used JavaScript and some frameworks (jQuery, Prototype, some node.js) for client-side web programming, but never on the desktop, where I do most of my scripting work in either Python or Bash.
But IMHO, JavaScript would make a great scripting language if used outside of the browser. Has anyone tried this? Can JavaScript be an adequate replacement for Python/Perl/Bash for quick and dirty scripting tasks?

A: I use javascript mainly for everything because I like it and my daily job is heavily influenced by it. Now what do I mean by saying everything:

*

*Custom tools(with node-webkit you are able to bring desktop experience)

*Custom scripts to run on my machine via node.js

*Mobile apps. I don't even need PhoneGap as I am pretty comfortable with visiting URL.

*Backend for my web apps with node.js . I can access filesystem and databases so what am I lacking? Well.. A mature enough framework and I hope this will be fixed in the feature.

*Well of course fancy jQuery stuff for websites.
Misc:

*

*I solve all the coding katas with javascript(project euler, codewars)

*I implement algorithms I am interested in Javascript

*3D experiments with three.js and webgl.
Someone will beat me because of performance but I want to satisfy performance of writing code and understanding a topic instead of making it run blazingly fast.
And as for desktop experience, for me working with HTML and CSS for user interface is the most pleasant way.

A: Qt offers QtScript. Wikipedia said:

QtScript is a scripting engine that has been part of the Qt cross-platform application framework since version 4.3.0.
The scripting language is based on the ECMAScript standard with a few extensions, such as QObject-style signal and slot connections.[1] The library contains the engine, and a C++ API for evaluating QtScript code and exposing custom QObject-derived C++ classes to QtScript.

If you don't know what Qt is: It's a cross-platform application framework in C++. It is good in taking complexity out of C++ front-end development, and is also supported on mobile systems. It has been long ago since I last developed with Qt but I liked it.
With QtScript I could imagine that one writes a minimal GUI and does the application logic in JavaScript.

A: Yes! You definitely can do that with Node.js or Rhino. For example the coffeescript compiler is nothing but a node.js script.
I will admit that it is not generally my first choice for desktop scripting but I see no reason why it would not work quite well for a number of tasks.

A: Windows has a component called Windows Scripting Host that allows you to automate administration and even mimic user activity to some extent through JScript.
Update in 2017: OSX now allows you to automate desktop tasks with Javascript. What was previously possible through AppleScript is now possible through Javascript.

A: If you're just talking 'purely outside the browser' then look at tools like Appcelerator and Servoy, both of which use Javascript for coding, which ultimately gets turned into Java.

A: I am using JScript.net right now to create an intelligent command line interface. Its working out pretty well for this project because eval() comes in handy, but not everything works as you expect (its not pure js). But it does offer some RAD. I think it would make a good prototyping platform. Its kind of weird being in a no-mans-land between js and .net though. (Its obsolete too, so hard to find good resources on it)


text:
Q: How do you properly close a JDBC connection for reuse? I am able to retrieve information from my database the first time I establish a connection but whenever I try to reconnect to the database and retrieve more information from the database in different classes it doesn't work. I am trying to put the information I am retrieving from the database into TextViews in Android Studio but they keep showing up as "null". I will show you the code from when I first connect to the database, my connection manager class, and the next time I try to connect to the database. I think it might be because the connection isn't properly being closed but I make sure to close the resultSet, statement, and connection.
This is for my senior project which is due soon so any help would be greatly appreciated. Thanks!
Here is the code from the first time I connect to the database:
public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {

    public final String mEmail;
    private final String mPassword;

    UserLoginTask(String email, String password) {
        mEmail = email;
        mPassword = password;
    }

    @Override
    protected Boolean doInBackground(Void... params) {
        try {
            Connection conn = ConnectionManager.getConnection();
            Statement st = null;
            if (conn != null)
                st = conn.createStatement();
            ResultSet resultSet = null;
            if (st != null)
                resultSet = st.executeQuery("SELECT * FROM userinfo WHERE email='" + mEmail + "'");
            int counter = 0;
            if (resultSet != null)
                while (resultSet.next()) {
                    counter++;
                    try {
                        if (mPassword.equals(resultSet.getString("password"))) {
                            UserLoginInfo.userEmail = mEmail;
                            UserLoginInfo.fName = resultSet.getString("firstname");
                            UserLoginInfo.lName = resultSet.getString("lastname");
                            st.close();
                            resultSet.close();
                            conn.close();
                            return (true);
                        } else
                            return (false);
                    } catch (SQLException e3) {
                        e3.printStackTrace();
                    }
                }
            if (counter == 0)
                return false;
            // TODO: register the new account here.
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return true;
    }

    @Override
    protected void onPostExecute ( final Boolean success){
        mAuthTask = null;
        showProgress(false);
        if (success) {
            finish();
            startActivity(new Intent("NavDrawer"));
        } else {
            mPasswordView.setError(getString(R.string.error_incorrect_password));
            mPasswordView.requestFocus();
        }
    }

    @Override
    protected void onCancelled () {
        mAuthTask = null;
        showProgress(false);
    }
}

Here is my connection manager class:
package com.capstone.hammond.wallstreetfantasyleaguefinal;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class ConnectionManager {

private static String url = "jdbc:oracle:thin:@141.216.24.31:1521:fsdb";
private static String driverName = "oracle.jdbc.driver.OracleDriver";
private static String username = "xxxx";
private static String password = "xxxx";
private static Connection con;

public static Connection getConnection() {
    try {
        Class.forName(driverName);
        try {
            if(con !=null)
                return con;
            else
                return con = DriverManager.getConnection(url, username, password);
        } catch (SQLException ex) {
            // log an exception. for example:
            System.out.println("Failed to create the database connection.");
        }
    } catch (ClassNotFoundException ex) {
        // log an exception. for example:
        System.out.println("Driver not found.");
    }
    return con;
}

}

Here is the second time I try to connect to the database:
package com.capstone.hammond.wallstreetfantasyleaguefinal;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class WeeklyMatchFragment extends Fragment {
    TextView user1;
    TextView user2;
    TextView bank1;
    TextView bank2;
    String oppFName;
    String oppLName;
    float oppBank;

View rootview;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    rootview = inflater.inflate(R.layout.fragment_weekly_match, container, false);
    return rootview;

}

public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    new MatchDetails();

    user1 = (TextView) view.findViewById(R.id.user1);
    user1.setText(UserLoginInfo.fName + " " + UserLoginInfo.lName);
    bank1 = (TextView) view.findViewById(R.id.bank1);
    bank1.setText("Bank: " + UserLoginInfo.bank);
    user2 = (TextView) view.findViewById(R.id.user2);
    user2.setText(oppFName + " " + oppLName);
    bank2 = (TextView) view.findViewById(R.id.bank2);
    bank2.setText("Bank: " + oppBank);

}

public class MatchDetails extends AsyncTask<Void, Void, Void> {

    @Override
    protected Void doInBackground(Void... params) {
        try {
            Connection conn = ConnectionManager.getConnection();

            ResultSet rs = null;
            Statement st = null;
            if (conn != null)
                st = conn.createStatement();
            if (st != null)
                rs = st.executeQuery("SELECT * FROM L1_Standings WHERE EMAIL = '" + UserLoginInfo.userEmail + "'");
            if (rs != null)
                while (rs.next()) {
                    try {
                        UserLoginInfo.bank = rs.getInt("BANK");
                        UserLoginInfo.currOpp = rs.getInt("CURR_OPP");
                    } catch (SQLException e3) {
                        e3.printStackTrace();
                    }
                }
            Statement st1 = null;

            if (conn != null)
                st1 = conn.createStatement();
            ResultSet rs1 = null;
            if (st != null)
                rs1 = st1.executeQuery("SELECT * FROM USERINFO WHERE EMAIL = '" + UserLoginInfo.currOpp + "'");
            if (rs1 != null)
                while (rs1.next()) {
                    try {
                        oppFName = rs1.getString("FIRSTNAME");
                        oppLName = rs1.getString("LASTNAME");
                    } catch (SQLException e3) {
                        e3.printStackTrace();
                    }
                }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
}

}

A: You should close the JDBC connection in finally block.
If you are using JAVA 7, use try with resource statement - try-with-Resource;

A: About your questions:

*

*You should alternatively a) close explicitly the connection b) write and call a close() method in ConnectionManager that does it

*it's a bad idea to reuse the same connection across several tasks. Although this could sound good, in a multithreaded environment it is not efficient. Direct connection must be "closed" as soon as possible. What you're looking for is a ConnectionPool

*yes you must close every database resource (in inverse order): ResultSet, Statement, Connection
Statements, Resultsets and connections are object wrappers of outbound network and database resources, and therefore they aren't infinite (both on client and server side). Leaving those resources open has therefore a different aspect, both on client and on server side.
On client side you're marking as busy some (outbound) resource (i.e. connection) that is instead idle (I mean, between one usage and another). If you don't release that resource that will be still marked as busy on server side as well (here I mean the server side representation of that resource), and since the server usually has a limited number of "slots" available, another client could see denied a request for a new connection, and this is wrong because maybe you're not actually using that.

A: I got it to finally work somewhat. The biggest issue was not that I wasn't closing the connection the first time, but I was not properly calling my Asynctask. It needed to be:
new MatchDetails().execute((Void) null);

Now the only problem that I am having is that the textViews do not change until the fragment opens twice. The first time I open them they appear null, but when I open it again they change to what they are supposed to be. Does anyone have any ideas for that?


text:
Q: Display MetaData of Directory with Hadoop How do I get the metadata of a directory using Hadoop through the command line?
I have tried utilizing hdfs dfsadmin -fetchImage which resulted in an error.  There were a few documents that said this metadata can be read through the fsimage, but I cannot seem to find an example of how to read this data.


text:
Q: Create Graphic from hDC results in arithmetic operation overflow I attempt to prepare printing document by using WinAPI instead of (System.Drawing.Printing.PrintDocument) because Graphic.DrawString does not render Khmer Unicode properly. Only TextRendering.DrawText renders it properly. I believe Graphic is GDI+ wrapper and TextRendering.DrawText is using GDI. Furthermore, PrintDocument does not work with TextRendering.DrawText.
Private Declare Function CreateDC Lib "gdi32" Alias "CreateDCA" _
(ByVal lpDriverName As String, ByVal lpDeviceName As String, _
 ByVal lpOutput As String, ByVal lpInitData As DEVMODE) As Long
Private Declare Function EndDoc Lib "gdi32" (ByVal hdc As Long) As Long
Private Declare Function StartDoc Lib "gdi32" Alias "StartDocA" (ByVal hdc As Long, ByVal lpdi As DOCINFO) As Long
Private Declare Function StartPage Lib "gdi32" (ByVal hdc As Long) As Long
Private Declare Function EndPage Lib "gdi32" (ByVal hdc As Long) As Long

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    '' Getting Printer hDC
    Dim printHandler As Long = CreateDC(Nothing, "Send To OneNote 2010", Nothing, Nothing)
    Dim docInfo As New DOCINFO
    docInfo.cbSize = Len(docInfo)
    docInfo.lpszDatatype = Nothing
    docInfo.lpszOutput = Nothing
    docInfo.lpszDocName = "Testing"

    StartDoc(printHandler, docInfo)
    StartPage(printHandler)

    Dim g As Graphics = Graphics.FromHdc(printHandler)
    TextRenderer.DrawText(g, "Hello World", Me.Font, New Point(10, 10), Color.Black)

    EndPage(printHandler)
    EndDoc(printHandler)
End Sub

Here is my attempt. It fails on this line of code: Dim g As Graphics = Graphics.FromHdc(printHandler). It seem like Long is 64-bits and IntPtr is 32-bits.
Is there any workaround for this?

A: All of your P/Invoke definitions are wrong for VB.NET. You've obviously copied them from a project or website targeting VB 6, but lots of things have changed with .NET.
The correct definitions look like:
<DllImport("gdi32.dll", SetLastError:=False, CharSet:=CharSet.Auto)> _
Private Shared Function CreateDC(lpszDriver As String, _
                                 lpszDevice As String, _
                                 lpszOutput As IntPtr, _
                                 ByRef lpInitData As DEVMODE) As IntPtr
End Function

<DllImport("gdi32.dll", SetLastError:=False)> _
Private Shared Function EndDoc(hdc As IntPtr) As Integer
End Function

<DllImport("gdi32.dll", SetLastError:=False)> _
Private Shared Function StartDoc(hdc As IntPtr, ByRef lpdi As DOCINFO) As Integer
End Function

<DllImport("gdi32.dll", SetLastError:=False)> _
Private Shared Function StartPage(hdc As IntPtr) As Integer
End Function

<DllImport("gdi32.dll", SetLastError:=False)> _
Private Shared Function EndPage(hdc As IntPtr) As Integer
End Function

And chances are good that your definitions for the DEVMODE and DOCINFO structures are wrong, as well. You're probably using Long instead of IntPtr for pointer types, and mixing up Long and Integer for numeric types, since the meaning of those types changed from VB 6 to VB.NET.
You probably don't need the DEVMODE structure at all, and if so, you can replace the CreateDC function definition with:
<DllImport("gdi32.dll", SetLastError:=False, CharSet:=CharSet.Auto)> _
Private Shared Function CreateDC(lpszDriver As String, _
                                 lpszDevice As String, _
                                 lpszOutput As IntPtr, _
                                 lpInitData As IntPtr) As IntPtr _
End Function

and pass IntPtr.Zero for lpInitData, just like you will for lpszOutput, as instructed by the documentation—IntPtr.Zero is effectively equivalent to NULL for pointer types.
The DOCINFO structure would be declared as:
<StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)> _
Private Structure DOCINFO
    Dim cbSize As Integer
    Dim lpszDocName As String
    Dim lpszOutput As String
    Dim lpszDatatype As String
    Dim fwType As Integer
End Structure

As per the documentation, the fwType member can be any of the following constants:

*

*0

*Private Const DI_APPBANDING As Integer = &H1

*Private Const DI_ROPS_READ_DESTINATION As Integer = &H2

All of that said…you do know there are easier ways of printing things in the world of .NET, right?


text:
Q: Trouble to opening t.co links I have trouble to open links from Tweetbot in Safari on the Mac. it just waits loading with the t.co domain.
On iOS I don't have this problems!
Is it because I use uBlock as an adblocker? I can not reproduce this problem. After opening the link a second or third time it usually works.

A: It is possible that it has something to do with uBlock. Have you tried disabling the extension temporarily? Try that and see if the problem persists, if it doesn't, then that is your answer. You might just need to whitelist the domain t.co.
If it doesn't solve the problem, then you might need to try something else. Is both your Mac and iOS device on the same WiFi network? There could be a firewall or something blocking the Mac from connecting to the domain, while the iOS device is on cellular data.

A: If you are browsing the twitter site itself in Safari (and perhaps Chrome), you might be happy with the detox extension by Shaun Inman.
It's not the detox listed on Apple's extension site as that one injects things into Facebook.
The twitter detox is intended to make your history work better, but it might also alleviate your redirection mess as well.


text:
Q: How to test a method that queries a database without actually performing the query? I am trying to write a unit test that will perform a check against a string returned from a method. That string is a part of an entity, which should be generated by a call to the database. I can easily stub such entity, but I don't know how to omit the call to the database, since it is a part of the method.
The method looks like this:
private string GetDescriptionForRelationEntry(string relAttrId, string client)
        {
            // here we are querying the database
            var relationEntities = new EntityDatabaseQuery<AttributeEntryEntity>();

            // the rest of the method
        }

The part specified as the rest of the method needs to be executed, because I have to obtain the string result to perform necessary checks. So, basically,  I need to "fake" only one line of code.
Right now I'm not able to say how extensive modifications on the SUT class are allowed, thus I'm not limiting this problem to any specific solution. Any help will be appreciated.

A: Usually a testable class would be an implementation of some interface or a derived class of some abstract class.
Thus, you can use an inversion of control container framework like Castle Windsor, Ninject or any that might you love more, and provide a fake implementation of the whole interface which won't hit the database, but it'll return a test query result.

A: You can simply create a mock method to represent your DB result
Use this link for more details : http://msdn.microsoft.com/en-us/library/ff650441.aspx

A: I'd advise you to take a look at a solution that lets you wrap a database in memory. For example there is the Effort library.

Effort is a powerful tool that enables a convenient way to create
  automated tests for Entity Framework based applications. It is
  basically an ADO.NET provider that executes all the data operations on
  a lightweight in-process main memory database instead of a traditional
  external database. It provides some intuitive helper methods too that
  make really easy to use this provider with existing ObjectContext or
  DbContext classes. A simple addition to existing code might be enough
  to create data driven tests that can run without the presence of the
  external database.

I explained how I use it in this answer: it was for Entity Framework but I think the same behavior can be used in your case.

A: Most mocking frameworks require you to change the architecture of your solution, creating and implementing interfaces, and loading implementations dynamically.
However, you can also use Microsoft Fakes, which requires no changes to your application. Fakes come with Visual Studio, so you don't need to download or install anything.
For more information, see http://msdn.microsoft.com/en-us/library/hh549175.aspx

Microsoft Fakes help you isolate the code you are testing by replacing other parts of the application with stubs or shims. These are small pieces of code that are under the control of your tests.


text:
Q: Install GNOME extensions through website: security vulnerability? I found a GNOME extension through a Google search (using Chromium), and was very surprised that I could simply toggle the On/Off switch to have the website install a full GNOME extension on my computer without any other manual steps involved. (tested, this works with Firefox as well.) Granted, it does pop up a dialog box asking me to confirm installation, but ...

*

*While this is great for ease of use and usability, aren't there security vulnerabilities with this? I would be interested in knowing how exactly this feature works, and whether I should be concerned about any "backdoors" that this might allow for hackers to easily install executables on my machine.

*Are the extensions on the GNOME site vetted? Is there a way to tell whether extensions are safe or not?

*Are the Chromium and Firefox browsers modified by GNOME in order to allow for this feature? Are there any other custom GNOME Chromium/Firefox changes that users should know about?
UPDATE: Having understood how this works, I now believe this is a really great feature especially for non-technical users, but it did alarm me a little when I first encountered it.

A: Yes, and no.
First the link you clicked on to install an extension was coded in, specifically (I think) to gnome 3.2 as a method for instillation. So in that sense it is a "trusted" site.
Second, gnome extensions are user scripts, stored only for your user. They don't have access to any information that the user does not have access to. So for example there can't be a shell extensions to write files to /.
Third, Browsers were not modified, but gnome shell was.
Basically the install method is no less safe then providing you a tar.gz file and telling you to manually extract it in your home directory. Rather or not the individual extensions are safe is a decision you need to make on a case by case basis. However gnome.org is a legit site, as is the extensions sub domain.


text:
Q: Qt Unit Testing I am new to Qt and unit testing. I have gone through the documentation and example of unit testing, but i couldnt figure out how to use the test scenario's in an application.
For eg. In the documentation a QLineEdit is created and then the value is checked with a specific value.
void testGUI()
{
   QLineEdit lineEdit;
   QTest::keyClicks(&lineEdit, "Hello");
   QCOMPARE(lineEdit.text(),QString("Hello"));
}

When i run the program all the result is shown in the console.
But how can i check if i have a QLineEdit and a QPushButton in a QMainWindow form.
How to do GUI Testing ?

A: You seem to be looking into GUI unit-testing.
Here you go: How can I unit test a GUI?

A: Unit testing usually doesn't include the user interface.  Unit testing should be the low level, testing of each unit (class/component).  Then integration testing tests the units working together to accomplish something.  Sometimes mock objects are employed here to act as stand ins for other components, so verify the behaviour is what you'd expect.
After you have unit testing and integration testing handled, the UI testing should be pretty strait forward.  For a Qt project, the cross platform gui testing framework from froglogic called squish might be your best bet.  However it is a paid product, and if you don't need its cross platform nature, you may be able to get away with some free tools.  Most come down to running your application under some sort of instrumentation, and then it replaying your interactions with the user interface, and verifying the values of text fields etc.
Anyway I believe XCode and Visual Studio provide some basic ui unit testing tools.  Their is also a wikipedia article here.


text:
Q: por que mi input submit no responde? tengo un formulario pero mi boton submit no responde a pesar que le doy  funcion para que lleve los datos a otra pagina, no hace nada
todo el codigo
<!DOCTYPE html>

    <meta charset="UTF-8" />

        <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0 , maximum-scale=1.0 , minimum-scale=1.0">
                <link href="../css/bootstrap.css" rel="stylesheet">
         <link href="//netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.css" rel="stylesheet">
        <title>ASPATPERU-SISBIO</title>
        <link rel="stylesheet" type="text/css" href="../css/default.css"/>
        <link rel="stylesheet" type="text/css" href="../css/component.css"/>
        <link rel="stylesheet" type="text/css" href="../css/demo.css"/>
        <link rel="stylesheet" type="text/css" href="../css/style2.css"/>
        <link rel="stylesheet" type="text/css" href="../css/estilo_esquema_mdr.css"/>

     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

  3

        <link href='http://fonts.googleapis.com/css?family=Terminal+Dosis' rel='stylesheet' type='text/css' />

                            <a href="../inicio.php?codcentro=<?php echo $codcentro; ?>">

                                Principal

                        <a href="paciente_incio.php?codcentro=<?php echo $codcentro; ?>">

                                Pacientes

                                Reporte

                                Ayuda

                                Contact

    <form id="fromulariof1" onsubmit="return guardarf1();" method="POST">
             <legend>DATOS DEL PACIENTE: <?php echo $apellidop.' '.$apellidom.' '.$nombre.'&nbsp&nbsp|&nbsp&nbsp'.$tipo_tratamiento;?></legend>

<?php

 $resultado_tipotuberculosis = mysqli_query($conexion,"SELECT * FROM localizacion_enfermedad");
  $resultado_localizacion = mysqli_query($conexion,"SELECT * FROM especificacion_localizacion");
  $resultado_comorbilidad = mysqli_query($conexion,"SELECT * FROM comorbilidad")
 ?>

             <input type="hidden"  name ="dni" id="dni" value=<?php echo $dni?>>
             <input type="hidden" name="nro_caso" id="nro_caso" value=<?php echo $nro_caso?>>
               <input type="hidden" name="nombre" id="nombre" value=<?php echo $nombre?>>
             <input type="hidden" name="apellidom" id="apellidom" value=<?php echo $apellidom?>>
             <input type="hidden" name="apellidop" id="apellidop" value=<?php echo $apellidop?>>
             <input type="hidden" name="tipo_tratamiento" id="tipo_tratamiento" value=<?php echo $tipo_tratamiento?>>
             <input type="hidden" name="centro" value=<?php echo $codcentro?>>

 <select class="tipo_tuberculosis" id="tipo_tuberculosis" name="tipo_tuberculosis" onchange="mostrarespe()">
               <option value="0" disabled selected>LOCALIZACION</option>
                  <?php
                   while ($rowtitu = $resultado_tipotuberculosis -> fetch_array())
                   {

                   ?>

          <option value="<?php echo $rowtitu['cod_localizacion_enf']; ?>"><?php echo $rowtitu['nombre_localizacion'];  ?></option>
          <?php
               }

            ?>

              </select>

              <select type="hidden" class="localizacion" id="localizacion" name="localizacion" onchange="mostrarespeotros();">
              <option value="0" disabled selected>ESPECIFICAR</option>
              <OPTION value="1">PLEURAL</OPTION>
              <OPTION value="4">GANGLIONAR</OPTION>
              <OPTION value="5">OSTEOARTICULAR</OPTION>
              <OPTION value="5">SISTEMA NERVIOSO CENTRAL</OPTION>
              <OPTION value="6">MILIAR</OPTION>
              <OPTION value="7">OTROS</OPTION>

              </select>

                 <input type="hide" name="otroses" id="otroses" style="
    margin-bottom: 10px; display: none;">

                   <input type="hide" id="otroscom" name="otroscom" id="otroscom" style="
    margin-bottom: 10px; display: none;">

        <div id="mujer_edad" <?php if($sexo=='1'){ ?> style="display: none" <?php } ?> >
                MUJER EN EDAD REPRODUCTIVA: &nbsp&nbspSI&nbsp&nbsp<input type="radio" id="mrsi" name="mr" value="1">&nbsp&nbsp&nbsp&nbspNO <input type="radio" id="mrno" name="mr" value="2">

              USA METODO ANTICONCEPTIVO &nbsp&nbsp
              &nbsp&nbspSI <input type="radio" id="masi" name="ma" value="1">&nbsp&nbsp&nbsp&nbspNO <input type="radio" id="mano" name="ma" value="2">

              <input type="text" name="nom_anti" id="nom_anti">

               INICIA TARGA: &nbsp&nbsp: &nbsp&nbspSI <input type="radio" id="tasi" name="ta" value="1">&nbsp&nbsp&nbsp&nbspNO <input type="radio" id="tano" name="ta" value="2">

               <dir id="targa">
                <input type="date" id="ftarga" name="ftarga">
               </dir>

                INICIA TPC &nbsp&nbsp: &nbsp&nbspSI <input type="radio" id="tpsi" name="tp" value="1">&nbsp&nbsp&nbsp&nbspNO <input type="radio" id="tp" name="tp" value="2">

               <dir id="tpc">
                <input type="date" id="ftpc" name="ftpc">
               </dir>

            ENFERMEDADES CONCONMITANTES
           <input type="text" name="enfconcomitantes">

              <input type='submit' id='btnenviar' class='btnenviar' name='btnenviar' value='GUARDAR'>

  </form>

    <form id="fromulariomdr" onsubmit="return guardarmdr1();" method="POST" class="form-horizontal">

             <legend>DATOS DEL PACIENTE: <?php echo $apellidop.' '.$apellidom.' '.$nombre.'&nbsp&nbsp|&nbsp&nbsp'.$tipo_tratamiento;?></legend>

<?php

 //$resultado_modalida_ingreso = mysqli_query($conexion,"SELECT * FROM modalidad_de_ingreso where obs='$condicion_ingreso'");
 $resultado_tipo_resistencia  = mysqli_query($conexion,"SELECT * FROM tipo_resistencia_mdr");
  //$resultado_metodo   = mysqli_query($conexion,"SELECT * FROM metodo");
  $resultado_tratamiento_mdr = mysqli_query($conexion,"SELECT * FROM tratamiento_mdr  where obs='$condicion_ingreso'");

  $consulta_cingreso = "SELECT * FROM condicion_ingreso WHERE obs='2' ";
$resultado_ingreso = mysqli_query($conexion,$consulta_cingreso);
 ?>

ESQUEMA DE TRATAMIENTO

    NUMERO DE CASO

      <input type="text" class="form-control" id="nro_caso" name="nro_caso" placeholder="NRO CASO .." autocomplete="off"  >

    FECHA DE INICIO DE TRATAMIENTO

      <input type="date" class="form-control" id="infechainimdr" name="infechainimdr">

    ESQUEMA

      <input type="radio" name="optradio" value="ESTANDARIZADO" >ESTANDARIZADO
       <input type="radio" name="optradio" value="EMPIRICO" >EMPIRICO
       <input type="radio" name="optradio" value="INDIVIDUALIZADO" >INDIVIDUALIZADO
      <input type="radio" name="optradio"  value="XDR" >XDR
       <input type="radio" name="optradio" value="APOYO RAM" >APOYO RAM

    DURACION

      <input type="number" class="form-control" id="tiempomdr" name="tiempomdr" placeholder="duracion ...." autocomplete="off"  onblur="obtenerfechafinmdr();">

    CONDICION DE INGRESO

      <select id="condicion_in"  name="condicion_ingreso"  >
  <option value="" disabled selected>CONDICION DE INGRESO </option>
                <?php
    while ( $row = $resultado_ingreso->fetch_array() )
    {
        ?>

                    <option value="<?php echo $row['cod_cingreso'] ?>"><?php echo $row['nombre_condicion_ingreso']; ?></option>

                                 <?php
    }
    ?>
                </select>

      <input type="radio" name="optradiotb">TB RESISTENTE CONFIRMADA
       <input type="radio" name="optradiotb">SOSPECHA DE TB RESISTENTE

    TIPO DE RESISTENCIA :

      <select id="tipo_res"  name="tipo_res"  >
  <option value="" disabled selected>TIPO DE RESISTENCIA</option>
                <?php
    while ( $row = $resultado_tipo_resistencia->fetch_array() )
    {
        ?>

                    <option value="<?php echo $row['id_tipo_mdr'] ?>"><?php echo $row['nombre']; ?></option>

                                 <?php
    }
    ?>
                </select>

         <input type='submit'  value='GUARDAR' onclick="guardarmdr1();">

 </form>

parte donde esta mi problema

    <form id="fromulariomdr" onsubmit="return guardarmdr1();" method="POST" class="form-horizontal">

             <legend>DATOS DEL PACIENTE: <?php echo $apellidop.' '.$apellidom.' '.$nombre.'&nbsp&nbsp|&nbsp&nbsp'.$tipo_tratamiento;?></legend>

<?php

 //$resultado_modalida_ingreso = mysqli_query($conexion,"SELECT * FROM modalidad_de_ingreso where obs='$condicion_ingreso'");
 $resultado_tipo_resistencia  = mysqli_query($conexion,"SELECT * FROM tipo_resistencia_mdr");
  //$resultado_metodo   = mysqli_query($conexion,"SELECT * FROM metodo");
  $resultado_tratamiento_mdr = mysqli_query($conexion,"SELECT * FROM tratamiento_mdr  where obs='$condicion_ingreso'");

  $consulta_cingreso = "SELECT * FROM condicion_ingreso WHERE obs='2' ";
$resultado_ingreso = mysqli_query($conexion,$consulta_cingreso);
 ?>

ESQUEMA DE TRATAMIENTO

    NUMERO DE CASO

      <input type="text" class="form-control" id="nro_caso" name="nro_caso" placeholder="NRO CASO .." autocomplete="off"  >

    FECHA DE INICIO DE TRATAMIENTO

      <input type="date" class="form-control" id="infechainimdr" name="infechainimdr">

    ESQUEMA

      <input type="radio" name="optradio" value="ESTANDARIZADO" >ESTANDARIZADO
       <input type="radio" name="optradio" value="EMPIRICO" >EMPIRICO
       <input type="radio" name="optradio" value="INDIVIDUALIZADO" >INDIVIDUALIZADO
      <input type="radio" name="optradio"  value="XDR" >XDR
       <input type="radio" name="optradio" value="APOYO RAM" >APOYO RAM

    DURACION

      <input type="number" class="form-control" id="tiempomdr" name="tiempomdr" placeholder="duracion ...." autocomplete="off"  onblur="obtenerfechafinmdr();">

    CONDICION DE INGRESO

      <select id="condicion_in"  name="condicion_ingreso"  >
  <option value="" disabled selected>CONDICION DE INGRESO </option>
                <?php
    while ( $row = $resultado_ingreso->fetch_array() )
    {
        ?>

                    <option value="<?php echo $row['cod_cingreso'] ?>"><?php echo $row['nombre_condicion_ingreso']; ?></option>

                                 <?php
    }
    ?>
                </select>

      <input type="radio" name="optradiotb">TB RESISTENTE CONFIRMADA
       <input type="radio" name="optradiotb">SOSPECHA DE TB RESISTENTE

    TIPO DE RESISTENCIA :

      <select id="tipo_res"  name="tipo_res"  >
  <option value="" disabled selected>TIPO DE RESISTENCIA</option>
                <?php
    while ( $row = $resultado_tipo_resistencia->fetch_array() )
    {
        ?>

                    <option value="<?php echo $row['id_tipo_mdr'] ?>"><?php echo $row['nombre']; ?></option>

                                 <?php
    }
    ?>
                </select>

         <input type='submit' id='btnenviar' class='btnenviar' name='btnenviar' value='GUARDAR' onclick="guardarmdr1();">

 </form>

funcion del boton
function guardarmdr1(){

  $.ajax({
     type : "POST",
     url : "traguardarmdr1.php",
     data : $("#fromulariomdr").serialize(),
     success : function(data){
        $("#resultadomdr").html(data);
     }
  })

  return false;
}

A: Agrégale al Form la opción Action y ahí pones el nombre de tu archivo PHP, una vez le des al Button, el formulario te llevara a él junto con los datos que suministraste por el método POST.
Seria así:
<!DOCTYPE html>

<meta charset="UTF-8">
<title>Document</title>

<form method="POST" action="modificar.php">

<input type="text" placeholder="Nombre del Hijo" name="hijo">
<input type="text" placeholder="email" name="email">

<button type="submit">ENVIAR</button>
</form>


text:
Q: Cron Jobs with Laravel 5.3 on Ubuntu 16.10 x64 I'm running a Digital Ocean's Ubuntu 16.10 x64 and have deployed the php Framework Laravel 5.3.28 on the server.
For the most part everything is working as normal however I'm trying to get the crontab to call artisan commands like php artisan schedule:run so that laravel's task scheduler can be put to use.
I do not wish to download any extra packages to make this work as I feel there shouldn't really be a need to since the cron can call, what looks like, any command if properly coded.
What I'm trying to do:
From within the crontab -e I'm trying to properly write the Ubuntu correct way to call php artisan schedule:run
What I've done:
I've currently tried multiple different ways of writing this command and nothing is working as noted below:
#Attempt for cron
SHELL=/bin/bash
#PATH=????? <---Confused if this is even needed
* * * * * php /path/to/artisan scheduled:run 1>> file.log 2>&1
* * * * * /path/to/php artisan scheduled:run 1>> file.log 2>&1
* * * * * /path/to/php artisan scheduled:run >> file.log
* * * * * /path/to/php artisan scheduled:run 1>> file.log
* * * * * /path/to/php artisan schedule:run
* * * * * /path/to/php /path/to/artisan scheduled:run 1>> file.log

I've gone to multiple resources to try and find the answer but nothing seems to be the answer to my specific problem.
Resources:

*

*https://laracasts.com/series/intermediate-laravel/episodes/2?autoplay=true

*http://laravel.io/forum/03-05-2014-automated-mysql-backups?page=1

*https://laracasts.com/discuss/channels/laravel/setting-up-larvel-cron

*https://community.centminmod.com/threads/how-to-run-a-cron-job-properly.2287/

*https://laravel.com/docs/5.3/scheduling

*https://laracasts.com/lessons/recurring-tasks-the-laravel-way

*https://laracasts.com/index.php/discuss/channels/laravel/laravel-artisan-commands-trough-cron-tab

*https://deploybot.com/guides/deploy-a-laravel-app-to-digitalocean
Conclusion:
At this point I'm stuck beyond stuck. Can someone please help me? All I'm trying to do is call the php artisan command using Ubuntu's cron and I don't know the exact way to do it. ANY and all assistance is greatly appreciated.
Thanks in advance,
Happy Holidays!!

A: Here we go. That's how mine looks like. :)
* * * * * php /home/spacemudd/laravel/artisan schedule:run >> /dev/null 2>&1

A: Several of your crontab entries should work. If they appear to not be working the next question is whether you have installed the php-cli package? Without it you will not be able to run php scripts from the command line, only via a web server. If you haven't already I would recommend installing php7.0-cli via:
sudo apt-get update
sudo apt-get install php7.0-cli
The case could be made that when you downloaded php7 via sudo apt-get install php7.0-fpm it downloaded a version that would work with Laravel 5.3 but not necessarily for cron jobs calling php commands with Ubuntu. This is a hypothetical though and I feel might still be worth investigating.


text:
Q: Yii function in layout file I'm using Yii and I'm new to it.
I have a default main.php layout file and i need to make some data extractions from DB and cookies.
I've written 2 functions:
public function getRegionId() {
        if(isset(Yii::app()->request->cookies['region_id'])) {
            $sk = Yii::app()->request->cookies['region_id']->value;
            settype($sk,integer);
            return $sk;
        } else {
            return 1;
        }
    }

    public function regionId2region($id) {
        if(empty($id) or gettype($id)!=='integer') {
            return null;
        } else {
            $reg = Regions::model()->findAll(array(
                'condition'=>"alive=1 AND id=".$id,
            ));
            return $reg;
        }
    }

Now it is not working in any controller. My question is: is it possible to make functions in the layout file or is there a way to pass data to layout file (so that it displays in all controllers)?

A: Move methods into Regions model and make it static. Or Create Helper class? contains just static methods.
class RegionHelper {
public static function getRegionId() {
        if(isset(Yii::app()->request->cookies['region_id'])) {
            return (int)$Yii::app()->request->cookies['region_id']->value;
        }
            return 1;
    }

    public static function regionId2region($id) {
        if(empty($id) or gettype($id)!=='integer') {
            return null;
        } else {
            $reg = Regions::model()->findAll(array(
                'condition'=>"alive=1 AND id=".$id,
            ));
            return $reg;
        }
    }
}

A: You can use BeforeAction in your controller, like this:
protected function beforeAction($action) {

    //Define your variable here:
    public $yourVaribale;

    //do your logic and assign any value to variable

}

Now, you can use this variable in the view file:
view:

<?php echo $this->yourVariable; ?>

A: If your functions are located in the controller that calls the view, you could use the $this reference to access the function. Note the public access of the function.
class UserController extends Controller
{
    //   :
    //   :
    public function fullName($a,$b) {
        return $a.' '.$b;
    }
}

...and in your view ...

Test for <?php echo $this->fullName('Tom', 'Jones'); ?>

If the function is in your model, there are a few choices.
class User extends Activerecord
{
    //   :
    //   :
    public function fullName($a,$b) {
        return $a.' '.$b;
    }
}

You could pass the model through the render function,
class UserController extends Controller
{
    //   :
    //   :
    public function actionDisplayView {
        $userModel = User::model()->findByPK(1);
        $this->render('user_view', array('model' => $model));
    }
}

and directly call the function in the view.

Test for <?php echo $model->fullName('Tom', 'Jones'); ?>

or, if you did not pass the function, you could call the function in the view (or helper classes). Watch the scope.
class User extends Activerecord
{
    //   :
    //   :
    // NOTE: You won't have access to $this.
    static public function fullName($a,$b) {
        return $a.' '.$b;
    }
}

and in the view

Test for <?php echo User::fullName('Tom', 'Jones'); ?>


text:
Q: how can i call prolog rule while asking prolog my_list([hello,hello,hello])

counthowmany(_, [], 0) :- !.
counthowmany(X, [X|Q], N) :- !, counthowmany(X, Q, N1), N is N1+1.
counthowmany(X, [_|Q], N) :- counthowmany(X, Q, N).

in the code above if ask Prolog after compile buffer
my_list(L),counthowmany(hello,L,N).

this question then it gives me the number of hello.....
now if i modify the code in the following way
my_list([hello,hello,hello])

counthowmany(_, [], 0) :- !.
counthowmany(X, [X|Q], N) :- !, counthowmany(X, Q, N1), N is N1+1.
counthowmany(X, [_|Q], N) :- counthowmany(X, Q, N).

numberofhello :- my_list(L), counthowmany(hello,L,N).

% i. e. I want to insert the question in a rule

and after compile buffer (though i get a singleton variable warning) if i ask Prolog
numberofhello.

it just gives me "true" and i don't get the number of hello.

A: Your problem is the fact that your query (numberofhello.) does not have a variable (i.e. a "wh-word"), thus becomes "Can you count how many hellos?" yes-no question instead of "How many hellos". This should fix it:
numberofhello(N) :- my_list(L), counthowmany(hello, L, N).

With this,
?- numberofhello(N).

you should be getting your N = 3.


text:
Q: Why the Accounting DB Schemas do not allow to maintain a clean Products Table? As far as I know, the database schema of the vast majority of Accounting Systems follows this architecture:

Considering all the FKs, I know that the product table is going to grow in time and, if I don't want to corrupt anything, it will not let me to delete any discontinued product. Same goes for most of the other tables. I understand the reason behind using all those FKs, but following this scenario, I am mortgaging myself using those FKs today for a great pain in the future. If we use this DB in a high volume transaction company for some years, I'm almost certain that we will encounter performance and maintenance issues.
I'm asking from an amateur point of view, does anybody know if there exists another DB schema for Accounting Systems that allow to clean those tables?

A: One practice I've seen in financial systems is to snapshot all relevant data at the time of the transaction and store it statically. This would entail relevant product, partner, transactional, audit etc. values being serialized (JSON, XML or proprietary binary format) into a single column. "Relevant" includes de-referencing foreign keys and eliminating system-internal surrogate keys.
Once serialized the future life of the transaction need not rely on the original normalized values being available. They can be amended or removed to satisfy the on-going needs of the OLTP system they are there to support.
Yes, this does duplicate the data and increase the size of the database. These systems did not leave the completed transactions in situ for long, however. Batch jobs promptly removed those rows from the OLTP database into fulfillment, archive and warehouse databases.
This had several benefits. The OLTP schema was separated from that of the other databases. Audit trail was guaranteed as the serialized values were never re-written. Patches to the reference tables could never possibly affect in-process activity. And, as in your case, no-longer needed values need not be retained simply to support history.