text:
Q: How to export a GMF diagram outside eclipse? One of the features of Papyrus that I find really useful is the ability to programmatically interrogate the UML models that it creates by using the UML2 runtime outside the Eclipse UI. This is great for running simple tools to, e.g., produce documentation using POI or write model driven configuration for the Talend MDM tool. However, while traversing and processing the model tree is easily achieved by loading up the resources in a resource set, manipulating the diagrams in the .notation files has proven to be more of a challenge.
I have got to the point (by examining the source for org.eclipse.papyrus.infra.export.ExportAllDiagrams) where I can load all the resources and find the Diagram elements from the .notation file thus:
    File uml = new File(model + ".uml");
    File di = new File(model + ".di");
    File notation = new File(model + ".notation");
    URI umlUri = URI.createFileURI(uml.getAbsolutePath());
    URI diUri = URI.createFileURI(di.getAbsolutePath());
    URI notationUri = URI.createFileURI(notation.getAbsolutePath());

    final ModelSet resourceSet = new ModelSet();

    resourceSet.getPackageRegistry().put(UMLPackage.eNS_URI, UMLPackage.eINSTANCE);
    resourceSet.getPackageRegistry().put(NotationPackage.eNS_URI, NotationPackage.eINSTANCE);

    resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put(Resource.Factory.Registry.DEFAULT_EXTENSION, new XMIResourceFactoryImpl());
    resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("notation", new XMIResourceFactoryImpl());
    resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put(UMLResource.FILE_EXTENSION, UMLResource.Factory.INSTANCE);

    try {
        resourceSet.getLoadOptions().put(XMLResource.OPTION_DEFER_IDREF_RESOLUTION, true);
        resourceSet.getLoadOptions().put(XMLResource.OPTION_DEFER_ATTACHMENT, true);

        resourceSet.getResource(diUri, true);
        resourceSet.getResource(umlUri, true);
        resourceSet.getResource(notationUri, true);

        List<Diagram> diagrams = new ArrayList<Diagram>();
        for (Iterator<Notifier> i = resourceSet.getAllContents(); i.hasNext();) {
            Notifier n = i.next();
            if (n instanceof Diagram) {
                diagrams.add((Diagram) n);
            }
        }

        //export(diagrams);
    } finally {
        // Unload the resource set so that we don't leak loads of UML content in the CacheAdapter
        unload(resourceSet);
    }

However, the ExportAllDiagrams class ultimately uses org.eclipse.gmf.runtime.diagram.ui.render.util.CopyToImageUtil to render the diagram, at which point it fails because it relies on the DiagramUIRenderPlugin and DiagramUIRenderPlugin.getInstance() returns null.
I then had a look at org.eclipse.gmf.runtime.diagram.ui.render.clipboard.DiagramSVGGenerator but had similar problems with the need for various eclipse plugins to be initialised.
I have no experience of the Eclipse plugin system but I am assuming that that the platform loads and initialises plugins and, therefore, the approaches tried so far need to be running within Eclipse GUI environment in order to work. Is there any other method that could be used to easily render the diagrams to SVG without relying on the whole of the Eclipse runtime?


text:
Q: Copying CCSprite animation and position randomly I'm using the code below to animation a leaf and at the same time drop it from the top of the screen to the bottom. I want to have multiple instances of it starting from random positions. Whats the best way to go about it?
    leaf1Sprite = [CCSprite spriteWithFile:@"LeafBrown0000.png"];
    leaf1Sprite.position = ccp(screenSize.width * 0.5f - 40.0f, screenSize.height);
    leaf1Sprite.contentSize = CGSizeMake([leaf1Sprite boundingBox].size.width, [leaf1Sprite boundingBox].size.height);
    [self addChild:leaf1Sprite z:10 tag:30];

CCAnimation *leaf1Ani = [CCAnimation animation];

[leaf1Ani addFrameWithFilename:@"LeafBrown0000.png"];
[leaf1Ani addFrameWithFilename:@"LeafBrown0001.png"];
[leaf1Ani addFrameWithFilename:@"LeafBrown0002.png"];
[leaf1Ani addFrameWithFilename:@"LeafBrown0003.png"];
[leaf1Ani addFrameWithFilename:@"LeafBrown0004.png"];
[leaf1Ani addFrameWithFilename:@"LeafBrown0005.png"];
[leaf1Ani addFrameWithFilename:@"LeafBrown0006.png"];
[leaf1Ani addFrameWithFilename:@"LeafBrown0007.png"];
[leaf1Ani addFrameWithFilename:@"LeafBrown0008.png"];
[leaf1Ani addFrameWithFilename:@"LeafBrown0009.png"];
[leaf1Ani addFrameWithFilename:@"LeafBrown0010.png"];
[leaf1Ani addFrameWithFilename:@"LeafBrown0011.png"];
[leaf1Ani addFrameWithFilename:@"LeafBrown0012.png"];
[leaf1Ani addFrameWithFilename:@"LeafBrown0013.png"];
[leaf1Ani addFrameWithFilename:@"LeafBrown0014.png"];
[leaf1Ani addFrameWithFilename:@"LeafBrown0015.png"];
[leaf1Ani addFrameWithFilename:@"LeafBrown0016.png"];
[leaf1Ani addFrameWithFilename:@"LeafBrown0017.png"];
[leaf1Ani addFrameWithFilename:@"LeafBrown0018.png"];
[leaf1Ani addFrameWithFilename:@"LeafBrown0019.png"];

id leaf1AniANIMATION = [CCAnimate actionWithDuration:1.9f animation:leaf1Ani restoreOriginalFrame:YES];

id repeatLeaf1Animation = [CCRepeatForever actionWithAction:leaf1AniANIMATION];

[leaf1Sprite runAction:repeatLeaf1Animation];

[leaf1Sprite runAction:[CCMoveTo actionWithDuration:5.0f position:ccp(screenSize.width * 0.5f + 10.0f, -100.0f)]];

A: Postion randomly  on screen:
float screenWidth = screenSize.width * 0.5f;
randomX = arc4random() % (int)screenWidth;

A: Take a look at the Particle System samples. In particular there's one called "Rain" that's similar to what you're asking for. I've not done animation within a particle system; hopefully that's possible.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Generating .exe file from Python code that uses Tix Recently I found a program's code that I used a lot (Pikasav) on Github and since I had recently learned Python syntax, decided to fork it to practice Python and implement some features that would make it easier/better to use.
After implementing a feature, I tried to generate an .exe file using py2exe and it didn't work because it couldn't find the Tix module. I tried copying Tix.py into my working directory, it also didn't work.
After that, I decided to try PyInstaller out, since I thought I was doing something wrong passing arguments to py2exe in the setup.py file, and it seemed much easier to use. However, it also didn't work, because of the same reason, which clearly means the problem is not from py2exe configuration.
Here's the PyInstaller output, although I don't think it will be that useful:
C:\Users\Afonso\Documents\Side Projects\PikaSav>PyInstaller --onefile pikasav.py
1421 INFO: PyInstaller: 3.1.1
1421 INFO: Python: 2.7.11
1421 INFO: Platform: Windows-10-10.0.10240
1421 INFO: wrote C:\Users\Afonso\Documents\Side Projects\PikaSav\pikasav.spec
1421 INFO: UPX is not available.
1437 INFO: Extending PYTHONPATH with paths
['C:\\Users\\Afonso\\Documents\\Side Projects\\PikaSav',
 'C:\\Users\\Afonso\\Documents\\Side Projects\\PikaSav']
1437 INFO: checking Analysis
1437 INFO: Building Analysis because out00-Analysis.toc is non existent
1437 INFO: Initializing module dependency graph...
1452 INFO: Initializing module graph hooks...
1530 INFO: running Analysis out00-Analysis.toc
1657 INFO: Adding Microsoft.VC90.CRT to dependent assemblies of final executable
  required by C:\Python27\python.exe
1780 INFO: Found C:\WINDOWS\WinSxS\Manifests\x86_policy.9.0.microsoft.vc90.crt_1fc8b3b9a1e18e3b_9.0.21022.8_none_60a5df56e60dc5df.manifest
1796 INFO: Found C:\WINDOWS\WinSxS\Manifests\x86_policy.9.0.microsoft.vc90.crt_1fc8b3b9a1e18e3b_9.0.30729.1_none_8550c6b5d18a9128.manifest
1796 INFO: Found C:\WINDOWS\WinSxS\Manifests\x86_policy.9.0.microsoft.vc90.crt_1fc8b3b9a1e18e3b_9.0.30729.9158_none_f47f259ef656232a.manifest
1873 INFO: Searching for assembly x86_Microsoft.VC90.CRT_1fc8b3b9a1e18e3b_9.0.30729.9158_none ...
1873 INFO: Found manifest C:\WINDOWS\WinSxS\Manifests\x86_microsoft.vc90.crt_1fc8b3b9a1e18e3b_9.0.30729.9158_none_5091b51ebcb97cdc.manifest
1889 INFO: Searching for file msvcr90.dll
1889 INFO: Found file C:\WINDOWS\WinSxS\x86_microsoft.vc90.crt_1fc8b3b9a1e18e3b_9.0.30729.9158_none_5091b51ebcb97cdc\msvcr90.dll
1889 INFO: Searching for file msvcp90.dll
1889 INFO: Found file C:\WINDOWS\WinSxS\x86_microsoft.vc90.crt_1fc8b3b9a1e18e3b_9.0.30729.9158_none_5091b51ebcb97cdc\msvcp90.dll
1889 INFO: Searching for file msvcm90.dll
1889 INFO: Found file C:\WINDOWS\WinSxS\x86_microsoft.vc90.crt_1fc8b3b9a1e18e3b_9.0.30729.9158_none_5091b51ebcb97cdc\msvcm90.dll
1967 INFO: Found C:\WINDOWS\WinSxS\Manifests\x86_policy.9.0.microsoft.vc90.crt_1fc8b3b9a1e18e3b_9.0.21022.8_none_60a5df56e60dc5df.manifest
1967 INFO: Found C:\WINDOWS\WinSxS\Manifests\x86_policy.9.0.microsoft.vc90.crt_1fc8b3b9a1e18e3b_9.0.30729.1_none_8550c6b5d18a9128.manifest
1967 INFO: Found C:\WINDOWS\WinSxS\Manifests\x86_policy.9.0.microsoft.vc90.crt_1fc8b3b9a1e18e3b_9.0.30729.9158_none_f47f259ef656232a.manifest
1967 INFO: Adding redirect Microsoft.VC90.CRT version (9, 0, 21022, 8) -> (9, 0, 30729, 9158)
2514 INFO: Analyzing C:\Users\Afonso\Documents\Side Projects\PikaSav\pikasav.py
4889 INFO: Looking for import hooks ...
4905 INFO: Processing hook   hook-_tkinter.py
5077 INFO: checking Tree
5077 INFO: Building Tree because out00-Tree.toc is non existent
5092 INFO: Building Tree out00-Tree.toc
5338 INFO: checking Tree
5338 INFO: Building Tree because out01-Tree.toc is non existent
5339 INFO: Building Tree out01-Tree.toc
5389 INFO: Processing hook   hook-encodings.py
7202 INFO: Looking for ctypes DLLs
7202 INFO: Analyzing run-time hooks ...
7202 INFO: Including run-time hook 'pyi_rth__tkinter.py'
7217 INFO: Looking for dynamic libraries
7530 INFO: Looking for eggs
7530 INFO: Using Python library C:\WINDOWS\system32\python27.dll
7530 INFO: Found binding redirects:
[BindingRedirect(name=u'Microsoft.VC90.CRT', language=None, arch=u'x86', oldVersion=(9, 0, 21022, 8), newVersion=(9, 0, 30729, 9158), publicKeyToken=u'1fc8b3b9a1e18e3b')]
7546 INFO: Warnings written to C:\Users\Afonso\Documents\Side Projects\PikaSav\build\pikasav\warnpikasav.txt
7827 INFO: checking PYZ
7827 INFO: Building PYZ because out00-PYZ.toc is non existent
7827 INFO: Building PYZ (ZlibArchive) C:\Users\Afonso\Documents\Side Projects\PikaSav\build\pikasav\out00-PYZ.pyz
8062 INFO: checking PKG
8062 INFO: Building PKG because out00-PKG.toc is non existent
8062 INFO: Building PKG (CArchive) out00-PKG.pkg
8280 INFO: Redirecting Microsoft.VC90.CRT version (9, 0, 21022, 8) -> (9, 0, 30729, 9158)
16608 INFO: Bootloader C:\Python27\lib\site-packages\pyinstaller-3.1.1-py2.7.egg\PyInstaller\bootloader\Windows-32bit\run.exe
16608 INFO: checking EXE
16608 INFO: Building EXE because out00-EXE.toc is non existent
16608 INFO: Building EXE from out00-EXE.toc
16702 INFO: Appending archive to EXE C:\Users\Afonso\Documents\Side Projects\PikaSav\dist\pikasav.exe

