text:
Q: Birt 3.7.2 integration report html deployment I integrated BIRT 3.7.2 report engine with my web app. Now the problem is, it creates a HTML page (if i am using render format html) in a specific location.
I don't want to save the report html page, instead i want it to show that html directly in my web app(saved in temp and deleted after use). Also it creates a image directory & every time a report with embedded image and/or graph in it, saves the image and/or graph in image directory unnecessary increase space.
Can somebody help me..??
I have followed steps provided in :
https://dev.c-ware.de/confluence/display/PUBLIC/Embeding+Birt+into+Application+built+with+Maven

A: I didn't delve into the Birt library to do it and didn't create any classes using their API like it shows in your link, so this may not be the most efficient solution.
This was some months ago and I don't have access to the source now but basically I just added the BirtRuntime to my webapp as a servlet as covered here.
This allowed me to load Birt reports, but I also needed to embed them in existing web pages. I already had a pretty simply proxy servlet in this app which would just read the html content of a url. So I just called this servlet using the url for my BIRT report and I would stick the output where I wanted it on the web page.
Proxy servlet was like this:
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;

public class ProxyServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException  {

        String urlString = request.getParameter("url");
        try {
            URL url = new URL(urlString);
            url.openConnection();
            InputStream in = url.openStream();
            ServletOutputStream out = response.getOutputStream();
            IOUtils.copy(in, out);
        }
        catch (MalformedURLException e) {
            throw new ServletException(e);
        }
        catch (IOException e) {
            throw new ServletException(e);
        }
    }
}


text:
Q: SaveAs function works on Microsoft PC but not on MAC I have VBA code that controls the user from saving the file in any other format than .xls, .xlsm or .pdf. This is to prevent the stripping out of macros during the save process.
I have inserted a line to check if the operating system is OSx (... Like "Mac") which works in other macros but not this one. The process fails with "Can;t find the file object or library" with 'msoFileDialogSaveAs' highlighted.
Here is my code:
    Option Explicit
    Option Compare Text

    Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, _
        Cancel As Boolean)

      Dim fso As Object 'FileSystemObject
      Dim PdfSave As Boolean
      Dim SheetName As String
      If Not Application.OperatingSystem Like "*Mac*" Then
      SheetName = ActiveSheet.Name
      'Save-As action?
      If SaveAsUI Then
        Set fso = CreateObject("Scripting.FileSystemObject")
        'Abort excel's dialog
        Cancel = True
        'Create our own
        With Application.FileDialog(msoFileDialogSaveAs)
          'Select the XLSM filter by default
          .FilterIndex = 2
    Again:
          'Ok clicked?
          If .Show = -1 Then
            'Which extension should we save?
            Select Case fso.GetExtensionName(.SelectedItems(1))
              Case "xlsm"
                'Okay
              Case "xls"
                'Okay
              Case "pdf"
                PdfSave = True
                'Okay
              Case Else
                MsgBox "Invalid file type selected!" _
                  & vbCr & vbCr & "Only the following file formats are   permitted:" _
                  & vbCr & "   1. Excel Macro-Enabled Workbook (*.xlsm)" _
                  & vbCr & "   2. Excel 97-2003 Workbook (*.xls)" _
                  & vbCr & "   3. PDF (*.pdf)" _
                  & vbCr & vbCr & "Please try again." _
                  & vbCr & vbCr & "NOTE: 'Excel 97-2003 Workbook (*.xls)' format should be used for" _
                  & vbCr & "backwards compatability only!", vbOKOnly + vbCritical
                GoTo Again
            End Select
            'Prevent that we call ourself
            Application.EnableEvents = False
            'Save the file
            If PdfSave = True Then
                ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF,   Filename:=ActiveWorkbook.Path & "\" & SheetName & ".pdf",  Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=True
            Else
                ThisWorkbook.SaveAs .SelectedItems(1)
            End If
            Application.EnableEvents = True
          End If
        End With
      End If
      End If
    End Sub

Can anyone suggest changes so that this code works for Office on both PC and MAC, or have different code that achieves the same thing.
Thanks
Mike

A: You're heading off the edge of the map when working in Mac and PC environments, I have to do it a lot and its choppy seas thats for sure! My advice is persist, you are on the right track.
Firstly, I have a similar OS check: -
BlnIsAPC = IIf(Left(Trim(UCase(Application.OperatingSystem)), 1) = "M", False, True)

This is simply trying to have the most future proofed way of getting the OS right.
Secondly, it's good you're late binding to Scripting.FileSystemObject as that is not in Mac Office (Its part of Windows not Office).
Thirdly, neither is FileDialog, hence the error 'Can't find the file object or library'. There is an alternative and you will end up needing to refer into it a fair bit. Its a built-in function called MacScript.
You'll want to work out how to do it in AppleScript, and then create that script and run it through MacScript in VBA. Below is an stripped down example of my work in which I have code that either uses Application.FileDialog(msoFileDialogOpen) on a PC or MacScript on a Mac, specifically this is only showing the Mac side.
Public Function GetFilePath(ByVal StrTitle As String, ByVal StrButtonName As String, ByVal BlnMultiSelect As Boolean, ByVal StrFilters As String) As String
'               StrTitle        = The title to go on the dialog box
'               StrButtonName   = What to show on the OK button
'               BlnMultiSelect  = Can the user select more than one file
'               StrFilters      = What can be selected pipe and colon delimited i.e. [name]:[suffix]|[name]:[suffix]

If Procs.Global_IsAPC Then
    GetFilePath = GetFilePath_PC(StrTitle, StrButtonName, BlnMultiSelect, StrFilters)
Else
    GetFilePath = GetFilePath_Mac(StrTitle, StrButtonName, BlnMultiSelect, StrFilters)
End If

End Function

Private Function GetFilePath_PC(ByVal StrTitle As String, ByVal StrButtonName As String, ByVal BlnMultiSelect As Boolean, StrFilters As String) As String
...
End Function

Private Function GetFilePath_Mac(ByVal StrTitle As String, ByVal StrButtonName As String, ByVal BlnMultiSelect As Boolean, StrFilters As String) As String
Dim AryTemp2()      As String
Dim LngCounter      As Long
Dim StrContainer    As String
Dim StrPath         As String

StrContainer = "tell application " & """" & "Finder" & """" & Chr(13)
StrContainer = StrContainer & "choose file with prompt " & """" & StrTitle & """"

If StrFilters <> "" Then
    StrContainer = StrContainer & " of type {"
    'Code was here that prepared the filters into AryTemp2
    For LngCounter = 0 To UBound(AryTemp2, 1)
        If Right(StrContainer, 1) <> "{" Then StrContainer = StrContainer & ", "
        StrContainer = StrContainer & """" & AryTemp2(LngCounter2) & """"
    Next
    StrContainer = StrContainer & "} "
End If

StrContainer = StrContainer & "without invisibles" & IIf(BlnMultiSelect, "", " and multiple selections") & " allowed" & Chr(13)
StrContainer = StrContainer & "end tell"
StrPath = MacScript(StrContainer)

If Left(StrPath, 6) = "alias " Then StrPath = Right(StrPath, Len(StrPath) - 6)

GetFilePath_Mac = StrPath

End Function

FYI at point of execution in MacScript, StrContainer looked as below: -
tell application "Finder"
choose file with prompt "Select the required Config stub" of type {"Config_Stub"} without invisibles and multiple selections allowed
end tell

Finally, VBA is not available on all versions of Office for Mac and there are subtle differences in ways of working between them that unfortunutly you'll only come to find via experience. Like I say 'You're heading off the edge of the map' into uncharted waters.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Force "Details" folder view to show standard columns in folders with music file in Windows In Windows explorer if I change the folder view to details, for a standard folder the columns shown are Name, Date modified, Type and Size. When I open a folder containing files with audio extensions (wav, mp3, etc), the columns change to something else such as artist, genre, etc. Is there a way to force the details view to always show the same standard columns, viz, Name, Date modified, Type and Size?
The view changing to thumbnails in case of image files is not a problem for me, as I can go to details rather quickly in a few clicks, and it shows the standard columns by default. My main problem is audio files which seem to change the columns that are shown. I have seen this, but preferably I would like to do this without registry hacks. I am using Windows 7 enterprise edition.

A: Edit: may be duplicate of Windows 7 Explorer: How to change the columns displayed for file attributes? Alternative systematic solution presented is not in other thread.
Those columns are because File Explorer sees the audio files in the folder and defaults to using its "music" template to show the folder's contents. There are 2 options depending on how systematic you want the changes you make to be.
You can force change the folder template back to "general items" for this folder so that it won't show those columns by:

*

*Go in to the folder's Properties

*Select the "Customize" tab

*Under the section "What kind of folder do you want?" change the "Optimize this folder for:" option from "Music" to "General Items".

Once it's applied, the folder's detail view should no longer have the columns specific to music files.
Keep in mind that the changes will only apply to this folder (and any contained subfolders if you selected that option when applying the new properties).
Alternatively, you can change the "music" template itself. So that any folder that windows explorer opens which it automatically applies the "music" template, will display whatever customized view you made.
In the currently open folder that is already in "Music" view mode/template (ie. with columns for artists, genre, etc.), manually change the columns to the desired fields by:

*

