text:
Q: Parametrized queries for ArcGIS? Since our ArcGIS applications are developed as desktop and as server applications, I'm looking for a way create our SQL-queries in a safe way. The state of the art to mitigate SQL-injection is, to use parametrized queries / prepared statements.
Prepared statements can only be implemented with support of the underlying database and I'm not aware that Esri offers support of those in their interfaces. Parametrized queries could partly be implemented in an external library.
Is anybody aware of a library, which offers parametrized queries for any of the ArcGIS products, or does Esri offer support for parametrized queries in one of their products?

Finally I opened an issue on ArcGIS Pro Ideas.

A: Out of the box, ArcGIS Server comes with two pieces of functionality you might explore:

*

*Feature services have ValidateSQL request available which can check your SQL query/statement.

validateSQL also prevents SQL injection. In addition, all table and
  field names used in the SQL expression or WHERE clause are validated
  to ensure they are valid tables and fields.

*Standardized queries available in ArcGIS Server.

ArcGIS Server includes a security option that forces developers to use
  standardized SQL queries when working with map, feature, image, and
  WFS services through REST or SOAP. This makes it easier for developers
  and applications to query ArcGIS Server services and helps prevent SQL injection attacks. Standardized queries are enforced by default, but
  can be disabled by the server administrator.
The standardized queries are enabled by default and apply to all map,
  feature, image, and WFS services in the ArcGIS Server site.

I am afraid parameterized queries is not something that is available out of the box and you would likely need to use 3rd party to integrate this. You might look at the ArcGIS Server SOI to learn more about intercepting incoming requests to your GIS services. SOI can be used for instance for:

Auditing and logging all requests—For debugging purposes, you can
  create a series of SOIs that log detailed information about incoming
  requests, such as full information about the input parameters and the
  user credentials passed in with the request.

This could help you building your extra layer of security if needed.


text:
Q: How to do an AJAX form submission WITH page refresh I have a HTML form that posts data to a Laravel/PHP login page.
When I use the native HTML form submission attributes like so:
<form name='login' class="form-horizontal" role="form" method="POST" action="https://somewebsite.com/login">
   // form here
</form>