And here's the warnpikasav.txt content, which is mentioned in the output above.
missing module named unicodedata.ucd_3_2_0 - imported by unicodedata, stringprep, encodings.idna
missing module named _sre.MAXREPEAT - imported by _sre, sre_constants
missing module named _warnings.warn_explicit - imported by _warnings, warnings
missing module named _warnings.filters - imported by _warnings, warnings
missing module named _warnings.once_registry - imported by _warnings, warnings
missing module named _warnings.default_action - imported by _warnings, warnings
missing module named _warnings.warn - imported by _warnings, warnings
missing module named strop.whitespace - imported by strop, string
missing module named strop.maketrans - imported by strop, string
missing module named strop.lowercase - imported by strop, string
missing module named strop.uppercase - imported by strop, string
missing module named itertools.islice - imported by itertools, repr, heapq
missing module named itertools.starmap - imported by itertools, collections
missing module named itertools.repeat - imported by itertools, collections
missing module named itertools.imap - imported by itertools, heapq, collections
missing module named itertools.tee - imported by itertools, heapq
missing module named itertools.izip - imported by itertools, heapq
missing module named itertools.count - imported by itertools, heapq, threading
missing module named itertools.chain - imported by itertools, tokenize, heapq, collections
missing module named org.PyStringMap - imported by org, copy
missing module named org - imported by copy
missing module named exceptions.ReferenceError - imported by exceptions, weakref
missing module named _weakref.ref - imported by _weakref, _weakrefset, weakref
missing module named _weakref.ReferenceType - imported by _weakref, weakref
missing module named _weakref.proxy - imported by _weakref, weakref
missing module named _weakref.getweakrefs - imported by _weakref, weakref
missing module named _weakref.getweakrefcount - imported by _weakref, weakref
missing module named _weakref.ProxyType - imported by _weakref, weakref
missing module named _weakref.CallableProxyType - imported by _weakref, weakref
missing module named copy.deepcopy - imported by copy, weakref
missing module named re._compile - imported by re, sre
missing module named re.__all__ - imported by re, sre
missing module named codecs.mbcs_encode - imported by codecs, encodings.mbcs
missing module named codecs.mbcs_decode - imported by codecs, encodings.mbcs
missing module named binascii.b2a_qp - imported by binascii, quopri
missing module named binascii.a2b_qp - imported by binascii, quopri
missing module named binascii.a2b_uu - imported by binascii, encodings.uu_codec
missing module named binascii.b2a_uu - imported by binascii, encodings.uu_codec
missing module named binascii.hexlify - imported by binascii, random
missing module named errno.EINVAL - imported by errno, StringIO
missing module named errno.ENOENT - imported by errno, gettext
missing module named cStringIO.StringIO - imported by cStringIO, gettext, pprint, shlex, tempfile, pickle, encodings.uu_codec, quopri, encodings.quopri_codec
missing module named struct.calcsize - imported by struct, ctypes
missing module named _struct.__doc__ - imported by _struct, struct
missing module named _struct._clearcache - imported by _struct, struct
missing module named _subprocess.STD_OUTPUT_HANDLE - imported by _subprocess, subprocess
missing module named _subprocess.CREATE_NEW_PROCESS_GROUP - imported by _subprocess, subprocess
missing module named _subprocess.STD_INPUT_HANDLE - imported by _subprocess, subprocess
missing module named _subprocess.STARTF_USESHOWWINDOW - imported by _subprocess, subprocess
missing module named _subprocess.CREATE_NEW_CONSOLE - imported by _subprocess, subprocess
missing module named _subprocess.STD_ERROR_HANDLE - imported by _subprocess, subprocess
missing module named _subprocess.STARTF_USESTDHANDLES - imported by _subprocess, subprocess
missing module named _subprocess.SW_HIDE - imported by _subprocess, subprocess
missing module named collections.namedtuple - imported by collections, inspect, unittest.util, difflib, doctest
missing module named cPickle.loads - imported by cPickle, collections
missing module named cPickle.dumps - imported by cPickle, collections
missing module named thread.get_ident - imported by thread, collections
missing module named thread._local - imported by thread, threading
missing module named thread.stack_size - imported by thread, threading
missing module named thread.allocate_lock - imported by thread, _strptime
missing module named collections.deque - imported by collections, shlex, threading
missing module named collections.OrderedDict - imported by collections, unittest.util
missing module named operator.itemgetter - imported by operator, collections, heapq
missing module named operator.eq - imported by operator, collections
missing module named operator.attrgetter - imported by operator, inspect
missing module named _collections.deque - imported by _collections, collections
missing module named _collections.defaultdict - imported by _collections, collections
missing module named time.time - imported by time, threading
missing module named time.sleep - imported by time, threading
missing module named datetime.date - imported by datetime, _strptime
missing module named _functools.partial - imported by _functools, functools
missing module named _functools.reduce - imported by _functools, functools
missing module named _hashlib.pbkdf2_hmac - imported by _hashlib, hashlib
missing module named math.sin - imported by math, random
missing module named math.sqrt - imported by math, random
missing module named math.cos - imported by math, random
missing module named math.acos - imported by math, random
missing module named math.ceil - imported by math, random
missing module named math.exp - imported by math, random
missing module named math.log - imported by math, random
missing module named math.e - imported by math, random
missing module named math.pi - imported by math, random
missing module named _io.DEFAULT_BUFFER_SIZE - imported by _io, io
missing module named _io.BytesIO - imported by _io, io
missing module named _io.open - imported by _io, io
missing module named _io.BufferedWriter - imported by _io, io
missing module named _io.FileIO - imported by _io, io
missing module named _io.BlockingIOError - imported by _io, io
missing module named _io.IncrementalNewlineDecoder - imported by _io, io
missing module named _io.BufferedReader - imported by _io, io
missing module named _io.BufferedRandom - imported by _io, io
missing module named _io.StringIO - imported by _io, io
missing module named _io.BufferedRWPair - imported by _io, io
missing module named _io.TextIOWrapper - imported by _io, io
missing module named _io.UnsupportedOperation - imported by _io, io
missing module named readline - imported by cmd, pdb
missing module named 'org.python'.PyStringMap - imported by 'org.python', pickle
missing module named 'org.python' - imported by pickle
missing module named fcntl - imported by tempfile, subprocess
missing module named threading.RLock - imported by threading, _threading_local
missing module named threading.current_thread - imported by threading, _threading_local
missing module named os.urandom - imported by os, random
missing module named riscosenviron._Environ - imported by riscosenviron, os
missing module named riscosenviron - imported by os
missing module named riscospath - imported by os
missing module named riscos._exit - imported by riscos, os
missing module named riscos - imported by os
missing module named ce._exit - imported by ce, os
missing module named ce - imported by os
missing module named _emx_link.link - imported by _emx_link, os
missing module named _emx_link - imported by os
missing module named os2._exit - imported by os2, os
missing module named os2 - imported by os
missing module named nt._isdir - imported by nt, ntpath
missing module named nt._getfullpathname - imported by nt, ntpath
missing module named nt._exit - imported by nt, os
missing module named pwd - imported by posixpath
missing module named posix._exit - imported by posix, os
missing module named posix - imported by os
missing module named resource - imported by posix
missing module named _ctypes._wstring_at_addr - imported by _ctypes, ctypes
missing module named _ctypes._string_at_addr - imported by _ctypes, ctypes
missing module named _ctypes._cast_addr - imported by _ctypes, ctypes
missing module named _ctypes._memset_addr - imported by _ctypes, ctypes
missing module named _ctypes._memmove_addr - imported by _ctypes, ctypes
missing module named _ctypes.get_last_error - imported by _ctypes, ctypes
missing module named _ctypes.set_last_error - imported by _ctypes, ctypes
missing module named _ctypes._check_HRESULT - imported by _ctypes, ctypes
missing module named _ctypes.set_conversion_mode - imported by _ctypes, ctypes
missing module named _ctypes._pointer_type_cache - imported by _ctypes, ctypes
missing module named _ctypes.POINTER - imported by _ctypes, ctypes
missing module named _ctypes._SimpleCData - imported by _ctypes, ctypes
missing module named _ctypes.get_errno - imported by _ctypes, ctypes
missing module named _ctypes.set_errno - imported by _ctypes, ctypes
missing module named _ctypes.alignment - imported by _ctypes, ctypes
missing module named _ctypes.addressof - imported by _ctypes, ctypes
missing module named _ctypes.resize - imported by _ctypes, ctypes
missing module named _ctypes.byref - imported by _ctypes, ctypes
missing module named _ctypes.sizeof - imported by _ctypes, ctypes
missing module named _ctypes.dlopen - imported by _ctypes, ctypes
missing module named _ctypes.FUNCFLAG_STDCALL - imported by _ctypes, ctypes
missing module named _ctypes.LoadLibrary - imported by _ctypes, ctypes
missing module named _ctypes.FUNCFLAG_USE_ERRNO - imported by _ctypes, ctypes
missing module named _ctypes.FUNCFLAG_USE_LASTERROR - imported by _ctypes, ctypes
missing module named _ctypes.FUNCFLAG_PYTHONAPI - imported by _ctypes, ctypes
missing module named _ctypes.FUNCFLAG_CDECL - imported by _ctypes, ctypes
missing module named _ctypes.FormatError - imported by _ctypes, ctypes
missing module named _ctypes.ArgumentError - imported by _ctypes, ctypes
missing module named _ctypes.RTLD_LOCAL - imported by _ctypes, ctypes
missing module named _ctypes.RTLD_GLOBAL - imported by _ctypes, ctypes
missing module named _ctypes.__version__ - imported by _ctypes, ctypes
missing module named _ctypes.CFuncPtr - imported by _ctypes, ctypes
missing module named _ctypes._Pointer - imported by _ctypes, ctypes
missing module named _ctypes.Structure - imported by _ctypes, ctypes
missing module named _ctypes.Array - imported by _ctypes, ctypes
missing module named _ctypes.Union - imported by _ctypes, ctypes

None of them refers Tix in any way - at least that I have found. I am also aware from my search that Tix is somewhat old, but it is what the program uses and I didn't want to change it since the author originally made it that way. He also managed to generate an .exe file for the program so not only that means it is possible to do it, but also that I'm probably doing something wrong here.
Thanks in advance.

A: This is a general setup.py that I use with Py2EXE
from distutils.core import setup
import os
import shutil
import py2exe

data_files = []
setup(
    name='ApplicationName',
    console=['Application.py'], # 'windows' means it's a GUI, 'console' It's a console program, 'service' a Windows' service, 'com_server' is for a COM server
    # You can add more and py2exe will compile them separately.
    options={ # This is the list of options each module has, for example py2exe, but for example, PyQt or django could also contain specific options
        'py2exe': {
            'packages': [],
            'dist_dir': 'dist', # The output folder
            'compressed': True, # If you want the program to be compressed to be as small as possible
            'includes': ['tix', 'os', 'logging', 'yaml', 'sqlalchemy', 'pymysql'], # All the modules you need to be included, This is where you put the package that is failing to be founhd. so if you import something inside main.py which also imports something, it might break.
        }
    },

    data_files=data_files # Finally, pass any data files

)