*Right-clicking on the title row (row containing Name, #, title, artists, album), and select More... in the pop-up menu.

*Change the column selection and order to your desired layout.

Save the changed layout as the default for the "Music" template by:

*Open up the File menu (top left)

*Select "Change folder and search options"

*Select the "View" tab

*Under the "Folders views" section, select "Apply to Folders"

Once that is applied, all folders that file explorer will default to "Music" view mode/template will now use this layout.
For more details and illustrations on the alternate method, please consult How-to-Geek's Guide on customizing the windows folder templates

A: Windows 10 is ignoring the Customize setting and persists in showing Windows Explorer folder with MP3 files in Music rather than General Items format.


text:
Q: MKMapView centerLocation In my application there is an MKMapView and I am trying to get the center coordinates of the map region that is currently visible. I am using following method so that if user moves the visible region I'll get new center coordinates.
- (void)mapView:(MKMapView *)mapView1 regionDidChangeAnimated:(BOOL)animated
{

CLLocationCoordinate2D centre = [mapView centerCoordinate];

NSLog(@"MAP CENTER = %f,%f",centre.latitude,centre.longitude);
}

the problem is that when I switch to the UIViewController that contains MKMapView it gives MAP CENTER = 0.000000,0.000000 for two times then gives the actual coordinates MAP CENTER = 55.755786,37.617633. I want the actual coordinates as soon as I switch to that UIViewController.

A: Is the coordinates (55.755786,37.617633) your current location ?
MKMapView takes some time  to get a lock on GPS to fetch the coordinates for your current location. Until then centerCoordinate might return (0,0)

A: Try this this may help you.
self.mapView.centerCoordinate = self.mapView.userLocation.location.coordinate;


text:
Q: Geopandas - split lines at intersection with polygons, retain polygon ID in new link attributes I have two geodataframes: one containing many Linestrings, and another containing many Polygons. These lines and polygons intersect each other. The output I am trying to achieve is a new geodataframe containing links which have been split at any location that they intersect a polygon.
Simplified test code is as follows:
import geopandas
from shapely.geometry import Polygon, LineString

#Create geodataframe containing 2 links:
linkID = ['1','2']
link_geom = [LineString([(0, 0), (10, 10)]),LineString([(10, 10), (20, 10)])]
a = {'linkID':linkID,'geometry':link_geom}
gdf_links = geopandas.GeoDataFrame(a)

#Create geodataframe containing 2 polygons:
polyID = ['100','200']
poly_geom = [Polygon([(2, 1), (2, 3), (4, 3), (4, 1)]),Polygon([(15, 7), (15, 13), (18, 13), (18, 7)])]
b = {'polyID':polyID,'geometry':poly_geom}
gdf_poly = geopandas.GeoDataFrame(b)

You can see that the lines intersect the polygons by running the following code:
links = gdf_links.unary_union
polys = gdf_poly.unary_union
geopandas.GeoSeries([links,polys]).plot(cmap='tab10')

Which generates the following figure (annotation added in red/green to show the various elements involved):

Splitting the two lines wherever they intersect a polgyon will results in 6 segments (as labelled in green in the figure above).
Ideally, the output I would like to achieve is something like shown below, with a 'poly_intersect' column listing the ID of the polygon at which the split has occurred. Note that items 2 and 5 list two polygon ID's, because they intersect the polygon twice.

A: You can get those linestrings by doing an "overlay" of the lines with the polygons (using the "union" operation while overlaying). However, it will not give exactly the expected result as you depicted for the "poly_intersect" column:
>> geopandas.overlay(gdf_links, gdf_poly, how='union').explode().reset_index(drop=True)

  linkID polyID                   geometry
0      1    100      LINESTRING (2 2, 3 3)
1      2    200  LINESTRING (15 10, 18 10)
2      1    NaN      LINESTRING (0 0, 2 2)
3      1    NaN    LINESTRING (3 3, 10 10)
4      2    NaN  LINESTRING (10 10, 15 10)
5      2    NaN  LINESTRING (18 10, 20 10)

Some remarks:

*

*I am using explode(), because the overlay() operation returns MultiLineStrings for the part of one linestring before and after intersecting the polygon. The explode will split those "multi" geometries.

*The "polyID" column indicates which linestrings originated from intersecting with which one the polygons. But it does not have information for the other linestrings of which polygon they touch.

So if you want require that information as well (the full "poly_intersect" column), you could do some follow-up analysis checking which of the linestrings is touching which of the polygons.


text:
Q: Tem como pegar o event.preventDefault() se a chamada tiver parâmetros? Estou fazendo uma operação onde eu tenho a chamada de um método, neste caso especifico como eu poderia pegar o event.preventDefault() do formulário.
<button type="button" class="btn btn-primary" onclick="AdicionarEditarRegistro('@controller','Edit')">Salvar</button>

Exemplo:
function AdicionarEditarRegistro(controller, action) {
  debugger;

  var t = $("input[name='__RequestVerificationToken']").val();
  var urlCompleto = "/" + controller + "/"+ action +"/";
  var formulario = $("#FormularioCompleto");

  alert('pegar o :' + 'event.preventDefault()');
}

A: Você pode passar o event como argumento para a função. Em atributos JavaScript, o event está no escopo.

function handle(name, event) {
  console.log(name); // Luiz
  console.log(typeof event.preventDefault); // function
}
<button onclick="handle('Luiz', event)">Clique-me!</button>

Como curiosidade, assim como você pode passar o event, você também pode passar this. :)

Como alternativa, se você não quiser usar atributos para determinar os eventos, pode criar data-attributes e usar o addEventListener. Algo assim:

const button = document.querySelector('button');

button.addEventListener('click', (event) => {
  const name = event.currentTarget.dataset.name;

  console.log(name); // Luiz
  console.log(typeof event.preventDefault); // function
});
<button data-name="Luiz">Clique-me!</button>

Eu pessoalmente prefiro essa segunda abordagem, já que deixo o JavaScript cuidar dos eventos, limitando o papel do HTML e aumentando a separação de responsabilidades.


text:
Q: ssis Error: Exception has been thrown by the target of an invocation The ssis controlflow consists of a script task which trying to open a n excel file and save it as txt file using workbookopen method and saveas methode.
It shows an error while runing the pkg
The file path is of the format \\11.111.111.1\folder1\folder2\file.xlsx

 at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
       at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
       at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
       at System.RuntimeType.InvokeMember(String name, BindingFlags bindingFlags, Binder binder, Object target, Object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams)
       at Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTATaskScriptingEngine.ExecuteScript()