My form submits fine, and once it validates I am sent to a new accounts page (dictated by the site in the action attribute link.
However, I want to do some javascript processing before I send this form off, so I'd like to do it via jQuery. At the moment, I do:
  $("#form").submit(function(){
      $.ajax({
          type: "POST",
          url: liveLink,
          data: dataObj,
          success: function(res, other, other2){
            // Do some javascript stuff in here

            // Then I would like to follow the URL with correct tokens sent back by the PHP page
          }
      });
    });

Is this possible to do?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unicode character name in variable I want to create an unicode string using the name of a character, like this (found here) :
>>> "\N{GREEK CAPITAL LETTER DELTA}"
'\u0394'

but having the name of the character in a variable. Like
myChar = "GREEK CAPITAL LETTER DELTA"
myString = "\N{myChar}"   # causes SyntaxError: (unicode error)

I tried many things based on format(), nothing worked.
Anyone know how to do it ?

A: Use unicodedata.lookup.
>>> import unicodedata
>>> my_char = "GREEK CAPITAL LETTER DELTA"
>>> unicodedata.lookup(my_char)
'Δ'


text:
Q: Can we do anything about Typosquatters? I mistyped a link. Fortunately I also borked markdown so I went back and double checked it.
The live site stackexcange dot com (intentional typo domain name) appears parked 100% of the time in Tor Browser. In Opera private, it redirects to random affiliate sites, some of which seem to be malware distributors purporting to be Microsoft or Adobe.
At the least they play obnoxious audio and try to get you to call a number while recording your location and presumably other info.
Is there anything that can be done about sites like this? More practically, could we at least make people aware if they type a link that is similar to  stackexchange.com but with a typo?

A: There is not much to do. We can't expect SE to purchase every domain that slightly looks like any Stack Exchange domain.
In some countries, there are laws that protect like malicious sites, but suing such sites is quite an expensive business.


text:
Q: XAML designer gets unhandled exception I have been searching for solution to my problem for a week and no help.
I'm running VS2015 pro on Windows 10 build 10586.
My XAML Designer failed to load with following when I created any blank C# universal app.
System.Runtime.Remoting.RemotingException
[5936] Designer process terminated unexpectedly!
   at Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.Primitives.ProcessDomainFactory.ProcessIsolationDomain.Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.IIsolationDomain.CreateInstance(String assemblyName, String assemblyCodeBase, String typeName)
   at Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.Primitives.IsolationBoundary.Initialize()
   at Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.Primitives.IsolationBoundary.CreateInstance[T](Type type)
   at Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.IsolatedObjectFactory.Initialize()
   at Microsoft.VisualStudio.DesignTools.DesignerHost.Services.VSIsolationService.CreateObjectFactory(IIsolationTarget isolationTarget, IObjectCatalog catalog)
   at Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.IsolationService.CreateLease(IIsolationTarget isolationTarget)
   at Microsoft.VisualStudio.DesignTools.DesignerContract.IsolatedDesignerService.CreateLease(IIsolationTarget isolationTarget, CancellationToken cancelToken, DesignerServiceEntry& entry, IServiceProvider serviceOverrides)
   at Microsoft.VisualStudio.DesignTools.DesignerContract.IsolatedDesignerService.IsolatedDesignerView.CreateDesignerViewInfo(CancellationToken cancelToken)
   at Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.IsolatedTaskScheduler.InvokeWithCulture[T](CultureInfo culture, Func`2 func, CancellationToken cancelToken)
   at Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.IsolatedTaskScheduler.<>c__DisplayClass10_0`1.<StartTask>b__0()
   at System.Threading.Tasks.Task`1.InnerInvoke()
   at System.Threading.Tasks.Task.Execute()

In Event Viewer I got this
Faulting application name: XDesProc.exe, version: 14.0.24720.0, time stamp: 0x564ea58d
Faulting module name: KERNELBASE.dll, version: 10.0.10586.0, time stamp: 0x5632da1c
Exception code: 0xe0434352
Fault offset: 0x000bd8a8
Faulting process id: 0x1a90
Faulting application start time: 0x01d1577281913da3
Faulting application path: C:\Users\incom\AppData\Local\Microsoft\VisualStudio\14.0\Designer\ShadowCache\15kmnzmb.f2e\g3ow5ih4.vje\XDesProc.exe
Faulting module path: C:\Windows\SYSTEM32\KERNELBASE.dll
Report Id: 28fbb682-7d0d-4dd4-8850-5496c96bf41a
Faulting package full name: fbd2dab3-4d5d-4565-9eb7-ae4409ee95fb_1.0.0.0_x86_NorthAmerica_8wekyb3d8bbwe
Faulting package-relative application ID: Designer.App

I believe there is something wrong with kernel base because when I tried to created a blank C++ universal app and built it, I got a breakpoint pointing to kernelbase.dll.
Plus, I tried many workarounds like deleting shadowcache, reinstalled VS (a few times), change target build but none seems to work for me.
Please help.


text:
Q: AttributeError: 'NoneType' object has no attribute 'add_internal I am making a 2d platforming game in Pygame.
'AttributeError: 'NoneType' object has no attribute 'add_internal''
This error is occuring on this line:
self.sprites.add(playerbanner)
     class Player(pygame.sprite.Sprite):

         def __init__(self,classname,movementspeed,jumpheight,damage,x,y,sprites,platforms,bullets,banner,spawndirection):
            super().__init__()
            self.classname=classname
            self.speed=movementspeed
            self.height=jumpheight
            self.damage=damage
            self.x=x
            self.y=y

            self.banner=banner
            self.startdirectionspawn=spawndirection

            self.walking=False
            self.jumping=False
            self.currentframe=0
            self.lastupdate=0

            self.velocityx=0
            self.velocityy=0
            self.accelerationy=0

            self.lastpress=1

            self.loadframes(classname)

            self.image=self.stationary

            self.rect=self.image.get_rect()
            self.rect.center=(self.x,self.y)
            self.image.set_colorkey(BLACK)

            self.sprites=sprites
            self.platforms=platforms
            self.bullets=bullets

        def countdown(self):
            gamecountdown(6)

        def updateposition(self,hit,jump):

            if self.accelerationy<0:
                hit=False

            if self.accelerationy!=0:
                jump=False

            if hit==False:
                self.accelerationy+=0.1

            if jump==True:
                self.accelerationy=-15

            if hit==True:
                self.velocityy=0
                self.velocityx=0
                self.accelerationy=0

            pressed=pygame.key.get_pressed()
            if pressed[pygame.K_a]:
                self.velocityx=-self.speed
                self.animate('left')
                self.lastpress='a'

            if pressed[pygame.K_d]:
                self.velocityx=self.speed
                self.animate('right')
                self.lastpress='d'

            if not pressed[pygame.K_a] and not pressed[pygame.K_d]:
                if self.lastpress=='d':
                    self.image=self.stationary

                elif self.lastpress=='a':
                    self.image=self.stationarya

            self.x+=self.velocityx
            self.y+=self.velocityy + (0.2*self.accelerationy)

            self.rect.center=(self.x,self.y)

            playerbanner=messagedisplay(self.banner,BLACK,self.x-15,self.y-50, 30, 30, 'smallfont')
            self.sprites.add(playerbanner)

            self.image.set_colorkey(BLACK)
            pygame.display.update()

I am trying to get a 'player 1' to print above the player's head. When I do not put it into a group, it still prints, but flickers on and off.
The group print statements are called from another file.


text:
Q: Delete activedocument Word 2013 I have a form that is send to users to complete and electronically submit, which really just sends an automated email with the doc as an attachment. In order to attach the doc in the email, it first saves to the users desktop automatically. What I want to do is find a way to delete this document after it's submitted. I found a few examples online but none have worked for me, and frankly I don't see how it would work if you have a line ActiveDocument.Close False followed by the line to delete the file path, the document closes and the macro is no longer running as far as I can imagine.
I found 1 unmarked answer to a question from another user: Delete doc when macro finishes
 Sub DeleteCurrentDoc()

    Dim Doc1 As Document
    Dim deletepath As String

    'get path of this document to delete it later
    deletepath = ActiveDocument.FullName

    'Close the document we are going to delete (Word should remain Open
    ActiveDocument.Close False

    'Delete it
    Kill (deletepath)

    'Tidy up and close Word (Optional Line, delete if necessary)
    Application.Quit

    End Sub

and another on word.tips.net :
https://wordribbon.tips.net/T011642_Deleting_the_Open_Document_File
Sub DeleteThisFile()
    Dim MyFile As String

    MyFile = ActiveDocument.Path & "\" & ActiveDocument.Name
    If MsgBox(MyFile & " will be deleted permanently", _
      vbYesNo, "Delete this File?") = vbYes Then
        ActiveDocument.Close (wdDoNotSaveChanges)
        Kill MyFile
    End If
End Sub

I tried to look into a code to open a new document and add a macro to it each time but I feel that is getting into some unwanted territory. I would really like to find a way to delete the file from the user's pc however, as they are to only have access to a single form upon request.
I'm using Word 2013, i'm not sure if perhaps the examples above work in earlier versions and just not mine, Is this possible?
thank you for any help.
UPDATE
I'm attempting a workaround currently, where the document will save as a read only file for the user after it sends the attachment, this way they can save for their records I suppose. Though the protection I'm setting in the workbook to make it read only is not applying, instead it is reverting back to the forms only protection of the original file and I cannot find out why.
`ActiveDocument.SaveAs2 FileName:="C:\Users\" & curUser & "\Desktop\My User Request_" & _
Format(Date, "mm.dd.yy") & ".docx", fileformat:=wdFormatDocumentDefault
Selection.HomeKey wdStory
With ActiveDocument
    .Protect 3, Password:="password"
    .Save
End With`

What I'm doing here is re-saving it with a different file name and as a non macro enabled workbook, I then delete the temporary file I originally saved to their desktop required to send the attachment, leaving them with only a copy of the form they filled out which they can no longer make any changes to.
I've tried a few ways where I added the protection then did the save as and each time I open the docx, the protection is still forms only instead of read only.
Ideally I would really like to know how to successfully delete the activedocument so I can save a pdf copy to the users desktop and then delete the Word doc.

A: This code will do the following:

*

*Open new instance of Word

*Copy contents of macro enable doc to the new instance of word

*save the new instance doc in the temp location

*you need to then add the code for emailing etc

*it will then delete the new instance word doc from the temp location

*close the new instance of word

*close the macro enables word doc

See Code below:
    Option Explicit

    Sub SaveAndDeleteBeforeClosing()

        'Tested and working well with Office 2010

        Dim FormDocument As Document
        'Activedocument can be changed to reference a specific document name.
        'Set FormDocument = Documents("Some Doc Name")
        Set FormDocument = ActiveDocument

        'Opening new instance of Word
        Dim WordProg As Word.Application
        Set WordProg = CreateObject("Word.Application")
        WordProg.Application.Visible = False

        'Adding a new document toi the new instance of Word
        WordProg.Documents.Add Template:="Normal", NewTemplate:=False, DocumentType:=0
        Dim WordDoc As Document
        Set WordDoc = WordProg.Documents(WordProg.Documents.Count)

        'Copy contents of Macro Document to new document
        FormDocument.Content.Copy
        WordDoc.Range.Paste

        'Use this to as a sanity check to see if everything is copied over correctly
        'otherwsie you will need to play around with the paste options
        WordProg.Visible = True

        'Saving New instance word doc to temp location

        Dim FileNameString As String
        'Enter your desired file name here
        FileNameString = "Some Doc Name"
        Dim FilePathString As String
        'Temp file for deleting
        FilePathString = "C:\Temp\" & FileNameString & ".docx"

        WordDoc.SaveAs2 FileName:=FilePathString, FileFormat:= _
            wdFormatDocumentDefault, LockComments:=False, Password:="", AddToRecentFiles _
            :=True, WritePassword:="", ReadOnlyRecommended:=False, EmbedTrueTypeFonts _
            :=False, SaveNativePictureFormat:=False, SaveFormsData:=False, _
            SaveAsAOCELetter:=False, CompatibilityMode:=14

        'Closing new instance word document
        WordDoc.Close

        'Some code to send the file as a email
        '
        '
        '
        '
        '
        'delete the file from the C:\Temp\ folder
        Kill (FilePathString)

        'Quitting the temp word application
        WordProg.Application.Quit
        'Quitting the word application inwhich the macro is stored
        Application.Quit False

    End Sub


text:
Q: textpad regexp replace all ampersands in url string for href Using textpad only, what regexp will find & amps; or &'s inside an href and replace them temporarily (even though I know the correct url encoding would have them be left as entities).. with a key that can be used later after TIDYING up. What I have now finds the first instance, but url params with multiple &'s don't get cleaned right, and doesn't account for items that are properly encoded with & amp; s already.
Here's what I have:
FIND WHAT: \(<a href="[^"]+?\)&

REPLACE WITH: \1-AMP-

What I want is something that will take this:

and turn it into this:

That way I can quickly search and replace to revert them back to their initial sate afterwards since this is only for validating, not for saving.
Thanks!

A: I'm not sure about how this would be achieved in textpad, however in powershell this could be done as:
$String =''
$String -replace '(?<=<a[^<>]*href="[^"<> ]*?)&',  "-AMP-"

yields

Dissecting the regex:

*

*The look around (?<= .... ) first validates that you're a anchor tag

*moves through that tag until it finds the href name

*moves through the string of non ", <, >, space characters looking for &

*All & strings are then found and replaced.


text:
Q: Xcode 6, Yosemite Mac app help book: topic unavailable I am attempting to make a simple non-localized help book for my Cocoa application. I've made a .help  file with the structure described in the somewhat out-of-date Apple Help Programming Guide.
When I run my app in the debugger from Xcode, the help item is correctly listed under the help menu. But selecting it just brings up a dialogue with "The selected topic is currently unavailable".
Opening the help bundle and going to the title page html file (in Safari) correctly navigates the structure of the help folder. This is only 3 pages. It seems like the help viewer is not getting to the title page. What is the correct structure of the help bundle and the related plist values for the help viewer to work?
I have:
contents/
Info.plist

Resources/

English.lproj/

title page.html, help index, pigs folder, sty folder etc
thanks
r


text:
Q: How to detect expired session vs. no session The requirement is this: When a user session is expired, call expired.htm page, but on the first connection to the web site, show login.htm.
I tried using a filter but it doesn't work, I'm not able to tell to filter how to understand if it's a new request or an old request expired. This is the code I used:
if (session.getAttribute("userProfile") == null) {

    logger.debug("Session: " + ( session.isNew() ? "true" : "false"));
    logger.debug(request.getSession().isNew());

    if ( request.getRequestedSessionId() != null && !request.isRequestedSessionIdValid() )  {
        return new ModelAndView("redirect:expired.htm");
    } else {
        return new ModelAndView("redirect:login.htm");
    }

}

I tried different solutions proposed here on Stack Overflow and on the general internet, but nothing has worked and every request goes to expired.htm.

A: How do you get the session object? Before doing that, use
if (request.getSession(false)==null) {
  // no session present (expired or new visitor)
  [... do something ...]
} else {
  // active session present
}

A: You need to use the validation above before use any attribute in the session. Because if the session don't exists you can't get an attribute of it.
You need to put false inside parentesis.
if(request.getSession(false) == null) { //Session don't exists
...
}

Java explain:
public HttpSession getSession(boolean create)
Returns the current HttpSession associated with this request or, if there is no current session and create is true, returns a new session.
If create is false and the request has no valid HttpSession, this method returns null.
To make sure the session is properly maintained, you must call this method before the response is committed. If the container is using cookies to maintain session integrity and is asked to create a new session when the response is committed, an IllegalStateException is thrown.
Parameters:
create - true to create a new session for this request if necessary; false to return null if there's no current session
Returns:
the HttpSession associated with this request or null if create is false and the request has no valid session


text:
Q: Creating a numpy array from list of lists, with various data types I'd like to create a numpy array with a list of lists. The data type should be float, float, string. Why doesn't this work? (Note: I already read this question).
import numpy

print numpy.array([[u'1.2', u'1.3', u'hello'], [u'1.4', u'1.5', u'hi']], dtype='f,f,str')

Output:
[[(4.2245014868923476e-39, 7.006492321624085e-44, '')
  (4.2245014868923476e-39, 7.146622168056567e-44, '')
  (9.275530846997402e-39, 9.918384925297198e-39, '')]
 [(4.2245014868923476e-39, 7.286752014489049e-44, '')
  (4.2245014868923476e-39, 7.42688186092153e-44, '')
  (9.642872831629367e-39, 0.0, '')]]

A: As stressed in my previous answer, and comments, the normal input for a compound dtype is a list of tuples.  To put it bluntly, that's how np.array is designed to work.
In [308]: numpy.array([[u'1.2', u'1.3', u'hello'], [u'1.4', u'1.5', u'hi']], dtype='f,f,str')
TypeError: a bytes-like object is required, not 'str'

With a list of tuples, and an improved dtype:
In [311]: numpy.array([(u'1.2', u'1.3', u'hello'), (u'1.4', u'1.5', u'hi')], dtype='f8,f8,U10')
Out[311]:
array([( 1.2,  1.3, 'hello'), ( 1.4,  1.5, 'hi')],
      dtype=[('f0', '<f8'), ('f1', '<f8'), ('f2', '<U10')])

A possible way around the normal list of tuples (I can't test it right now):
Make a zeros array of the right shape and dtype
Make an object array from the list of lists (or a 2d array of strings)
Assign columns of the 2d array to fields of the structured (a loop)

Looping on the few fields is usually faster than looping on the many records.
But, converting a list of lists into a list of tuples shouldn't be that expensive.

In [314]: alist = [[u'1.2', u'1.3', u'hello'], [u'1.4', u'1.5', u'hi']]
In [316]: dt = np.dtype('f8,f8,U10')

Setting with list of tuples:
In [317]: np.array([tuple(a) for a in alist], dtype=dt)
Out[317]:
array([( 1.2,  1.3, 'hello'), ( 1.4,  1.5, 'hi')],
      dtype=[('f0', '<f8'), ('f1', '<f8'), ('f2', '<U10')])

Setting fields:
In [319]: res = np.zeros(len(alist), dtype=dt)
In [320]: temp = np.array(alist)
In [321]: temp                    # default string dtype
Out[321]:
array([['1.2', '1.3', 'hello'],
       ['1.4', '1.5', 'hi']],
      dtype='<U5')
In [322]: for i,n in enumerate(dt.names):
     ...:     res[n] = temp[:,i]
     ...:
In [323]: res
Out[323]:
array([( 1.2,  1.3, 'hello'), ( 1.4,  1.5, 'hi')],
      dtype=[('f0', '<f8'), ('f1', '<f8'), ('f2', '<U10')])

For this small case, the list of tuples approach is faster.  With a much longer one the fields might be faster, but it has to be tested
In [325]: timeit np.array([tuple(a) for a in alist], dtype=dt)
6.26 µs ± 6.28 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
In [326]: %%timeit
     ...: res = np.zeros(len(alist), dtype=dt)
     ...: temp = np.array(alist)
     ...: for i,n in enumerate(dt.names):
     ...:     res[n] = temp[:,i]
     ...:
18.2 µs ± 1.63 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

But even with many rows, tuple conversion is faster:
In [334]: arr = np.random.randint(0,100,(100000,3)).astype('U10')
In [335]: alist = arr.tolist()
In [336]: timeit np.array([tuple(a) for a in alist], dtype=dt)
93.5 ms ± 322 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
In [337]: %%timeit
     ...: res = np.zeros(len(alist), dtype=dt)
     ...: temp = np.array(alist)
     ...: for i,n in enumerate(dt.names):
     ...:     res[n] = temp[:,i]
     ...:
124 ms ± 114 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

Pulling the tuple comprehension out of the timing loop saves some time:
In [341]: %%timeit temp = [tuple(a) for a in alist]
     ...: np.array(temp, dtype=dt)
     ...:
65.4 ms ± 98.3 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

Pulling the str array creation out of the timing:
In [342]: %%timeit temp = np.array(alist)
     ...: res = np.zeros(len(alist), dtype=dt)
     ...: for i,n in enumerate(dt.names):
     ...:     res[n] = temp[:,i]
     ...:
71 ms ± 447 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

Simply creating an string array from the list is more expensive than the tuple conversion.

A: As I described in this post in this post it works with dtype = 'object'
print(numpy.array([[u'1.2', u'1.3', u'hello'], [u'1.4', u'1.5', u'hi']], dtype='object'))

(works with python 3.7.1)


text: Q: Android Studio 2.1 is not opening after updating Java jDK 8? Now i updated android studio to 2.1 and JDK to version 8.but android studio is not opening.i changed the environment variable to JDK 8.still its not working.let me know what i did wrong .


text:
Q: glCreateShader gives same ID Background :
I have a Shader class in my c++/OpenGL3.1/GLSL/Qt program. My program uses several shaders based on different GLSL sources files.
My application can run many different 3D renderers based on the QGLWidget implementation and each one creates its own shaders.
When I create my first 3d renderer and initialize my shaders, shaders IDs are generated with the help of glCreateShader & glCreateProgram, without any problem.
Problem :
But when I create a second 3d renderer, the OGL functions retrieving the ID give exactly the same but I expect to have new ones. It means that my two renderers will send the data to the same GPU program...
It's obvious that in the GPU program, uniform variables are mixed and when running the second renderer, the first one displays a weird rendering.
Indeed, when I close one of the two renderer, all shaders are killed... and the second renderer cannot display anything.
Idea ?
I'm completely lost and my logical deduction is that glCreateShader & glCreateProgram give ID according to their own thread id. QGLWidget running probably its own thread to call the rendering functions, it may trouble the persistence...
Any idea of how to solve this problem  ?

A: If both your QOpenGLWidget share the same parent window, then by default they share the same context. If you don't want that, the easier is probably to create a new top-level widget (any QWidget with no parent) with your second QOpenGLWidget.
Please note that this is different from the older QGLWidget class. From Qt documentation:

When multiple QOpenGLWidgets are added as children to the same top-level widget, their contexts will share with each other. This does not apply for QOpenGLWidget instances that belong to different windows.
This means that all QOpenGLWidgets in the same window can access each other's sharable resources, like textures, and there is no need for an extra "global share" context, as was the case with QGLWidget.

A: There is no problem to solve.
Each QGLWidget has its own OpenGL context. And, unless you are explicitly sharing objects between them, each context has its own separate list of objects.
You can only use an OpenGL object with the OpenGL context that created it. So long as you keep the objects separate, and only use them with the context that created it, you should be fine.


text:
Q: Simple templating with str_replace I'm just experimenting first of all.
I just came up with an idea of making my own in a simple way here:
class Template
{
    function parse($template_file, $braces)
    {
        if(file_exists($template_file))
        {
            $template = file_get_contents($template_file);

            foreach($braces as $brace => $replacement)
            {
                $brace = trim(strtoupper($brace));
                $build = str_replace('{' . $brace . '}', $replacement, $template);
            }

            echo $build;
        }
        else
        {
            trigger_error('Template file does not exist: ' . $template_file, E_ERROR);
        }
    }
}

This in order to work:
$template = new Template();

$template->parse('index_body.html', array('ONE' => 'one',
                                          'TWO' => 'two',
                                          'THREE' => 'three'));

index_body.html:
{ONE}
{TWO}
{THREE}

The problem is, that it only outputs:
{ONE} {TWO} three

It always replaces the last brace, how come not the whole array?

A: $build = str_replace('{' . $brace . '}', $replacement, $template);
                                                       ^^^^^^^^^

You're always replacing against the original template, never against the updated one. Either keep assigning $template, or update $build

A: $template = file_get_contents($template_file);

$build = $template;

foreach($braces as $brace => $replacement)
                {
                    $brace = trim(strtoupper($brace));
                    $build = str_replace('{' . $brace . '}', $replacement, $build);
                }

A: It only replaces the last place because in each case, you're replacing the value in the original $template variable. It's not updating the variable each iteration.

A: You echo $build, which is being reassigned every foreach iteration.
You should've written this instead
 $template = str_replace('{' . $brace . '}', $replacement, $template);

A: How about using like full php engine power (similar to smarty interface):
just for experimenting:
class Template {
    private $_file;
    private $_variables = array();

    public function __construct($file = null) {
        $this->_file = $file;
    }

    public function set($key, $value) {
        $this->_variables[$key] = $value;
    }
    public function fetch($file = null) {
        if (!$file) {
            $file = $this->_file;
        }

        extract($this->_variables);
        ob_start();

        require($file);

        $content = ob_get_contents();

        ob_end_clean();

        return $content;
    }

    public function display($file = null) {
        if (!$file) {
            $file = $this->_file;
        }

        $result = $this->fetch($file);

        echo $result;
    }
}

=============

$tpl = new Template('hello.tpl');
$tpl->set('world', 'earth');
$tpl->display();

=============
Template sample:hello.tpl

Hello <?=$world;?>

A: Your $build is overwritten in each iteration.  This will solve the issue.
class Template
{
    function parse($template_file, $braces)
    {
        if(file_exists($template_file))
        {
            $template = file_get_contents($template_file);

            foreach($braces as $brace => $replacement)
            {
                $brace = trim(strtoupper($brace));
                $temp = str_replace('{' . $brace . '}', $replacement, $template);//create a temporary array
                $build  = array_merge($build ,$temp);
            }

            echo $build;
        }
        else
        {
            trigger_error('Template file does not exist: ' . $template_file, E_ERROR);
        }
    }
}


text:
Q: Macro shortcut problem with texstudio I'm using TeXstudio 2.12.6 for mac. The shortcuts for macros can be customized in Preference, but these shortcuts seem to be bound to the positions of the macros in the list, rather than the names of the macros. So, for example, if there're two macros A,B at the beginning, with shortcuts a,b, and I add another macro C between A and B, then the shortcut b would be bound to C, rather than B. How can I prevent this automatic change of shortcuts when macros are added or removed?

A:  Converting my comment into a community wiki answer, and kindly request to be informed to delete this answer in the future should the feature request be fulfilled by the TXS core developers.
This is a known issue since 2014, and is currently in the feature request list.
The desired functionality is not available as an option currently as far as I can tell.


text:
Q: MySQL: Loop through databases and run a stored procedure on it I'm very new to MySQL and I have a stored procedure that I'd like to add to several legacy databases.  I'm using SQLyog and I would like to loop through each database on the connection and if it matches 'application_%' (databases are called application_clientName, there are dozens) to run the stored procedure.
A script I can save and run through SQLyog would be ideal.
I'm kind of looking to loop through all the databases in SHOW DATABASES and run a statement if their name is LIKE 'application_%'. The statement will create a generic stored procedure in that database.

A: Okay, it looks like the SCHEMATA table in the information_scheme database contains a list of all databases. Thus, in order to get a list of all the databases you want to run the procedure on, you can do:
SELECT schema_name FROM information_schema.schemata
WHERE schema_name LIKE 'application_%';

The next step is to work this into some kind of procedure. Unfortunately, MySQL doesn't do well with executing dynamically generated SQL if it involves creating procedures. Thus, the purely-SQL version I came up with is a bit messy. It comes down to first creating the 'generator' procedure, then calling it, and finally executing the result of the generator:
delimiter //
DROP PROCEDURE IF EXISTS create_procedures//
CREATE PROCEDURE create_procedures()
BEGIN
    DECLARE done INT DEFAULT 0;
    DECLARE db VARCHAR(255);
    DECLARE appDBs CURSOR FOR SELECT schema_name FROM information_schema.schemata WHERE schema_name LIKE 'application_%';
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;

    SET @procName = "simpleproc"; -- Change this to your proc name

    SET @output = "delimiter //";

    OPEN appDBs;
    REPEAT
        FETCH appDBs INTO db;
        IF NOT done THEN
            -- Replace this procedure declaration with your procedure.
            -- Make sure to keep the ',db,' syntax there.
            -- You should really only have to change the parameters
            -- and the stuff between the BEGIN and END clauses.
            SET @output = CONCAT(@output,'
    DROP PROCEDURE IF EXISTS ',db,'.',@procName,'//
    CREATE PROCEDURE ',db,'.',@procName,'()
        BEGIN
            SELECT 1;
        END//');

        END IF;
    UNTIL done END REPEAT;

    CLOSE appDBs;

    SET @output = CONCAT(@output,'\ndelimiter ;');

    SELECT @output AS procs;
END//
delimiter ;

After this procedure is generated, call the procedure:
CALL create_procedures();

This will output a single column that contains the SQL necessary to create procedures for all the application_% tables. Select the entire column (it'll be rather long), and execute it as a new SQL query.
I've never used SQLyog, but if that doesn't work properly, then you may need to use MySQL's command line interface. First, generate a file input.sql containing:
CALL create_procedures();

Then execute the following commands:
mysql -u <username> -p --database=<dbname> -N -r -B < input.sql > proc.sql
mysql -u <username> -p --database=<dbname> < proc.sql

changing <username> and <dbname> to appropriate values (<dbname> can be any database you have permission to access). If you don't run into any errors, then you should have stored procedures defined for every database.


text:
Q: iOS Cache Library not working I built a VERY simple cache class for my iOS app yet while it seems to save the data given to it it's never able to retrieve it. My Cache system should work by creating a CachedObject that stores the Object to cache, the key, and an expiration date. It then should archive that object and save to a file named key.cache.
Cache.h
    #import <Foundation/Foundation.h>

    @interface Cache : NSObject

    +(void)setValue:(NSObject<NSCoding> *)value forKey:(NSString *)key expires:(NSDate *)expire;

    +(NSObject<NSCoding> *)getValueFromKey:(NSString *)key;

    @end

Cache.m
    #import "Cache.h"
    #import "CachedObject.h"
    #define CACHE_LOCATION @"Library/test"

    @implementation Cache

    +(void)setValue:(NSObject<NSCoding> *)value forKey:(NSString *)key expires:(NSDate *)expire
    {
        if ((value == nil) || (key == nil))
        {
            return;
        }
        CachedObject *obj = [[CachedObject alloc] initWithObject:value expires:expire forKey:key];
        NSError *error;
        if (![[NSFileManager defaultManager] createDirectoryAtPath:CACHE_LOCATION withIntermediateDirectories:YES attributes:nil error:&error])
        {
            [error release];
            return;
        }
        NSString *fileName = [[NSString alloc] initWithFormat:@"%@.cache", key];
        NSString *fileFullPath = [CACHE_LOCATION stringByAppendingPathComponent:fileName];
        [NSKeyedArchiver archiveRootObject:obj toFile:fileFullPath];
        [fileName release];
        [obj release];
    }

    +(NSObject<NSCoding> *)getValueFromKey:(NSString *)key
    {
        NSString *fileName = [[NSString alloc] initWithFormat:@"%@.cache", key];
        NSString *fileFullPath = [CACHE_LOCATION stringByAppendingPathComponent:fileName];
        CachedObject *obj = [NSKeyedUnarchiver unarchiveObjectWithFile:fileFullPath];
        NSDate *today = [NSDate date];
        if ((obj != nil) && (obj.expires != nil) && ([obj.expires compare:today] != NSOrderedAscending))
        {
            obj = nil;
        }
        [fileName release];
        if (obj != nil)
        {
            obj = [obj autorelease];
        }
        return obj;
    }

    @end

CachedObject.h
    #import <Foundation/Foundation.h>

    @interface CachedObject : NSObject<NSCoding>
    {
        NSObject<NSCoding> *_object;
        NSDate       *_expires;
        NSString     *_key;
    }

    @property (readonly) NSObject<NSCoding> *object;
    @property (readonly) NSDate       *expires;
    @property (readonly) NSString     *key;

    -(id)initWithObject:(NSObject<NSCoding> *)aObject expires:(NSDate *)aExpires forKey:(NSString *)aKey;

    @end

CachedObject.m
    #import "CachedObject.h"
    #define EXPIRE_KEY @"expires"
    #define KEY_KEY @"key"

    @implementation CachedObject

    @synthesize object = _object;
    @synthesize expires = _expires;
    @synthesize key = _key;

    -(void)encodeWithCoder:(NSCoder *)aCoder
    {
        [_object encodeWithCoder:aCoder];
        [aCoder encodeObject:_expires forKey:EXPIRE_KEY];
        [aCoder encodeObject:_key forKey:KEY_KEY];
    }

    -(id)initWithCoder:(NSCoder *)aDecoder
    {
        if (self = [super init])
        {
            _object = [_object initWithCoder:aDecoder];
            if (self.object == nil)
            {
                return nil;
            }
            _expires = [[aDecoder decodeObjectForKey:EXPIRE_KEY] retain];
            _key = [[aDecoder decodeObjectForKey:KEY_KEY] retain];
        }
        return self;
    }

    -(id)initWithObject:(NSObject<NSCoding> *)aObject expires:(NSDate *)aExpires forKey:(NSString *)aKey
    {
        if (self = [super init])
        {
            _object = aObject;
            _expires = aExpires;
            _key = aKey;
        }
        return self;
    }

    @end

A: According to the NSComparator docs,
NSArray *sortedArray = [array sortedArrayUsingComparator: ^(id obj1, id obj2) {

    if ([obj1 integerValue] > [obj2 integerValue]) {
        return (NSComparisonResult)NSOrderedDescending;
    }

    if ([obj1 integerValue] < [obj2 integerValue]) {
        return (NSComparisonResult)NSOrderedAscending;
    }
    return (NSComparisonResult)NSOrderedSame;
}];

You need to replace NSOrderedAscending with NSOrderedDescending in your -getValueForKey: method.

A: I think part of the issue might be the way you're serializing your _object instance variable inside CachedObject.m (Perhaps any NSCoding experts can prove me wrong?)
I think instead of:
-(void)encodeWithCoder:(NSCoder *)aCoder
    {
        [_object encodeWithCoder:aCoder];
        [aCoder encodeObject:_expires forKey:EXPIRE_KEY];
        [aCoder encodeObject:_key forKey:KEY_KEY];
    }

You want to use:
-(void)encodeWithCoder:(NSCoder *)aCoder
    {
        [aCoder encodeObject:_object forKey:OBJECT_KEY];
        [aCoder encodeObject:_expires forKey:EXPIRE_KEY];
        [aCoder encodeObject:_key forKey:KEY_KEY];
    }

Since you want to treat _object as an instance variable, similar to your _expires and _key objects.
Side Note: When autoreleasing objects, you don't need to do this:
if (obj != nil)
{
    obj = [obj autorelease];
}
return obj;

You can just do:
return [obj autorelease];


text:
Q: Get top users rank position depends on max count with join query Depends on highest count i want to get the rank for each user.
Here is the query:
SELECT @a:=@a+1 serial_number, `tbl_users`.`user_id`,
`tbl_users`.`first_name`,
`tbl_users`.`last_name`,
 COUNT(`tbl_qa_questions`.`question_id`) AS qs_count
FROM `tbl_qa_questions`
LEFT JOIN `tbl_users`
ON `tbl_qa_questions`.`user_id` = `tbl_users`.`user_id`
, (SELECT @a:= 0) AS a
WHERE 1 AND DATE(`tbl_qa_questions`.`post_date`) BETWEEN '2015-01-01' AND '2015-01-19'
AND `tbl_qa_questions`.`status` = 1
GROUP BY `tbl_qa_questions`.`user_id`
ORDER BY qs_count DESC  LIMIT 5

It is showing result
serial_number   user_id     first_name  last_name   qs_count
10              47          Sourav      Sen         26
11              32          Alan        Donald      15
9               587         Abraham     Harrison    2
8               586         Thomas      Broad       2
6               13          Sumanta     Sen         2

But it should:
serial_number   user_id     first_name  last_name   qs_count
1               47          Sourav      Sen         26
2               32          Alan        Donald      15
3               587         Abraham     Harrison    2
4               586         Thomas      Broad       2
5               13          Sumanta     Sen         2
.
.
.
29              14          xyz         Sen         2
30              15          abc         Sen         2
31              16          cdf         Sen         2

i.e. serial number for each row should be 1,2,3,4 and 5.

A: Just add the numbering in an outer query, nesting your aggregation. The problem is that the variable gets incremented before GROUP BY kicks in, so you get a bit random results. It's actually always the case when using something in SELECT that is not in GROUP BY, specific to MySQL (other DBs just give you error).
SELECT @a:=@a+1 serial_number, aa.* from (

sELECT
`tbl_users`.`first_name`,
`tbl_users`.`last_name`,
 COUNT(`tbl_qa_questions`.`question_id`) AS qs_count
FROM `tbl_qa_questions`
LEFT JOIN `tbl_users`
ON `tbl_qa_questions`.`user_id` = `tbl_users`.`user_id`
, (SELECT @a:= 0) AS a
WHERE 1 AND DATE(`tbl_qa_questions`.`post_date`) BETWEEN '2015-01-01' AND '2015-01-19'
AND `tbl_qa_questions`.`status` = 1
GROUP BY `tbl_qa_questions`.`user_id`
ORDER BY qs_count DESC  LIMIT 5
) aa


text:
Q: Where can I find a free C# eBook? Does anyone know a good (free) C# eBook for intermediate programmers? I want something that covers generics, threads, events, delegates, etc.

A: I found these two books fairly useful.
The C# School Book - this one covers just about everything you asked about, although it's a bit dated.
and of course, Rob Miles' C# Yellow Book

A: Here are a few open source books:

*

*C# Yellow Book

*C Sharp Programming

*Programmer's Heaven C# School Book

*Threading in C#

*C# Essentials

*.NET Book Zero

*Data Structures and Algorithms with Object-Oriented Design Patterns in C#


text:
Q: How can a URL change while reading the same article in WordPress? I saw a blog in which the URL is automatically changing while reading the content.
Example: If the actual URL for the post is www.example.com/articlereading
while I read this article in between half the article it changes automatically to www.example.com/articlereading-1 and after some more it changes to www.example.com/articlereading-2.
Can you please help me how to implement this in WordPress?

A: If I understand your question you are looking for a redirect. Have you tried this plugin https://wordpress.org/plugins/shortcode-redirect/.

A: You are asking to implement the infinite scroll with URL refresh via history.pushState().
For that you need to use the Jetpack plugin from wordpress.
It contains infinite scroll feature that you need to enable from settings panel of Jetpack. Also checkout how to embed the infinite scroll into theme.
For article single page , you can use Infinite Transporter which extends Jetpack's infinite scroll functionality.


text:
Q: Can the default size of Windows 7's "drag to the left or right to resize window" feature be changed? Windows 7 includes a feature for easily arranging windows on larger monitors - drag a window to the left or right side of the screen and it will be resized to use half the monitor (or drag to the top to maximize). The most obvious use of this is to drag one window to the left and one to the right to quickly get 2 side by side windows.
My question is, even on a 1920x1200 screen the width of a split window is not enough for many applications - in particular web pages tend to be designed for 1024x768 and up. Is there a way (registry?) to change the split between left and right? So that a window dragged to the left will be resized to 60% of the screen, and one to the right will occupy 40%?

A: I've been looking for about 30 minutes but everything I've found points to it being a hard-coded ratio within windows. I did find this setting in the registry:
HKEY_CURRENT_USER\Control Panel\Desktop
Snap Sizing. Mine is set to 1.
Not sure what it does but, since it's binary, I'd assume 1 is on and 0 is off. You may want to set it to 0, save, use Aero Snap, resize your windows, close and reopen to see if they 'remember' the previous size.

A: There is a program called WinSplit Revolution that will allow you to move and resize windows with preset sizes. You use hotkeys to move them.

A: From: http://www.sevenforums.com/customization/56312-how-change-default-window-size.html
"Hi lavecoi,
You can resize dialog boxes by click-and-dragging the textured area in the lower right corner of the window. Unfortunately there's no way to set a default size for dialog boxes, although your resizings will be remembered on a per-application basis between restarts.
Hope this was helpful...
Cheers,
Walker
Windows Outreach Team"


text:
Q: Запись данных в SQLite. orm sugar Получают с сервера json в котором хранится 18 тыс. записей. При выполнении метода  onResponse , приложение зависает. Использую orm sugar, retrofit
@Override
public void onResponse(Response<List<ModelJoke>> response, Retrofit retrofit) {
    List < ModelJoke > list=response.body();

    for (ModelJoke ob:list)
    {
        jokes=new dbJokes(ob.id,ob.cid,ob.value);
        jokes.save();
    }

    mProgressDialog.dismiss();
}

После завершения записи, приложение опять работает.
В чем может быть проблема?

A: Я пробовал использовать ваш вариант сохранения, работало через одно место
Попробуйте использовать SugarRecord.saveInTx(). У меня всё прекрасно с ним работает.


text:
Q: Distinguish knex client from knex transaction Knex promise-based transactions can be used like regular knex client.
const db = knex.transaction() //or just const db = require('knex')(knexOptions)
db('books').insert(books);    // it works in both case

I need to accept knex object as an argument of my function and execute transaction inside it.  Can i distingue somehow if knex object or knex transaction passed as argument? In case if this is not a transaction, I want to wrap client object with knex.transaction.
Could I use something like db.isTransaction syntax?
function myFunc(db) {
if (!db.isTransaction)
  {
    db=knex.transaction()
  }
db('books').insert(books);
}

A: Use the knex.isTransaction property to tell if the object is a knex transaction or a client.
function myFunction(db) {
  if (db.isTransaction) {
    console.log('Inside transaction')
    return db.from('table_1').select()
  } else {
    console.log('Wrapping client in a transaction')
    return db.transaction(trx => myFunction(trx))
  }
}

In both cases, you query should be executed within a transaction


text:
Q: Don't understand why I can't import music21 I am new to Python so I could perhaps learn the basics first... I'm a musician and keen to learn how to use Python with music.
I installed Python 3.8 x64 for Windows 10. I then used pip to install music21.
Opened the Python Shell, typed import music21 and got this:
    Python 3.8.0 (tags/v3.8.0:fa919fd, Oct 14 2019, 19:37:50) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> import music21
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    import music21
  File "D:\Python\lib\site-packages\music21\__init__.py", line 170, in <module>
    from music21 import base
  File "D:\Python\lib\site-packages\music21\base.py", line 94, in <module>
    from music21 import common
  File "D:\Python\lib\site-packages\music21\common\__init__.py", line 39, in <module>
    from music21.common.parallel import *
  File "D:\Python\lib\site-packages\music21\common\parallel.py", line 19, in <module>
    from music21.ext.joblib import Parallel, delayed  # @UnresolvedImport # type: ignore
  File "D:\Python\lib\site-packages\music21\ext\joblib\__init__.py", line 119, in <module>
    from .parallel import Parallel
  File "D:\Python\lib\site-packages\music21\ext\joblib\parallel.py", line 32, in <module>
    from .externals.cloudpickle import dumps, loads
  File "D:\Python\lib\site-packages\music21\ext\joblib\externals\cloudpickle\__init__.py", line 3, in <module>
    from .cloudpickle import *
  File "D:\Python\lib\site-packages\music21\ext\joblib\externals\cloudpickle\cloudpickle.py", line 167, in <module>
    _cell_set_template_code = _make_cell_set_template_code()
  File "D:\Python\lib\site-packages\music21\ext\joblib\externals\cloudpickle\cloudpickle.py", line 148, in _make_cell_set_template_code
    return types.CodeType(
TypeError: an integer is required (got type bytes)

I have found example code to run with music21 but I can't use it if I get errors.
Hope someone can help. Apologies if I'm being a complete n00b. Did look at other questions but didn't find or didn't understand the answers.

A: So from your output, the main piece that seems most useful is the TypeError: an integer is required (got type bytes) in the _make_cell_set_template_code function in the D:\Python\lib\site-packages\music21\ext\joblib\externals\cloudpickle\cloudpickle.py file. This issue could be an issue with music21 not being compatible with Python 3.8. I'm reading the documentation from https://web.mit.edu/music21/ and it says v.5 support Python 3.4-3.6, so I would try to get on one of those versions and restart the process you did to get to the step above. Hope this helps!

A: music21 v5 does not support Python 3.8 -- choose 3.7 or download the latest Git from github.
EDIT: v5.7.2 now supports 3.8


text:
Q: Renaming an SQL database in android When referring to database tables I usually use syntax like this: my_database_name.my_table_name
I am trying to do the same in Android but am having trouble understanding how to name a database.
Would you just execute this SQL as you would in the Sqlite3 client? i.e.
ATTACH "my_database_file" AS my_database_name;

Here is what I tried in my onCreate method:
db.execSQL("Attach 'hq_db' AS hq_db;");

but I'm getting this error:
04-05 11:13:35.676: ERROR/AndroidRuntime(860): Caused by: android.database.sqlite.SQLiteException: cannot ATTACH database within transaction: Attach 'hq_db' AS hq_db;

How do I execute SQL statements on Android outside of a transaction to make this work?
Edit: It might also have something to so with the superclass constuctor, though the super class constructor string sets the file name (which is working properly) and it seems nothing else:
private class databaseOpenHelper extends SQLiteOpenHelper {

        public q_player_databaseOpenHelper() {
            super(MyApp.getContext(), "my_db_file", null, 1);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {

            db.execSQL("Attach 'my_db_file' AS my_db_name;");
            db.execSQL("PRAGMA foreign_keys=ON;");

        }

Note: I have stripped this code down so it would fit my problem

A: You need to call db.execSQL("ATTACH 'hq_db' AS hq_db;"); before you start any kind of transaction. Do the attachment first, and then start the transaction.
Are you calling beginTransaction or executing SQL which begins a transaction before trying to attach your other database?

A: You're probably creating the database with AutoCommit=0.  This puts you in a transaction so that it doesn't need to write to the database file after every INSERT.  But it also means you can't ATTACH to another database.  Create the DB, set AutoCommit=1, ATTACH, then set AutoCommit=0.


text:
Q: Connect to SQL Server 2005 with PHP from linux I have Windows and Linux servers. SQL Server 2005 is installed on the Windows machine and I want to connect to Windows database from my other Linux server using PHP. Servers are in different locations.
I have tried everything but not successful. Here is my phpinfo output:
Configure Command    './configure' '--with-apxs2' '--with-curl=/usr/local/lib' '--with-gd' '--with-ttf' '--with-gettext' '--with-jpeg-dir=/usr/local/lib' '--with-freetype-dir=/usr/local/lib' '--with-kerberos' '--with-openssl' '--with-mcrypt' '--with-mhash' '--with-mysql=/usr' '--with-mysqli=/usr/bin/mysql_config' '--with-pdo-mysql=/usr' '--with-unixODBC=/usr' '--with-pcre-regex=/usr/local' '--with-pear' '--with-png-dir=/usr/local/lib' '--with-xsl' '--with-mssql=/usr/local/freetds' '--with-pdo-dblib=/usr/local' '--with-zlib' '--with-zlib-dir=/usr/local/lib' '--with-iconv=/usr/local' '--enable-bcmath' '--enable-calendar' '--enable-exif' '--enable-ftp' '--enable-gd-native-ttf' '--enable-magic-quotes' '--enable-safe-mode' '--enable-soap' '--enable-sockets' '--enable-mbstring' '--enable-zip' '--enable-wddx'

ODBC support, dblib, Mssql are enabled.
There is no firewall on the Windows machine. I have forwarded 1433 port from modem. I am able to connect from Windows sql studio, from WAMP on my machine (local), but not able to connect from PHP :(
Any suggestions?

A: Have you configured your these files on your Linux server?  (These are taken from an Ubuntu 12.04 server)
/etc/odbc.ini
# Define a connection to the MSSQL server.
# The Description can be whatever we want it to be.
# The Driver value must match what we have defined in /etc/odbcinst.ini
# The Database name must be the name of the database this connection will connect to.
# The ServerName is the name we defined in /etc/freetds/freetds.conf
# The TDS_Version should match what we defined in /etc/freetds/freetds.conf
[mssql]
Description             = MSSQL Server
Driver                  = freetds
Database                = MyDatabase
ServerName              = mssql
TDS_Version             = 8.0

/etc/odbcinst.ini
# Define where to find the driver for the Free TDS connections.
[freetds]
Description     = MS SQL database access with Free TDS
Driver          = /usr/lib/i386-linux-gnu/odbc/libtdsodbc.so
Setup           = /usr/lib/i386-linux-gnu/odbc/libtdsS.so
UsageCount      = 1

/etc/freetds/freetds.conf
# The basics for defining a DSN (Data Source Name)
# [data_source_name]
#       host = <hostname or IP address>
#       port = <port number to connect to - probably 1433>
#       tds version = <TDS version to use - probably 8.0>

# Define a connection to the MSSQL server.
[mssql]
        host = mssql_server_ip_or_domain_name
        port = 1433
        tds version = 8.0

I've read several accounts of the tds version causing problems. It seems like 8.0 words best but I've also seen people say they got things working with 7.5 and 7.0.
And here's an example PDO connection:
$pdo = new PDO("dblib:dbname=$database_name;host=$database_server", $temp_username, $temp_password);


text:
Q: Como atribuir efeitos de clique em um ImageButton? Por exemplo,
Adicionei ao meu layout xml uma ImageButton, coloquei uma imagem e deixei com background transparente, por ter feito isso ele perdeu as características de um botão, como faço para adicionar efeito de clique?

A: Você precisa criar um drawable para ele, informando quais as cores para os respectivos estados. Para isto, crie um arquivo .xml dentro da pasta drawable:
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_pressed="true">
        <shape>
            <solid android:color="@color/sua_cor_selecionado" />
            <padding android:bottom="3dp" android:left="3dp" android:right="3dp" android:top="3dp" />
        </shape>
    </item>
    <item android:state_focused="true">
        <shape>
            <solid android:color="@android:color/transparent" />
            <padding android:bottom="3dp" android:left="3dp" android:right="3dp" android:top="3dp" />
        </shape>
    </item>
    <item android:state_enabled="false">
        <shape>
            <solid android:color="@android:color/transparent" />
            <padding android:bottom="3dp" android:left="3dp" android:right="3dp" android:top="3dp" />
        </shape>
    </item>
    <item>
        <shape>
            <solid android:color="@android:color/transparent" />
            <padding android:bottom="3dp" android:left="3dp" android:right="3dp" android:top="3dp" />
        </shape>
    </item>

</selector>

E, após criar, atribua em seu ImageButton:
<ImageButton
    android:id="@+id/seu_botao"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/seu_arquivo_criado"/>


text:
Q: Some images among thousands return 403 Forbidden When downloading a large amount of pictures (via cURL / file_get_contents) from a server, about 99% of them display smoothly on a website, but a few of them (around 15-20 out of over 15k) do not show up. Instead, they return a 403 Forbidden error.
Permissions have been set to 777 for all files and folders but nothing changes.
Has anyone else had the same problem and was able to solve it?

A: You can try to create a php script that returns content of files
<?php
$file = file_get_contents("path/to/file");
//You can add headers using header("..."); for make sure that images will works.
//var_dump($file);exit; // uncomment to check is it even loading #debug
die($file);

A: The filenames of the 403 images all contained inside the word "chat". That's the reason why the server returned 403 Forbidden.
Hope someone find it helpful


text:
Q: Please explain this regex I have regex which reads:
@"]*>(?:\s*?)?

Can someone please explain this part:  (?:\s*?)?
What is that?

A: match but don't capture any number of whitespace followed by a close image tag, zero or one times:
(?: = match but don't capture

\s*? = any number of whitespace (not greedy)

 = close image tag

)? = zero or one times

:)

A: (?:\s*?) selects any whitespace, if it exists, after the image tag. The ?: at the beginning tells the regex engine to not capture that group (meaning it won't be returned in the matches array)

A: non-capturing group of any number of whitespace characters, followed by a closing img tag

A: The entire expression will capture any  tags that have corresponding  tags (but it won't capture the close tags). It doesn't capture the close tags because the (?:) syntax means "match but don't capture".
Some restrictions that are part of this regex:

*

*The \s* in the opening tag is redundant because [^>]* will capture this too

*Only whitespace is allowed between the opening and closing tags

Some examples:

*

* will not match

* will match, but only capture

* will match, but only capture

*<imgabc> will not match

*   will match, but only capture

*ab will not match

I highly recommend the Regular Expression Designer available for free at www.radsoftware.com.au for testing regexs


text:
Q: RecyclerView in NestedScrollView is not working in android I have list of item which I want to display in recyclerview and in the  main layout I added CollapsingToolbarLayout .Before applying CollapsingToolbarLayout recyclerview worked fine but after adding it to layout it is not visible.
Here is the layout file in which i added collapsingtoolbar layout
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/main_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/MyAppbar"
        android:layout_width="match_parent"
        android:layout_height="256dp"
    android:fitsSystemWindows="true">

    <android.support.design.widget.CollapsingToolbarLayout
        android:id="@+id/collapse_toolbar"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_scrollFlags="scroll|exitUntilCollapsed"
        android:background="@color/material_deep_teal_500"
        android:fitsSystemWindows="true">

        <android.support.v7.widget.Toolbar
            android:id="@+id/MyToolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:layout_collapseMode="parallax" />

    </android.support.design.widget.CollapsingToolbarLayout>

</android.support.design.widget.AppBarLayout>

<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="fill_vertical"
app:layout_behavior="@string/appbar_scrolling_view_behavior">

    <android.support.v7.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="fill_parent"
        android:id="@+id/rv"
        />

</android.support.v4.widget.NestedScrollView>

    </android.support.design.widget.CoordinatorLayout>

I followed this tutorial to work with collapsingtoolbarlayout
here is the main activity
  protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final Toolbar toolbar = (Toolbar) findViewById(R.id.MyToolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        CollapsingToolbarLayout collapsingToolbar =
                (CollapsingToolbarLayout) findViewById(R.id.collapse_toolbar);
        collapsingToolbar.setTitle("My Toolbar Tittle");
        ArrayList<AppModel> arrayList = getDataFromDataBase();
        try {
            RecyclerView recyclerView = (RecyclerView)findViewById(R.id.rv);
            recyclerView.setHasFixedSize(false);

            recyclerView.setItemAnimator(new DefaultItemAnimator());
            recyclerView.setLayoutManager(new LinearLayoutManager(this));
            recyclerView.setAdapter(new AppsListAdapter(this,arrayList));
        }catch (Exception e){
            Toast.makeText(this,e.getMessage(),Toast.LENGTH_LONG).show();
        }

here are my gradle dependencies
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:design:23.0.1'
    compile 'com.android.support:appcompat-v7:23.0.1'
    compile 'com.android.support:design:23.0.1'
    compile 'com.android.support:cardview-v7:22.2.0'
    compile 'com.android.support:recyclerview-v7:22.2.0'
}

I have tried with solutions for the similar question in stackoverflow but it didn't work.Please help me .did i do any thing wrong ?

A: no need to use nestedscrollview, you only need the recyclerview
    <?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/main_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/MyAppbar"
        android:layout_width="match_parent"
        android:layout_height="256dp"
    android:fitsSystemWindows="true">

    <android.support.design.widget.CollapsingToolbarLayout
        android:id="@+id/collapse_toolbar"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_scrollFlags="scroll|exitUntilCollapsed"
        android:background="@color/material_deep_teal_500"
        android:fitsSystemWindows="true">

        <android.support.v7.widget.Toolbar
            android:id="@+id/MyToolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:layout_collapseMode="parallax" />

    </android.support.design.widget.CollapsingToolbarLayout>

</android.support.design.widget.AppBarLayout>

    <android.support.v7.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="fill_parent"
        android:id="@+id/rv"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
        />

    </android.support.design.widget.CoordinatorLayout>


text:
Q: how to reshape a dataset for RNN/LSTM model? I am trying to build an RNN/LSTM model for binary classification 0 or 1
a sample of my dataset (patient number, time in mill/sec., normalization of X Y and Z, kurtosis, skewness, pitch, roll and yaw, label) respectively.
1,15,-0.248010047716,0.00378335508419,-0.0152548459993,-86.3738760481,0.872322164158,-3.51314800063,0

1,31,-0.248010047716,0.00378335508419,-0.0152548459993,-86.3738760481,0.872322164158,-3.51314800063,0

1,46,-0.267422664673,0.0051143782875,-0.0191247001961,-85.7662354031,1.0928406847,-4.08015176908,0

1,62,-0.267422664673,0.0051143782875,-0.0191247001961,-85.7662354031,1.0928406847,-4.08015176908,0

and this my code
import numpy as np
from keras.datasets import imdb
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
from keras.layers import Bidirectional
from keras.preprocessing import sequence
# fix random seed for reproducibility
np.random.seed(7)

train = np.loadtxt("featwithsignalsTRAIN.txt", delimiter=",")
test = np.loadtxt("featwithsignalsTEST.txt", delimiter=",")

x_train = train[:,[2,3,4,5,6,7]]
x_test = test[:,[2,3,4,5,6,7]]
y_train = train[:,8]
y_test = test[:,8]

# create the model
model = Sequential()
model.add(LSTM(20, dropout=0.2, input_dim=6))
model.add(Dense(4, activation = 'sigmoid'))
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
model.fit(x_train, y_train, epochs = 2)

I am trying to reshape the dataset to be able to feed it to an RNN/LSTM model.
because it gives me the following error

Error when checking input: expected lstm_1_input to have 3 dimensions,
  but got array with shape (1415684, 6)

can anyone help me?
thanks in advance.

A: What you need is TimeseriesGenerator which converts your data into sequences of a fixed window size. Currently you are passing the entire dataset (..., 6), if you use a sliding window let's say size 10 (this might not necessary correspond to 10ms depending on your data), the generator will give inputs of shape (..., 10, 6) which is what the LSTM expects. The LSTM will process the 10 timesteps, ie the datapoints in that window and the model will make a prediction.


text:
Q: I want to continue to process image and store it when iOS App in background I tried to use NSOperation and NSOperationQueue.
But As getting into background, NSOperation didn't work. it stopped.
Calling
- (void)viewDidLoad
{
    findFQueue = [[NSOperationQueue alloc] init];
    FindFeatureOperation *testOperation = [[FindFeatureOperation alloc] init];
    [findFQueue addOperation:testOperation];
}

NSOperation define
#import "FindFeatureOperation.h"

@implementation FindFeatureOperation
- (void)main
{
for (int i = 0; i < 999999 ; i++) {
    NSLog(@"Operation %d", i);
    [NSThread sleepForTimeInterval:1];
}
}
@end

Let me Know Please.

A: 1 way: inside the op
to keep just running the operation:
- (main) {
    bgTask = [application beginBackgroundTaskWithExpirationHandler:^{
        // Clean up any unfinished task business by marking where you
        // stopped or ending the task outright.
        [application endBackgroundTask:bgTask];
        bgTask = UIBackgroundTaskInvalid;
    }];

    for (int i = 0; i < 999999 ; i++) {
        NSLog(@"Operation %d", i);
        [NSThread sleepForTimeInterval:1];
    }

    [application endBackgroundTask];
}

2 way: using inside of applicationDidEnterBG:
- (void)applicationDidEnterBackground:(UIApplication *)app {
    _bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
         // When Expired the limit time for background NSLog(@"Expired Background Task Limit Time");
             [app endBackgroundTask:_bgTask];
            _bgTask = UIBackgroundTaskInvalid;
         }];
        dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
             [findFQueue waitUntilAllOperationsAreFinished];
            [app endBackgroundTask];
        });
}

Note: you can still be canceled if you use too much cpu / men / energy ... see the docs
Note 2: This can be written anywhere. I placed it in the OP but maybe in the VC is a better place... I don't think so but might be
Note 3: Read the docs! :: https://developer.apple.com/library/ios/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/ManagingYourApplicationsFlow/ManagingYourApplicationsFlow.html


text:
Q: Fabric: Issues running a def runtime(): So I'm just starting on Python and trying to craft my second script using fabric and localhost.  Following the documentation here: How to use Fabric in Python.
from fabric.api import *

env.user = 'skeer'
env.password = 'PASSWORD'
env.hosts = ['localhost']

def runtime():
    run("uptime")
    print()

The python console returns finished with exit code 0.  Should I be expecting the value for uptime returned instead?  Am I doing something wrong?


text:
Q: The precision of scipy.special.gammaln The Problem
A lot of my programming involves the statistics functions in scipy.stats. A new problem required computing the pmf of the beta-binomial distribution. Because it has an analytic form, but doesn't show up in scipy.stats, I needed to define a function for its pmf myself. I am using scipy version 0.12.0 and numpy version 1.7.0.
import numpy
from scipy.special import gammaln, betaln

def beta_binomial_pmf(k, n, K, N):
    # compute natural log of pmf
    ln_pmf = ( gammaln(n+1) - gammaln(k+1) - gammaln(n-k+1) ) + \
        - betaln(K+1,N-K+1) + betaln(K+k+1,N-K+n-k+1)
    return numpy.exp(ln_pmf)

In the statistics problem I am trying to solve the values of n and k normally range between 0 and 100, but K and N can be as large as 1e9. My issue is that this function will return the same value for different inputs.
Examples
k = 0
n = 5
K = numpy.array([12, 10, 8])
N = 101677958
beta_binomial(k, n, L, N)

The resulting array is
array([ 0.99999928,  0.99999905,  0.99999928])

which is rather odd given that each of values of K is different. To get a better sense of the similarity between the first and third values in the array
1 - beta_binomial(k, n, L, N)
array([  7.15255482e-07,   9.53673862e-07,   7.15255482e-07])

A really simple test of the precision of the gammaln function is 1-(Gamma(N+1)/Gamma(N))/N. It is useful because the result is exactly 0 if you work out the algebra on paper.
N = numpy.logspace(0,10,11)
1-numpy.exp(gammaln(N+1)-gammaln(N))/N
array([  0.00000000e+00,  -1.11022302e-15,   1.90958360e-14,
    -9.94537785e-13,  -4.96402919e-12,   7.74684761e-11,
    -1.70086167e-13,   1.45905219e-08,   2.21033640e-07,
    -7.64616381e-07,   2.54126535e-06])

Question
I recognize that there is a limit to the precision one can compute, but what happens at around N=1e7 that makes the precision change in gammaln by five orders of magnitude? Suggestions on how to get around this problem?

A: Your problem has to do with loss of floating point precision in subtractions. This in fact does not depend on the precision of Scipy's gammaln and betaln. The issue is that for large N, gammaln(N+1) is of the same order of magnitude as gammaln(N), but much bigger than gammaln(N+1)-gammaln(N). As a consequence, when you compute the difference, you lose ~ log10(gammaln(N)) digits of precision. This is a general issue with floating point.
You can work around this via asymtotic expansions (cf. betaln implementation, which has to deal with the same issue). Namely, you can use an expansion for Gamma(a + b) - Gamma(a) for a >> |b|, 1. In Sympy:

In [44]: def lnstirling3(z): return (z - sympify('1/2')) * log(z) - z + log(sqrt(2*pi)) + 1/(12*z) - 1/(360*z*z*z)

In [45]: a, b = symbols('a, b')

In [46]: (lnstirling3(a + b) - lnstirling3(a)).series(a, oo, 4)

 4    3    2      3    2         2
b    b    b      b    b    b    b    b
── - ── + ──   - ── + ── - ──   ── - ─
12   6    12     6    4    12   2    2        ⎛1⎞    ⎛1        ⎞
──────────── + ────────────── + ────── - b⋅log⎜─⎟ + O⎜──; a → ∞⎟
      3               2           a           ⎝a⎠    ⎜ 4       ⎟
     a               a                               ⎝a        ⎠

Similar asymptotic formulas can be derived for your pmf in a similar way, and they can be used instead of the usual expression when the parameters have large values.
EDIT: if you are feeling lazy, you can use the original formula together with mpmath and turn on a higher precision via mpmath.mp.dps. Be sure to cast k, n, K, N to mpmath.mpf first, before summing them, however.


text:
Q: opengl make spotlight act like a flashlight I'm trying to mimic a flashlight in opengl. Basically I want the spotlight to be in the same position as the camera and point in the same direction that the camera is pointing in.
Here is my code:
gluLookAt (xAt, yAt, zAt, xLookAt, yLookAt, zLookAt, 0, 1, 0);
light_pos [4] = {xAt, yAt, zAt, 1.0};
glLightfv (GL_LIGHT0, GL_POSITION, light_pos);

spotDir [] = {xLookAt - xAt, yLookAt - yAt, zLookAt - zAt};
glLightfv (GL_LIGHT0, GL_SPOT_DIRECTION, spotDir);

I've made calls to initialize the light and I've calculated the surface normals of all my objects.
Now the above code kind of works, when the camera is moved then the spotlight follows. However when I move the camera closer to an object the object gets less light shone on it. And when I move the camera further away the object gets more light.
I want the opposite to happen - the further away the camera is from an object there should be less light being shone on the object. How is this done? Or is this not the behaviour of an opengl spotlight?

A: So I looked into this and apparently modifying the attenuation of the light will yield correct results. Hope this helps anyone else who stumbles across this.


text:
Q: Direct2D - Emulating Color Keyed Transparent Bitmaps I'm currently updating a Windows GDI application to use Direct2D rendering and I need to support "transparent" bitmaps via color-keying for backwards compatibility.
Right now I'm working with a HWND render target and a converted WIC bitmap source (to GUID_WICPixelFormat32bppPBGRA).  My plan so far is to create a IWICBitmap from the converted bitmap, Lock() it, and then process each pixel setting it's alpha value to 0 if it matches the color key.
This seems a bit "brute force" - Is this the best method of approaching this or is there a better way?
Edit: In the interests of completeness here's an extract of what I went with - looks like it's working fine but I'm open to any improvements!
// pConvertedBmp contains a IWICFormatConverter* bitmap with the pixel
// format set to GUID_WICPixelFormat32bppPBGRA

IWICBitmap* pColorKeyedBmp = NULL;
HRESULT hr    = S_OK;
UINT    uBmpW = 0;
UINT    uBmpH = 0;

pConvertedBmp->GetSize( &uBmpW, &uBmpH );

WICRect rcLock = { 0, 0, uBmpW, uBmpH };

// GetWIC() returns the WIC Factory instance in this app
hr = GetWIC()->CreateBitmapFromSource( pConvertedBmp,
                                       WICBitmapCacheOnLoad,
                                       &pColorKeyedBmp );
if ( FAILED( hr ) ) {
   return hr;
}

IWICBitmapLock* pBitmapLock = NULL;
hr = pColorKeyedBmp->Lock( &rcLock, WICBitmapLockRead, &pBitmapLock );
if ( FAILED( hr ) ) {
   SafeRelease( &pColorKeyedBmp );
   return hr;
}

UINT  uPixel       = 0;
UINT  cbBuffer     = 0;
UINT  cbStride     = 0;
BYTE* pPixelBuffer = NULL;

hr = pBitmapLock->GetStride( &cbStride );
if ( SUCCEEDED( hr ) ) {
   hr = pBitmapLock->GetDataPointer( &cbBuffer, &pPixelBuffer );
   if ( SUCCEEDED( hr ) ) {

      // If we haven't got a resolved color key then we need to
      // grab the pixel at the specified coordinates and get
      // it's RGB

      if ( !clrColorKey.IsValidColor() ) {
         // This is an internal function to grab the color of a pixel
         ResolveColorKey( pPixelBuffer, cbBuffer, cbStride, uBmpW, uBmpH );
      }

      // Convert the RGB to BGR
      UINT   uColorKey = (UINT) RGB2BGR( clrColorKey.GetRGB() );
      LPBYTE pPixel    = pPixelBuffer;

      for ( UINT uRow = 0; uRow < uBmpH; uRow++ ) {

         pPixel = pPixelBuffer + ( uRow * cbStride );

         for ( UINT uCol = 0; uCol < uBmpW; uCol++ ) {

            uPixel = *( (LPUINT) pPixel );

           if ( ( uPixel & 0x00FFFFFF ) == uColorKey ) {
              *( (LPUINT) pPixel ) = 0;
           }
           pPixel += sizeof( uPixel );
        }
     }
   }
}

pBitmapLock->Release();

if ( FAILED( hr ) ) {
   // We still use the original image
   SafeRelease( &pColorKeyedBmp );
}
else {
   //  We use the new image so we release the original
   SafeRelease( &pConvertedBmp );
}

return hr;

A: If you only need to "process" the bitmap to render it, then the fastest is always GPU. In Direct2D there are effects (ID2D1Effect) for simple bitmap processing. You can write your own [it seems comparatively complicated], or use one of the built-in effects [which is rather simple]. There is one called chroma-key (CLSID_D2D1ChromaKey).
On the other hand, if you need to do further processing on CPU, it gets more complex. You might be better off optimizing the code you have.


text:
Q: Know this "maximum of sums towards minimum" distribution? Let we have N integer slots initially containing 0's and an infinite sequence of similar independent negative binomial variables wi ~ NB(l, q). Each next value from the sequence is added to the slot containing the minimal value. The question is: what is the distribution of the step number at which any of the slots exceeds given limit k?
If you ask, it's a simplified model of attack on vulnerable ("one unit lost means all die") stack of units in Freeciv game.


text:
Q: Remember me functionality in IBM Worklight We are using Worklight 6.1 for our app. I want the app to remember the user id (with no limitation on the duration & it should be accurate & reliable).I want to use JSONStore API for this purpose.
In our app, after we gather the user credentials, we are sending them
to an adaptor function, where we are invoking some java classes to
validate the credentials aginst IBM bluepages & also against dbs
I have two questions:
1) When i ensure that user has been authenticated successfully for the first time, I will open a JSON store & keep the userid to the local storage, If I choose to encrypt it , which password I need to supply to make it encrypted ?
2) When the user tries to access the app from the same mobile device, the server should send a login form by pre populating the user id, how do I do this?
Thanks..

A: Encrypted Offline Cache is deprecated, so you might as well use JSONStore.
In MobileFirst Platform 6.3 ("Worklight"), there is a tutorial that accomplishes exactly your scenario. You should read it and try to implement it in 6.1; depending on JSONStore's featureset in 6.1, you might be able to. You'll need to try.
Here it is: Offline Authentication


text:
Q: NullPointerException can't find the error Can't find the reason why I'm getting this NullPointException. It's pointing to 2 specific line.
This is the error:
Exception in thread "main" java.lang.NullPointerException
at Railroad.dijkstra(Railroad.java:52)
at Railroad.main(Railroad.java:36)

These are the 2 lines:
dijkstra(A);

for (Edge x : w.edges){

This is the whole code for convenience:
Posting the whole code for easier to understand where I'm coming from. Hopefully it'll help, thanks!
    Vertex[] vertices = { A, B, C, D, E, F, G, H, I, J, K, L, M };
    dijkstra(A);
    for (Vertex v : vertices)
{
    System.out.println("Distance to " + v + ": " + v.shortestDist);
    List<Vertex> trip = cheapestTrip(v);
    System.out.println("Path: " + trip);
}
}

public static void dijkstra(Vertex s){
    s.shortestDist = 0;
    PriorityQueue<Vertex> cityQueue = new PriorityQueue<Vertex>();
    cityQueue.add(s);

    while(!cityQueue.isEmpty()){
        Vertex w = cityQueue.poll();
        for (Edge x : w.edges){
            Vertex v = x.city;
            int price = x.price;
            int priceOfTrip = w.shortestDist + price;
            if(priceOfTrip < v.shortestDist){   //relaxes the edge that it's on
                cityQueue.remove(v);
                v.shortestDist = priceOfTrip;
                v.prev = w;
                cityQueue.add(v);
            }
        }
    }

}

A: You're getting the NullPointerException because the edges field on your Vertex object isn't getting properly initialized. It's generally best to use private fields and getters; this would have caused warnings about the potential problem.
Inside your Vertex class, you should initialize edges. Since you haven't posted the code, we don't know what type it is, but if it's a Set, for example, you would say:
Set<Edge> edges = Collections.emptySet(); // if you are going to replace edges
Set<Edge> edges = new HashSet<>();        // if you are going to use edges.add()

Edit: edges is an array. The same principle applies; you aren't setting that edges variable anywhere, and so it defaults to null. A default that will prevent the immediate problem is
Edge[] edges = new Edge[0];

but you're better off refactoring to a collection type that will let you add an arbitrary number of edges, and better off still refactoring to enforce field encapsulation among your different classes.
Edit 2: The specific problem is with K (DC) and M (NY). You set the edges field on other cities, but not on those.


text:
Q: Js position button in bottom right corner instead of centered I'm trying to position this button for my quickview in the bottom right corner of the image instead of centered, but I can't figure out how to do it. The code is using top and left offsets to position the button in the center. How can I position it in the bottom right corner instead? To see an example of the positioning I'm hoping to achieve, go to: http://www.shrimptoncouture.com/collections/all-clothing.
Here's what I'm working with. Any help would be greatly appreciated:
Cmsmart.noConflict();
Cmsmart(function($) {
    var producturl;

    function geturlrewrite(){
        var mypath = arguments[0];
        var patt = /\/[^\/]{0,}$/ig;
        if(mypath){
            if(mypath[mypath.length-1]=="/"){
                mypath = mypath.substring(0,mypath.length-1);
                return (mypath.match(patt)+"/");
            }
            return mypath.match(patt);
        }
        return '';
    }

    function urltrim(){
        return arguments[0].replace(/^\s+|\s+$/g,"");
    }

    function installquickview(){
        if (typeof CMSMART == 'undefined') return;
        var argInput = arguments[0];
        var productlistBlocks = $(argInput.productlistClassArr);
        var datasaved = [];
        var mypath = 'cmsmquickview/index/index';
        if(CMSMART.QuickView.BASE_URL.indexOf('index.php') == -1){
            mypath = 'cmsmquickview/index/index';
        }else{
            mypath = 'cmsmquickview/index/index';
        }
        var baseUrl = CMSMART.QuickView.BASE_URL + mypath;

        var _quickviewbutton = '' + CMSMART.QuickView.BOTTON_LABEL + '';
        var _quickform = '
' +
            '

' +
        '
';

        $(document.body).append(_quickform);
        $(document.body).append(_quickviewbutton);

        var quickviewButton = $('#cmsmart_quickview_button');
        //alert(encodeURIComponent(CMSMART.QuickView.BASE_URL + 'ab=3dfd&ddfdfd=234'));
        $.each(productlistBlocks, function(i, vl){
        var productlist = $(vl);
        $.each(productlist, function(index, value) {
            var reloadurl = '';

            var aClass = argInput.aClass[i]?argInput.aClass[i]:argInput.aClass[0];
            producturl = $(aClass, value);

            if(producturl.attr('href')){
                var producturlpath = producturl.attr('href').replace(CMSMART.QuickView.BASE_URL,"");
                //var producturlpath = geturlrewrite(producturl.attr('href'))[0];
                //producturlpath[0] == "\/" ? producturlpath = producturlpath.substring(1,producturlpath.length) : producturlpath;
                //producturlpath = urltrim(producturlpath);

                reloadurl += baseUrl+ ("/path/"+producturlpath).replace(/\/\//g,"/");
                //alert(reloadurl);
                var imgClass = argInput.imgClass[i]?argInput.imgClass[i]:argInput.imgClass[0];
                $(this).bind('mouseover', function() {
                    //var o = $(this).offset();
                    //var o = $(this);
                    var o = $(imgClass+':eq(0)', this);

                    $('#cmsmart_quickview_button').attr('href',reloadurl).show()
                        .css({
                        'top': o.offset().top+(o.height() - quickviewButton.height())/2+'px',
                            'left': o.offset().left+(o.width() - quickviewButton.outerWidth())/2+'px',
                            'visibility': 'visible'
                        });
                });
                $(value).bind('mouseout', function() {
                    $('#cmsmart_quickview_button').hide();
                });
            }
        });
        });

        if(CMSMART.QuickView.CENTER)
        {
            $("#quickviewshow").css('margin', ($(window).height() / 2 - $("#quickviewshow").height() / 2) + "px auto auto auto");
        }

        $('#cmsmart_quickview_button')
            .bind('mouseover', function() {
                $(this).show();
            })
            .bind('click', function() {
                idbyurl = ($(this).attr('href')).replace(/\W/g,"");
                showqv();
                $("#quickviewshow").html(' ');
                $("#cmsmart_quickview_button_close").on( "click", function() {
                    closeqv();
                    $("div.zoomContainer").remove();
                });

                $(this).hide();
                if(datasaved[idbyurl]){
                    $("#quickviewshow").html(' ');
                    $("#cmsmart_quickview_button_close").on( "click", function() {
                        closeqv();
                    });
                    $("#quickviewshow").append(datasaved[idbyurl]);
                    showqv();
                    relimg();
                    return false;
                }
                else{
                    $.ajax({
                        url: $(this).attr('href'),
                        cache: false
                    }).done(function( html ) {

                        $("#quickviewshow").html(' ');
                        $("#cmsmart_quickview_button_close").on( "click", function() {
                            closeqv();
                            $("div.zoomContainer").remove();
                        });
                        $("#quickviewshow").append(html);
                        showqv();
                        datasaved[idbyurl] = html;
                        relimg();
                    });
                }

                return false;
            });

            $('#csmm_quickform').click(function(e) {
                if($(e.target).is('#quickviewshow, #quickviewshow *')) return;
                $('#csmm_quickform').hide();
                $("div.zoomContainer").remove();
            });

    }

    $( document ).ready(function() {
        installquickview(CMSMART.QuickView.BUTTON_CONFIG);
    });

    $(window).resize(function() {
        $("#quickviewshow").css('margin', ($(window).height() / 2 - $("#quickviewshow").height() / 2) + "px auto auto auto");
    });

    function relimg(){
        maxh = $('div.product-quickview').outerHeight() - 45;
        if($('div.qvtabhead')) maxh = maxh - $('div.qvtabhead').outerHeight();
        if($('div.qvformaddtocart')) maxh = maxh - $('div.qvformaddtocart').outerHeight();
        if($('div.tabquickshow')) $('div.tabquickshow').css('max-height', maxh + "px");

        //submitbqv();
        $('#showlargeimg').elevateZoom({ zoomWindowWidth:300, zoomWindowHeight:300, borderSize: 2, zoomWindowOffetx:15, cursor:'move' });
         $('#mycarousel').jcarousel({
            scroll: 4
        });

        $("li img.p_image_hover").click(
            function () {
                smallImage = $(this).attr('src');
                largeImage = $(this).attr('data-zoom-image');
                $('img#showlargeimg').attr('src', smallImage);
                var ez = $('#showlargeimg').data('elevateZoom');
                ez.swaptheimage(smallImage, largeImage);
            }
        );

        $('a.tabquickviewcontrol').click(
            function(){
                $('a.tabquickviewcontrol').removeClass("highlight");
                $(this).addClass("highlight");
                var divsl = $(this).attr('href');
                $('.tabquickshow').css('display', 'none');
                $(divsl).css('display', 'block');
                return false;
            }
        )
    }

    function showqv(){ $("#csmm_quickform").css("display", "block"); }
    function closeqv(){ $("#csmm_quickform").css("display", "none"); }

    function btcloseqv(){
        $("#cmsmart_quickview_button_close").on( "click", function() {
            $("#csmm_quickform").css("display", "none");
        });
    }

    function submitbqv(){
        var fr = $('#product_addtocart_form');
        var btc = $('.btn-cart', fr);

        btc.attr('onclick', '');
        btc.click(function(){
            var cansubmit = true;
            $('select.required-entry', fr).each(function(){
                if($(this).val() == ''){
                    $(this).addClass('validation-failed');
                    $(this).focus();
                    cansubmit = false;
                    return false;
                }else { $(this).removeClass('validation-failed'); }
            });
            if(cansubmit) fr.submit();
        });
    }
    btcloseqv();
});

A: It might be something like:
            $('#cmsmart_quickview_button').attr('href',reloadurl).show()
                .css({
                'top' : o.offset().top + o.height() - quickviewButton.height()+'px',
                'left': o.offset().left+ o.width() - quickviewButton.outerWidth()+'px',
                    'visibility': 'visible'
                });

If that isn't it, keep playing with that code until you get what you want. You might try o.offset().bottom and o.offset().right but I don't know if they are defined.


text:
Q: pulling universal quantifiers in front of a disjunction Knowing that $$(∀xP) ∨ (∀xQ)$$ is not equivalent with $$∀x(P ∨ Q),$$ how can I pull the quantifiers in front of the formula simple formula $$ (∀xP) ∨ (∀xQ)$$
Or $$(∃xP) ∧ (∃xQ)$$ for that matter.

A: The distributive law works here just like it would for finite conjunctions and disjunctions. By analogy with
$$
(w\land x)\lor(y\land z)=(w\lor y)\land(w\lor z)\land(x\lor y)\land(x\lor z)
$$
you get
$$
(\forall xP)\lor(\forall xQ)\Leftrightarrow\forall(x,y)(P(x)\lor Q(y))\;,
$$
and likewise
$$
(\exists xP)\land(\exists xQ)\Leftrightarrow\exists(x,y)(P(x)\land Q(y))\;.
$$

A: You can change $$(\forall x P(x)) \vee (\forall x Q(x)) $$
to
$$(\forall x P(x)) \vee (\forall y Q(y)) $$ by changing the choice of dummy variable, and $\textit{then}$ move the quantifiers to the front to get
$$\forall x \forall y (P(x) \vee Q(y)) $$.


text:
Q: How to calculate the distance between the centroid and the nearest point of the polygon in QGIS? I have a shapefile as shown in the picture. I have estimated the centroid points of these polygons. How to estimate the distance between between the centroid and the minimum edge of the polygon in QGIS?

A: You can easily be done in two steps:

*

*Convert the polygons into lines (eg. using the Polygons to lines algorithm).

*Run the Join attributes by nearest algorithm from the processing toolbox, using the centroids as input layer and the polygon borders as target layer.

This algorithm not only joins the attributes of the nearest polygon boundary to your centroids, it also outputs a distance field (as well as x/y fields for the nearest point on the boundary).


text:
Q: How could I make the raspberry pi as a WIFI and ssh module For a digital design course, we have to use a microcontroller as the CPU of the system. The chip we plan to use is STM32L0C8T6. We want to integrate the SSH function into a keyboard. The way we plan to do it is to connect the STM32 with a Raspberry pi zero or 2 through UART or SPI. The Pi will connect to the WIFI and connect to other hosts through SSH. An LCD display is also connected to the STM32 which will work like the monitor, displaying all things you will see when ssh, like whatever is shown in the terminal when ssh.
My question is how to build the connection between the terminal and STM32. One possible way is to dump everything in the terminal into a file and send the file back to STM32 for display. I think this will be really slow. Are there any better ideas?
The question sounds wired, and I know we could connect LCD directly to the Pi, but this is the project requirement to have to follow. The LCD has to connect to the microcontroller.
Thank you so much!!!!


text:
Q: Philips Hue command limitation First of all I'm developing my own C# library for controlling Philips Hue, which means I'm not using the official SDK. (I'm guessing that the SDK will make sure you won't have any problems)
I'm a little confused about the limitation in the Core concepts page in the API, which states:

We can't send commands to the lights too fast. If you stick to around 10 commands per second to the /lights resource as maximum you should be fine. For /groups commands you should keep to a maximum of 1 per second.

I intend to respect this limitation, but does the limitation still apply when you are performing GET requests on the /lights resource, or is it only for sending actual commands with PUT requests to /lights/<id>/state that change the state of the light? Same question goes for the /groups resource.
Also is it even possible to damage anything by sending too many requests, or will it just take longer to get all responses?
Edit:
My overall question is: How should I understand the API limitation?
A more specific sub-question is: Should I wait 100 ms before sending another /lights command, relative to when I received a response, or relative to when I sent the previous command?
Another sub-question is: Should I consider this limitation only when using PUT requests on e.g. /lights/<id>/state, or on all request types GET/PUT/POST/DELETE

A: I don't know if anything was changed in firmware updates, but I have discovered that the bridge might not be so simple as you would think, and that the API description isn't very clear.
I've done a little testing while running firmware 01009914.
The bridge seems to have some kind of queue of incoming commands. I sent {"bri":254} to a group 9 times and 1 final command of {"bri":1}. From the first command to when the light is actually dimmed, takes roughly 3-4 seconds. Each time I sent a command the bridge replied almost instantly with success token.
I did the same small tests sending other commands, 10 of each JSON object:

*

*{"bri":254} 3-4 seconds

*{"on":true, "bri":254} 6-7 seconds

*{"on":true, "bri":254, "alert":"none", "effect":"none"} 12-13 seconds

This actually shows that each change of attributes takes roughly 0.3 seconds for the bridge to handle.
I will claim that for each attribute we change, the bridge takes about 300 ms to finish, and the limitation of commands should be understood as: As long as you stick with changing one attribute of a group each second, you should be fine.
Note: I only tried with one group consisting of three lights, and I don't know if the bridge actually does have a queue of incoming commands, and in case it does have a queue, I don't know what the limit of items in it is.
Edit:
Now we have some official clarification of the Hue System Performance.

A: I'm fairly certain that the 10 commands per second is a guideline to prevent failure of the Bridge, and is a technical limitation of the hardware. Any more than that and you're apt to overload the bridge. I believe this applies to commands as well as requests.
Both approaches are reasonable. For laziness' sake, you could wait for 100ms to send a response, but I would only rely on this method if you don't plan on any other interactions with the Bridge.
I consider this limitation on all request types.

A: You won't damage anything if you send commands too fast. However, if you send commands too fast the bridge might become unresponsive and/or some messages can be ignored.
When it comes to the bridge, the way I think of it is that the bridge is more or less single threaded, so it works best if you make sure you don't send the next command before the previous one has returned.
In practice we've found that this works much better than waiting a fixed time between each request. In fact, you can pretty much send commands as fast as you want as long as you wait for the previous one to finish.
When you send a command to the bridge, the bridge has to then send it to the lamps through Zigbee. Since it's a mesh network in some cases the message has to make a couple of hops from lamp to lamp before it reaches the target. Depending on how many lamps you have and how many hops the signal needs to take, this can take a while. Also, it's possible that some messages randomly take much longer than others.
In general the system is not designed to handle very fast changes, but if you keep the above in mind you can make many cool effects :)