A: Okay, I seem to have found the answer. After comparing the files in my python directory and the generated files, I found out that the problem is that py2exe, for some reason, is not copying the files from Tix.
After that, I decided to Google again and found this page again, and noticed that I had a different Tix version from the one in the example, and just changed the script to match my version, making it work perfectly.
Here is the script:
import glob
import os
import sys
from distutils.core import setup
import py2exe

def files(folder):
    for path in glob.glob(folder+'/*'):
        if os.path.isfile(path):
            yield path

data_files=[
            ('.', glob.glob(sys.prefix+'/DLLs/tix84*.dll')),
            ('tcl/tix8.4.3', files(sys.prefix+'/tcl/tix8.4.3/')),
            ('tcl/tix8.4.3/bitmaps', files(sys.prefix+'/tcl/tix8.4.3/bitmaps/')),
            ('tcl/tix8.4.3/pref', files(sys.prefix+'/tcl/tix8.4.3/pref/')),
           ]

setup(
      script_args=['py2exe'],
      windows=['pikasav.py'],
      data_files=data_files,
     )

If you ever happen to come across this question in the future and have a different Tix version, just remember to change it if needed. Now I need to figure out a way to make this have the minimum number of files possible, but that's a whole different story.


text:
Q: Restricting user to leave input field blank using javascript getElementsByClassName method Created a form. I just want to make form validation. Used javascript to do the job here. Inside jS code created a function named check. In that function if some user leaves the input field blank then the function returns false and in that way I think, can restrict user, but not happening. My question is addressing both getElement..() method and as well as form validation.

function check(){
  //fname is the value provided into the input field
    var fname = document.getElementsByClassName('fname').value;
    //checks the inpur field and it is blank then return false
    if (fname == '') {
    return false;
  }
  else {
  //if the input field is provided then will pass the validity
    return true;
  }
}

  <form class="" action="output.html.php" method="post" onsubmit="return check()">

    <input class="fname" type="text" name="name" value="" placeholder="Name">
    <button type="submit" name="button">Send</button>
  </form>

A: The problem is that getElementsByClassName returns an array, so you should use either document.getElementsByClassName('fname')[0].value or document.querySelector('.fname').value (querySelector returns only first found entity)

A: Here is my complete code after execution.

function check(){
  //fname is the value provided into the input field
    var fname = document.getElementsByClassName('fname')[0].value;
  //var fname = document.querySelector('.fname').value;

    //checks the input field and if it is blank then return false
    if (fname == '') {
    return false;
  }
  else {
  //if the input field is provided then will pass the validity
    return true;
  }
}

  <form class="" action="output.html.php" method="post" onsubmit="return check()">

    <input class="fname" type="text" name="name" value="" placeholder="Name">
    <button type="submit" name="button">Send</button>
  </form>


text:
Q: Explain question mark (?) used in ES6/JSX code I'm using a library called react-forms in my React app. To better understand how it works I've been reading the code, but a convention keeps popping up which confuses me. Here's the ES6/JSX code:
'use strict';

var React = require('react/addons');
var cx = React.addons.classSet;

var Checkbox = React.createClass({

  propTypes: {
/...code.../
  },

  render(): ?ReactElement {
    /...code.../
  },

  onChange(e: {target: {checked: boolean}}) {
    /...code.../
  }
});

module.exports = Checkbox;

Note render(): ?ReactElement {}. That's the part which is confusing me. Could someone offer guidance on where to learn more about this syntax? I've hit a lot of dead ends via Google.

A: If you go to the package.json of react-forms, and look at the browserify section:
  "browserify": {
    "transform": [
      [
        "reactify",
        {
          "es6": true,
          "target": "es5",
          "stripTypes": true
        }
      ]
    ]
  },

stripTypes is enabled.  It strips out things like ?ReactElement, which means it maybe returns a ReactElement (and otherwise null or undefined)
The {target: {checked: boolean}} means e has a target property, which has a checked property which is a boolean.
These are hints for the Flow type checker.  You'll also see @flow in a comment at the top of all files that should be type checked.  A type checker is a tool – like unit tests – that makes you more confident of your program's correctness, in a way that doesn't require manual testing.  In many cases those little type annotations replace unit tests we'd otherwise write.
If you use flow in your project and try to do something like:
<Checkbox />

It would give you an type error because value and onChange are required props.  Unlike the runtime props check, this happens without actually running the code (often as soon as you save the file).


text:
Q: Include with projection does not work I have this query
    var test = context.Assignments
        .Include(a => a.Customer)
        .Include(a => a.Subscriptions)
        .Select(a => new AssignmentWithSubscriptionCount { SubscriptionCount = a.Subscriptions.Count(), Assignment = a })
        .ToList();

    var name = test.First().Assignment.Customer.Name;

It failes to eagerly load Customer, I've seen similar problems here on stackoverflow and it looks like you cant use projections with include. But I have not found a solution to my problem.. Anyone?
edit: Here is a eager load with projection that work, its more complex than the example above so I cant for my life understand whats wrong, thanks.
    var test = context.PublicationStateGroups
        .Include(p => p.PublicationStates.Select(ps => ps.AllowedPublicationStateActions.Select(aps => aps.PublicationStateAction)))
        .Select(psg => new StateAndGroupInfo
        {
            ShowReport = psg.PublicationStates.Any(p => p.PublicationStateReportTypeId.HasValue),
            Actions = psg.PublicationStates.SelectMany(state => state.AllowedPublicationStateActions)
                .Select(a => a.PublicationStateAction)
                .Distinct()
        }).ToList();

    var eagerTest = test.First().Actions.First().Name;

A: This is by design. Include is not for scenarios with projection or custom joins.

A: Add the customer to your projection:
var test = context.Assignments
    .Select(a => new AssignmentWithSubscriptionCount
    {
        SubscriptionCount = a.Subscriptions.Count(),
        Assignment = a,
        Customer = a.Customer
    });

var name = test.First().Customer.Name;

The EF context will probably ensure that Assignment.Customer gets populated automatically.
Edit
If you don't want or can't change the AssignmentWithSubscriptionCount class you can also project into an anonymous type and then copy the result in memory into this class:
var test = context.Assignments
    .Select(a => new
    {
        SubscriptionCount = a.Subscriptions.Count(),
        Assignment = a,
        Customer = a.Customer
    });

test.ToList() // executes query
    .Select(o =>
    {
        o.Assignment.Customer = o.Customer;
        return new AssignmentWithSubscriptionCount
        {
            SubscriptionCount = o.SubscriptionCount,
            Assignment = o.Assignment
        }
    });

Another option is explicite loading (requires one additional roundtrip per loaded Assignment though).


text:
Q: Boolean expression with integer increments gives unexpected results     #include <stdio.h>
    int main()
    {
       int x, y, z;
       x=y=z=1;
       z = ++x || ++y && ++z;
       printf("%d, %d, %d", x, y,z);
       return 0;
    }

I am getting output 2, 1, 1. I need and explanation why Y is 1 in output?