The script being used is
Public Sub Main()

        Dim WScript As Object                                    '''= Nothing   '' with out nothing it was showing an error
        Dim oExcel As Object
        Dim oBook As Object

        Dim varoroviderFileLocation_script As String
        Dim varFileName_script As String
        Dim FullPath_script As String

        Dim v_Reversestring As String
        Dim v_ReplaceString As String

        varoroviderFileLocation_script = Dts.Variables("User::varoroviderFileLocation").Value.ToString()
        varFileName_script = Dts.Variables("User::varFileName").Value.ToString()
        FullPath_script = Dts.Variables("User::varoroviderFileLocation").Value.ToString() + "\" + Dts.Variables("User::varFileName").Value.ToString()

        MessageBox.Show(varoroviderFileLocation_script)
        MessageBox.Show(varFileName_script)
        MessageBox.Show(FullPath_script)

        oExcel = CreateObject("Excel.Application")

        oBook = oExcel.Workbooks.Open(FullPath_script)

        MessageBox.Show("FullPath_script " + FullPath_script)

        v_Reversestring = StrReverse(FullPath_script)
        v_Reversestring = v_Reversestring.Substring(5, Len(v_Reversestring) - 5)
        MessageBox.Show(v_Reversestring)
        v_Reversestring = StrReverse(v_Reversestring)

        v_ReplaceString = v_Reversestring + ".txt"

        MessageBox.Show("v_ReplaceString  " + v_ReplaceString)

        oBook.SaveAs(v_ReplaceString, -4158)

        oBook.Close(False)
        oExcel.Quit()
        WScript.Echo("Done")

        Dts.TaskResult = ScriptResults.Success
    End Sub

A: In my experience, when working with Office, this error is due to the 64bit runtime.  In project properties under configuration you should have this set to false.  Other times I see this error are when a referenced DLL is not in the GAC or a variable being referenced is spelled incorrectly.


text:
Q: How can I aling / synchronize two signals? I have two signals A and B (please, see them attached), which have been recorded from different devices with different sampling frequencies, on the same events.
I am trying to align both signals through cross-correlation methods. However, when using the alignsignals function, it does seem to actually delay even more the signals:
load A
load B

% Sampling frequencies
Fs_A = 1000; %
Fs_B = 1926; % 1925.93 Hz is the one provided by the device

% Resample signal A
A = resample(A, Fs_B, Fs_A);

% Plot of the two signals "delayed"
figure(1)
plot(A)
hold
plot(B*1000)

% Aling both signals
X = A;
Y = B;

[Xa,Ya,D] = alignsignals(X,Y,[],'truncate');
figure(2) % plot both signals "aligned"
plot(Xa)
hold
plot(Ya*1000)

I have also tried using xcorr function, with similar result:
load A
load B

% Sampling frequencies
Fs_A = 1000; %
Fs_B = 1926; % 1925.93 Hz is the one provided by the device

% Resample signal A
A = resample(A, Fs_B, Fs_A);

% Plot to visualize that one signal is delayed
figure(1)
plot(A)
hold
plot(B*1000)

% Aling both signals using xcorr

[C,lag] = xcorr(A,B);
figure(2)
plot(lag,C);
[M,I] = max(C);
D = lag(I);
figure(3),plot(1:length(A), A, 'b',1+abs(D):length(B)+abs(D), B*1000, 'r'), title(' "Synchronised" signals ');

Am I making any mistake?
Thank you


text:
Q: Failed in opening neo4j DB Hi i'm deploying an app that i wrote on a machine (all deployment with tomcat).
when running the application (in browser) i get the error
 taken out from catalina.out :

java.lang.RuntimeException: Error starting org.neo4j.kernel.impl.factory.CommunityFacadeFactory,

/home/ubu01/neo4jDB
        at org.neo4j.kernel.impl.factory.GraphDatabaseFacadeFactory.newFacade(GraphDatabaseFacadeFactory.java:143)
        at org.neo4j.kernel.impl.factory.CommunityFacadeFactory.newFacade(CommunityFacadeFactory.java:43)
        at org.neo4j.kernel.impl.factory.GraphDatabaseFacadeFactory.newFacade(GraphDatabaseFacadeFactory.java:108)
        at org.neo4j.graphdb.factory.GraphDatabaseFactory.newDatabase(GraphDatabaseFactory.java:129)
        at org.neo4j.graphdb.factory.GraphDatabaseFactory$1.newDatabase(GraphDatabaseFactory.java:117)
        at org.neo4j.graphdb.factory.GraphDatabaseBuilder.newGraphDatabase(GraphDatabaseBuilder.java:185)
        at com.saeedh.utils.NeoQuery.InitDatabase(NeoQuery.java:46)
        at com.saeedh.utils.NeoQuery.AuthinUser(NeoQuery.java:153)
        at com.saeedh.servlets.start.Login.doGet(Login.java:79)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
        at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
        at com.saeedh.filters.PageValidationFilter.doFilter(PageValidationFilter.java:48)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
        at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:521)
        at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1096)
        at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:674)
        at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
        at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
        at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
        at java.lang.Thread.run(Thread.java:745)
      Caused by: org.neo4j.kernel.lifecycle.LifecycleException: Component 'org.neo4j.kernel.NeoStoreDataSource@4724a951' was
  successfully initialized, but failed to start. Please see attached
  cause exception.
        at org.neo4j.kernel.lifecycle.LifeSupport$LifecycleInstance.start(LifeSupport.java:462)
        at org.neo4j.kernel.lifecycle.LifeSupport.start(LifeSupport.java:111)
        at org.neo4j.kernel.impl.transaction.state.DataSourceManager.start(DataSourceManager.java:112)
        at org.neo4j.kernel.lifecycle.LifeSupport$LifecycleInstance.start(LifeSupport.java:452)
        at org.neo4j.kernel.lifecycle.LifeSupport.start(LifeSupport.java:111)
        at org.neo4j.kernel.impl.factory.GraphDatabaseFacadeFactory.newFacade(GraphDatabaseFacadeFactory.java:139)

but the application works fine on my machine .
i tried the solution suggested here :
Error Obtaining Lock (org.neo4j.kernal.StoreLockException)
it didn't work , i am accessing the DB using :
db = new GraphDatabaseFactory().newEmbeddedDatabaseBuilder(new File("path to the database")).loadPropertiesFromFile("path to properties file")
        .newGraphDatabase();
registerShutdownHook(db);

what could be the problem ?

A: Only one process at a time can access the store directory on disk.
As you start an embedded database, make sure that all servers and other processes accessing that same database are stopped cleanly.


text:
Q: What is the definition of $\text{weight or Hodge-Tate weight}$ in the p-adic Hodge theory? My question is about p-adic Hodge-Tate theory and p-adic Galois representation.
What is the definition of $\text{weight or Hodge-Tate weight}$ in the above theory?
For example, I have the following two definitions of weights in the above context as follows:
Def 1:  (https://math.uchicago.edu/~emerton/pdffiles/egh.pdf)
A $\text{weight}$ is an isomorphism class of irreducible representations $V$ of $G(k)$ over $\bar k$, where $k$ is the residue field in the finite extension of $\mathbb{Q}_p$. Since $G(k)$ is finite, there are finitely many weights.
Def 2:(http://math.bu.edu/people/bergdall/seminars/hodge-notes/week11.pdf)
A Hodge-Tate weight $i \in \mathbb{Z}$ is defined such that $Gr^{i}D_{HT}(V)=(V \otimes_{\mathbb{Q}_p} \mathbb{C}_p)^{Gal}=\frac{Fil^{i}D_{dR}(V)}{Fil^{i+1}D_{dR}(V)} \neq 0$.
This different definitions makes me into confusion though the later one is a definition of HT weight while the first one is simply weight.
Are the above two weights same or different?
Can someone explain and gives definition of weight in the above sense?


text:
Q: Undefined type 'Psr\Log\LoggerInterface' I am looking for a solution to this problem
i use php 7.4 , this error in SMTP.php in phpMailer folder
my code :
 //Is this a PSR-3 logger?
    if ($this->Debugoutput instanceof \Psr\Log\LoggerInterface) {
        $this->Debugoutput->debug($str);
        return;
    }

this error :
Undefined type 'Psr\Log\LoggerInterface

A: It seems like Visual Studio Code does not see your vendor folder or you dont installed the psr/log package via composer.
try to run the command
composer require psr/log

in order to get the PSR-3 Interfaces

A: That should not be an error in the first place. When using instanceOf, the class you are checking for dos not need to exist, just as it does not need to exist in use statements either. For example:
$a = 1;
if ($a instanceOf \Cocktails\Gin\Tonic) {
    echo 'true';
} else {
    echo 'false';
}
exit;

This will simply display false, and not generate an error even though the class it's looking for is not defined - it simply means that the instanceOf check will fail for a different reason.


text:
Q: How can i solve this? It regards the indexing and for loops Write a function that takes two lists (l1, l2) as parameters. The two lists contain integer numbers.
The second list contains numbers in the range [0, len(l1)), those numbers represent the indexes of
the first list. The function has to return the sum of the elements in l1 that have their indexes in l2.
Notice that if l2 contains the same index multiple times, you have to count the respective element in l1 only once
For example: if l1 = [11, 2, 0, −3, 3] and l2 = [0, 1, 3, 0], the function has to return 10, because
11 + 2 + (−3) = 10.

A: In python,
l2 = set(l2)
summation = sum([l1[i] for i in l2])

A: In Perl,
use List::Util qw(sum0 uniqnum);

sub ($l1, $l2) {
    sum0 @$l1[uniqnum @$l2]
}

In Haskell,
fmap (fmap sum) (fmap (flip fmap nub) (fmap fmap (!!)))

In Haskell,
{-# LANGUAGE ParallelListComp #-}
\l1 l2 -> sum [ x * fromEnum (i `elem` l2) | x <- l1 | i <- [0 ..]]

In Python,
lambda l1, l2: sum([l1[i] for i in range(len(l1)) if i in l2])

In C,
#include <stddef.h>
#include <stdbool.h>

static bool h(const long *v, size_t n, long k) {
    return !n || *v != k && h(v + 1, n - 1, k);
}

static long g(const long *u, const long *w, size_t n, size_t c) {
    return c >= n ? 0 : h(w, c, w[c]) * u[w[c]] + g(u, w, n, c + 1);
}

static long f(const long *l1, const long *l2, size_t n) {
    return g(l1, l2, n, 0);
}

In C,
#include <stddef.h>
#include <setjmp.h>

static long f(const long *l1, const long *l2, size_t n) {
    volatile long r = 0;
    volatile size_t c = 0;
    jmp_buf d;
    setjmp(d);
    if (c >= n) return r;
    volatile size_t i = c;
    jmp_buf e;
    setjmp(e);
    if (!i--) r += l2[c][l1]; else
    if (l2[i] != c[l2]) longjmp(e, 0);
    c++;
    longjmp(d, 1);
}

A: In Java:
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class SumList {

    public static Integer calcualteListSum(List<Integer> elements, List<Integer> indexes) {
        Set<Integer> uniqueIndexes = new HashSet<Integer>(indexes);

        Integer sum = 0;
        for(Integer index : uniqueIndexes) {
            sum += elements.get(index);
        }

        return sum;
    }
}


text:
Q: VueJS How can I use computed property with v-for How can I use computed property in lists. I am using VueJS v2.0.2.
Here's the HTML:

        {{fullName}}

Here's the Vue code:
var items = [
    { id:1, firstname:'John', lastname: 'Doe' },
    { id:2, firstname:'Martin', lastname: 'Bust' }
];

var vm = new Vue({
    el: '#el',
    data: { items: items },
    computed: {
        fullName: function(item) {
            return item.firstname + ' ' + item.lastname;
        },
    },
});

A: You can't create a computed property for each iteration. Ideally, each of those items would be their own component so each one can have its own fullName computed property.
What you can do, if you don't want to create a user component, is use a method instead. You can move fullName right from the computed property to methods, then you can use it like:
{{ fullName(user) }}

Also, side note, if you find yourself needing to pass an arguments to a computed you likely want a method instead.

A: What you're missing here is that your items is an array, which holds all the items, but the computed is a single fullName, which just can't express all the fullNames in items. Try this:
var vm = new Vue({
    el: '#el',
    data: { items: items },
    computed: {
        // corrections start
        fullNames: function() {
            return this.items.map(function(item) {
                return item.firstname + ' ' + item.lastname;
            });
        }
        // corrections end
    }
});

Then in the view:

        {{fullNames[index]}}

The way Bill introduces surely works, but we can do it with computed props and I think it's a better design than method in iterations, especially when the app gets larger. Also, computed has a performance gain compared to method on some circumstances: http://vuejs.org/guide/computed.html#Computed-Caching-vs-Methods

A: I like the solution posted by PanJunjie潘俊杰. It gets at the heart of the issue by only iterating over this.items once (during the component creation phase), and then caching the result. This is of course the key benefit for utilizing a computed prop instead of a method.
computed: {
    // corrections start
    fullNames: function() {
        return this.items.map(function(item) {
            return item.firstname + ' ' + item.lastname;
        });
    }
    // corrections end
}

.

    {{fullNames[index]}}

The only thing I don't like is that, in the DOM markup, fullNames is accessed by the list index. We could improve that by using .reduce() instead of .map() in the computed prop to create an Object with a key for each item.id in this.items.

Consider this example:

computed: {
    fullNames() {
        return this.items.reduce((acc, item) => {
            acc[item.id] = `${item.firstname} ${item.lastname}`;
            return acc;
        }, {});
    },
},

.
<p v-for="item in items" :key="`person-${item.id}`">
    {{ fullNames[item.id] }}

Note: the above example assumes that item.id is unique, such as from typical database output.

A: Maybe add another v-for that iterates through a one-item-long list:

        <template v-for="fullName in [item.firstName + ' ' + item.lastName]">
            {{fullName}}
        </template>

Not nice, but that's what you're looking for: an object around that span that has a property called fullName that contains that specific value.
And it's not just a vanity feature, because we may need to use that value at more than one place, eg.:
I am {{fullName}}
You are {{fullName}}
Who is {{fullName}}?

My use case was that I was constructing dates in v-for loops (yes, another calendar), like:
<v-row v-for="r in 5">
    <v-col v-for="c in 7">
        <template v-for="day in [new Date(start.getTime() + 24*60*60*1000*((c-1) + 7*(r-1)))]">

                Some rendering of a day like {{day.getYear()}} and
                {{day.getMonth()}} etc.

        </template>
    </v-col>
</v-row>

(For brevity I omitted the :key="whatever" settings)
I admit that the nicest way would be to move that  to a separate component, but if we create a new component for every two-liner like this, and use that component only at this single place, then we just pollute another namespace.
Maybe a v-let="day as new Date(...)" directive would be handy for such purpose.

A: you have to pass argument in the function call

           {{fullName(item)}}


text:
Q: The supremum-like definition of greatest common divisor I have reasonable experience with analysis, but I have just recently begun studying abstract algebra from Dummit and Foote.
I am frightened that I am already getting tripped up on pp.4, with the definition of greatest common divisor.
My intuitive understanding of greatest common divisor, from grade school, would be the maximal common element of two integers' factor trees.   I am having trouble aligning this with Dummit and Foote's definition, which parallels the definition of a supremum.
First, they make a predefinition:  if $a,b \in \mathbb{Z}$ with $a \neq 0$, then they say $a$ divides $b$, or $a|b$, if $\exists c \in \mathbb{Z} : b= ac$.
Then, they proceed with the definition: if $a,b \in \mathbb{Z} - \{0\}$, then there exists a unique positive integer $d$, called the greatest common divisor of $a$ and $b$, satisfying:

*

*$d | a$ and $d | b$ (so $d$ is a common divisor of $a$ and $b$)

*if $e|a$ and $e|b$ then $e|d$ (so $d$ is the greatest such divisor)

Now I can't actually figure out how to prove the second property.
What I mean is that, suppose I assume $d|a$,$d|b$,$e|a$,$e|b$.  Then why does $d>e \implies e|d$?

A: Let $g$ be the gcd of $a$ and $b$. The we can write
$$a=m*g$$
$$b=n*g$$
Where $m$ and $n$ are co-prime ie their gcd is 1. ( This is evident ). Now let us assume $e$ divides both $a$ and $b$. Then $e$ can't be a divisor of $m$ and $n$ because they are co-prime , it means $e$ has to be a divisor of $g$ so that it can divide both $a$ and $b$.


text:
Q: Android HTC Sense - Http Request/ Response exception Working on the emulator, but when I am trying on an HTC Sense, i have got an exception on the last line of this code
url = new URL(urlString);
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
                "application/json; charset=utf-8");

//Send request
Gson requestGson = new Gson();
OutputStream wr = connection.getOutputStream();

The exception is java.net.ProtocolException: Does not support output for the connection.getOutputStream();
I am testing on API 10, Gingerbread on an HTC Sense (remote debugging).
anyone has encountered this problem before?
Thanks.
David.

A: Try calling setDoOutput(true).  It is needed for POST requests.  The first part of your code would change to look like this:
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
            "application/json; charset=utf-8");
connection.setDoOutput(true);

Source: https://groups.google.com/forum/?fromgroups=#!topic/android-developers/2aEYpsZEMvs
See also this other StackOverflow answer: What exactly does URLConnection.setDoOutput() affect?


text:
Q: How to include file multiple times in PHP? I have a standardized sequence of code which I used to display topic information on the home page and other pages on my site. I want to throw it in an include file so that I don't have to keep fixing multiple pages. The problem is sometimes this include occurs in a while statement which means there was a previous query supplying information for sorting purposes.
When the code is raw in the while statement, it works as it should and if there are multiple ids being served to the code from the previous query, it shows multiple results. However, if this code is in an include, I will only see one result. I assume because the include file only executes once. How would I serve an include file as the equivalent as my raw code?
Include
//outside query
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
    $topic_id=htmlspecialchars( $row['topic_id'], ENT_NOQUOTES, 'UTF-8' );
    //code to display topics
    include('display_topics.php');
}

Raw Code
//outside query
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
    //code to display topics
    $sql = "SELECT * FROM topic WHERE id=?";
    $stmt = $conn->prepare($sql);
    $stmt->bindValue(1,topic_id, PDO::PARAM_INT);
    $result=$stmt->execute();
}

while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
    //yada yada
    ...
}

A: Don't do it this way.
It's much better to do one include, and to declare a function in it that does what you need:
function display_topics($topic_id)
 {
   ....
 }

Call that function inside the loop, and pass all necessary data to it.

A: Include the file as normal, but put the repeated code in a function.  Then, where you wish to add the code simply call the function.

A: That word, I don't think it is for what you think it is for.
Generally, include's use should not be used that way. That's why God invented functions (or Ada Byron, if you're not theologically inclined).
Try this instead:
function execute_row($row, $conn)
{
    $topic_id=htmlspecialchars( $row['topic_id'], ENT_NOQUOTES, 'UTF-8' );
    $sql = "SELECT * FROM topic WHERE id=?";
    $stmt = $conn->prepare($sql);
    $stmt->bindValue(1,topic_id, PDO::PARAM_INT);
    return $stmt->execute();
}

Then, in your while statement:
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
    $result = execute_row($row, $conn);
}

TADA! And the best part is, it makes your code smaller, easier to read, and faster to parse.


text:
Q: Validación PDO, si el documento no existe, muestre el valor 0 Tengo la siguiente consulta PDO para mostrar un saldo traído de la BD:
Vista
<?php
     $item = "documento";
     $valor = $documento;
     $saldo = ControladorCuadros::ctrMostrarSaldo($item, $valor);
              foreach ($saldo as $key => $value) {
                    $saldo = $value["saldo"];
              }
?>

Controlador
static public function ctrMostrarSaldo($item, $valor){
        $tabla = "datos";
        $respuesta = ModeloCuadros::mdlMostrarSaldo($tabla, $item, $valor);
        return $respuesta;
    }

Modelo
static public function mdlMostrarSaldo($tabla, $item, $valor){
        $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla WHERE $item = :$item");
        $stmt -> bindParam(":".$item, $valor, PDO::PARAM_STR);
        $stmt -> execute();
        return $stmt -> fetchAll();

        $stmt -> close();
        $stmt = null;
    }

Hasta ahí, todo bien... Me muestra el saldo cuando el documento existe en la tabla pero si no existe, muestra este error:
Notice:  Array to string conversion in C:\xampp\htdocs...\vista.php.
Cómo puedo validar si el documento no existe que me muestre el valor en cero?

A: Teniendo en cuenta lo que dice el Manual de PHP sobre fetchAll:

Valores devueltos
PDOStatement::fetchAll() devuelve un array que contiene tadas las
  filas restantes del conjunto de resultados. El array representa cada
  fila como un array con valores de las columnas, o como un objeto con
  propiedades correspondientes a cada nombre de columna. Es devuelto
  un array vacío si hay cero resultados que obtener, o FALSE en caso de
  fallo.

Puedes usar un operador ternario que evalúe el resultado de fetchAll, devolviendo dicho resultado o 0.
static public function mdlMostrarSaldo($tabla, $item, $valor){
        $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla WHERE $item = :$item");
        $stmt -> bindParam(":".$item, $valor, PDO::PARAM_STR);
        $stmt -> execute();
        /*Almacenamos el resultado en $data*/
        $data=$stmt -> fetchAll();
        /*Esto debe ir antes del return. Ya tenemos los datos, podemos cerrarlo*/
        $stmt = NULL; //Si quieres, para tranquilizar la conciencia

        /*
           *Aquí se evalúa $data:
           * - si no es FALSE o NULL devuelve $data
           * - si es FALSE o NULL devuelve 0
        */
        return ( $data ) ? $data : 0;
    }

Corrigiendo el error de lógica al recibir los datos
Dado que mdlMostrarSaldo retornará 0 en caso de no haber resultados, debes adaptar el código donde lees el resultado de la llamada a esa función. Cuando retorne 0 no puedes usar un foreach para leer los datos, porque 0 no es un array. Entonces tienes que hacer algo así:
 $saldo = ControladorCuadros::ctrMostrarSaldo($item, $valor);
 if ($saldo!=0) {
          foreach ($saldo as $key => $value) {
                $saldo = $value["saldo"];
          }
  }

ADVERTENCIA SOBRE UN ERROR DE LÓGICA: En tu código se aprecia un problema de lógica. En esta línea dentro del foreach: $saldo=$value["saldo"]; se van a sobre-escribir las posibles filas que
  retorne fetchAll, y el valor de $saldo se quedará únicamente con
  el último registro. Esto no tiene ningún sentido. No sé que uso le das
  a esos datos luego, pero lo correcto sería crear una variable de
  retorno para devolverla a la vista o donde sea. Dentro del foreach, se va concatenando cada fila (con .=) a esa variable  de retorno. Algo así:
 $saldo = ControladorCuadros::ctrMostrarSaldo($item, $valor);
 $output="No se encontraron registros";

 if ($saldo!=0) {
          $output="";
          foreach ($saldo as $key => $value) {
                $output .= $value["saldo"].PHP_EOL;
          }
  }
  //retornar o imprimir $output

Otra cosa de la que debes asegurarte es que los datos que retorna fetchAll tengan una clave llamado saldo. Para verificar puedes hacer un var_dump($saldo) antes del foreach.


text:
Q: How to align JavaScript variables from comma in PhpStorm? Before raising your finger and shoot "that's duplicate !", read carefully.
I checked in the options of PhpStorm editor, and i am not trying to do that :
var myVar           = 1;
var anotherGreatVar = 2;

or
var myVar           = 1
,anotherGreatVar    = 2;

What I am trying to do is :
var myVar           = 1
    ,anotherGreatVar = 2;

I don't care to have the variables' values aligned, what I want is the variables' names to be aligned. I really like this syntax but PhpStorm seems not to have that particular option to set, or am I wrong ?

A: I'm sure it has a source format option. Like Aptana.
I'm not sure why you want the comma before second instead after the first:
var var1 = "something",
    var2 = "someother"


text:
Q: gcd of $X^a - 1$ and $X^b - 1$ I can prove that $X^a - 1 \mid X^b - 1$ if $a\mid b$, and even that the integer division of $a$ by $b$ translates in some sense into a division of $X^a$ by $X^b$. However, I do not know how to deduce
$$\gcd(X^a-1, X^b-1) = X^{\gcd(a,b)}-1$$
I would like to know both formally why it can be proved, but also if there is something deeper to be understood (e.g. if there is a hidden notion of "morphism preserving the integer division" or so)

A: You can show that for $m\ge n$ we have
$$
\gcd(X^m - 1, X^n - 1) = \gcd(X^{m-n}-1, X^n-1), \tag{$\star$}
$$
which mimics $\gcd(m,n)=\gcd(m-n,n)$ exactly and allows you to perform the Euclidean algorithm on $m$ and $n$ instead of $X^m-1$ and $X^n-1$.
Here's the proof of $(\star)$:
\begin{align}
\gcd(\color{red}{X^m - 1}, \color{blue}{X^n - 1})
&= \gcd(\color{red}{X^m-1}-X^{m-n}(\color{blue}{X^n-1}), \color{blue}{X^n-1}) \\
&= \gcd(\color{green}{X^{m-n}-1},\color{blue}{X^n-1}).
\end{align}
Thus, using the same steps as in the Euclidean algorithm for $\gcd(m,n)$ you end up with
$$
\gcd(X^m-1,X^n-1) = \gcd(X^{\gcd(m,n)}-1,\underbrace{X^0-1}_0) = X^{\gcd(m,n)}-1.
$$


text:
Q: Convert base64 string into hex How can I convert the bytes of a base64 string to the hex representation of them using AMPScript?

A: Convert the base64 to string and that string to hex
Base 64
String tohex


text:
Q: Is there a way to launch several node tasks in a specific order? I've created a kind of framework that is a bit tedious to install right now. It needs 4 user inputs before actually starting to work and I want to reduce it to only one input.
Basically I'm just trying to know if there is a way to launch those 4 commands with only 1 input, but not all at the same time! Each task must wait the end of the previous task. My node.js knowledge is not good so I didn't really know how to find an anwser efficiently on google.
$npm install
$bower install
$gulp task1
$gulp task2

A: ok, then I made this bat file, which works :
@ECHO off
ECHO Program name
ECHO Press any key...
PAUSE > nul
CALL task1
CALL task2
CALL task3
CALL task4
PAUSE

thanks


text:
Q: Changing the Unity Color Gradient Inspector Field I'm using Unity's color gradient property field in a custom inspector drawer like this:
SerializedProperty colorGradient = property.FindPropertyRelative("colorGradient");
EditorGUI.PropertyField(pos, colorGradient);

This initializes with no valid gradient being selected. I'd like to preload the first one in the project set before the user selects one from the stored set or creates a new one.
With other PropertyField types like IntSlider, it's simple to access its .intValue member for setting it directly. From the debugger, I can see a non-public .gradientValue member, but I don't see any relevant value member for the colorGradient type that is accessible to set directly from a script. Any ideas?

A:
I want to set the default gradient to something other than a null instance that is a blank, white gradient.

Since your field is serialized it will not be null (otherwise you would already get a NullReferenceException). It is rather simply the default value used by new Gradient().
In order to have a default gradient in the Inspector you actually wouldn't need a special editor or property drawer. You only would need to assign some default values to it when you declare the field in your class:
using UnityEngine;

public class ExampleScript : MonoBehaviour
{
    [SerializeField]
    private Gradient exampleGradient = new Gradient
    {
        alphaKeys = new[]
        {
            new GradientAlphaKey(0, 0f),
            new GradientAlphaKey(1, 1f)
        },

        colorKeys = new[]
        {
            new GradientColorKey(Color.red, 0f),
            new GradientColorKey(Color.cyan, 0.5f),
            new GradientColorKey(Color.green, 1f)
        }
    };
}


text:
Q: Combo box default value I want to use combo box and the following code is working but now I want to
add to the combo box header default value ,i.e. there is value and like
Item and when you open it you have the option to change it,how I can do that?
<ComboBox  ItemsSource="{Binding Items}" SelectedValue="{Binding SelectedItem}"
 Name="comboBox1" Text="Item" Grid.Column="3" Grid.Row="2" />

the code
private List<String> _items;
private String _selectedItem;
private String _selectedBusinessItem;
public List<String> Items
{
    get { return _items; }
    set
    {
        _items = value;
        OnPropertyChanged("Items");
    }
}

public String SelectedItem1
{
    get { return _selectedItem; }
    set
    {
        _selectedItem = value;
        OnPropertyChanged("Items");
    }
}

private void InitCombo()
{
    Items = new List<string> { "item",  "Item2", "Item3" };
    SelectedItem1 = Items[0];
}

A: It's hard to understand you are asking, but I think you are just looking for the ComboBox to show the first value in the collection of Items.
I believe you can do this a few ways.
First you need to fix SelectedValue binding to match your property name, and drop the Text="Item":
<ComboBox  ItemsSource="{Binding Items}" SelectedValue="{Binding SelectedItem1}"
           Name="comboBox1" Grid.Column="3" Grid.Row="2" />

From your code you can set the SelectedValue1 property that you have to any of the string items. Examples of this:
SelectedValue1 = "item";

-or-
SelectedValue1 = Items.FirstOrDefault();

I used FirstOrDefault as a safety incase these items didn't exist.
-or-
SelectedValue1 = Items[0];

And there are several more options here. But I'm going to try and limit the scope of the answer.
Also, you should be able to set the ComboBox.SelectedIndex to 0.
<ComboBox  ItemsSource="{Binding Items}" SelectedValue="{Binding SelectedItem1}"
           Name="comboBox1" Grid.Column="3" Grid.Row="2"
           SelectedIndex="0"/>

A: I think that you're talking about the ComboBox.Text Property... from the linked page:

Gets or sets the text of the currently selected item

This is not a free field that you can display a message in. It displays the value of the currently selected item from the ComboBox.Items collection. If the text is not in one of the items, then this TextBox 'should' not display that value.
However, there are always workarounds. The correct way to do it would be to define a new ControlTemplate for the ComboBox that contains a TextBlock that is overlayed on top of the selected item TextBox and hidden when required.
Some people think that that is too much work though and so you can find a number of alternative solutions in the How to display default text "--Select Team --" in combo box on pageload in WPF? post here on StackOverflow.

A: *

*List Items = new List { "item",  "Item 2", "Item 3" };

*Set the Selected Index = 0, It will select the first element in the combo box Item-source
XAML:
<ComboBox  ItemsSource="{Binding Items}"
           Name="comboBox1" Grid.Column="3" Grid.Row="2"
           SelectedIndex="0"/>


text:
Q: Facebook Javascript SDK show value of array I'm trying to show the tags of a checkin in facebook javascript sdk, but shows only [object Object] because it is an array, I tried several ways to show this array, but could not.
The following code:
<!DOCTYPE html>

        <title>New JavaScript SDK</title>

Updated JS SDK example

<button id="fb-auth">Login</button>

I tried a few ways, such as:
checkin.tags // shows [object Object]
checkin.tags.length // shows undefined
checkin.tags.name // shows undefined
checkin.tags[0] // shows undefined
checkin.tags[0].name // Can not read property 'name' of undefined

This happens with tags, likes and comments. The others that are NOT array works fine, like "checkin.place.name", and even "checkin.place.location.latitude" brings the correct value.
I did an "console.log(JSON.stringify(checkin.tags));" and it returns:
{"data":[{"id":"100001702765878","name":"Mauricio Forte Neto"},{"id":"100001174670611","name":"Mario Celso"}],"paging":{"next":"https://graph.facebook.com/402127889842448/tags?access_token=AAAD5ih3qDDEBAIo3nB8P3ZCAwXrivw5lunDRAUvkRZCCFZBUy5au3ImicViq80HHVZC29hLDit6QwlZCXZB5WEBkDF3Pp2DrnUGWLrAwhpWddLoliyFDqd&limit=25&offset=25&__after_id=100001174670611"}}

Please, help.
Thanks in advance.

A: Since it's an object and has data in it, I have to request the data type in it.
What I been missing is to add an ".data" like:
checkin.tags.data[0].name

Now it works!!!


text:
Q: How to compute summary statistics and quantiles of user defined discrete distribution? I am interested to find out the mean, median, Variance, Skewness, Kurtosis and Quantiles of the following discrete distribution with pmf (E^((1 - E^[Nu]) n) [Nu]^x BellB[n, x])/x! with x=0,1,2......
please guide me how I compute these measures using methematica? share mathematica code.
Reg;
Amin

A: $Version

(* "12.1.1 for Mac OS X x86 (64-bit) (June 19, 2020)" *)

Clear["Global`*"]

dist = ProbabilityDistribution[(E^((1 - E^Nu) n) Nu^x BellB[n, x])/x!, {x, 0,
    Infinity, 1},
   Assumptions -> {Element[n, Integers], n >= 0},
   Method -> "Normalize"];

Verifying that the distribution is valid for some typical values of n
And @@ Table[
  Sum[PDF[dist, x], {x, 0, Infinity}] == 1, {n, 0, 5}]

(* True *)

For a specific value of n
n = 3;

Join[
  {{Style[StringForm["n = ``", n], 14, Bold], SpanFromLeft}},
  {#, #[dist]} & /@ {Mean, Variance, Skewness, Kurtosis}] //
 Grid[#, Frame -> All] &

The median and other quartiles cannot be found symbolically.


text:
Q: Google Maps Marker On Load Handler? All,
Very simply - is there an onload handler / event for when all markers have loaded?
Eg we have 26 markers being loaded, and this is loading well before the markers:
google.maps.event.addListenerOnce(map, 'idle', function(){
    // do something only the first time the map is loaded
});

Also fyi this does not work:
google.maps.event.addListenerOnce(marker,'load',function(){
// onload stuff
});

Thoughts?

A: Team,
Ok so I think I answered my own question - Not as elegant as I'd hoped but this works:
In our createMarker function, I added a 'checkloaded()' bit to the end, which checks if locations.length = markers.length:
function createMarker(add,lat,lng,marker_label) {
        var contentString = '
'+marker_label+'
';
        var marker = new google.maps.Marker({
           position: new google.maps.LatLng(lat,lng),
           map: map,
           draggable: true,
           label: labels[labelIndex++ % labels.length]
                 });

        // open marker on load
        google.maps.event.trigger(marker,'click');

        bounds.extend(marker.position);

        //Add marker to the array.
        markers.push(marker);

        checkloaded();

       }

And then:
function checkloaded(){
  if(locations.length == markers.length){
    // do onload stuff here
  }
}

If there is a proper way to do that, let me know and thank you all


text: Q: Save calculated records on non-calculated datasource First of all, really sorry for my english, I'll try to be as clear as possible. From the client I set query parameters of a datasource in a calculated model and reload the datasource. The query script call a server script that create new records for the calculted datasource. At the end I have data correctly displayed on a chart widget. Now I would like to save this data permanently in a non calculated model. Which is the best way ? I've tried to run a server script then create calculated records again, read and save all them in the non-calculated model, but in this way I created the calculated records twice, and it's not so efficient. Unfortunatly is not possible to pass items that I display on chart to server script, so which is a better ways?


text:
Q: Change of Variables -- is it always an isomorphism? I think I'm fundamentally confused about what it means to make a change of variables (in the context of an affine/projective variety).
From the usage I see, it seems to be some sort of transformation $\varphi : k[x_1,..,x_n] \rightarrow k[x_1,..,x_n]$ that relabels a polynomial expression as a variable, e.g. $\varphi(y^2/2 + x) = X$.
Do we also require a change of variables to be an isomorphism of $k[x_1,..,x_n]$? (Does anyone have a reference for the definition?)
For a concrete example, I realized my confusion reading the answers here: Hartshorne exercise 1.1 (c). I'm not sure I understand why the change of variables used there in the second answer leads to an isomorphism.

A: The concept of "changing variables" is a blanket name for the general technique of replacing some variables with other (more convenient) expressions. I'm not sure I've ever seen a rigorous definition in a text - most of the time anyone who's using it will explain enough to clue in the readers as to what they're doing.
Let's look at your concrete troubles. In both answers in your linked post, the specific changes of variable are of the form $$ x\mapsto ax+by+p$$ $$y\mapsto cx+dy+q$$ for $a,b,c,d,p,q\in k$ and each author assumes various facts which imply $ad-bc\neq 0$ in each transformation they discuss. These transformations are all automorphisms of $k[x,y]$, and we can determine their explicit inverse: all such transformations are in fact "affine transformations" of the plane $k^2$, and can be recorded in a matrix as $$\begin{pmatrix} a & b & p \\ c & d & q \\ 0 & 0 & 1 \end{pmatrix},$$ whence composition of transformations corresponds to multiplication of matrices, and inversion corresponds to inverting the matrix representing the transformation. The explicit inverse therefore corresponds to the transformation represented by the matrix $$\begin{pmatrix} \frac{d}{ad-bc} & \frac{-b}{ad-bc} & \frac{bq-dp}{ad-bc} \\ \frac{-c}{ad-bd} & \frac{a}{ad-bc} & \frac{cp-aq}{ad-bd} \\ 0 & 0 & 1 \end{pmatrix}. $$

Back to the general picture, I have seen "change of variables" used for various birational equivalences relating to elliptic curves which are not necessarily isomorphisms. I would say that generally a "change of coordinates" on an affine variety means picking different generators for the coordinate algebra - this will necessarily be an isomorphism. A "projective coordinate change" usually means acting by some automorphism of $\Bbb P^n$, which are all linear maps represented by some element in $PGL(n+1)$. So the phrasing "change of coordinates" should always imply that it's an isomorphism, while "change of variables" may not in some cases.

A: A change of variables always means an isomorphism. In the case of the answer to the linked question, we have $$p(x,y) = x^2 + a(y)x+b(y) = \left(x+ \frac{a(y)}{2}\right)^2 + b(y)-\frac{a(y)^2}{4}= \left(x+ \frac{a(y)}{2}\right)^2 + B(y) $$
where we put $B(y) = b(y)-\frac{a(y)^2}{4}$. The change of variables is just $$(z,w) = \varphi(x,y) = \left(x+ \frac{a(y)}{2}, y \right)$$
which is an isomorphism $k[x,y] \rightarrow k[z,w]$ if the characteristic of $k$ is different from two.
In these new variables the curve is given by $( p \circ \varphi^{-1}) (z,w) = z^2 + B(w) $ as it is claimed.


text: Q: Как приостановить выполнения скрипта до пользовательских действий? Есть следующая проблема. Во время ajax-запроса формируется модальное окно. Я заменяю все alert() и confirm() на модальные окна. Необходимо приостановить выполнение скрипта до пользовательских действий. Грубо говоря, если пользователь нажмет кнопку "ok" скрипт продолжиться выполняться дальше, а если нажмет кнопку отмены, то скрипт будет отрабатывать по другому варианту. Нужно именно функционал как при alert() приостановить скрипт пока пользователь не нажмет кнопку


text:
Q: How do I add a Linode-hosted subdomain to a Namecheap domain hosted on NearlyFreeSpeech? I have the domain somedomain.com registered with Namecheap. NearlyFreeSpeech hosts the site.
I've added ns.phx1.nearlyfreespeech.net and
ns.phx2.nearlyfreespeech.net to that domain's custom nameservers
list on Namecheap.
I'd like to add a subdomain
"test" so that test.somedomain.com goes to my Linode box. Where must I change/add records to accomplish this?
Update
I added A and AAAA records to my NearlyFreeSpeech DNS settings.
My A record looks kinda like this:
test.somedomain.com A MY.IP.ADDRESS.HERE
But when I go to test.somedomain.com, I get a Bad Request (400) error.
Update 2
I'm using nginx. I followed Linode's tutorial on setting up a Django project on an Ubuntu 14.04 box.
Maybe I configured the hostname file wrong?
Here's what's in my /etc/hosts:
127.0.0.1       localhost.localdomain   loclhost
127.0.1.1       ubuntu.members.linode.com       ubuntu
MY.LINODE.IP.ADDRESS    dev.somedomain.com       dev


text:
Q: Object Memory Management Python Vs Java Can some one explain on the way Python manages memory management during creation of an object in class.
For example in java we can only declare member variables and the initialisation part happens inside the constructor. That means memory used when an object is constructed.
But in python we can initialise a class variable outside the init method. Where is this data stored?

A: As a precursor, this question has already been answered here, this may also be a good reference. However, I will try to explain it again. The init method in Python is designed for conventional use and although a special method in the fact that it is reserved to go at the beginning of a method it is not required. Memory management in Python involves a private heap containing all Python objects and data structures. If you were to initialize a class variable outside the init method declaration, it would simply be stored in the heap along with those initialized in the init method. Hope this helps!


text:
Q: Python Primary to Secondary colors so I have a problem that asks me for two primary colors and tells me the color they create, however when I enter the two primary colors I keep getting the error message that I put in if they don't enter two primary colors. Here is what I have.
red = '1'
blue = '2'
yellow = '3'

p1 = (input('Enter primary color: '))
p2 = (input('Enter primary color: '))

if p1 == '1' and p2 == '2':
    print('When you mix red and blue, you get purple')
elif p1 == '3' and p2 == '1':
    print('When you mix yellow and red, you get orange')
elif p1 == '2' and p2 == '3':
    print('When you mix blue and yellow, you get green')
else:
    print('You didnt input two primary colors.')

A: It seems you're using Python 2.x. Replace the occurrences of input with raw_input and you will achieve your goal.

A: I'm treating this as a python 3 problem, as you have tagged both.
Your problem is that when you type in your primary colour, you are entering "red", "yellow" or "blue". Python doesn't recognise these as values, as p1 is being set to "red" not "1", thus the comparison will not work.
This code should work:
p1 = (input('Enter primary color (red: 1, blue: 2, yellow: 3): '))
p2 = (input('Enter primary color (red: 1, blue: 2, yellow: 3): '))

if p1 == '1' and p2 == '2':
    print('When you mix red and blue, you get purple')
elif p1 == '3' and p2 == '1':
    print('When you mix yellow and red, you get orange')
elif p1 == '2' and p2 == '3':
    print('When you mix blue and yellow, you get green')
else:
    print('You didnt input two primary colors.')

EDIT: the below code does as you have asked
p1 = input('Enter primary color (red, blue, yellow): ')
p2 = input('Enter primary color (red, blue, yellow): ')

red = 'red'
blue = 'blue'
yellow = 'yellow'

if p1 == red and p2 == blue:
    print('When you mix red and blue, you get purple')
elif p1 == yellow and p2 == red:
    print('When you mix yellow and red, you get orange')
elif p1 == blue and p2 == yellow:
    print('When you mix blue and yellow, you get green')
else:
    print('You didnt input two primary colors.')


text:
Q: Java Wait and Notify: IllegalMonitorStateException I don't completely understand how wait and notify (of Object) work, and as a result I'm forced to slim down my attempts into the following section of code.
Main.java:
import java.util.ArrayList;

class Main
{
  public static Main main = null;

  public static int numRunners = 4;
  public static ArrayList<Runner> runners = null;

  public static void main(String[] args)
  {
    main = new Main();
  }

  Main()
  {
    runners = new ArrayList<Runner>(numRunners);

    for (int i = 0; i < numRunners; i++)
    {
      Runner r = new Runner();
      runners.add(r);
      new Thread(r).start();
    }

    System.out.println("Runners ready.");
    notifyAll();
  }
}

Runner.java:
class Runner implements Runnable
{
  public void run()
  {
    try
    {
      Main.main.wait();
    } catch (InterruptedException e) {}
    System.out.println("Runner away!");
  }
}

Currently I get an IllegalMonitorStateException when calling Main.main.wait();, but I don't understand why.  From what I can see, I need to synchronize Runner.run, but in doing so I assume it would only notify one thread, when the idea is to notify them all.
I've looked at java.util.concurrent, but I can't find a suitable replacement (maybe I'm just missing something).

A: You can't wait() on an object unless the current thread owns that object's monitor. To do that, you must synchronize on it:
class Runner implements Runnable
{
  public void run()
  {
    try
    {
      synchronized(Main.main) {
        Main.main.wait();
      }
    } catch (InterruptedException e) {}
    System.out.println("Runner away!");
  }
}

The same rule applies to notify()/notifyAll() as well.
The Javadocs for wait() mention this:

This method should only be called by a thread that is the owner of this object's monitor. See the notify method for a description of the ways in which a thread can become the owner of a monitor.

  Throws:

  IllegalMonitorStateException – if the current thread is not the owner of this object's monitor.

And from notify():

A thread becomes the owner of the object's monitor in one of three
  ways:

*

*By executing a synchronized instance method of that object.

*By executing the body of a synchronized statement that synchronizes on the object.

*For objects of type Class, by executing a synchronized static method of that class.

A: You're calling both wait and notifyAll without using a synchronized block. In both cases the calling thread must own the lock on the monitor you call the method on.
From the docs for notify (wait and notifyAll have similar documentation but refer to notify for the fullest description):

This method should only be called by a thread that is the owner of this object's monitor. A thread becomes the owner of the object's monitor in one of three ways:

*

*By executing a synchronized instance method of that object.

*By executing the body of a synchronized statement that synchronizes on the object.

*For objects of type Class, by executing a synchronized static method of that class.

Only one thread at a time can own an object's monitor.

Only one thread will be able to actually exit wait at a time after notifyAll as they'll all have to acquire the same monitor again - but all will have been notified, so as soon as the first one then exits the synchronized block, the next will acquire the lock etc.


text:
Q: logo will change when scroll down I'm kinda stuck doing this, so I need your help :)
I am currently working on a project in Shopify
and here are the problem on my site:

*

*Scroll down a bit, the navigation Menu will appear with its heritage logo [black] with white background. Now open the shop button then scroll it up, the white background of the navigation should remain along with the heritage logo [black] plus the search icon [black]

*Scroll down a bit, the navigation Menu will appear with its heritage logo [black] with white background. now open the shop button then close it, the heritage logo [black] should remain with the white background plus the search icon [black]
You can test my work here JSbin
or if you want to see the live website:
click here and the password is: chough
Please let me know what further information needed, to understand it better.
Thanks in Advance :)
JAVASCRIPT & HTML

$(document).ready(function(){

  //jQuery.scrollSpeed(50, 800);

  $('#shop-menu-dropdown').on('click', function (e) {

    if($('.livery-collection-menu-container').hasClass('hide')) {

      $('.sticky-target-menu').addClass('collection-menu-open').css('transition', 'all 0.5s ease-in-out');
      $('.livery-collection-menu-container').slideDown().removeClass('hide');
      $('#logo-img img')
              .css( {'height': '55px', 'position': 'relative', 'top': '10px',} )
              .attr('src','https://cdn.shopify.com/s/files/1/0893/1740/t/2/assets/logoblack2.png?16348450756183240677');
      $('.livery-search-button')
              .attr('src','http://cdn.shopify.com/s/files/1/0893/1740/t/2/assets/icon-search.png?2506340321008419925');

    } else {

      $('.sticky-target-menu').removeClass('collection-menu-open').css('transition', 'all 0.5s ease-in-out');
      $('.livery-collection-menu-container').slideUp().addClass('hide');
      $('#logo-img img')
          .css( {'height': '70px', 'position': 'relative', 'top': '10px',} )
              .attr('src','https://cdn.shopify.com/s/files/1/0893/1740/t/2/assets/logo.png?15237508448918884431');
      $('.livery-search-button')
              .attr('src','http://cdn.shopify.com/s/files/1/0893/1740/t/2/assets/icon-search-light.png?16581710301453831089');
    }
    e.preventDefault();

  });
      $(window).scroll(function(){
        if($(this).scrollTop() > 1) {
          // $('#logo-img img').fadeOut('slow');
          $('#logo-img img')
              .css( {'height': '55px', 'position': 'relative', 'top': '10px',} )
              .attr('src','https://cdn.shopify.com/s/files/1/0893/1740/t/2/assets/logoblack2.png?16348450756183240677');
          $('.livery-search-button')
              .attr('src','http://cdn.shopify.com/s/files/1/0893/1740/t/2/assets/icon-search.png?2506340321008419925');

        }
        if($(this).scrollTop() < 1) {
          // $('#logo-img img').fadeIn('fast');
          $('#logo-img img')
              .css( {'height': '70px', 'position': 'relative', 'top': '10px',} )
              .attr('src','https://cdn.shopify.com/s/files/1/0893/1740/t/2/assets/logo.png?15237508448918884431');
          $('.livery-search-button')
              .attr('src','http://cdn.shopify.com/s/files/1/0893/1740/t/2/assets/icon-search-light.png?16581710301453831089');
        }
        if($(this).scrollTop() > 1) {
          // $('#logo-img img').fadeOut('slow');
          $('#logo-img2 img')

              .attr('src','https://cdn.shopify.com/s/files/1/0893/1740/t/2/assets/good_company_logo.png?15237508448918884431');
        }
        if($(this).scrollTop() < 1) {
          // $('#logo-img img').fadeIn('fast');
          $('#logo-img2 img')

              .attr('src','https://cdn.shopify.com/s/files/1/0893/1740/t/2/assets/goodcompanylogo.png?15237508448918884431');
        }
    });
});

          {% if template contains 'product' or template contains 'page' or template contains 'search' or template contains 'cart' or template contains 'checkouts'%}

              {% include 'dropdown-tumblr' %}

                     {% if settings.use_logo %}

                     {% else %}
                     {{ shop.name }}
                     {% endif %}

                    ${{amount}} CAD
                   {% include 'custom-currency-picker' %}

                {% include 'mobile-menu' %}

                  {% for link in linklists.collection-menu.links %}
                  {% if linklists[link.handle] == empty %}

                      {{ link.title }}

                  {% else %}

                    {{ link.title }}

                      {% for l in linklists[link.handle].links %}

{{ l.title }}

                      {% endfor %}

                  {% endif %}
                  {% endfor %}

          {% elsif blog.title == 'Good Company' %}
          {{ 'changelogo.js' | asset_url | script_tag }}

              {% include 'dropdown-blog' %}

                     {% if settings.use_logo %}

                     {% else %}
                     {{ shop.name }}
                     {% endif %}

                    ${{amount}} CAD
                   {% include 'custom-currency-picker' %}

                {% include 'mobile-menu-blog' %}

          {% else %}

          {{ 'changelogo.js' | asset_url | script_tag }}

              {% include 'dropdown' %}

                     {% if settings.use_logo %}

                     {% else %}
                     {{ shop.name }}
                     {% endif %}

                    ${{amount}} CAD
                   {% include 'custom-currency-picker' %}

                  {% include 'mobile-menu' %}

                  {% for link in linklists.collection-menu.links %}
                  {% if linklists[link.handle] == empty %}

                      {{ link.title }}

                  {% else %}

                    {{ link.title }}

                      {% for l in linklists[link.handle].links %}

{{ l.title }}

                      {% endfor %}

                  {% endif %}
                  {% endfor %}

          {% endif %}

A: Why not trying adding a condition for the sticky-target-menu and comment your scroll functions out. Even when the bar is open  at the top, to show the black logo. You don't have problems when it's closed down.
if ($('.sticky-target-menu').hasClass('collection-menu-open')){
    $('#logo-img img')
    .css( {'height': '55px', 'position': 'relative', 'top': '10px',} )
    .attr('src','https://cdn.shopify.com/s/files/1/0893/1740/t/2/assets/logoblack2.png?16348450756183240677');
      $('.livery-search-button')
              .attr('src','http://cdn.shopify.com/s/files/1/0893/1740/t/2/assets/icon-search.png?2506340321008419925');

}


text:
Q: Is converting a number to string using string template a bad idea? I am learning Kotlin and I came across string template, and find it very amazing!
Soon I discovered that a number can be converted to string with the help of it.
I know that toString() is the recommended way. But I want to understand, is the below method advisable to use and what good is the efficiency?
fun main() {
    val integer: Int = 19
    val string1: String = "$integer"
    val string2: String = integer.toString()
    println(string1)
    println(string2)
}

Output:
19
19

A: Check This SO thread to understand how string interpolation is actually implemented in kotlin:
Bottom line you'll have a StringBuilder that is created every time when you perform an interpolation. This alone makes this method less efficient then a "simple and straight-to-the-point" integer.toString()
An additional reason is code clarity I would say: the usage of string interpolation for conversion from integer to string looks non-intuitive - so use the right tool for the right job, you know :)


text:
Q: How to use immutable object without operator=() in procedural code Given an immutable C++ object (its members are const, which means its operator=() method does not exist), how do you implement this simple procedural pattern (which would require Object::operator=() to exist):
Object someObject {17};

// ...

if (...) {
   someObject = Object {42};
}

// ...

use(someObject);

A: A workaround is to use shared_ptr.
shared_ptr<Object> someObject(new  Object(17));
shared_ptr<Object> anotherObject(new Object(42));
// ...

if (...) {

   someObject = anotherObject;
}

use(someObject);

A: My pattern in such a situation is to extract initialization code into a function:
Object ini(...){
      if(...) {
            return Object{42};
      }
      return Object{17};
}
.....
Object someObject=ini(...);// copy constructor used (or not, because of RVO)
use(someObject);

If initialization is simple you could use:
Object someObject = ...? Object{42} : Object{17};

It is not very different to declaring your o-variable const.

If the someObject=17 is used and then replaced with someObject=42 - it's just undermining the good intentions which were pursued by declaring some members const.
There are two alternatives:

*

*declaring some members const was not such bright idea - it can be undone and  an assigment operator can be added.

*using Object  as it was meant to be used.

What should not be done lightly: making some tricks with pointers/references - it will just make your code more complex as it is. Better to use a new variable if needed:
Object someObject {17};

// ...

Object newSomeObject = ... ? Object {42} : someObject {17};
use(newSomeObject);

In the case that copying of the old object could be a performance problem, the code can be refactored in such a way, that
use(need42(..) ? create42() : object17);

can be used without copying data. This solution assumes that use uses a const reference of its argument or the parameter is passed by-value.

In my opinion every change of an immutable object should yield a new object, otherwise, the following can happen:
ImmutableObject obj(1);
ImmutableObject &ref=obj;//ref.member=1
...
obj=ImmutableObject(2);
//ref.member!=1, that is puzzling, I assumed ref to be immutable!

Now, the user of your object (via ref) gets irritated because the object was changed! The whole point of the immutability is that you can reason, that the values never ever change. If they can change, there is not that many advantages in using "immutables" in the first place.

A: The other answers work when your initialization logic may be simple, but if you're detangling some spaghetti code, this might help.
If it isn't, take from java (they might not have invented it, but I see java programmers use this most) -- the builder pattern. Here are two possible ways of implementing it in C++.
#include <string>

class ImmutableClass {
 public:
  ImmutableClass(int a, int b, std::string c) : a_(a), b_(b), c_(c) {}
  // Getters...
 private:
  ImmutableClass& operator=(const ImmutableClass&) = delete;
  const int& GetA() {return a_;}
  const int& GetB() {return b_;}
    const std::string& GetC() {return c_;}
    const int a_;
    const int b_;
    const std::string c_;
};

struct ImmutableClassBuilderExampleOne {
 public:
  // Note the default initialization to avoid undefined behavior.
  int a = 0;
  int b = 0;
  std::string c;
};
// Less boilerplate, less encapsulation, if that's your thing.
ImmutableClass BuildImmutableClass(const ImmutableClassBuilderExampleOne& icb) {
    return ImmutableClass(icb.a, icb.b, icb.c);
}

// More boilerplate, more encapsulation, can be "tidied" with macros.
class ImmutableClassBuilderExampleTwo {
 public:
  const ImmutableClass build() {
    return ImmutableClass(a_, b_, c_);
  }
  ImmutableClassBuilderExampleTwo& setA(const int a) {
    a_ = a;
    return *this;
  }
  ImmutableClassBuilderExampleTwo& setB(const int b) {
    b_ = b;
    return *this;
  }
  ImmutableClassBuilderExampleTwo& setC(const std::string& c) {
    c_ = c;
    return *this;
  }
 private:
  // Note the default initialization to avoid undefined behavior.
  int a_ = 0;
  int b_ = 0;
  std::string c_;
};


text:
Q: How HashSet works with regards to hashCode()? I'm trying to understand java.util.Collection and java.util.Map a little deeper but I have some doubts about HashSet funcionality:
In the documentation, it says: This class implements the Set interface, backed by a hash table (actually a HashMap instance). Ok, so I can see that a HashSet always has a Hashtable working in background. A hashtable is a struct that asks for a key and a value everytime you want to add a new element to it. Then, the value and the key are stored in a bucket based on the key hashCode. If the hashcodes of two keys are the same, they add both key values to the same bucket, using a linkedlist. Please, correct me if I said something wrong.
So, my question is: If a HashSet always has a Hashtable acting in background, then everytime we add a new element to the HashSet using HashSet.add() method, the HashSet should add it to its internal Hashtable. But, the Hashtable asks for a value and a key, so what key does it use? Does it just uses the value we're trying to add also as a key and then take its hashCode? Please, correct me if I said something wrong about HashSet implementation.
Another question that I have is: In general, what classes can use the hashCode() method of an java object? I'm asking this because, in the documentation, it says that everytime we override equals() method we need to override hashCode() method. Ok, it really makes sense, but my doubt is if it's just a recommendation we should do to keep everything 'nice and perfect' (putting in this way), or if it's really necessary, because maybe a lot of Java defaults classes will constantly uses hashCode() method of your objects. In my vision, I can't see other classes using this method instead of those classes related to Collections. Thank you very much guys

A: If you look at the source for HashSet (the source comes with the JDK and is very informative), you will see that it creates an object to use as the value:
// Dummy value to associate with an Object in the backing Map
private static final Object PRESENT = new Object();

Each value that is added to the HashSet is used as a key to the backing HashMap with this PRESENT object as the value.
Regarding overriding equals() whenever you override hashCode() (and vice versa), it is very important that these two methods return consistent results. That is, they should agree with one another. For more details, see the book Effective Java by Josh Bloch.

A: If you look at the actual javacode of HashSet you can see what it does:
 // Dummy value to associate with an Object in the backing Map
private static final Object PRESENT = new Object();
...

 public boolean add(E e) {
    return map.put(e, PRESENT)==null;
}

So the element you are adding is the Key in the backing hashmap with a dummy value as the value.  this dummy value is never actually used by the hashSet.
Your second question regarding overriding equals and hashcode:
It is really necessary to always override both if you want to override either one.  This is because the contract for hashCode says equal objects must have the same hashcode.  the default implementation of hashcode will give different values for each instance.
Therefore, if you override equals() but not hashcode() This could happen
object1.equals(object2) //true

MySet.add(object1);

MySet.contains(object2); //false but should be true if we overrode hashcode()

Since contains will use hashcode to find the bucket to search in we might get a different bucket back and not find the equal object.


text:
Q: puts statements in production It happens many a times that in development mode to debug we intensively use puts statements and later miss to remove them when the code moves to production. Does removing them help us increase the response time? I am unable to test this scenario in local as they get printed in the server console, but in production i'm sure they are not getting printed in any of the logs. I'm also curious if they are executed then where is the output directed to in production. Is there a way to find out?

A: First, don't use puts sprinkled everywhere. Bottleneck your "debug" output in a single method. That way you can very easily control the output, redirect it, massage it, etc. For instance, these might be the growth from a simple logging method to something more sophisticated:
def debug_output(s)
  STDERR.puts s
end

---

DEBUG_OUTPUT_MINIMUM_LEVEL = 3
def debug_output(s, level=DEBUG_OUTPUT_MINIMUM_LEVEL)
  STDERR.puts s if level >= DEBUG_OUTPUT_MINIMUM_LEVEL
end

---

require 'logger'

LOGGER_OUTPUT_FILE = '/path/to/log/output'
def debug_output(s)
  @logger ||= Logger.new(LOGGER_OUTPUT_FILE)
  @logger << s
end

There are better tools available to you than puts though. Learn to use the debugger, or PRY in debugging mode and/or use Ruby's built-in Logger or Syslog so you can control the debugging level output.
Historically, Ruby's documentation for using Syslog was pretty... lacking. In Ruby v2.0 it's MUCH improved and quite well documented now, so if you want real power look at either Logger or Syslog and Syslog::Logger.
This is from the documentation for Syslog. Consider the impact to your code debugging/logging if you could do these things:

Syslog messages are typically passed to a central logging daemon. The daemon may filter them; route them into different files (usually found under /var/log); place them in SQL databases; forward them to centralized logging servers via TCP or UDP; or even alert the system administrator via email, pager or text message.

A: It is for certain that having puts increases response time. The real question is how much. If you have a console open, then it will take up much time. I usually use emacs instead of a console, and just having things printed out on the emacs shell mode sometimes takes enormous time. But no matter how less the extra time is, there is no reason you should not remove them when you do not need them.
In the long run, what the Tin Man suggests is right, but if you want to be lazy and do a temporal hack, one way to deal with it is to overwrite puts to do nothing.
def puts *_; end


text:
Q: Can I login gmail before use selenium to click gmail menu? I want to use selenium click gmail menu but when I run selenium it alway have to login gmail. Can I login gmail for bypass login before use selenium to click gmail menu?
browser = webdriver.Firefox()
browser.get('https://mail.google.com/mail/u/1/?ogbl#inbox')

A: You can use Selenium to login for you with your username and password:
email = browser.find_element_by_id('Email')
email.send_keys('username')
next_button = browser.find_element_by_id('next')
next_button.click()
time.sleep(1)
password = browser.find_element_by_id('Passwd')
password.send_keys('password')
login = browser.find_element_by_id('signIn')
login.click()

A: One way or another you will have to login to gmail. I am not a selenium expert buy why can't you simply do the following:
browser = webdriver.Firefox()
browser.get('https://mail.google.com/mail/u/1/?ogbl#inbox')
input('Manually login and hit return when done:')
# continue from the post-login screen (i.e. the inbox)

But it would probably be simpler to just program the login as suggested by @olenscki (I have not verified whether his solution works or not).


text:
Q: Windows Phone 7 Emulator is very long to load I have the Windows Phone 7.1 SDK on my computer with Visual Studio 2010 Ultimate.
I have developped an application but when I want to start it in emulator, it takes about 2 hours to load it, and it's just the O/S! The application isn't started!
Is there a way to view the Task Managerof Windows Phone to know why it doesn't load?
Specs:
Intel Core 2 Duo 3.0Ghz VT-x
2GB of DDR2 RAM (800Mhz)
Windows 7 Professionnal SP1 64-bit

A: Well I think your system is simply to weak.
2GB RAM itself are enough to use windows 7 and some aplications but for your purpose that should be not enough. From myself developing (not for mobile devices though) I know that you have at least some different tools open besides your IDE. Visual Studio 2010 itself is not so memory hungry, but the Ultimate Edition (can) install a lot of junk. The whole sql database stuff and more, I personally never used that though. I guess there is a browser open, too, maybe some pdf-reader and some text editor. Your chat client etc pp.
All this stuff eats up memory and emulation itself is a very complex task to do. Eg a gameboy itself is not a very powerful device, but emulating a gameboy can eat a lot of a x86 CPUs power, because of architectural differences. Emulating the Win Phone Architecture will surely be a heavy task, too.
The WinPhone SDK has a minimum memory requirement of 3GB RAM. If you don't have enough memory available your OS will begin swapping memory to the harddrive, because you don't have enough memory available for the application itself this can lead windows to swap parts of the application away that it will need just seconds later. Windows basically does not execute the SDK from RAM (as it should) but from your harddrive. And besides all of that your CPU will have to emulate some other architecture.
I think you are just trying to stretch your computer far beyond its abilities.


text:
Q: Sonata Admin - Boolean editable not working after update Boolean edition from list is not working anymore after updating Sonata Admin Bundle to dev-master. I can't click on the field.
Here is my admin class
protected function configureListFields(ListMapper $listMapper)
{
    $listMapper
        ->add('highlighted', 'boolean', ["editable" => true])
    ;
}

Here is my composer.json
"sonata-project/core-bundle": "dev-master",
"sonata-project/block-bundle" : "dev-master",
"sonata-project/exporter" : "1.3.1",
"sonata-project/jquery-bundle" : "dev-master",
"sonata-project/cache-bundle" : "dev-master",
"sonata-project/intl-bundle" : "dev-master",
"sonata-project/admin-bundle" : "dev-master",
"sonata-project/doctrine-orm-admin-bundle" : "dev-master"

My question is : Is it a bundle version problem? Is edition from list just not supported anymore by the latest version of Sonata Admin Bundle? Or am I doing it wrong?
Thanks for you help

A: I had similar problem, not with boolean, but with sonata_type_model_list type. It is not working with dev-master. Then I revert doctrine-orm-admin-bundle to latest stable version and now it works.
Solution might be (if you are using doctrine/orm 2.3)
"sonata-project/doctrine-orm-admin-bundle": "2.2.*",

if you are using doctrine/orm 2.4
"sonata-project/doctrine-orm-admin-bundle": "2.3.*",

A: I had a similar problem too.
In composer.json I have:
    "sonata-project/doctrine-orm-admin-bundle": "2.2.x@dev",
    "sonata-project/admin-bundle": "2.2.*@dev"

All the other bundles will come from dependencies.
Before you run 'composer install', do not forget to run 'composer self-update' and delete the vendors folder!


text:
Q: Deep linking. Is it possible to create intent filter to detect urls without https or http scheme? I'm trying to get deep linking working in my app. I'd like to detect three url types: one with https (for example https://my-app.com), one with http (http://my-app.com) and one without any scheme (my-app.com). First two works just fine, but how to get third one working?
So far i get this code:
<intent-filter>
            <data
                android:host="my-app.com"
                android:scheme="http" />
            <data
                android:host="my-app.com"
                android:scheme="https" />

            <action android:name="android.intent.action.VIEW" />

            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />
        </intent-filter>

I tried with <data android:scheme="my-app.com" />, but no luck.
Thanks in advance for any hints.


text:
Q: AWS Python Athena Install Error on pip install jupyter-athena-sql Facing issue on installing jupyter-athena-sql . Seems like its because of jupyter-athena-sql requires a package from  pyathena.converter called TypeConverter.
!pip install pyathena # Worked
from pyathena.converter import Converter # Worked
!pip install jupyter-athena-sql # **Error**

from .connection import get_connection
File "/tmp/pip-install-t_sccvpk/jupyter-athena-sql_94bbe189a6af434d96bd640e62b8dfbf/athena/connection.py",
line 11, in

    from pyathena.converter import TypeConverter
ImportError: cannot import name 'TypeConverter'
---------------------------------------- WARNING: Discarding https://files.pythonhosted.org/packages/43/ea/f8dc5177d8048ef1fa84eb6861d758c254c8438d9826dd84a92b26c48d2e/jupyter-athena-sql-0.0.4.tar.gz#sha256=4b45d8fbaa730cdd4ce70e71c445571d80be35769baaabe4394808c7f2b9d36c

(from https://pypi.org/simple/jupyter-athena-sql/).

Command errored

out with exit status 1: python setup.py egg_info Check the logs for
full command output. ERROR: Could not find a version that satisfies
the requirement jupyter-athena-sql (from versions: 0.0.4) ERROR: No
matching distribution found for jupyter-athena-sql

A:  pip uninstall pyathena
 pip install pyathena==1.2.0

See: https://github.com/markfink/jupyter-athena-sql/blob/develop/requirements.txt


text:
Q: Django use multiple databases dynamically without defining in settings TL;DR: Besides my default django database, i need data pulled in from two different user-selected databases. not sure how to setup django to access these besides just running manual queries using connection.cursor().execute("SQL")
Situtaion:
A process creates a sqlitedb. The database is imported into mysql. I'm writing a django app that interacts with that mysql database (call it StreamDB), another mysql database with additional info user needs to see (call this SourceDB), and of course the default Django app mysql DB (call it AppDB).
There will be two versions of SourceDB (prod and test) the StreamDB imported maps to data to one and only one of these SourceDB's.
I have a table/model in my "AppDB" that identifies these sources (the StreamDB name, which of the two SourceDB's it maps to, and some other data. Here's a sample record:
name: foo
path: /var/www/data/test/foo.sqlite
db_name: foo
source_db_name: bar
date_imported: 2014-05-03 10:20:30

These are managed through the django admin and added manually (or dyanmically via external script)
Dilemma
Depending on which source is selected, my SQL needs to join the tables from those two DB's. Example query with dyanmic db names in :
SELECT a.image_id, a.image_name, b.title, b.begin_time
FROM <selected_streamdb>.image a JOIN <selected_sourcedb>.event b ON b.event_id = a.event_id
WHERE a.image_type = 'png'

Do I fill in  and  with variables perhaps?
Question
Is there anyway to use Django's ORM model in a situation like this? Can django grab the DATABASE.settings from a DB table? Do I create a model that manages this? (i.e. the source-table above?)
I don't mind managing db permissions on the backend (assume app database user in django settings has access to all of the databases)
Hope all of the above makes sense.


text:
Q: How Can I Retrieve A MySQL Table Into An Array Then Use The Array Contents In A Function I'm trying to work something out but I just can't get it to work. I need to do the following:

*

*Pull data from a MySQL Table

*Store that data in an array

*Use that data from the array in a Function.

Current code looks like this (currently pulls data from MySQL Table and iterates over it, putting it in a table (purely to check it worked).
mysql_connect("localhost", "*****", "*****") or die(mysql_error());

mysql_select_db("*****") or die(mysql_error());

$data = mysql_query("SELECT batch FROM widgetBatches")  or die(mysql_error());

Print "
";

while($info = mysql_fetch_array( $data ))  {  Print "
";
                                            Print "Batch:	 ".$info['batch'] . "	 ";
                                            Print "" . "
";
                                           }  Print "
";

Here's the function, $widgetBatches needs to take the array from the previous code however nothing i've tried works. (there is more to the Widget() however it's not relevant to this issue. Thanks in advance!
$uI = 550;

Widget($uI);

function Widget($input) {
    $currentValue = $input;
    $i = 0;
    $widgetBatches = [250, 500, 1000, 2000];

    while ($currentValue > 0) {
        $i++;
        echo "Batch Number " . $i . "
";
        echo "Widgets Left To Fulfill Order: " . $currentValue . "
";
        $closest = ClosestBatch($widgetBatches, $currentValue);
        echo "Closest Batch Available: " . $closest . "
";
        $currentValue = $currentValue - $closest;
        echo "Remaining Widgets: " . abs($currentValue) . "
";
    }

    echo "
";
}