A: The || operator is short-circuiting; the right operand is not evaluated (and side effects never executed, i.e. the variables never incremented) if the left operand evaluates to != 0.
(Remember that "multiplication comes before addition", or in boolean logic AND comes before OR. Because of the operator precedences the expression becomes, fully bracketed, (++x) || ((++y) && (++z)); in other words, everything to the right of || is the OR's ignored right hand side.)
The evaluation of the left operand ++x increments x to 2. z is assigned the boolean value of the result of || which is 1, as it was all along.

As an aside, gcc warned and I think it is true that the statement is also undefined behavior. The C 11 standard draft n1570 says in 6.5/2:

If a side effect on a scalar object is unsequenced relative to [...]
  a value computation using the value of the same scalar
  object, the behavior is undefined.

The standard gives the example of i = ++i + 1; for this. In your right hand side expression z plays that role. The side effect is the increment, the value computation is the && sub-expression.

1 It is possible (i.e. I'm not sure) that it is defined as long as the right hand side is never evaluated. In that case the compiler would be allowed to assume that ++x  is never 0 and omit the test. The generated code for the complicated boolean expression would just boil down to an increment of x.

A: The part || ++y && ++z is not evaluated, because ++x is already true. See
Short circuit evaluation

A: The logical operation || is so-called "short-circuit" or "lazy" operation.
If the left operand of such an operator is evaluating to logical true or a non-zero, the right operand won't be evaluated.
So in your case:
z = ++x || ++y && ++z;

++x is evaluating to 2, making x equal 2. This is non-zero, so everything on the right side is not evaluated, so y and z are not incremented. And z is assigned by the result of the logical OR operation, i.e. 1. And this is what you see.


text:
Q: Is it possible to set fixed y-axis to spline chart update every second I am working on real time data stream with spline chart https://www.highcharts.com/demo/dynamic-update/dark-green. Here i want to set fixed y-axis scale (I know my data range from 0 to 4 max) but here chart update dynamically.

Is it possible to set fixed y-axis so that chart update as per fixed y-axis scale.

A: For any axis you can set a minimum and a maximum value with axis.min (doc)  and axis.max (doc). If you want to be very precise (or your ticks are causing problems) you might have to disable startOnTick and endOnTick to set your specific values, as described in the documentation of min and max.
For example (JSFiddle demonstration):
yAxis: {
    min: 0.25,
    max: 0.75,
    startOnTick: false, // optional
    endOnTick: false, // optional
    // ...
}


text:
Q: Why *nix command line enable execution via path relative to current directory? For a long time I was under impression that *NIX shells do not support running executables via path relative to current directory. Also there're a number of posts explaining why having working directory in path is a bad practice. Still it's easy to see that following example works:
% cat<<EOF > temp/a
? #!/bin/sh
? echo "Hello looser!"
? EOF
% chmod 750 temp/a
% temp/a
Hello looser!

(I tested at CentOS and OSX).
Why it works?
Upd: it's not purely academic question, I had cases when binaries run via full path and the way described above worked different way.
Upd 2: libc execv accepts both absolute and relative paths with no problem. Hence, support for subpath/exe while failing to run exe looks as shell feature common to bash and tcsh. There must be some logic behind it??

A: You can always execute a program by specifying its relative path. There is no requirement that you would have to use an absolute path. Actually, the way you are executing your program, is quite common.

A: If you write command with no / then the shell searches $PATH for the command.
If you write dir/command with a relative directory, there's a / and the shell does not search $PATH. It interprets it relative to the current directory. dir/command always resolves to ./dir/command.
Putting . in the $PATH is dangerous because you may type command intend ing to run /usr/bin/command but actually get ./command if it exists in the current directory. Indeed, it's not just . that's dangerous: any relative path is dangerous. $PATH should only ever contain absolute paths.

So, you're saying that relative paths shall be implicitly prefixed with current directory, with exceptional case when relative path is empty that shall be treated as direction to search in $PATH?

Yes, you could say that. But I prefer to reframe it. A better way to think of it is to understand what the shell is doing versus what the kernel is doing.
Interpreting relative paths is handled implicitly by the kernel. When the shell performs a system call like execve("dir/command", ...) to execute a program the kernel knows the parent process's current directory and resolves dir/command relative to it. The shell does not have to first convert the path into an absolute one. The kernel can handle both absolute and relative paths.
The kernel knows nothing about $PATH, though. That's a shell construct. Keep in mind that the shell is a higher level piece of software. The shell decides that if you type a simple command name without a / in it, it will not simply pass that command to the kernel. If it did, typing cat would simply execute ./cat. Nobody wants that.
Instead, the shell decides that the lack of a / means it will search for the command in the $PATH. It'll search /bin, /usr/bin, $HOME/bin, etc. If you listed . in the $PATH then it would also search the current directory—don't do that! You don't want it to run ./cat. No sir.
If the shell finds an executable in the $PATH then it converts it to an absolute path name and passes that to the kernel. The kernel sees execve("/usr/bin/cat", ...).

If so and you know it from some formal specification, I'd appreciate the reference. I do need to know precisely.

See the bash man page:

If the command name contains no slashes, the shell attempts to locate it. …
If the name … contains no slashes, bash searches each element of the PATH for a directory containing an executable file by that name. …
If the search is successful, or if the command name contains one or more slashes, the shell executes the named program ….

A: This as nothing to do with execution. It is due to the fact that you can name a file with an absolute or a relative name, and that executables are just ordinary files.

Why is it dangerous? (.in PATH)

Think about a script that calls a command like cat foo, if you have . in the path then it could be possible to create a command cat in the same directory that would be executed in place of the original one.


text:
Q: Using Euler Phi function to show that there are infinitely many primes I know Euclid's clever way of proving that there are infinitely many primes but while I was studying, I also saw a sentence on the book: "Euler-phi function can also be used to show that there are infinitely many primes." but could not figure out how. Could you please help me to understand it?
Regards

A: Assume that there are only a finite number of primes say $p_1,p_2,\ldots,p_k$. Look at the product of these finite primes i.e. $$m = p_1 p_2 \cdots p_k$$
Now consider any number $n > 1$. Since there are only finite primes, one of the $p_j$'s must divide $n$. Hence, $\gcd(m,n) > 1$. Hence, $\phi(m) = 1$.
Can you now finish it off?


text:
Q: Multiple SQL Server Databases and Single/Multi Server Setup Can I get a list of disadvantages and advantages for this question, or the correct one to use.
If a company has around 6 websites, each with there on SQL Server Database, should those Database's be on their own Server and SQL Server instance, or can they all exist on one Server under one SQL Server instance under different databases?

A: I can't see any reason (at least not without more info) as to why they couldn't be under the same SQL instance.  We use a consolidated SQL instance model (meaning multiple apps to 1 SQL server) and it works fine.
The disadvantages that I see are:

*

*A little more difficult to troubleshoot performance issues

*All your eggs in one basket (unless you cluster / mirror / log ship)

*One site sites DB usage "could" affect the others from a CPU / memory perspective.

The advantages that I see are:

*

*Easier to admin (backup for example only needs to be configured once)

*Less SQL servers to manage (sort of realted to 1)

As far as I can tell, the 1 app to 1 SQL server model is sort of going by way side.  I'm bias and personally a big fan of multiple apps to one SQL server.  Just don't skimp on the resources for that SQL server.  That's not to say that you need to over spec, understand what performance needs the sites need.  Also, as an FYI, all our SQL servers are virtual, incase anyone trys to throw that gotcha at you, we've had no problems.  All comes down to proper sizing.

A: It app depends on the load required by each database.  If the IO, memory and CPU load for each one is minimal then they can all sit on a single SQL Server instance.  As the requirements increase you'll need to move the instances to a different SQL Server.
The main reason to put the databases on different instances is because the instance have different, conflicting security requirements.  Another reason is because you want to control the size of the buffer pool and procedure cache for one database so you would put it on a different instance.  Otherwise putting everything in a single instance is just fine.

A: We run one database instance for "app" data (e.g., Drupal, WP, Mediawiki) and a separate instance for business data.  That way there are no potential contention/escalation issues between the two.  If you're truly paranoid about interference between applications, I don't think MySQL will give you the level of separation you need resource-wise.


text:
Q: Need to provide a SettingKey from a plugin I use in my sbt plugin I am using the s3 resolver plugin and would like to override it in my AutoPlugin.
I have tried added the value to projectSettings and globalSettings.
Error
not found: value s3CredentialsProvider
[error]     s3CredentialsProvider := s3CredentialsProviderChain

Code
lazy val s3CredentialsProviderChain = {bucket: String =>
    new AWSCredentialsProviderChain(
      new EnvironmentVariableCredentialsProvider(),
      CustomProvider.create(bucket)
    )
  }

 override lazy val projectSettings = Seq(
publishTo := {
   if (Keys.isSnapshot.value) {
      Some("my-snapshots" at "s3://rest-of-stuff")
    } else {
      Some("my-releases" at "s3://rest-of-stuff")
    }
  },
  s3CredentialsProvider := s3CredentialsProviderChain
)

The plugin code I'm working on does not define any custom settings of it's own thus has no autoImport of it's own.
Update
I have been unable to resolve the fm.sbt.S3ResolverPlugin in MyPlugin and the code won't compile.
I have tried adding it to enablePlugins on MyPlugin's build.sbt as well as adding it to the dependencies like this:
libraryDependencies ++= Seq(
  "com.amazonaws" % "aws-java-sdk-sts" % amazonSDKVersion,
  "com.frugalmechanic" % "fm-sbt-s3-resolver" % "0.17.0"
)

I get an error from sbt which I've asked below:
sbt fails to resolve a plugin as dependency

A: If you create an AutoPlugin in project directory. You need to add this to plugins.sbt.
addSbtPlugin("com.frugalmechanic" % "fm-sbt-s3-resolver" % "0.16.0")

If you create an independent plugin, add this to build.sbt of the plugin
sbtPlugin := true
addSbtPlugin("com.frugalmechanic" % "fm-sbt-s3-resolver" % "0.16.0")

autoImport does not work in scala files that are compiled for sbt, ie plugins for example. You have specify imports statements as in simple scala program. Something like this
import fm.sbt.S3ResolverPlugin
import sbt._

object TestPlugin extends AutoPlugin {

  override def requires = S3ResolverPlugin

  override def trigger = allRequirements

  override def projectSettings: Seq[Def.Setting[_]] = Seq(
    S3ResolverPlugin.autoImport.s3CredentialsProvider := ???
  )
}

Note that to enable TestPlugin, you have to call enablePlugins(S3ResolverPlugin) in build.sbt


text:
Q: Uncaught SyntaxError: Unexpected identifier in StringBuilder I am trying to embed HTML code into StringBuilder in Razor View Page but while running i am getting Uncaught SyntaxError: Unexpected identifier error.Here is my Code..
 @{
    System.Text.StringBuilder sb = new System.Text.StringBuilder();
    foreach(var row in Model)
    {
     sb.AppendFormat("['{0}', '{1}', '{2}', '{3}','{4}','{5}'],",
     "<input type='checkbox' name='select' id='' value=''>", "", row.CompanyCode, row.CompanyName, row.PrimaryContactName, row.PrimaryContactEmail);
  }
  }

and this is my Values from the Console of the developer tool of Chrome..
var dataSet = [['<input type='checkbox' name='select' id='' value=''>', '', '73878', 'Systems','hgfjhf','systems.com'],['<input type='checkbox' name='select' id='' value=''>', '', '99878', 'Microsoft Systems','Archit','ems.com'],];

Please help me to resolve this.Thanks

A: Generate string using escape double quotes \" or "", so that it doesn't breaks the string when using combination of single and double quotes
sb.AppendFormat("[\"{0}\", '{1}', '{2}', '{3}','{4}','{5}'],",
 "<input type='checkbox' name='select' id='' value=''>", "", row.CompanyCode, row.CompanyName, row.PrimaryContactName, row.PrimaryContactEmail);


text:
Q: Volume adjust and channel merge on video using FFMPEG I'm trying to convert a recorded AVI (1 video stream, 2 audio streams[1st is stereo, 2nd is mono]) video file to H264/AAC.
I want the second audio stream to be at 60% volume and the first at 100%.
I also want to merge the first and second audio stream.
Output should be H264 with AAC audio.
The command I tried to use is:
"ffmpeg.exe"
  -i "input.avi"
  -filter_complex "
    [0:a:0]aformat=channel_layouts=stereo,volume=1.0[a1];
    [0:a:1]aformat=channel_layouts=mono,volume=0.6[a2];
    [a1][a2]amerge,pan=stereo|c0<c0+c2|c1<c1+c2[out]
  "
  -map 0:v
  -map "[out]"
  -c:v libx264 -preset slow -crf 26
  -c:a aac -strict experimental -ab 128000 -ac 2 -ar 48000
  "output.mp4"

But I get the error:
[AVFilterGraph @ 0000000ceb630c00] The following filters could not choose their formats: Parsed_amerge_4
Consider inserting the (a)format filter near their input or output.
Error configuring complex filters.
Error number -5 occurred
What am I doing wrong and how can it be fixed?
Complete Console Log:
ffmpeg version N-76456-g6df2c94 Copyright (c) 2000-2015 the FFmpeg developers
  built with gcc 5.2.0 (GCC)
  configuration: --enable-gpl --enable-version3 --disable-w32threads --enable-avisynth --enable-bzlib --enable-fontconfig --enable-frei0r --enable-gnutls --enable-iconv --enable-libass --enable-libbluray --enable-libbs2b --enable-libcaca --enable-libdcadec --enable-libfreetype --enable-libgme --enable-libgsm --enable-libilbc --enable-libmodplug --enable-libmp3lame --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-libopus --enable-librtmp --enable-libschroedinger --enable-libsoxr --enable-libspeex --enable-libtheora --enable-libtwolame --enable-libvidstab --enable-libvo-aacenc --enable-libvo-amrwbenc --enable-libvorbis --enable-libvpx --enable-libwavpack --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxavs --enable-libxvid --enable-lzma --enable-decklink --enable-zlib
  libavutil      55.  5.100 / 55.  5.100
  libavcodec     57. 14.100 / 57. 14.100
  libavformat    57. 14.100 / 57. 14.100
  libavdevice    57.  0.100 / 57.  0.100
  libavfilter     6. 14.101 /  6. 14.101
  libswscale      4.  0.100 /  4.  0.100
  libswresample   2.  0.100 /  2.  0.100
  libpostproc    54.  0.100 / 54.  0.100
[avi @ 000000b1cfa6bc20] non-interleaved AVI
Guessed Channel Layout for  Input Stream #0.1 : stereo
Guessed Channel Layout for  Input Stream #0.2 : mono
Input #0, avi, from 'input.avi':
  Metadata:
    encoder         : DxtoryCore ver2.0.0.122
    ISRC            : Video:Lagarith Lossless Codec Audio0:Lautsprecher (2- USB Audio CODEC ) Audio1:Mikrofon (2- USB Audio CODEC )
  Duration: 00:27:55.60, start: 0.000000, bitrate: 181780 kb/s
    Stream #0:0: Video: lagarith (LAGS / 0x5347414C), rgb24, 1920x1017, 179663 kb/s, 30 fps, 30 tbr, 30 tbn, 30 tbc
    Stream #0:1: Audio: pcm_s16le ([1][0][0][0] / 0x0001), 44100 Hz, 2 channels, s16, 1411 kb/s
    Stream #0:2: Audio: pcm_s16le ([1][0][0][0] / 0x0001), 44100 Hz, 1 channels, s16, 705 kb/s
[Parsed_amerge_4 @ 000000b1cfaf3200] No channel layout for input 1
Last message repeated 1 times
[AVFilterGraph @ 000000b1cfa70c00] The following filters could not choose their formats: Parsed_amerge_4
Consider inserting the (a)format filter near their input or output.
Error configuring complex filters.
Error number -5 occurred

A: It seems this can be fixed by splitting all audio streams into separate channels first and then feeding it back into the amerge filter.
"ffmpeg.exe"
  -i "input.avi"
  -filter_complex "
    [0:a:0]volume=1.0,channelsplit=channel_layout=stereo[a1][a2];
    [0:a:1]volume=0.6,channelsplit=channel_layout=mono[a3];
    [a1][a2][a3]amerge=inputs=3,pan=stereo|c0<c0+c2|c1<c1+c2[out]
  "
  -map 0:v
  -map "[out]"
  -c:v libx264 -preset slow -crf 26
  -c:a aac -strict experimental -ab 128000 -ac 2 -ar 48000
  "output.mp4"


text:
Q: Unable to load seed data from Rspec spec_helper.rb file I am trying to load some seed data before any tests are run. I am doing the following:
spec_helper.rb
# This file was generated by the `rails generate rspec:install` command. Conventionally, all
# specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`.
# The generated `.rspec` file contains `--require spec_helper` which will cause
# this file to always be loaded, without a need to explicitly require it in any
# files.
#
# Given that it is always loaded, you are encouraged to keep this file as
# light-weight as possible. Requiring heavyweight dependencies from this file
# will add to the boot time of your test suite on EVERY test run, even for an
# individual file that may not need all of that loaded. Instead, consider making
# a separate helper file that requires the additional dependencies and performs
# the additional setup, and require it from the spec files that actually need
# it.
#
# The `.rspec` file also contains a few flags that are not defaults but that
# users commonly want.
#
# See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
RSpec.configure do |config|

      config.before(:suite) do
        Rails.application.load_seed # loading seeds
      end

  # rspec-expectations config goes here. You can use an alternate
  # assertion/expectation library such as wrong or the stdlib/minitest
  # assertions if you prefer.
  config.expect_with :rspec do |expectations|
    # This option will default to `true` in RSpec 4. It makes the `description`
    # and `failure_message` of custom matchers include text for helper methods
    # defined using `chain`, e.g.:
    #     be_bigger_than(2).and_smaller_than(4).description
    #     # => "be bigger than 2 and smaller than 4"
    # ...rather than:
    #     # => "be bigger than 2"
    expectations.include_chain_clauses_in_custom_matcher_descriptions = true
  end

  # rspec-mocks config goes here. You can use an alternate test double
  # library (such as bogus or mocha) by changing the `mock_with` option here.
  config.mock_with :rspec do |mocks|
    # Prevents you from mocking or stubbing a method that does not exist on
    # a real object. This is generally recommended, and will default to
    # `true` in RSpec 4.
    mocks.verify_partial_doubles = true
  end

config.before(:each) { ActionMailer::Base.deliveries.clear }

# The settings below are suggested to provide a good initial experience
# with RSpec, but feel free to customize to your heart's content.
=begin
  # These two settings work together to allow you to limit a spec run
  # to individual examples or groups you care about by tagging them with
  # `:focus` metadata. When nothing is tagged with `:focus`, all examples
  # get run.
  config.filter_run :focus
  config.run_all_when_everything_filtered = true

  # Allows RSpec to persist some state between runs in order to support
  # the `--only-failures` and `--next-failure` CLI options. We recommend
  # you configure your source control system to ignore this file.
  config.example_status_persistence_file_path = "spec/examples.txt"

  # Limits the available syntax to the non-monkey patched syntax that is
  # recommended. For more details, see:
  #   - http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/
  #   - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/
  #   - http://rspec.info/blog/2014/05/notable-changes-in-rspec-3/#zero-monkey-patching-mode
  config.disable_monkey_patching!

  # Many RSpec users commonly either run the entire suite or an individual
  # file, and it's useful to allow more verbose output when running an
  # individual spec file.
  if config.files_to_run.one?
    # Use the documentation formatter for detailed output,
    # unless a formatter has already been configured
    # (e.g. via a command-line flag).
    config.default_formatter = 'doc'
  end

  # Print the 10 slowest examples and example groups at the
  # end of the spec run, to help surface which specs are running
  # particularly slow.
  config.profile_examples = 10

  # Run specs in random order to surface order dependencies. If you find an
  # order dependency and want to debug it, you can fix the order by providing
  # the seed, which is printed after each run.
  #     --seed 1234
  config.order = :random

  # Seed global randomization in this process using the `--seed` CLI option.
  # Setting this allows you to use `--seed` to deterministically reproduce
  # test failures related to randomization by passing the same `--seed` value
  # as the one that triggered the failure.
  Kernel.srand config.seed
=end
end

I am getting an error as follows:
spec/factories/employees.rb:25:in `block (2 levels) in <top (required)>': undefined method `id' for nil:NilClass (NoMethodError)

employees.rb Factory
require 'faker'

FactoryGirl.define do
  factory :employee do
    first_name { Faker::Name.first_name}
    last_name { Faker::Name.last_name}
    sequence(:email) { |n| "peterjohnson#{n}@example.com" }
    mobile 66816927867
    bio "MyText"
    address { Faker::Address.street_address}
    province_state { Faker::Address.state}
    country { Faker::Address.country}
    postal_code { Faker::Address.postcode}
    status :active
    bachelor_degree "B.Sc"
    password Faker::Internet.password(8)
    sequence(:paypal_email) { |n| "paypal_peterJohnson#{n}@example.com" }
    sequence(:skype_id) {|n| "peterjohnson_skype#{n}" }
    os :mac
    role_ids [Role.first.id]

    trait :proofreader do
        after(:create) {|employee| employee.add_role(:proofreader)}
    end

    trait :admin do
        after(:create) {|employee| employee.add_role(:admin)}
    end

    trait :super_admin do
        after(:create) {|employee| employee.add_role(:super_admin)}
    end
  end
end

seeds.rb
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
#   cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
#   Mayor.create(name: 'Emanuel', city: cities.first)

#Seeding the Role table
#
p "Removing existing #{Role.all.count} roles"
Role.destroy_all
p "Creating 3 roles"
[:proofreader, :admin, :super_admin].each do |role|
  Role.create( name: role )
end
p "Should have created 3 Roles, roles created: #{Role.all.count}"

#Seed the Employee table

#create super_admin employee
p "Removing existing #{Employee.all.count} employees"
Employee.destroy_all
p "Creating one employee"

super_admin = Employee.create(first_name: "Mitchell", last_name: "Gould", email: "mitchell@provenword.com", paypal_email: "go_mitchell@yayoo.ca", skype_id: "chellgouda", mobile: 66816927867, bachelor_degree: "Science", password: "chokta400",postal_code: "50100",address: "211/195 Soi 27, Sriwalee Klong Chun, T. Mae Hia, A. Muang", province_state: "Chiangmai", country: "Thailand", status: "active", os: "mac", role_ids: [Role.last.id])
super_admin.add_role(:proofreader)

p "Should have created #{Employee.all.count} employee with name #{Employee.first.first_name}."

Why is the Factory running before the seed data is loaded?

A: You probably use FactoryGirl in your db/seeds.rb.

A: Instead of your spec_helper file, add this to your rails helper file.
Rails.application.load_seed
I put it near the top after
require 'rspec/rails'
However, depending on your seed data and what gems you are using (i.e. database cleaner) you'll need to make modifications so that your seed data isn't erased until appropriate.


text:
Q: How to get the test result status from TestNG/Selenium in @AfterMethod? For a research I'm doing, I'm in need of capturing the result status (Passed/Failed) after running the test method (@Test), from @AfterMethod.
I have been using the import org.testng.ITestResult; as an out come of my research to get my work easier after going the several online blogs, but It seems like it didn't success my expectation as always the result outputs as passed, even though an assertion failed.
My Code is as follows :
public class SampleTestForTestProject {
ITestResult result;

@Test(priority = 1)
public void testcase(){

    // intentionally failing the assertion to make the test method fail
    boolean actual = true;
    boolean expected = false;
    Assert.assertEquals(actual, expected);

}

@AfterMethod
public void afterMethod()  {

    result = Reporter.getCurrentTestResult();

    switch (result.getStatus()) {
    case ITestResult.SUCCESS:
        System.out.println("======PASS=====");
        // my expected functionality here when passed
        break;

    case ITestResult.FAILURE:
        System.out.println("======FAIL=====");
        // my expected functionality here when passed
        break;

    case ITestResult.SKIP:
        System.out.println("======SKIP BLOCKED=====");
        // my expected functionality here when passed
        break;

    default:
        throw new RuntimeException("Invalid status");
    }
  }
}

Result in the Console :
[TestNG] Running:  C:\Users\USER\AppData\Local\Temp\testng-eclipse--988445809\testng-customsuite.xml

======PASS=====

FAILED: testcaseFail
java.lang.AssertionError: expected [false] but found [true]

My expectation is to get the test result to a variable to get through the switch, as given in the above code snippet, and get printed "======FAIL=====" when the test method fail.
Will someone be able assist me kindly to catch the execution test result for each test method (@Test). If the method I have approached is wrong, please assist me with a code snippet to the correct approach, kindly.
Thank you in advance

A: just do it:
public class stacktest  {

@Test
public void teststackquestion() {

    boolean actual = true;
    boolean expected = false;
   Assert.assertEquals(actual, expected);

}

@AfterMethod
public void afterMethod(ITestResult result)
{
    try
 {
    if(result.getStatus() == ITestResult.SUCCESS)
    {

        //Do something here
        System.out.println("passed **********");
    }

    else if(result.getStatus() == ITestResult.FAILURE)
    {
         //Do something here
        System.out.println("Failed ***********");

    }

     else if(result.getStatus() == ITestResult.SKIP ){

        System.out.println("Skiped***********");

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

}

}

A: The TestListenerAdapter has methods for each of those situations (success, skipped, failure). My suggestions is to make your own listener like this.
public class MyTestResultListener extends TestListenerAdapter {

    @Override
    public void onTestFailure(ITestResult result) {
        // do what you want to do
    }

    @Override
    public void onTestSuccess(ITestResult result) {
        // do what you want to do
    }

   @Override
    public void onTestSkipped(ITestResult result) {
        // do what you want to do
    }
}

Then add your listener to the test class.
@Listeners(MyTestResultListener.class)
public class MyTest {

// your tests

}


text:
Q: Android GPS and wifi Status In application I have implemented Android GPS application and cell-id application for location tracing separately, now I want to combine the functionality of both the applications, I want to trace the location via GPS if wifi not available or vice verca. Kindly guide me how can I get the status of GPS and wifi.

A: http://developer.android.com/guide/topics/location/obtaining-user-location.html


text:
Q: JDBC unclosed connections If we forget to close Java JDBC connection (say oracle) in the code , would like to know will the connection stays at DB end forever (oracle) or the Oracle has any implementation at its end to auto release DB connections after some time?
try{
       ds.getConnection();
       //do some business logic

   }catch(Exception e){
       //handle exceptions

   }  finally{
           //let's say DB connection is NOT cosed..
      }

What happens to the open connection in the code above? Does the connection gets auto released at database side once the java program exits?
I understand it is highly not recommended and bad practice to not close DB connections. I just want to know the implications and understand how oracle handles unclosed connections.

A: Once the VM is terminated, whether more or less normally (all non-daemon threads end, System.exit is invoked, or a kill signal is received, such as hitting CTRL+C in the terminal), or abnormally (you trip over a powercord, or a terminate signal causes the kernel to just hard-exit your VM), all TCP/IP connections go away automatically, and with that, the connection is cleaned up.
But, until the VM exits, you get no guarantees. The behaviour is intentionally unspecified (as in, you must close them yourself. If you do not, no guarantees are provided), and what actually happens depends on the state of your computer (as it depends on gc runs and when those go depends on everything from which song is playing in your music player to the phase of the moon), and the JDBC driver being used.
You can use lint tools and IDE plugins to recognize that you aren't closing your connections. Also, your snippet is over 10 years out of date. The recommended and much simpler way to ensure your connection does not die on you is to use:
try (Connection con = ds.getConnection()) {
    // use 'con' here
} // no need for a catch or finally.

Or, use connection poolers (like HikariCP), along with an abstraction to make JDBC less annoying, such as JDBI or JOOQ.


text:
Q: Regular expression to separate smileys from text I am trying to create a regular expression in Javascript to separate any occurrence of :) from the surrounding text.
Given the following:

:)This is a line of text :) with several smileys in it :). So there.,:):)

I would like to get the resulting 8 groups:

*

*:)

*This is a line of text

*:)

*with several smileys in it

*:)

*. So there.,

*:)

*:)

At the moment I use ([^:)]+) which only groups the surrounding text without the smileys. What adjustment could I make so that the smileys are also grouped?

A: split:
var string = "Given the following: :)This is a line of text :) with several smileys in it :). So there.,:):)";
var groups = string.split(/:\)/);

This will return an array in which each element is a part of text without :).
Since the text has been split on each :), we can construct the result you want by adding a :) between each parts of text:
var parts = [groups[0]];
for (var i = 1; i < groups.length; ++i) {
    parts.push(':)');
    parts.push(groups[i]);
}

The result is this:

*

*:)

*This is a line of text

*:)

*with several smileys in it

*:)

*. So there.,

*:)

*:)

Try this here: http://jsfiddle.net/Gxr6U/3/

If you want to replace smilies by images, you could do this:
var frags = document.createDocumentFragment();

frags.appendChild(document.createTextNode(groups[0]));

for (var i = 1; i < groups.length; ++i) {

    var img = document.createElement('img');
    img.src='http://../smiley.png';

    frags.push(img);

    frags.appendChild(document.createTextNode(groups[i]));
}

If you just want to remove smilies:
var text = groups.join('');

A: I'd suggest:
var str = ":)This is a line of text :) with several smileys in it :). So there.,:):)",
    matches = str.split(/(\:\))/);
console.log(matches);

JS Fiddle demo.
Added filtering to remove the empty matches from the above:
var str = ":)This is a line of text :) with several smileys in it :). So there.,:):)",
    matches = str.split(/(\:\))/),
    matched = [];
for (var i = 0, len = matches.length; i < len; i++) {
    if (matches[i].length) {
        matched.push(matches[i]);
    }
}
console.log(matched);

JS Fiddle demo.
A further version, with actual on-screen output:
var str = ":)This is a line of text :) with several smileys in it :). So there.,:):)",
    matches = str.split(/(\:\))/),
    matched = [], li,
    list = document.createElement('ol');
document.body.appendChild(list);
for (var i = 0, len = matches.length; i < len; i++) {
    if (matches[i].length) {
        matched.push(matches[i]);
        li = document.createElement('li');
        txt = document.createTextNode(matches[i]);
        li.appendChild(txt);
        list.appendChild(li);
    }
}
console.log(matched);

JS Fiddle demo.

A: The following will successfully group the string you mentioned as you want:
your_match = your_string.match(/(:\)|[^:)]*)/g)

However, like your original RegExp, you will encounter problems if a : or ) appears without being in a smiley.  These characters will disappear from the match groups if not within a smiley.

A: You can use this pattern:
/:\)|(?:[^:]+|:(?!\)))+/g

This matches either :) or any character except : or a : that is not followed a ).


text:
Q: While click google oauth URL - If add # after like localhost:4200/#/login, redirect uri not working properly Using Angular Tried Auth uris,
this is the google oauth url -->
public static GOOGLE_AUTH_URL = "http://localhost:8080/oauth2/authorize/google?redirect_uri=http://localhost:4200/#/login";
While click google icon to sigin via google
(the login text is missed so i can't get token and more)


text:
Q: Debugging JavaScript - Need a plugin solution suggestion I am trying to see what Javascript functions are triggered when I do a certain action on a website. However, I can't seem to find a suitable solution that will be able to do this for me, and I can't manually go through the whole JS code since it's a lot, and I am not all that good with JS.
Any help would be appreciated.

A: Use Chrome and press the  f12 key of your keyboard to display debugging interface. You can do step by step debugging from the 'Sources' tab.

A: Use Firebug (https://getfirebug.com/), a plugin for Firefox.

A: You might want to look into "Visual Event".  It's a Chrome Extension that lets you inspect events that are bound to elements on the page. It also exists as a bookmarklet for other browsers.
It won't help you with all events that are happening on the page, but it at least shows you the ones that are bound to elements.


text:
Q: Add Web Role Project in solution option freezed I am trying to migrate a small ASP.NET 'web site' (not web application) to Windows Azure. I have added the website to the solution by Add Existing Project> Selecting the *.sln file.
After this, when I right click on the Web Role in Windows Azure, the "Add Web Role Project in solution" is freezed and so, I am not able to create the web role?

Why is the option freezed? What's going wrong in here?

A: You have to convert your web site to a web application before you can upload it to Azure.
To do this, follow these instructions - http://msdn.microsoft.com/en-us/library/aa983476(VS.80).aspx


text:
Q: How to perform a clean json for a carriage return? I've a problem on a clean json string on a textarea.
I've a form with a textarea. A validation, it sends an email by taking the forms of information.
But I get an error when I pass a line in my textarea.
Ma fonction JS :
function submit() {
  var path = $(location).attr('href');
        try {
        var parameters = '{  "url" : "' + escape(path) +
                        '", "prénom" : "' + cleanJSONString($("#inputFirstname").val()) +
                        '", "nom" : "' + cleanJSONString($("#inputLastname").val()) +
                        '", "email" : "' + cleanJSONString($("#inputEmail").val()) +
                        '", "message" : "' + cleanJSONString($("#inputMessage").val()) +
                        '", "captchachallenge" : "' + capchallenge +
                        '", "captcharesponse" : "' + capresponse  + '" }';

        contentSubmit = $("#submitArea").html();
        $("#submitArea").empty().html('');

        jQuery.ajax({
            type: "POST",
            url: '_vti_bin/json/service.svc/submit',
            contentType: "application/json; charset=utf-8",
            dataType: 'json',
            data: parameters,
            success: function (msg) {
                submitSucceeded(msg);
                $("#submitArea").empty().html(contentSubmit);
                 resetRealPersonCaptcha();
            },
            error: submitFailed
        });
    }
    catch (e) {
        alert('Error invoking service' + e);
        clearUploadPart();
    }
    //Recaptcha.reload();
}

The function who clean values in json properties so as to send a valid json request :
function cleanJSONString(str) {
    if (typeof str == 'undefined' || str == null)
        return "";

    //clean values in json properties so as to send a valid json request
    return str.replace(/[/\\""]/g, "")
              .replace(/\\n/g, "")
              .replace(/\\&/g, "\\&")
              .replace(/\\r/g, "\\r")
              .replace(/\\t/g, "\\t")
              .replace(/\\b/g, "\\b")
              .replace(/\\f/g, "\\f");
}

And my ASP form :

Submit

<input id="inputFirstname" type="text" value="First name *" class="watermark" name="firstname"/>

<input id="inputLastname" type="text" value="Last name *" class="watermark" name="lastname"/>

<input id="inputEmail" type="text" value="E-mail *" class="watermark" name="email"/>

                            **
<textarea id="inputMessage" name="message" class="watermark">Add your message here</textarea>
**

<input id="captchaInput" type="text" value="Enter validation text *" name="captchaInput" class="watermark" style="margin-top:10px;"/>

                            SEND FORM

I don't understand why i've an error when I pass a line in my textarea.
Do you have any idea ?
Is this an error in json properties so as to send a valid json request ?


text:
Q: Stumped on function involving click and addclass After many a headache, I am still wrestling with this function...
$(document).ready(function(){
    var items = $(".tabs-group .sidebar ul li:not(:last-child) a");
    var home = $(".tabs-group .sidebar ul li:last-child a");

    $("home").click( function () {
        $("items").addClass("pulse");
    $("items").click( function () {
       $("items").removeClass("pulse");
    });
});

Basically it adds class "pulse" to "items" when "home" is clicked, and removes "pulse" from "items" when "items" is clicked.
Is the syntax correct? I am using jsFiddle to work with it. I don't have a program to check for errors, what is a good quick one to use?
Here is the jsfiddle with the function: http://jsfiddle.net/bsapaka/KjcnL/

A: Close, but your syntax is wrong: Try this:
$(document).ready(function(){
    var items = $(".tabs-group .sidebar ul li:not(:last-child) a");
    var home = $(".tabs-group .sidebar ul li:last-child a");

    home.click( function () {
        $(this).addClass("pulse");
    });
    items.click( function () {
       $(this).removeClass("pulse");
    });
});


text:
Q: Insert data into a trie So I'm trying to insert data into a trie, and my code works fine. But then I change my insert function a little bit and it doesn't work anymore and also causes the memory leak. To me, both versions of insert do the same thing but obviously, they are not. Can someone please explain to me why? Thanks in advance.
Here is the code that works
#include <stdio.h>
#include <stdbool.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>

#define SIZE 26

#define hash(c) (tolower(c) - (int)'a')

typedef struct node{
    bool endWord;
    struct node* children[SIZE];
} node;

void freeTrie(node* root){

    if(root == NULL) return;

    for (size_t i = 0; i < SIZE; i++) {
        freeTrie(root->children[i]);
    }

    free(root);
}

node* newNode(){
    node* new = NULL;

    new = (node*) malloc(sizeof(node));

    if(new != NULL){

        new->endWord = false;

        for(int i = 0; i < SIZE; i++)
            new->children[i] = NULL;
    }

    return new;
}

void insert(node* root, const char* data){

    node* temp = root;

    for (size_t i = 0, len = strlen(data); i < len; i++) {

        int index = hash(data[i]);

        if(temp->children[index] == NULL){

            temp->children[index] = newNode();

            if (temp->children[index] /*still*/ == NULL){
                printf("Something went wrong\n");
                return;
            }
        }

        temp = temp->children[index];
    }
    temp->endWord = true;
}

bool search(node* root, const char* data){

    node* temp = root;

    for (size_t i = 0, len = strlen(data); i < len; i++) {

        int index = hash(data[i]);

        temp = temp->children[index];

        if (temp == NULL){
            printf("search end here\n");
            return false;
        }
    }

    return (temp != NULL && temp->endWord);
}

int main() {

    char data[][8] = {"fox", "foo", "dog", "do"};

    node* root = newNode();

    if(root == NULL){
        printf("Something went wrong\n");
        return 1;
    }

    for (size_t i = 0, dataSize = sizeof(data)/sizeof(data[0]); i < dataSize; i++) {
        insert(root, data[i]);
    }

    printf("Check: \n");

    char output[][32] = {"not found", "found"};

    // char s[5];
    // fscanf(stdin, "%s", s);

    printf("%s\n", output[search(root, "fox")]);

    freeTrie(root);

    printf("Done\n");

    return 0;
}

Here is the insert that makes me confused
void insert(node* root, const char* data){

    node* temp = root;

    for (size_t i = 0, len = strlen(data); i < len; i++) {

        int index = hash(data[i]);

        temp = temp->children[index];

        if(temp == NULL){

            temp = newNode();

            if (temp /*still*/ == NULL){
                printf("Something went wrong\n");
                return;
            }
        }
    }

    temp->endWord = true;
}

PS: I do this for a problem set of the CS50x course, in which I have to load a dictionary of 143091 words (in alphabetical order) into my trie. My program takes about 0.1s to load and 0.06s to unload when the staff's does the same job with just 0.02s and 0.01s. I am not allowed to see the staff's source code but I guess they used a trie to store data. How can I improve my code for faster runtime? Would it run faster if I store data in an array and then binary search instead?

A: When you write
temp = temp->children[index];

you copy value contained in temp->children[index] (I'll call it A) into a completely independent variable named temp. When you later modify temp, you modify temp only, not A. That is, all new nodes do not get inserted into the trie.


text:
Q: streamWriter does not apply changes until I restart my game I'm making a game in Unity with an editor level that writes the level data in a .txt
My problem is that changes to the file are not applying correctly because I only can see them when I restart the game.
When the player creates a new level i use this:
TextAsset txtFile = Resources.Load<TextAsset>("Levels");
StreamWriter streamWriter = new StreamWriter(new FileStream("Assets/Resources/" + levelsManager.filename + ".txt", FileMode.Truncate, FileAccess.Write));

And at the end of the method I close the StreamWriter.
    streamWriter.Flush();
    streamWriter.Close();
    streamWriter.Dispose();

Moreover if the user creates multiple levels, only the last one is saved.
Changing the filemode to apend does not work because after restarting the game and creating a level it also creates again the stored levels.
¿Is there a way of refreshing the document so I don't have to restart the game everytime I create a level?
Thank you in advance.

A: You just need to refresh the assets in Unity using AssetDatabase.Refresh.

However

When the player creates a new level i use this

Note that none of this will work in a built application!
After building your app the Resources are read-only. Anyway note from Best practices -> Resources

Don't use it!

You probably rather would want to store the default file in StreamingAssets and use Application.streamingassetsPath and then later in a build use Application.persistentDataPath instead and fallback to streamingAssetsPath for reading only (again StreamingAssets is read-only after building)
For example like
public string ReadlevelsFile()
{
    try
    {
#if UNITY_EDITOR
        // In the editor always use "Assets/StreamingAssets"
        var filePath = Path.Combine(Application.streamingAssetsPath, "Levels.txt");
#else
        // In a built application use the persistet data
        var filePath = Path.Combine(Application.persistentDataPath, "Levels.txt");

        // but for reading use the streaming assets on as fallback
        if (!File.Exists(filePath))
        {
            filePath = Path.Combine(Application.streamingAssetsPath, "Levels.txt");
        }
#endif
        return File.ReadAllText(filePath);
    }
    catch (Exception e)
    {
        Debug.LogException(e);
        return "";
    }
}

public void WriteLevelsFile(string content)
{
    try
    {
#if UNITY_EDITOR
        // in the editor always use "Assets/StreamingAssets"
        var filePath = Path.Combine(Application.streamingAssetsPath, "Levels.txt");
        // mke sure to create that directory if not exists yet
        if(!Directory.Exists(Application.streamingAssetsPath))
        {
            Directory.CreateDirectory(Application.streamingAssetsPath);
        }
#else
        // in a built application always use the persistent data for writing
        var filePath = Path.Combine(Application.persistentDataPath, "Levels.txt");
#endif

        File.WriteAllText(filePath, content);

#if UNITY_EDITOR
        // in Unity need to refresh the data base
        UnityEditor.AssetDatabase.Refresh();
#endif
    }
    catch(Exception e)
    {
        Debug.LogException(e);
    }
}


text:
Q: Resistance and energy cost in an AC circuit I'm learning on my own about EE concepts. According to Ohm's law if voltage is constant then current and resistance will affect each other primarily. I believe most household AC circuits provide roughly constant voltage (110 V - 120 V).
So pretend my appliance is 1 amp. That means I would need a lot of resistance to prevent my appliance from exploding. Resistors convert energy to heat.
So if something is plugged into an outlet, regardless of its amperage requirements, is the electrical usage the same? Either it's being used by the appliance or burned off in heat? How do resistors handle that level of heat?

A: A 120V appliance that is limited to 1 Amp has to have an internal resistance of 120 ohms, and would thus dissipate (use) 120W.
(We'll set aside AC vs. DC for the moment. For our purpose here - resistive loads - it doesn't matter.)
That is:

*

*Resistance(appliance) = 120V / 1A = 120 Ohms (Ohm's Law R = E / I)

*Power(appliance) = 120V * 1A = 120 Watts (Ohm's Law P = E * I)

Where does the appliance 'use' that power? By doing some sort of work, such emitting light, spinning a motor, charging a battery, making heat, or some other use of energy.
Where does the electricity 'go'? It flows in and out of the circuit as a loop. In fact, at 1A, one Coulomb of charge per second flows in that loop. It enters at high electromotive potential (120V), and exits at lower potential (0V), giving up energy (120W) in the process. But it's still one Coulomb in and one Coulomb out.
(What's a Coulomb? It's a quantity of electron charges, 6.24 * 10^18 of them.)
Think of the water analogy. Voltage is like pressure, current is like volume. Now consider a closed pressure system running a turbine. The water (charge) flows in at high pressure (voltage), does work in the turbine (resistive load), then flows back out at lower pressure (voltage.) Yet, the water volume (current) is the same going in as going out, and throughout the whole loop.
This same-in, same-out, same-everywhere electrical flow of is known as Kirchhoff's Current Law. No electrons are lost, they just move from a higher potential to a lower one, and give off energy wherever they do work (encounter resistance.)
Now consider a loop with no resistance at all. It could conduct infinite current and give off no energy, but it also can't have any voltage difference at all. Superconductors come very close to this. In fact, a superconducting loop (like an MRI magnet) can have a current circulating in it nearly forever. Such loops have even been studied as a means to store energy, like perfect flywheels.


text:
Q: .htaccess Mod Rewrite 'pretty ur'l to actual doesn't work I'm trying to get htaccess to rewrite this url :
http://127.0.0.1/papercut3/article/post-title/

to this:
http://127.0.0.1/papercut3/article.php?p=post-title/

My current .htaccess is:
Options +FollowSymLinks
RewriteEngine On

RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f

RewriteRule ^article/(\d+)*$ ./article.php?p=$1
RewriteRule ^section/(\d+)*$ ./section.php?s=$1

And my urls written in the code:
http://127.0.0.1/papercut3/article/execution-call-for-cinema-killer/

My problem is that when I click the link I get this:
Not Found

The requested URL /papercut3/article/syria-suffers-deadliest-month/ was not found on this server.

I'm using WAMP, the .htaccess is in the root of the /papercut3 directory with all the core files. Any help would be greatly appreciated!:)

A: If you can use .htaccess files, you want it to look like:
Options +FollowSymLinks
RewriteEngine On

RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f

RewriteRule ^article/(.+)$ ./article.php?p=$1
RewriteRule ^section/(.+)$ ./section.php?s=$1

Or, you can be slightly more specific with what is allowed, but the one in your question only allows character [0-9], this way it opens it up and let's the respective PHP files do the checking/error-handling.

A: You may find help in the log file of apache, but I think this is related to AllowOverride directive, which must be set to None.
As said in the documentation, you need AllowOverride to contain at least FileInfo.
Edit: By the way, your rule won't match any of your url since you expect a int \d but don't provide any in input.


text:
Q: ModuleConcatenation bailout: Module is referenced from these modules with unsupported syntax In my React + mobx project while building I am getting below warning:

ModuleConcatenation bailout: Module is referenced from these modules
with unsupported syntax: ./app/containers lazy ^./.*$ namespace
object (referenced with context element).

This warning is for only some files.
Can anyone explain what this warning actually refer for, if possible provide an example?
Using webpack 4+.


text:
Q: Video thumbnail arrayadopter is slow on scroll I have created an adopter to display images thumbnail of video form the specific folder
but when I scroll it lags a little but why is that?
Below is the code:
Main activity class
public class TestvideolistingActivity extends ListActivity {

    String filename = null;
    String filePath = null;
    String dirNameSlash = "/videotest/";
    String dirName = "videotest";
    String path = Environment.getExternalStorageDirectory() + dirNameSlash ;
    String[] values;
    String deleteFile ;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // getting the own adapter
        getInit();
    }

    @Override
    protected void onResume() {
        getInit();
        super.onResume();
    }
    public void getInit() {

        deleteFile = null;
        values = getFilesArrayFromSdCard();
        setListAdapter(new MyAdapter(this, values));
    }

    protected void onListItemClick(ListView l, View v, int position, long id) {
        String item = (String) getListAdapter().getItem(position);
        Intent intentToPlayVideo = new Intent(Intent.ACTION_VIEW);
        intentToPlayVideo.setDataAndType(Uri.parse(path + item), "video/*");
        startActivity(intentToPlayVideo);
    }

    public String[] getFilesArrayFromSdCard() {
        String[] fileList = null;
        File videoFiles = new File(path);
        if (videoFiles.isDirectory()) {
            fileList = videoFiles.list();
        }
        return fileList;
    }
}

this the adopter class which show;s the text and the thumbnail

public class MyAdapter extends ArrayAdapter<String> {

    private final Activity context;
    private final String[] names;
    private String filePath = null;
    private Bitmap bmThumbnail;

    private String dateFormat = "dd/MM/yyyy HH:mm:ss";
    private SimpleDateFormat formatter;
    private String filename;
    String dirNameSlash = "/videotest/";

    static class ViewHolder {
        // value for the name of the file
        public TextView text;
        // video file thumbnail
        public ImageView image;
    }

    public MyAdapter(Activity context, String[] names) {
        super(context, R.layout.rowlayout, names);
        this.context = context;
        this.names = names;
        filePath = Environment.getExternalStorageDirectory() + dirNameSlash;
        formatter = new SimpleDateFormat(dateFormat);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View rowView = convertView;
        if (rowView == null) {
            LayoutInflater inflater = context.getLayoutInflater();
            rowView = inflater.inflate(R.layout.rowlayout, null);
            ViewHolder viewHolder = new ViewHolder();
            viewHolder.text = (TextView) rowView.findViewById(R.id.label);
            viewHolder.image = (ImageView) rowView.findViewById(R.id.icon);
            rowView.setTag(viewHolder);
        }

        ViewHolder holder = (ViewHolder) rowView.getTag();
        // Video file name
        String s = names[position];

        holder.text.setText(s);

        bmThumbnail = ThumbnailUtils.createVideoThumbnail(filename, Thumbnails.MICRO_KIND);
        holder.image.setImageBitmap(bmThumbnail);

        return rowView;
    }
}

This is the error by using Akhil code
    04-04 18:09:59.078: E/AndroidRuntime(10625): FATAL EXCEPTION: main
04-04 18:09:59.078: E/AndroidRuntime(10625): java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
04-04 18:09:59.078: E/AndroidRuntime(10625):    at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:257)
04-04 18:09:59.078: E/AndroidRuntime(10625):    at java.util.ArrayList.get(ArrayList.java:311)
04-04 18:09:59.078: E/AndroidRuntime(10625):    at com.koders.testvideolisting.MyPerformanceArrayAdapter.getView(MyPerformanceArrayAdapter.java:111)
04-04 18:09:59.078: E/AndroidRuntime(10625):    at android.widget.AbsListView.obtainView(AbsListView.java:1315)
04-04 18:09:59.078: E/AndroidRuntime(10625):    at android.widget.ListView.makeAndAddView(ListView.java:1727)
04-04 18:09:59.078: E/AndroidRuntime(10625):    at android.widget.ListView.fillDown(ListView.java:652)
04-04 18:09:59.078: E/AndroidRuntime(10625):    at android.widget.ListView.fillFromTop(ListView.java:709)
04-04 18:09:59.078: E/AndroidRuntime(10625):    at android.widget.ListView.layoutChildren(ListView.java:1580)
04-04 18:09:59.078: E/AndroidRuntime(10625):    at android.widget.AbsListView.onLayout(AbsListView.java:1147)
04-04 18:09:59.078: E/AndroidRuntime(10625):    at android.view.View.layout(View.java:7034)
04-04 18:09:59.078: E/AndroidRuntime(10625):    at android.widget.FrameLayout.onLayout(FrameLayout.java:333)
04-04 18:09:59.078: E/AndroidRuntime(10625):    at android.view.View.layout(View.java:7034)
04-04 18:09:59.078: E/AndroidRuntime(10625):    at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1249)
04-04 18:09:59.078: E/AndroidRuntime(10625):    at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1125)
04-04 18:09:59.078: E/AndroidRuntime(10625):    at android.widget.LinearLayout.onLayout(LinearLayout.java:1042)
04-04 18:09:59.078: E/AndroidRuntime(10625):    at android.view.View.layout(View.java:7034)
04-04 18:09:59.078: E/AndroidRuntime(10625):    at android.widget.FrameLayout.onLayout(FrameLayout.java:333)
04-04 18:09:59.078: E/AndroidRuntime(10625):    at android.view.View.layout(View.java:7034)
04-04 18:09:59.078: E/AndroidRuntime(10625):    at android.view.ViewRoot.performTraversals(ViewRoot.java:1049)
04-04 18:09:59.078: E/AndroidRuntime(10625):    at android.view.ViewRoot.handleMessage(ViewRoot.java:1744)
04-04 18:09:59.078: E/AndroidRuntime(10625):    at android.os.Handler.dispatchMessage(Handler.java:99)
04-04 18:09:59.078: E/AndroidRuntime(10625):    at android.os.Looper.loop(Looper.java:144)
04-04 18:09:59.078: E/AndroidRuntime(10625):    at android.app.ActivityThread.main(ActivityThread.java:4937)
04-04 18:09:59.078: E/AndroidRuntime(10625):    at java.lang.reflect.Method.invokeNative(Native Method)
04-04 18:09:59.078: E/AndroidRuntime(10625):    at java.lang.reflect.Method.invoke(Method.java:521)
04-04 18:09:59.078: E/AndroidRuntime(10625):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
04-04 18:09:59.078: E/AndroidRuntime(10625):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
04-04 18:09:59.078: E/AndroidRuntime(10625):    at dalvik.system.NativeStart.main(Native Method)

A: The listview is lagging because you are creating new Thumbnails in getView() every time. There is just no caching or re-use. As the use scrolls up/down , getView() is called and time consuming process of creating thumbnails happen, hence the lag. You will also run Out of Memory soon.
Create and keep an Array of Bitmaps, with the same length as the number of elements in the datasource and store your thumbnails in the array. Take out the bitmap from the array for that particular position inside getView(). This should considerably increase the performance.
EDIT
I have added a Hasmap of bitmaps to demonstrate the re-use.
 public MyAdapter(Activity context, String[] names) {
    super(context, R.layout.rowlayout, names);
    this.context = context;
    this.names = names;
    filePath = Environment.getExternalStorageDirectory() + dirNameSlash;
    formatter = new SimpleDateFormat(dateFormat);
cacheBitmap = new HashMap<String, Bitmap>(names.length);
initCacheBitmap();
}

private void initCacheBitmap() {
    for(String string:names)
        cacheBitmap.put(string, ThumbnailUtils.createVideoThumbnail(filePath+string, Thumbnails.MICRO_KIND));

}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    View rowView = convertView;
    if (rowView == null) {
        LayoutInflater inflater = context.getLayoutInflater();
        rowView = inflater.inflate(R.layout.rowlayout, null);
        ViewHolder viewHolder = new ViewHolder();
        viewHolder.text = (TextView) rowView.findViewById(R.id.label);
        viewHolder.image = (ImageView) rowView.findViewById(R.id.icon);
        rowView.setTag(viewHolder);
    }

    ViewHolder holder = (ViewHolder) rowView.getTag();
    // Video file name
    String s = names[position];

    holder.text.setText(s);

    holder.image.setImageBitmap(cacheBitmap.get(s));

    return rowView;
}}

A: Since you are creating Thumnail for video inside getView() it slow down your scrolling.
So you have to save your bitmap in Arrarys and list it i scroll.. Try this Sample for this will really helps you for fast scrolling. This Sample includes images , you have to change for Video in Media Content Providers. Fast Scroll Sample


text:
Q: Find an explicit isomorphism of rings Find and explicit isomorphism of rings $$\lambda:\mathbb{F}_5[x]/(x^2+x+2)\rightarrow\mathbb{F}_5[x]/(x^2+4x+2)$$
I know that both fields minus the zero element are isomorphic to $C_{24}$ with generator x, but how do I describe the isomorphism between the two with the zero element?
I also know that 0 must get mapped to zero and 1 mapped to 1, so do i simply state what x gets mapped to (and map it to x) ?

A: Denote by $t$ the image of $x$ under the canonical homomorphism $\mathbb{F}_5[x]\to\mathbb{F}_5[x]/(x^2+4x+2)$, so that $t^2+4t+2=0$.
You know that every element of $\mathbb{F}_5[x]/(x^2+4x+2)=\mathbb{F}_5[t]$ can be uniquely written as $a+bt$, with $a,b\in \mathbb{F}_5$.
If $(a+bt)^2+(a+bt)+2=0$, we get
$$
a^2+2abt+b^2(-4t-2)+a+bt+2=0
$$
that is,
$$
(a^2-2b^2+a+2)+(2ab-4b^2+b)t=0
$$
so $b=0$ (contradiction) or $2a-4b+1=0$, that is, $b=-2a-1$. Substituting in the condition $a^2-2b^2+a+2=0$, we get
$$
a^2+a=0
$$
that means $a=0$ or $a=-1$. Thus the roots of $x^2+x+2=0$ in $\mathbb{F}_5[t]$ are $-t$ and $4+t=t-1$. Thus the kernel of the homomorphism
$$
\mathbb{F}_5[x]\to\mathbb{F}_5[t]
$$
sending $x$ to $-t$ is $(x^2+x+2)$. You can also choose the homomorphism sending $x$ to $t-1$.

Of course, you could also note that the homomorphism $\mathbb{F}_5[x]$ to $\mathbb{F}_5[x]$ sending $x$ to $-x$ transforms the polynomial $x^2+x+2$ into $x^2-x+2=x^2+4x+2$.

A: Factoring the polynomials over $\mathbb F_5$, we get that the first polynomial have roots $x_1=3 \pm 3 \sqrt{3}$, and the other polynomial have roots $x_2=-3 \pm 3\sqrt{3}$.
To find the isomorphism, note that $x_2 = x_1-6$.


text:
Q: Problem related to remainder theorem I want to show that for any $n\in\mathbb{N}$, all the coefficients of $R(x)$ are even where $x^{7n}+1=(x^3+x+1)Q(x)+R(x)$. Any ideas? ($Q(x),R(x)\in\mathbb{Z}[x]$ and the degree of $R(x)$ is at most 2).

A: We remark that $$x^7+1\equiv (x + 1) (x^3 + x + 1) (x^3 + x^2 + 1) \pmod 2$$ so the claim is true for $n=1$.
Working $\pmod 2$, we note that the roots of $x^{7n}+1$ are precisely the $7n-$roots of unity over the field of order $2$.  Of course the $7-$roots of unity are a subset of those, hence $x^{7n}+1$ is divisible by $x^7+1\pmod 2$.  But $x^3+x+1$ divides $x^7+1\pmod 2$ so we are done.


text:
Q: How to Stop EC2 Instance from the list I have the below code it is working very well in local for stopping EC2 Instance but while I am trying to move its production it is stopping only the first instance not the second one/nth one
import boto3
import json

access_key = "AKIAJSVXXXXXXXXXX"
secret_key = "mSvhX5q7uw8dTZ543qtC6OXXXXXXXXXXXX"
client = boto3.client('ec2', aws_access_key_id=access_key, aws_secret_access_key=secret_key, region_name='us-east-1')
file1 = open("Myfile.txt", "r").read().split("\n")
print(file1)

ec2_result = client.describe_instances(
    Filters=[
        {
            'Name': 'tag:Name',
            'Values': file1

        }
    ]
)

ids = [ec2_result['Reservations'][0]['Instances'][i]['InstanceId'] for i in
       range(len(ec2_result['Reservations'][0]['Instances']))]
print(ids)
response = client.stop_instances(
    InstanceIds=ids
)

print("stooped now")

Myfile.txt
instanceonename
instance2name

It is working very well in my local system but in production, it is stopping only the first EC2 instance
not second one

A: It stops only one instance, because your list comprehension iterates only over one instance. You need double for:
ids = [instance['InstanceId'] \
         for reservation in ec2_result['Reservations'] \
         for instance in reservation['Instances']]


text:
Q: Cannon matrix multiplication in MPI I'm trying to implement Cannon's matrix multiplication algorithm in C using MPI and nonblocking communication. I've tried the example code at http://siber.cankaya.edu.tr/ozdogan/GraduateParallelComputing.old/ceng505/node133.html, but I can't get it to work.
It works fine when executed with a single node, but more than that and it's not finishing.
I'm trying to use a randomized 4*4 matrix on 4 nodes. From what I can gather with absolutely no debugging tools aside from printf process with rank 0 finishes executing the function, but other processes get stuck at MPI_Wait on line 68. I'm pretty new to C and parallel programming and can't figure out what's wrong.
EDIT: During debugging I found one incredibly baffling thing - calling MPI_Barrier seems to hang the whole program.
I call MPI_Barrier in main after the multiplication function is completed. To make debugging a little easier i decided to split the function code into parts and separate them with barriers. placing the barrier at the end of main computation loop ( so that every process has to complete one iteration for any process to start the next one ) resulted in the loop not even reaching second iteration.
It seems that when a single process reaches the barrier after non blocking sends/receives and consequent calls to MPI_Wait it causes other processes to wait indefinitely and never reach the barrier.
Here's an example code:
void generateArray(int * vector, int size){
int i;
for (i = 0; i < size; i ++){
    vector[i] = rand()%10 + 1;
}
}

int test_size = 4;

int main( int argc, char **argv )
{
MPI_Init (&argc, &argv);

int comm_size, myrank;
int my2drank, mycoords[2];
MPI_Comm_size(MPI_COMM_WORLD, &comm_size);
MPI_Comm_rank(MPI_COMM_WORLD, &myrank);

MPI_Request requests[4];
MPI_Status status[4];

MPI_Comm comm_2d;
int dims[2], periods[2];
dims[0] = dims[1] = sqrt(comm_size);
periods[0] = periods[1] = 1;
MPI_Cart_create(MPI_COMM_WORLD, 2, dims, periods, 1, &comm_2d);

int sizelocal = test_size/dims[0];

srand(time(NULL));
int a[sizelocal*sizelocal], b[sizelocal*sizelocal];
generateArray(a, sizelocal*sizelocal);
generateArray(b, sizelocal*sizelocal);

MPI_Comm_rank(comm_2d, &my2drank);
MPI_Cart_coords(comm_2d, my2drank, 2, mycoords);

int uprank, downrank, leftrank, rightrank;
MPI_Cart_shift(comm_2d, 0, -1, &rightrank, &leftrank);
MPI_Cart_shift(comm_2d, 1, -1, &downrank, &uprank);

int *buffersA[2], *buffersB[2];

buffersA[0] = a;
buffersA[1] = (int *)malloc(sizelocal*sizelocal*sizeof(int));
buffersB[0] = b;
buffersB[1] = (int *)malloc(sizelocal*sizelocal*sizeof(int));

int shiftsource, shiftdest;
MPI_Cart_shift(comm_2d, 0, -mycoords[0], &shiftsource, &shiftdest);
MPI_Sendrecv_replace(buffersA[0], sizelocal*sizelocal, MPI_INT,shiftdest, 1, shiftsource, 1, comm_2d, &status[0]);

MPI_Cart_shift(comm_2d, 1, -mycoords[1], &shiftsource, &shiftdest);
MPI_Sendrecv_replace(buffersB[0], sizelocal*sizelocal, MPI_INT,shiftdest, 1, shiftsource, 1, comm_2d, &status[0]);

printf("Rank %d at point 1\n", my2drank);

int i;
for (i = 0; i < 2; i ++){
    printf("Rank %d started iteration %d\n", my2drank, i);
    MPI_Isend(buffersA[i%2], sizelocal*sizelocal, MPI_INT,leftrank, 1, comm_2d, &requests[0]);
    MPI_Isend(buffersB[i%2], sizelocal*sizelocal, MPI_INT,uprank, 1, comm_2d, &requests[1]);
    MPI_Irecv(buffersA[(i+1)%2], sizelocal*sizelocal, MPI_INT,rightrank, 1, comm_2d, &requests[2]);
    MPI_Irecv(buffersB[(i+1)%2], sizelocal*sizelocal, MPI_INT,downrank, 1, comm_2d, &requests[3]);

    MPI_Waitall(4, requests, status);
    printf("Rank %d stopped waiting in iteration %d\n", my2drank, i);
    MPI_Barrier(comm_2d);
}

printf("Rank %d at point 2\n", my2drank);

MPI_Barrier(MPI_COMM_WORLD);
MPI_Finalize();
return 0;
}

And here's the output:
Rank 0 at point 1
Rank 0 started iteration 0
Rank 1 at point 1
Rank 1 started iteration 0
Rank 2 at point 1
Rank 2 started iteration 0
Rank 3 at point 1
Rank 3 started iteration 0
Rank 0 stopped waiting in iteration 0