问:
Crystal Report sends Object reference not set to an instance of an object
I am using Crystal Report for VS and WFP to view the report on a window.
At the beginning I was facing this error:

```<code>System.ArgumentNullException -- System.ArgumentNullException: Value cannot be null.
Parameter name: window
</code>```

Then I fixed it following this solution.

Now another vague message appears that I couldn't find for it a solution even following this:

```<code>System.NullReferenceException -- System.NullReferenceException: Object reference not set to an instance of an object.
   at SAPBusinessObjects.WPF.Viewer.ReportAlbum.RefreshReport()
   at SAPBusinessObjects.WPF.Viewer.CrystalReportsViewer.RefreshReport_Executed(Object sender, ExecutedRoutedEventArgs e)
   at System.Windows.Input.CommandBinding.OnExecuted(Object sender, ExecutedRoutedEventArgs e)
   at System.Windows.Input.CommandManager.ExecuteCommandBinding(Object sender, ExecutedRoutedEventArgs e, CommandBinding commandBinding)
   at System.Windows.Input.CommandManager.FindCommandBinding(CommandBindingCollection commandBindings, Object sender, RoutedEventArgs e, ICommand command, Boolean execute)
   at System.Windows.Input.CommandManager.FindCommandBinding(Object sender, RoutedEventArgs e, ICommand command, Boolean execute)
   at System.Windows.Input.CommandManager.OnExecuted(Object sender, ExecutedRoutedEventArgs e)
   at System.Windows.UIElement.OnExecutedThunk(Object sender, ExecutedRoutedEventArgs e)
   at System.Windows.Input.ExecutedRoutedEventArgs.InvokeEventHandler(Delegate genericHandler, Object target)
   at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
   at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
   at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
   at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
   at System.Windows.UIElement.RaiseEvent(RoutedEventArgs args, Boolean trusted)
   at System.Windows.Input.RoutedCommand.ExecuteImpl(Object parameter, IInputElement target, Boolean userInitiated)
   at System.Windows.Input.RoutedCommand.ExecuteCore(Object parameter, IInputElement target, Boolean userInitiated)
   at MS.Internal.Commands.CommandHelpers.CriticalExecuteCommandSource(ICommandSource commandSource, Boolean userInitiated)
   at System.Windows.Controls.Primitives.ButtonBase.OnClick()
   at System.Windows.Controls.Button.OnClick()
   at System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(MouseButtonEventArgs e)
   at System.Windows.UIElement.OnMouseLeftButtonUpThunk(Object sender, MouseButtonEventArgs e)
   at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
   at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
   at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
   at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
   at System.Windows.UIElement.ReRaiseEventAs(DependencyObject sender, RoutedEventArgs args, RoutedEvent newEvent)
   at System.Windows.UIElement.OnMouseUpThunk(Object sender, MouseButtonEventArgs e)
   at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
   at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
   at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
   at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
   at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
   at System.Windows.UIElement.RaiseTrustedEvent(RoutedEventArgs args)
   at System.Windows.UIElement.RaiseEvent(RoutedEventArgs args, Boolean trusted)
   at System.Windows.Input.InputManager.ProcessStagingArea()
   at System.Windows.Input.InputManager.ProcessInput(InputEventArgs input)
   at System.Windows.Input.InputProviderSite.ReportInput(InputReport inputReport)
   at System.Windows.Interop.HwndMouseInputProvider.ReportInput(IntPtr hwnd, InputMode mode, Int32 timestamp, RawMouseActions actions, Int32 x, Int32 y, Int32 wheel)
   at System.Windows.Interop.HwndMouseInputProvider.FilterMessage(IntPtr hwnd, WindowMessage msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   at System.Windows.Interop.HwndSource.InputFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
   at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
   at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
   at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
   at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
   at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
   at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
   at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
   at System.Windows.Application.RunDispatcher(Object ignore)
   at System.Windows.Application.RunInternal(Window window)
   at System.Windows.Application.Run(Window window)
   at System.Windows.Application.Run()
   at Inspector_Reporter_MDK.App.Main() -- Object reference not set to an instance of an object.
</code>```

My report doesn't have any fields, and of course there are no
parameters I send.

All the text are contained in the page size.

My code behind setting the report to print:

```<code>public void PrintReport()
{
    string reportPath = System.IO.Path.Combine(new System.IO.DirectoryInfo("reports").FullName, "taklif-tansik.rpt");
    //MessageBox.Show(reportPath);
    try
    {
        cryRpt = new ReportDocument();
        cryRpt.Load(reportPath);
        if (cryRpt.IsLoaded)
        {
            ReportPrintWindow = new ReportWindow();
            //cryRpt.Refresh();
            ReportPrintWindow.RptViewer.ViewerCore.ReportSource = cryRpt;
            ReportPrintWindow.Show();
        }
    }
    catch (Exception exEngineException)
    {
        MessageBox.Show("exEngineException " + exEngineException.ToString());
    }
}
</code>```

The XAML for Crystal Report viewer:

```<code><metro:MetroWindow
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:syncfusion="http://schemas.syncfusion.com/wpf" x:Class="Inspector_Reporter_MDK.ReportWindow"
        xmlns:my="clr-namespace:SAPBusinessObjects.WPF.Viewer;assembly=SAPBusinessObjects.WPF.Viewer"
        xmlns:metro="http://metro.mahapps.com/winfx/xaml/controls"
        GlowBrush="{DynamicResource AccentColorBrush}"
        BorderThickness="1"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:loc="clr-namespace:Inspector_Reporter_MDK"
        xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
        mc:Ignorable="d"Loaded="MetroWindow_Loaded" >
    <Grid >
        <my:CrystalReportsViewer x:Name="RptViewer" />
    </Grid>
</metro:MetroWindow>
</code>```

Code behind for Crystal Report viewer:

```<code>private void ReportWindow_Loaded(object sender, RoutedEventArgs e)
{
    try
    {
        RptViewer.Owner = this;
        //MessageBox.Show("RptViewer5");
    }
    catch (Exception exEngineException)
    {
        MessageBox.Show("RptViewer " + exEngineException.ToString());
    }
}
</code>```

答:
It turns mismatch run-time dll files of Crystal Report between development machine and the client machine caused this problems:

```<code>Memory full.
Not enough memory for operation.
</code>```

The second:

```<code>System.NullReferenceException -- System.NullReferenceException: Object reference not set to an instance of an object.
</code>```

Solution:

Install the same version used in development machine in client machine. My installed version was 13.0.19, and client machine 13.0.12, by deinstalling 13.0.12 and installing a 13.0.19 in the client machine, that solved my problem.

It is better also to install Microsoft Visual C++ Redistributable related to your Visual Studio version.

Body:
I am using Crystal Report for VS and WFP to view the report on a window.
At the beginning I was facing this error:

System.ArgumentNullException -- System.ArgumentNullException: Value cannot be null.
Parameter name: window

Then I fixed it following this solution.

Now another vague message appears that I couldn't find for it a solution even following this:

System.NullReferenceException -- System.NullReferenceException: Object reference not set to an instance of an object.
   at SAPBusinessObjects.WPF.Viewer.ReportAlbum.RefreshReport()
   at SAPBusinessObjects.WPF.Viewer.CrystalReportsViewer.RefreshReport_Executed(Object sender, ExecutedRoutedEventArgs e)
   at System.Windows.Input.CommandBinding.OnExecuted(Object sender, ExecutedRoutedEventArgs e)
   at System.Windows.Input.CommandManager.ExecuteCommandBinding(Object sender, ExecutedRoutedEventArgs e, CommandBinding commandBinding)
   at System.Windows.Input.CommandManager.FindCommandBinding(CommandBindingCollection commandBindings, Object sender, RoutedEventArgs e, ICommand command, Boolean execute)
   at System.Windows.Input.CommandManager.FindCommandBinding(Object sender, RoutedEventArgs e, ICommand command, Boolean execute)
   at System.Windows.Input.CommandManager.OnExecuted(Object sender, ExecutedRoutedEventArgs e)
   at System.Windows.UIElement.OnExecutedThunk(Object sender, ExecutedRoutedEventArgs e)
   at System.Windows.Input.ExecutedRoutedEventArgs.InvokeEventHandler(Delegate genericHandler, Object target)
   at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
   at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
   at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
   at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
   at System.Windows.UIElement.RaiseEvent(RoutedEventArgs args, Boolean trusted)
   at System.Windows.Input.RoutedCommand.ExecuteImpl(Object parameter, IInputElement target, Boolean userInitiated)
   at System.Windows.Input.RoutedCommand.ExecuteCore(Object parameter, IInputElement target, Boolean userInitiated)
   at MS.Internal.Commands.CommandHelpers.CriticalExecuteCommandSource(ICommandSource commandSource, Boolean userInitiated)
   at System.Windows.Controls.Primitives.ButtonBase.OnClick()
   at System.Windows.Controls.Button.OnClick()
   at System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(MouseButtonEventArgs e)
   at System.Windows.UIElement.OnMouseLeftButtonUpThunk(Object sender, MouseButtonEventArgs e)
   at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
   at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
   at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
   at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
   at System.Windows.UIElement.ReRaiseEventAs(DependencyObject sender, RoutedEventArgs args, RoutedEvent newEvent)
   at System.Windows.UIElement.OnMouseUpThunk(Object sender, MouseButtonEventArgs e)
   at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
   at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
   at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
   at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
   at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
   at System.Windows.UIElement.RaiseTrustedEvent(RoutedEventArgs args)
   at System.Windows.UIElement.RaiseEvent(RoutedEventArgs args, Boolean trusted)
   at System.Windows.Input.InputManager.ProcessStagingArea()
   at System.Windows.Input.InputManager.ProcessInput(InputEventArgs input)
   at System.Windows.Input.InputProviderSite.ReportInput(InputReport inputReport)
   at System.Windows.Interop.HwndMouseInputProvider.ReportInput(IntPtr hwnd, InputMode mode, Int32 timestamp, RawMouseActions actions, Int32 x, Int32 y, Int32 wheel)
   at System.Windows.Interop.HwndMouseInputProvider.FilterMessage(IntPtr hwnd, WindowMessage msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   at System.Windows.Interop.HwndSource.InputFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
   at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
   at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
   at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
   at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
   at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
   at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
   at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
   at System.Windows.Application.RunDispatcher(Object ignore)
   at System.Windows.Application.RunInternal(Window window)
   at System.Windows.Application.Run(Window window)
   at System.Windows.Application.Run()
   at Inspector_Reporter_MDK.App.Main() -- Object reference not set to an instance of an object.

My report doesn't have any fields, and of course there are no
parameters I send.

All the text are contained in the page size.

My code behind setting the report to print:

public void PrintReport()
{
    string reportPath = System.IO.Path.Combine(new System.IO.DirectoryInfo("reports").FullName, "taklif-tansik.rpt");
    //MessageBox.Show(reportPath);
    try
    {
        cryRpt = new ReportDocument();
        cryRpt.Load(reportPath);
        if (cryRpt.IsLoaded)
        {
            ReportPrintWindow = new ReportWindow();
            //cryRpt.Refresh();
            ReportPrintWindow.RptViewer.ViewerCore.ReportSource = cryRpt;
            ReportPrintWindow.Show();
        }
    }
    catch (Exception exEngineException)
    {
        MessageBox.Show("exEngineException " + exEngineException.ToString());
    }
}

The XAML for Crystal Report viewer:

<metro:MetroWindow
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:syncfusion="http://schemas.syncfusion.com/wpf" x:Class="Inspector_Reporter_MDK.ReportWindow"
        xmlns:my="clr-namespace:SAPBusinessObjects.WPF.Viewer;assembly=SAPBusinessObjects.WPF.Viewer"
        xmlns:metro="http://metro.mahapps.com/winfx/xaml/controls"
        GlowBrush="{DynamicResource AccentColorBrush}"
        BorderThickness="1"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:loc="clr-namespace:Inspector_Reporter_MDK"
        xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
        mc:Ignorable="d"Loaded="MetroWindow_Loaded" >
    <Grid >
        <my:CrystalReportsViewer x:Name="RptViewer" />
    </Grid>
</metro:MetroWindow>

Code behind for Crystal Report viewer:

private void ReportWindow_Loaded(object sender, RoutedEventArgs e)
{
    try
    {
        RptViewer.Owner = this;
        //MessageBox.Show("RptViewer5");
    }
    catch (Exception exEngineException)
    {
        MessageBox.Show("RptViewer " + exEngineException.ToString());
    }
}

Body:
It turns mismatch run-time dll files of Crystal Report between development machine and the client machine caused this problems:

Memory full.
Not enough memory for operation.

The second:

System.NullReferenceException -- System.NullReferenceException: Object reference not set to an instance of an object.

Solution:

Install the same version used in development machine in client machine. My installed version was 13.0.19, and client machine 13.0.12, by deinstalling 13.0.12 and installing a 13.0.19 in the client machine, that solved my problem.

It is better also to install Microsoft Visual C++ Redistributable related to your Visual Studio version.


来源: stackexchange

问:
Parse XML string to JSON array
```<code>$xmlString = '<?xml version="1.0" encoding="UTF-8" ?>
<corpsms>
    <transaction id="44444774">
        <status num="923337896466" date="14-11-2017 10:02:58">Successful</status>
        <status num="923337897246" date="14-11-2017 10:02:59">Successful</status>
    </transaction>
</corpsms>';
</code>```

Failed to catch 'status num="923337896466"' And failed to catch date="14-11-2017 10:02:58"

JSON output should be like:

```<code>{
    "transaction id": "44444774",
    "Total status num": "02",
    "status": [
        {
            "status num": "923337896466",
            "date": "14-11-2017 10:02:58",
            "output": "Successful"
        },
        {
            "status num": "923337897246",
            "date": "14-11-2017 10:02:59",
            "output": "Successful"
        }
    ]
}
</code>```

答:
```<code>$xmlString = '<?xml version="1.0" encoding="UTF-8" ?>
<corpsms>
    <transaction id="44444774">
        <status num="923337896466" date="14-11-2017 10:02:58">Successful</status>
        <status num="923337897246" date="14-11-2017 10:02:59">Successful</status>
    </transaction>
</corpsms>';

$xml = simplexml_load_string($xmlString, "SimpleXMLElement", LIBXML_NOCDATA);
$json = json_encode($xml);
$array = json_decode($json,TRUE);
</code>```

The output will be

```<code>{
    "transaction id": "44444774",
    "Total status num": "02",
    "status": [
        {
            "num": "923337896466",
            "date": "14-11-2017 10:02:58",
            "output": "Successful"
        },
        {
            "num": "923337897246",
            "date": "14-11-2017 10:02:59",
            "output": "Successful"
        }
    ]
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Parse XML string to JSON array

Body:
$xmlString = '<?xml version="1.0" encoding="UTF-8" ?>
<corpsms>
    <transaction id="44444774">
        <status num="923337896466" date="14-11-2017 10:02:58">Successful</status>
        <status num="923337897246" date="14-11-2017 10:02:59">Successful</status>
    </transaction>
</corpsms>';

Failed to catch 'status num="923337896466"' And failed to catch date="14-11-2017 10:02:58"

JSON output should be like:

{
    "transaction id": "44444774",
    "Total status num": "02",
    "status": [
        {
            "status num": "923337896466",
            "date": "14-11-2017 10:02:58",
            "output": "Successful"
        },
        {
            "status num": "923337897246",
            "date": "14-11-2017 10:02:59",
            "output": "Successful"
        }
    ]
}

Body:
$xmlString = '<?xml version="1.0" encoding="UTF-8" ?>
<corpsms>
    <transaction id="44444774">
        <status num="923337896466" date="14-11-2017 10:02:58">Successful</status>
        <status num="923337897246" date="14-11-2017 10:02:59">Successful</status>
    </transaction>
</corpsms>';

$xml = simplexml_load_string($xmlString, "SimpleXMLElement", LIBXML_NOCDATA);
$json = json_encode($xml);
$array = json_decode($json,TRUE);

The output will be

{
    "transaction id": "44444774",
    "Total status num": "02",
    "status": [
        {
            "num": "923337896466",
            "date": "14-11-2017 10:02:58",
            "output": "Successful"
        },
        {
            "num": "923337897246",
            "date": "14-11-2017 10:02:59",
            "output": "Successful"
        }
    ]
}


问:
Angular2: How to enable save button if any model value changed on edit page
I am new for angular 2. I have a page where we can edit details of customer profile. How to enable save button if any property of has been changed. I know it is possible in angular1 by using $watch.</p>

答:
This worked for me, pls try.
In your html,

```<code><input type="text" [ngModel]="name" (ngModelChange)="changeVal()" >
<input type="text" [ngModel]="address" (ngModelChange)="changeVal()" >
<input type="text" [ngModel]="postcode" (ngModelChange)="changeVal()" >

<button [disabled]="noChangeYet" (click)="clicked()" >
  <span>SUBMIT</span>
</button>
</code>```

In your component

```<code>export class customer implements OnInit {
  name: string;
  address: string;
  postcode: string;
  noChangeYet:boolean = true;

  constructor() {}

  changeVal(){ // triggers on change of any field(s)
    this.noChangeYet = false;
  }

  clicked(){
    // your function data after click (if any)
  }
}
</code>```

Hope this is what you need.

Body:
This worked for me, pls try.
In your html,

<input type="text" [ngModel]="name" (ngModelChange)="changeVal()" >
<input type="text" [ngModel]="address" (ngModelChange)="changeVal()" >
<input type="text" [ngModel]="postcode" (ngModelChange)="changeVal()" >

<button [disabled]="noChangeYet" (click)="clicked()" >
  <span>SUBMIT</span>
</button>

In your component

export class customer implements OnInit {
  name: string;
  address: string;
  postcode: string;
  noChangeYet:boolean = true;

  constructor() {}

  changeVal(){ // triggers on change of any field(s)
    this.noChangeYet = false;
  }

  clicked(){
    // your function data after click (if any)
  }
}

Hope this is what you need.


问:
How to enable autostart option for my app in ASUS zenfone2 and other ASUS models
I tried a lot of solution and links but nothing being helpful, there were many links for MI and few more, but no particular solution there for ASUS phone, so if any body have solution that works, please provide such solution.Because I am not able to know exact activity name of ASUS phone</p>

答:
You can do something like this,
1.From the HOME screen, tap on APPS.
2. From the APPS screen, tap on the AUTO-START MANAGER icon.
3.You will first see the DOWNLOADED apps field you can toggle apps to ALLOW or DENY with a tap in this field.
Choose the APPS accordingly to your preference to which you want to start up on first boot which also gives it full start up privilege access in RAM on the OS level.
4.Tapping on the PRELOADED option will show the PRELOADED apps. Choose with you want to toggle privileges by tapping on the applicable app to ALLOW or DENY start-up access in the OS.
5.Finally, tapping on ADVANCE options/settings (The three dots on the upper right hand corner) will toggle advance selections for the AUTO-START MANAGER app. Selections to choose are - SORT BY, SHOW ALL APPS, ENABLE NOTIFICATIONS, RESTORE TO INITIAL CONFIGURATION, NOTICE, FEEDBACK & HELP.

Did you try this ?


问:
Trouble mapping SQL Query to Entity spring-data-jpa
I'm new to Spring and trying to workout how to map a SQL Query to a model object. The prototype I'm developing serves a rest api over the top of a data warehouse. Mapping a database table to an object is easy enough but some objects will be represented by more complex queries. So far I have tried @NamedNativeQuery with @SqlResultsMapping and @Entity annotations but have run into some problems. I suspect I'm not using them properly?

I can get the server up and running but I get an error when trying to access via localhost:8080/admissionEvents. I'm using a sqlite db but have the same issue using the production mssql db. From what I can tell from there's a SQLException that is looking for a table? That would suggest something is wrong in my mapping? Are the annotations in the right place?

I don't have a persistence.xml file defined but my db connection details are set in application.properties. Not sure though if thats the source of the problem?

Any help much appreciated.

Error

```<code>org.sqlite.SQLiteException: [SQLITE_ERROR] SQL error or missing database (no such table: admission_event)
    at org.sqlite.core.DB.newSQLException(DB.java:909) ~[sqlite-jdbc-3.20.1.jar:na]
    at org.sqlite.core.DB.newSQLException(DB.java:921) ~[sqlite-jdbc-3.20.1.jar:na]
    at org.sqlite.core.DB.throwex(DB.java:886) ~[sqlite-jdbc-3.20.1.jar:na]
    at org.sqlite.core.NativeDB.prepare_utf8(Native Method) ~[sqlite-jdbc-3.20.1.jar:na]
    at org.sqlite.core.NativeDB.prepare(NativeDB.java:127) ~[sqlite-jdbc-3.20.1.jar:na]
    at org.sqlite.core.DB.prepare(DB.java:227) ~[sqlite-jdbc-3.20.1.jar:na]
    at org.sqlite.core.CorePreparedStatement.<init>(CorePreparedStatement.java:41) ~[sqlite-jdbc-3.20.1.jar:na]
    at org.sqlite.jdbc3.JDBC3PreparedStatement.<init>(JDBC3PreparedStatement.java:30) ~[sqlite-jdbc-3.20.1.jar:na]
    at org.sqlite.jdbc4.JDBC4PreparedStatement.<init>(JDBC4PreparedStatement.java:19) ~[sqlite-jdbc-3.20.1.jar:na]
    at org.sqlite.jdbc4.JDBC4Connection.prepareStatement(JDBC4Connection.java:48) ~[sqlite-jdbc-3.20.1.jar:na]
    at org.sqlite.jdbc3.JDBC3Connection.prepareStatement(JDBC3Connection.java:263) ~[sqlite-jdbc-3.20.1.jar:na]
    at org.sqlite.jdbc3.JDBC3Connection.prepareStatement(JDBC3Connection.java:235) ~[sqlite-jdbc-3.20.1.jar:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_131]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_131]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_131]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_131]
    at org.apache.tomcat.jdbc.pool.ProxyConnection.invoke(ProxyConnection.java:126) ~[tomcat-jdbc-8.5.23.jar:na]
    at org.apache.tomcat.jdbc.pool.JdbcInterceptor.invoke(JdbcInterceptor.java:108) ~[tomcat-jdbc-8.5.23.jar:na]
    at org.apache.tomcat.jdbc.pool.interceptor.AbstractCreateStatementInterceptor.invoke(AbstractCreateStatementInterceptor.java:75) ~[tomcat-jdbc-8.5.23.jar:na]
    at org.apache.tomcat.jdbc.pool.JdbcInterceptor.invoke(JdbcInterceptor.java:108) ~[tomcat-jdbc-8.5.23.jar:na]
    at org.apache.tomcat.jdbc.pool.DisposableConnectionFacade.invoke(DisposableConnectionFacade.java:81) ~[tomcat-jdbc-8.5.23.jar:na]
    at com.sun.proxy.$Proxy63.prepareStatement(Unknown Source) ~[na:na]
    at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$5.doPrepare(StatementPreparerImpl.java:146) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$StatementPreparationTemplate.prepareStatement(StatementPreparerImpl.java:172) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.engine.jdbc.internal.StatementPreparerImpl.prepareQueryStatement(StatementPreparerImpl.java:148) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1929) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1898) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1876) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.loader.Loader.doQuery(Loader.java:919) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:336) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.loader.Loader.doList(Loader.java:2617) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.loader.Loader.doList(Loader.java:2600) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2429) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.loader.Loader.list(Loader.java:2424) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:501) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:371) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:216) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1326) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.internal.QueryImpl.list(QueryImpl.java:87) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.jpa.internal.QueryImpl.list(QueryImpl.java:606) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.jpa.internal.QueryImpl.getResultList(QueryImpl.java:483) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.jpa.criteria.compile.CriteriaQueryTypeQueryAdapter.getResultList(CriteriaQueryTypeQueryAdapter.java:50) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
    at org.springframework.data.jpa.repository.support.SimpleJpaRepository.findAll(SimpleJpaRepository.java:329) ~[spring-data-jpa-1.11.8.RELEASE.jar:na]
    at org.springframework.data.jpa.repository.support.SimpleJpaRepository.findAll(SimpleJpaRepository.java:74) ~[spring-data-jpa-1.11.8.RELEASE.jar:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_131]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_131]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_131]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_131]
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.executeMethodOn(RepositoryFactorySupport.java:504) ~[spring-data-commons-1.13.8.RELEASE.jar:na]
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:489) ~[spring-data-commons-1.13.8.RELEASE.jar:na]
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:461) ~[spring-data-commons-1.13.8.RELEASE.jar:na]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:56) ~[spring-data-commons-1.13.8.RELEASE.jar:na]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99) ~[spring-tx-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282) ~[spring-tx-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96) ~[spring-tx-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136) ~[spring-tx-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:133) ~[spring-data-jpa-1.11.8.RELEASE.jar:na]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92) ~[spring-aop-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:57) ~[spring-data-commons-1.13.8.RELEASE.jar:na]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213) ~[spring-aop-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at com.sun.proxy.$Proxy77.findAll(Unknown Source) ~[na:na]
    at com.andrew.restlite.admission.AdmissionEventController.getAllAdmissionEvents(AdmissionEventController.java:15) ~[main/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_131]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_131]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_131]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_131]
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205) ~[spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133) ~[spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97) ~[spring-webmvc-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827) ~[spring-webmvc-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738) ~[spring-webmvc-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) ~[spring-webmvc-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967) ~[spring-webmvc-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901) ~[spring-webmvc-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) ~[spring-webmvc-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861) ~[spring-webmvc-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:635) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) ~[spring-webmvc-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) ~[tomcat-embed-websocket-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:108) ~[spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81) ~[spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197) ~[spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1459) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_131]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_131]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at java.lang.Thread.run(Thread.java:748) [na:1.8.0_131]
</code>```

AdmissionEvent

```<code>package com.andrew.restlite.admission;

import javax.persistence.*;

@NamedNativeQuery(name = "AdmissionEvent.admissionEvents",
                  query = "SELECT fact_admission_event.fact_admission_event_key, fact_admission_event.ward FROM fact_admission_event",
                  resultSetMapping = "admissionEventsMapping")
@SqlResultSetMapping(
        name = "admissionEventsMapping",
        classes = {
                @ConstructorResult(
                        targetClass = AdmissionEvent.class,
                        columns = {
                                @ColumnResult(name="fact_admission_event_key"),
                                @ColumnResult(name="ward")
                        }
                )
        }
)
@Entity
public class AdmissionEvent {
    @Id
    private int id;
    private String wardLocation;

    protected AdmissionEvent() {
    }

    public AdmissionEvent(int id, String wardLocation) {
        this.id = id;
        this.wardLocation = wardLocation;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getWardLocation() {
        return wardLocation;
    }

    public void setWardLocation(String wardLocation) {
        this.wardLocation = wardLocation;
    }
}
</code>```

AdmissionEventRepository

```<code>package com.andrew.restlite.admission;

import org.springframework.data.repository.CrudRepository;

public interface AdmissionEventRepository extends CrudRepository<AdmissionEvent, Integer> {
}
</code>```

AdmissionEventController

```<code>package com.andrew.restlite.admission;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class AdmissionEventController {
    @Autowired
    private AdmissionEventRepository admissionEventRepository;

    @RequestMapping(path="/admissionEvents", method = RequestMethod.GET)
    public Iterable<AdmissionEvent> getAllAdmissionEvents() {
        return admissionEventRepository.findAll();
    }

}
</code>```

Gradle Build Script

```<code>group 'com.andrew.restlite'
version '1.0-SNAPSHOT'

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:1.5.8.RELEASE")
    }
}

apply plugin: 'java'
apply plugin: 'idea'
apply plugin: 'org.springframework.boot'

jar {
    baseName = 'restlite'
    version =  '0.1.0'
}

repositories {
    mavenCentral()
}

sourceCompatibility = 1.8
targetCompatibility = 1.8

dependencies {
    compile("org.springframework.boot:spring-boot-starter-web")
    compile 'org.springframework.boot:spring-boot-starter-data-jpa'
    compile 'org.xerial:sqlite-jdbc:3.20.1'
    compile 'com.zsoltfabok:sqlite-dialect:1.0'

    testCompile('org.springframework.boot:spring-boot-starter-test')
}
</code>```

答:
Managed to find a solution by adding the @Subselect and @Synchonize annotations to the Entity Class.</p>

```<code>@Entity(name="AdmissionEvent")
@Subselect("SELECT fact_admission_event.fact_admission_event_key,fact_admission_event.ward FROM fact_admission_event")
@Synchronize({"fact_admission_event"})
public class AdmissionEvent {
@Id
@Column(name="fact_admission_event_key")
private int id;

@Column(name="ward")
private String wardLocation;

protected AdmissionEvent() {
}
{}
</code>```

Body:
I'm new to Spring and trying to workout how to map a SQL Query to a model object. The prototype I'm developing serves a rest api over the top of a data warehouse. Mapping a database table to an object is easy enough but some objects will be represented by more complex queries. So far I have tried @NamedNativeQuery with @SqlResultsMapping and @Entity annotations but have run into some problems. I suspect I'm not using them properly?

I can get the server up and running but I get an error when trying to access via localhost:8080/admissionEvents. I'm using a sqlite db but have the same issue using the production mssql db. From what I can tell from there's a SQLException that is looking for a table? That would suggest something is wrong in my mapping? Are the annotations in the right place?

I don't have a persistence.xml file defined but my db connection details are set in application.properties. Not sure though if thats the source of the problem?

Any help much appreciated.

Error

org.sqlite.SQLiteException: [SQLITE_ERROR] SQL error or missing database (no such table: admission_event)
    at org.sqlite.core.DB.newSQLException(DB.java:909) ~[sqlite-jdbc-3.20.1.jar:na]
    at org.sqlite.core.DB.newSQLException(DB.java:921) ~[sqlite-jdbc-3.20.1.jar:na]
    at org.sqlite.core.DB.throwex(DB.java:886) ~[sqlite-jdbc-3.20.1.jar:na]
    at org.sqlite.core.NativeDB.prepare_utf8(Native Method) ~[sqlite-jdbc-3.20.1.jar:na]
    at org.sqlite.core.NativeDB.prepare(NativeDB.java:127) ~[sqlite-jdbc-3.20.1.jar:na]
    at org.sqlite.core.DB.prepare(DB.java:227) ~[sqlite-jdbc-3.20.1.jar:na]
    at org.sqlite.core.CorePreparedStatement.<init>(CorePreparedStatement.java:41) ~[sqlite-jdbc-3.20.1.jar:na]
    at org.sqlite.jdbc3.JDBC3PreparedStatement.<init>(JDBC3PreparedStatement.java:30) ~[sqlite-jdbc-3.20.1.jar:na]
    at org.sqlite.jdbc4.JDBC4PreparedStatement.<init>(JDBC4PreparedStatement.java:19) ~[sqlite-jdbc-3.20.1.jar:na]
    at org.sqlite.jdbc4.JDBC4Connection.prepareStatement(JDBC4Connection.java:48) ~[sqlite-jdbc-3.20.1.jar:na]
    at org.sqlite.jdbc3.JDBC3Connection.prepareStatement(JDBC3Connection.java:263) ~[sqlite-jdbc-3.20.1.jar:na]
    at org.sqlite.jdbc3.JDBC3Connection.prepareStatement(JDBC3Connection.java:235) ~[sqlite-jdbc-3.20.1.jar:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_131]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_131]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_131]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_131]
    at org.apache.tomcat.jdbc.pool.ProxyConnection.invoke(ProxyConnection.java:126) ~[tomcat-jdbc-8.5.23.jar:na]
    at org.apache.tomcat.jdbc.pool.JdbcInterceptor.invoke(JdbcInterceptor.java:108) ~[tomcat-jdbc-8.5.23.jar:na]
    at org.apache.tomcat.jdbc.pool.interceptor.AbstractCreateStatementInterceptor.invoke(AbstractCreateStatementInterceptor.java:75) ~[tomcat-jdbc-8.5.23.jar:na]
    at org.apache.tomcat.jdbc.pool.JdbcInterceptor.invoke(JdbcInterceptor.java:108) ~[tomcat-jdbc-8.5.23.jar:na]
    at org.apache.tomcat.jdbc.pool.DisposableConnectionFacade.invoke(DisposableConnectionFacade.java:81) ~[tomcat-jdbc-8.5.23.jar:na]
    at com.sun.proxy.$Proxy63.prepareStatement(Unknown Source) ~[na:na]
    at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$5.doPrepare(StatementPreparerImpl.java:146) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$StatementPreparationTemplate.prepareStatement(StatementPreparerImpl.java:172) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.engine.jdbc.internal.StatementPreparerImpl.prepareQueryStatement(StatementPreparerImpl.java:148) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1929) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1898) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1876) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.loader.Loader.doQuery(Loader.java:919) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:336) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.loader.Loader.doList(Loader.java:2617) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.loader.Loader.doList(Loader.java:2600) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2429) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.loader.Loader.list(Loader.java:2424) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:501) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:371) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:216) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1326) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.internal.QueryImpl.list(QueryImpl.java:87) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.jpa.internal.QueryImpl.list(QueryImpl.java:606) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.jpa.internal.QueryImpl.getResultList(QueryImpl.java:483) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.jpa.criteria.compile.CriteriaQueryTypeQueryAdapter.getResultList(CriteriaQueryTypeQueryAdapter.java:50) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
    at org.springframework.data.jpa.repository.support.SimpleJpaRepository.findAll(SimpleJpaRepository.java:329) ~[spring-data-jpa-1.11.8.RELEASE.jar:na]
    at org.springframework.data.jpa.repository.support.SimpleJpaRepository.findAll(SimpleJpaRepository.java:74) ~[spring-data-jpa-1.11.8.RELEASE.jar:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_131]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_131]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_131]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_131]
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.executeMethodOn(RepositoryFactorySupport.java:504) ~[spring-data-commons-1.13.8.RELEASE.jar:na]
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:489) ~[spring-data-commons-1.13.8.RELEASE.jar:na]
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:461) ~[spring-data-commons-1.13.8.RELEASE.jar:na]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:56) ~[spring-data-commons-1.13.8.RELEASE.jar:na]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99) ~[spring-tx-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282) ~[spring-tx-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96) ~[spring-tx-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136) ~[spring-tx-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:133) ~[spring-data-jpa-1.11.8.RELEASE.jar:na]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92) ~[spring-aop-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:57) ~[spring-data-commons-1.13.8.RELEASE.jar:na]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213) ~[spring-aop-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at com.sun.proxy.$Proxy77.findAll(Unknown Source) ~[na:na]
    at com.andrew.restlite.admission.AdmissionEventController.getAllAdmissionEvents(AdmissionEventController.java:15) ~[main/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_131]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_131]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_131]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_131]
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205) ~[spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133) ~[spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97) ~[spring-webmvc-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827) ~[spring-webmvc-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738) ~[spring-webmvc-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) ~[spring-webmvc-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967) ~[spring-webmvc-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901) ~[spring-webmvc-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) ~[spring-webmvc-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861) ~[spring-webmvc-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:635) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) ~[spring-webmvc-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) ~[tomcat-embed-websocket-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:108) ~[spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81) ~[spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197) ~[spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1459) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_131]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_131]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at java.lang.Thread.run(Thread.java:748) [na:1.8.0_131]

AdmissionEvent

package com.andrew.restlite.admission;

import javax.persistence.*;

@NamedNativeQuery(name = "AdmissionEvent.admissionEvents",
                  query = "SELECT fact_admission_event.fact_admission_event_key, fact_admission_event.ward FROM fact_admission_event",
                  resultSetMapping = "admissionEventsMapping")
@SqlResultSetMapping(
        name = "admissionEventsMapping",
        classes = {
                @ConstructorResult(
                        targetClass = AdmissionEvent.class,
                        columns = {
                                @ColumnResult(name="fact_admission_event_key"),
                                @ColumnResult(name="ward")
                        }
                )
        }
)
@Entity
public class AdmissionEvent {
    @Id
    private int id;
    private String wardLocation;

    protected AdmissionEvent() {
    }

    public AdmissionEvent(int id, String wardLocation) {
        this.id = id;
        this.wardLocation = wardLocation;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getWardLocation() {
        return wardLocation;
    }

    public void setWardLocation(String wardLocation) {
        this.wardLocation = wardLocation;
    }
}

AdmissionEventRepository

package com.andrew.restlite.admission;

import org.springframework.data.repository.CrudRepository;

public interface AdmissionEventRepository extends CrudRepository<AdmissionEvent, Integer> {
}

AdmissionEventController

package com.andrew.restlite.admission;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class AdmissionEventController {
    @Autowired
    private AdmissionEventRepository admissionEventRepository;

    @RequestMapping(path="/admissionEvents", method = RequestMethod.GET)
    public Iterable<AdmissionEvent> getAllAdmissionEvents() {
        return admissionEventRepository.findAll();
    }

}

Gradle Build Script

group 'com.andrew.restlite'
version '1.0-SNAPSHOT'

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:1.5.8.RELEASE")
    }
}

apply plugin: 'java'
apply plugin: 'idea'
apply plugin: 'org.springframework.boot'

jar {
    baseName = 'restlite'
    version =  '0.1.0'
}

repositories {
    mavenCentral()
}

sourceCompatibility = 1.8
targetCompatibility = 1.8

dependencies {
    compile("org.springframework.boot:spring-boot-starter-web")
    compile 'org.springframework.boot:spring-boot-starter-data-jpa'
    compile 'org.xerial:sqlite-jdbc:3.20.1'
    compile 'com.zsoltfabok:sqlite-dialect:1.0'

    testCompile('org.springframework.boot:spring-boot-starter-test')
}

Body:
Managed to find a solution by adding the @Subselect and @Synchonize annotations to the Entity Class.

@Entity(name="AdmissionEvent")
@Subselect("SELECT fact_admission_event.fact_admission_event_key,fact_admission_event.ward FROM fact_admission_event")
@Synchronize({"fact_admission_event"})
public class AdmissionEvent {
@Id
@Column(name="fact_admission_event_key")
private int id;

@Column(name="ward")
private String wardLocation;

protected AdmissionEvent() {
}
{}


问:
How to capitalize the first character of sentence using Swift
I have a String description that holds my sentence and want to capitalize only the first letter. I tried different things but most of them give me exceptions and errors. I'm using Xcode 6.

Here is what I tried so far:

```<code>let cap = [description.substringToIndex(advance(0,1))] as String
    description = cap.uppercaseString + description.substringFromIndex(1)
</code>```

It gives me:

```<code>Type 'String.Index' does not conform to protocol 'IntegerLiteralConvertible'
</code>```

I tried:

```<code> func capitalizedStringWithLocale(locale:0) -> String
</code>```

But I haven't figured out how to make it work.

答:
```<code>extension String {
    var capitalizedFirstLetter:String {
          let string = self
          return string.replacingCharacters(in: startIndex...startIndex, with: String(self[startIndex]).capitalized)
    }
}
</code>```

Answer:

```<code>let newSentence = sentence.capitalizedFirstLetter
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a String description that holds my sentence and want to capitalize only the first letter. I tried different things but most of them give me exceptions and errors. I'm using Xcode 6.

Here is what I tried so far:

let cap = [description.substringToIndex(advance(0,1))] as String
    description = cap.uppercaseString + description.substringFromIndex(1)

It gives me:

Type 'String.Index' does not conform to protocol 'IntegerLiteralConvertible'

I tried:

 func capitalizedStringWithLocale(locale:0) -> String

But I haven't figured out how to make it work.

Body:
extension String {
    var capitalizedFirstLetter:String {
          let string = self
          return string.replacingCharacters(in: startIndex...startIndex, with: String(self[startIndex]).capitalized)
    }
}

Answer:

let newSentence = sentence.capitalizedFirstLetter


问:
How to find the endangle for beizerpath for a curve drawn in swift?
I have drawn a beizer path with start & end angle which create a whole circle

```<code>circle = UIView(frame: CGRect(x: 100, y: 100, width: 200, height:200))
        circle.layoutIfNeeded()
        self.view.addSubview(circle)
        let centerPoint = CGPoint (x: circle.bounds.width / 2, y: circle.bounds.width / 2)
        let circleRadius : CGFloat = circle.bounds.width / 2 * 0.83
        circlePath = UIBezierPath(arcCenter: centerPoint, radius: circleRadius, startAngle: CGFloat(-0.5 * M_PI), endAngle: CGFloat(1.5 * M_PI), clockwise: true)
</code>```

After that i draw a Curve on that circle & does not fill it full to the circle.

```<code>progressCircle = CAShapeLayer ()
        progressCircle.path = circlePath?.cgPath
        progressCircle.strokeColor = UIColor.red.cgColor
        progressCircle.fillColor = UIColor.clear.cgColor
        progressCircle.lineWidth = 4.0
        progressCircle.strokeStart = 0
        progressCircle.strokeEnd = 0.7
        circle.layer.addSublayer(progressCircle)
</code>```

After that i want to add image at then end of curve so to do that i created another biezer path.But here problem is it should be ended as the curve end.So i am not able to find the end angle for the beizer path based on the endStroke of CASHAPELAYER. Please tell me how can i find the end angle of new beizer path based on the curve end point.

```<code>let centerPoint = CGPoint (x: circle.bounds.width / 2, y: circle.bounds.width / 2)
        let circleRadius : CGFloat = circle.bounds.width / 2 * 0.83
        let arcStartAngle: Double = 0.0

        let rotationDiff = 360 - abs((0.0 - 270))
        let startAngle: CGFloat = -1.57
        let endAngle: CGFloat = CGFloat(Double.pi * 0.7)
        let bpath = UIBezierPath(arcCenter: centerPoint, radius: circleRadius, startAngle: startAngle, endAngle: endAngle, clockwise: true)
</code>```

答:
```<code>class ViewController: UIViewController {

    var array = [[CGFloat:CGFloat]]()
    var midX : CGFloat = CGFloat()
    var midY : CGFloat = CGFloat()
    let radius : CGFloat = 100.0

    override func viewDidLoad() {
        super.viewDidLoad()

        midX = self.view.frame.midX
        midY = self.view.frame.midY

        let path = UIBezierPath()
        path.addArc(withCenter: CGPoint.init(x: midX, y: midY), radius: radius, startAngle: 0, endAngle:2 * .pi, clockwise: true)
        let shape = CAShapeLayer()
        shape.path = path.cgPath
        shape.lineWidth = 5.0
        shape.fillColor = UIColor.clear.cgColor
        shape.strokeColor = UIColor.lightGray.cgColor
        self.view.layer.addSublayer(shape)

        var temp090x = [CGFloat:CGFloat]()
        var temp90180x = [CGFloat:CGFloat]()
        var temp180270x = [CGFloat:CGFloat]()
        var temp270360x = [CGFloat:CGFloat]()

        for i in 1...360 {
            let path3 = UIBezierPath()
            path3.move(to: CGPoint.init(x: midX, y: midY))
            path3.addLine(to:CGPoint.init(x: midX + radius * sin(CGFloat(i)), y:midY + radius*cos(CGFloat(i))))
            //design path in layer
            if midX + radius * sin(CGFloat(i)) > midX && midY + radius*cos(CGFloat(i)) < midY {
                temp090x[midX + radius * sin(CGFloat(i))] = midY + radius*cos(CGFloat(i))
            }else if midX + radius * sin(CGFloat(i)) > midX && midY + radius*cos(CGFloat(i)) > midY {
                temp90180x[midX + radius * sin(CGFloat(i))] = midY + radius*cos(CGFloat(i))
            }else if midX + radius * sin(CGFloat(i)) < midX && midY + radius*cos(CGFloat(i)) > midY {
                temp180270x[midX + radius * sin(CGFloat(i))] = midY + radius*cos(CGFloat(i))
            }else if midX + radius * sin(CGFloat(i)) < midX && midY + radius*cos(CGFloat(i)) < midY {
                temp270360x[midX + radius * sin(CGFloat(i))] = midY + radius*cos(CGFloat(i))
            }
            let shapeLayer3 = CAShapeLayer()
            shapeLayer3.path = path3.cgPath
            shapeLayer3.strokeColor = UIColor.clear.cgColor
            shapeLayer3.lineWidth = 1.0
            self.view.layer.addSublayer(shapeLayer3)
        }

        let tempSorted090x = BubbleAsceSort(array: temp090x)
        let tempSorted90180x = BubbleDescSort(array: temp90180x)
        let tempSorted180270x = BubbleDescSort(array: temp180270x)
        let tempSorted270360x = BubbleAsceSort(array: temp270360x)

        for item in tempSorted090x {
            array.append(item)
        }
        for item in tempSorted90180x {
            array.append(item)
        }
        for item in tempSorted180270x {
            array.append(item)
        }
        for item in tempSorted270360x {
            array.append(item)
        }

        let lbl = UILabel()
        lbl.frame = CGRect.init(x: 0, y: 0, width: 30, height: 30)
        lbl.backgroundColor = UIColor.black
        lbl.layer.cornerRadius = 15

        for i in 1...180 {
            let xpos = Array(array[i-1].keys)[0]
            let ypos = Array(array[i-1].values)[0]

            let xpos1 = Array(array[i].keys)[0]
            let ypos1 = Array(array[i].values)[0]

            let path3 = UIBezierPath()
            path3.move(to: CGPoint.init(x: xpos, y: ypos))
            path3.addLine(to:CGPoint.init(x: xpos1, y:ypos1))
            let shapeLayer3 = CAShapeLayer()
            shapeLayer3.path = path3.cgPath
            shapeLayer3.strokeColor = UIColor.red.cgColor
            shapeLayer3.lineWidth = 5.0
            self.view.layer.addSublayer(shapeLayer3)

        }
        lbl.center = CGPoint.init(x: Array(array[180].keys)[0], y: Array(array[180].values)[0])
        self.view.addSubview(lbl)
    }

    func BubbleDescSort(array : [CGFloat:CGFloat]) -> [[CGFloat:CGFloat]] {
        var sortedArray = Array(array.keys)
        var sortedvalueArray = Array(array.values)
        var sortedAboveIndex = sortedArray.count-1 // Assume all values are not in order
        repeat {
            var lastSwapIndex = 0

            for i in 1...sortedAboveIndex{
                if (sortedArray[i] as AnyObject) as! CGFloat > (sortedArray[i - 1] as AnyObject) as! CGFloat  {
                    sortedArray.swapAt(i, i-1)
                    sortedvalueArray.swapAt(i, i-1)
                    lastSwapIndex = i
                }
            }
            sortedAboveIndex = lastSwapIndex

        } while (sortedAboveIndex != 0)
        var index = 0
        var arr = [[CGFloat:CGFloat]]()
        for item in sortedArray {
            var dic = [CGFloat:CGFloat]()
            dic[item] = sortedvalueArray[index]
            arr.append(dic)
            index += 1
        }
        return arr
    }

    func BubbleAsceSort(array : [CGFloat:CGFloat]) -> [[CGFloat:CGFloat]] {
        var sortedArray = Array(array.keys)
        var sortedvalueArray = Array(array.values)
        var sortedAboveIndex = sortedArray.count-1 // Assume all values are not in order
        repeat {
            var lastSwapIndex = 0

            for i in 1...sortedAboveIndex{
                if (sortedArray[i - 1] as AnyObject) as! CGFloat > (sortedArray[i] as AnyObject) as! CGFloat {
                    sortedArray.swapAt(i, i-1)
                    sortedvalueArray.swapAt(i, i-1)
                    lastSwapIndex = i
                }
            }
            sortedAboveIndex = lastSwapIndex

        } while (sortedAboveIndex != 0)
        var index = 0
        var arr = [[CGFloat:CGFloat]]()
        for item in sortedArray {
            var dic = [CGFloat:CGFloat]()
            dic[item] = sortedvalueArray[index]
            arr.append(dic)
            index += 1
        }
        return arr
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}
</code>```

In this code you need to Set Progress Percentage based on the 360 degree. in the upper limit of for loop and Round lbl Center point x and y pos. Here is need only 180 replace to your progress percentage

Body:
I have drawn a beizer path with start & end angle which create a whole circle

circle = UIView(frame: CGRect(x: 100, y: 100, width: 200, height:200))
        circle.layoutIfNeeded()
        self.view.addSubview(circle)
        let centerPoint = CGPoint (x: circle.bounds.width / 2, y: circle.bounds.width / 2)
        let circleRadius : CGFloat = circle.bounds.width / 2 * 0.83
        circlePath = UIBezierPath(arcCenter: centerPoint, radius: circleRadius, startAngle: CGFloat(-0.5 * M_PI), endAngle: CGFloat(1.5 * M_PI), clockwise: true)

After that i draw a Curve on that circle & does not fill it full to the circle.

progressCircle = CAShapeLayer ()
        progressCircle.path = circlePath?.cgPath
        progressCircle.strokeColor = UIColor.red.cgColor
        progressCircle.fillColor = UIColor.clear.cgColor
        progressCircle.lineWidth = 4.0
        progressCircle.strokeStart = 0
        progressCircle.strokeEnd = 0.7
        circle.layer.addSublayer(progressCircle)

After that i want to add image at then end of curve so to do that i created another biezer path.But here problem is it should be ended as the curve end.So i am not able to find the end angle for the beizer path based on the endStroke of CASHAPELAYER. Please tell me how can i find the end angle of new beizer path based on the curve end point.

let centerPoint = CGPoint (x: circle.bounds.width / 2, y: circle.bounds.width / 2)
        let circleRadius : CGFloat = circle.bounds.width / 2 * 0.83
        let arcStartAngle: Double = 0.0

        let rotationDiff = 360 - abs((0.0 - 270))
        let startAngle: CGFloat = -1.57
        let endAngle: CGFloat = CGFloat(Double.pi * 0.7)
        let bpath = UIBezierPath(arcCenter: centerPoint, radius: circleRadius, startAngle: startAngle, endAngle: endAngle, clockwise: true)

Body:
class ViewController: UIViewController {

    var array = [[CGFloat:CGFloat]]()
    var midX : CGFloat = CGFloat()
    var midY : CGFloat = CGFloat()
    let radius : CGFloat = 100.0

    override func viewDidLoad() {
        super.viewDidLoad()

        midX = self.view.frame.midX
        midY = self.view.frame.midY

        let path = UIBezierPath()
        path.addArc(withCenter: CGPoint.init(x: midX, y: midY), radius: radius, startAngle: 0, endAngle:2 * .pi, clockwise: true)
        let shape = CAShapeLayer()
        shape.path = path.cgPath
        shape.lineWidth = 5.0
        shape.fillColor = UIColor.clear.cgColor
        shape.strokeColor = UIColor.lightGray.cgColor
        self.view.layer.addSublayer(shape)

        var temp090x = [CGFloat:CGFloat]()
        var temp90180x = [CGFloat:CGFloat]()
        var temp180270x = [CGFloat:CGFloat]()
        var temp270360x = [CGFloat:CGFloat]()

        for i in 1...360 {
            let path3 = UIBezierPath()
            path3.move(to: CGPoint.init(x: midX, y: midY))
            path3.addLine(to:CGPoint.init(x: midX + radius * sin(CGFloat(i)), y:midY + radius*cos(CGFloat(i))))
            //design path in layer
            if midX + radius * sin(CGFloat(i)) > midX && midY + radius*cos(CGFloat(i)) < midY {
                temp090x[midX + radius * sin(CGFloat(i))] = midY + radius*cos(CGFloat(i))
            }else if midX + radius * sin(CGFloat(i)) > midX && midY + radius*cos(CGFloat(i)) > midY {
                temp90180x[midX + radius * sin(CGFloat(i))] = midY + radius*cos(CGFloat(i))
            }else if midX + radius * sin(CGFloat(i)) < midX && midY + radius*cos(CGFloat(i)) > midY {
                temp180270x[midX + radius * sin(CGFloat(i))] = midY + radius*cos(CGFloat(i))
            }else if midX + radius * sin(CGFloat(i)) < midX && midY + radius*cos(CGFloat(i)) < midY {
                temp270360x[midX + radius * sin(CGFloat(i))] = midY + radius*cos(CGFloat(i))
            }
            let shapeLayer3 = CAShapeLayer()
            shapeLayer3.path = path3.cgPath
            shapeLayer3.strokeColor = UIColor.clear.cgColor
            shapeLayer3.lineWidth = 1.0
            self.view.layer.addSublayer(shapeLayer3)
        }

        let tempSorted090x = BubbleAsceSort(array: temp090x)
        let tempSorted90180x = BubbleDescSort(array: temp90180x)
        let tempSorted180270x = BubbleDescSort(array: temp180270x)
        let tempSorted270360x = BubbleAsceSort(array: temp270360x)

        for item in tempSorted090x {
            array.append(item)
        }
        for item in tempSorted90180x {
            array.append(item)
        }
        for item in tempSorted180270x {
            array.append(item)
        }
        for item in tempSorted270360x {
            array.append(item)
        }

        let lbl = UILabel()
        lbl.frame = CGRect.init(x: 0, y: 0, width: 30, height: 30)
        lbl.backgroundColor = UIColor.black
        lbl.layer.cornerRadius = 15

        for i in 1...180 {
            let xpos = Array(array[i-1].keys)[0]
            let ypos = Array(array[i-1].values)[0]

            let xpos1 = Array(array[i].keys)[0]
            let ypos1 = Array(array[i].values)[0]

            let path3 = UIBezierPath()
            path3.move(to: CGPoint.init(x: xpos, y: ypos))
            path3.addLine(to:CGPoint.init(x: xpos1, y:ypos1))
            let shapeLayer3 = CAShapeLayer()
            shapeLayer3.path = path3.cgPath
            shapeLayer3.strokeColor = UIColor.red.cgColor
            shapeLayer3.lineWidth = 5.0
            self.view.layer.addSublayer(shapeLayer3)

        }
        lbl.center = CGPoint.init(x: Array(array[180].keys)[0], y: Array(array[180].values)[0])
        self.view.addSubview(lbl)
    }

    func BubbleDescSort(array : [CGFloat:CGFloat]) -> [[CGFloat:CGFloat]] {
        var sortedArray = Array(array.keys)
        var sortedvalueArray = Array(array.values)
        var sortedAboveIndex = sortedArray.count-1 // Assume all values are not in order
        repeat {
            var lastSwapIndex = 0

            for i in 1...sortedAboveIndex{
                if (sortedArray[i] as AnyObject) as! CGFloat > (sortedArray[i - 1] as AnyObject) as! CGFloat  {
                    sortedArray.swapAt(i, i-1)
                    sortedvalueArray.swapAt(i, i-1)
                    lastSwapIndex = i
                }
            }
            sortedAboveIndex = lastSwapIndex

        } while (sortedAboveIndex != 0)
        var index = 0
        var arr = [[CGFloat:CGFloat]]()
        for item in sortedArray {
            var dic = [CGFloat:CGFloat]()
            dic[item] = sortedvalueArray[index]
            arr.append(dic)
            index += 1
        }
        return arr
    }

    func BubbleAsceSort(array : [CGFloat:CGFloat]) -> [[CGFloat:CGFloat]] {
        var sortedArray = Array(array.keys)
        var sortedvalueArray = Array(array.values)
        var sortedAboveIndex = sortedArray.count-1 // Assume all values are not in order
        repeat {
            var lastSwapIndex = 0

            for i in 1...sortedAboveIndex{
                if (sortedArray[i - 1] as AnyObject) as! CGFloat > (sortedArray[i] as AnyObject) as! CGFloat {
                    sortedArray.swapAt(i, i-1)
                    sortedvalueArray.swapAt(i, i-1)
                    lastSwapIndex = i
                }
            }
            sortedAboveIndex = lastSwapIndex

        } while (sortedAboveIndex != 0)
        var index = 0
        var arr = [[CGFloat:CGFloat]]()
        for item in sortedArray {
            var dic = [CGFloat:CGFloat]()
            dic[item] = sortedvalueArray[index]
            arr.append(dic)
            index += 1
        }
        return arr
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

In this code you need to Set Progress Percentage based on the 360 degree. in the upper limit of for loop and Round lbl Center point x and y pos. Here is need only 180 replace to your progress percentage


问:
WordPress edit post or page that contain CSS will display 404 not found
I am working on a WordPress project. Wordpress displays 404 not found when update post or page.

Every time create or update (page/post) without css, It works, but it will display 404 not found (the link is www.website.com/wp-admin/post.php) when it having CSS (example change the color of text)

The css I mean here is

```<code><p style="color:red">hello</p>
</code>```

class as well not working

```<code><p class = "red">class cannot as well</p>
</code>```

Note:

Everything works well on localhost

Theme no problem, works well on localhost

It only happens when I put CSS or class name like
, if no CSS inside the content, everything is fine

Sometimes only, after it displays 404 not found, the server will disconnect from FileZilla and cannot access the website (other device can access). But after restart router and keep refresh, everything fine again.

答: Thanks, Guys. I solved the problem by disabling the ModSecurity in Cpanel -> Security -> ModSecurity. I not sure what is the reason but anyway it's working.</p>

Body:
I am working on a WordPress project. Wordpress displays 404 not found when update post or page.

Every time create or update (page/post) without css, It works, but it will display 404 not found (the link is www.website.com/wp-admin/post.php) when it having CSS (example change the color of text)

The css I mean here is

hello

class as well not working

class cannot as well

Note:

Everything works well on localhost

Theme no problem, works well on localhost

It only happens when I put CSS or class name like
, if no CSS inside the content, everything is fine

Sometimes only, after it displays 404 not found, the server will disconnect from FileZilla and cannot access the website (other device can access). But after restart router and keep refresh, everything fine again.


问:
How to troubleshoot the code that makes up an Ansible plugin?
Currently, I am trying to troubleshoot an action plugin that calls other working Ansible modules to reuse the code, making the playbook for those modules a lot simpler to use.

Previously when testing the other smaller modules, if I couldn't uncover the error when running my test playbook, I would make a json file of the playbook's arguments and supply it to pdb like so: python -m pdb /path/to/module.py ./test.json

With an action plugin, Ansible does far more set up than I am able to surmise from reading through the ActionBase files in the main Ansible repository, rendering my json tests unable to aid my diagnosis of the issue.

Using the Ansible debug features only steps through the various tasks and plays in the playbook, but not the underlying code. Embedding import pdb;pdb.set_trace() in the plugin/module doesn't help as running pdb when running a play causes halting, rather than an interactive debugger to appear.

答:
You should enforce tty. This code works for me when debugging Ansible plugins:

```<code>import sys; sys.stdin = open('/dev/tty')
import pdb; pdb.set_trace()
</code>```

Body:
You should enforce tty. This code works for me when debugging Ansible plugins:

import sys; sys.stdin = open('/dev/tty')
import pdb; pdb.set_trace()


问:
Django: Model.objects.filter(a=X, b=Y) not returning desired objects
So I'm trying to query my database for all submissions that have user=request.user and id=12. I know for certain that there are multiple submissions that match this, but filter() only returns one submission. What is wrong with my query?

Thanks

```<code>Submission.objects.filter(user=request.user, id=puzzleID)
</code>```

Edit:
Thank you to all responders. Here is my model for Submission and Puzzle:

```<code>class Submission(models.Model):
user = models.ForeignKey(
    User,
    on_delete=models.CASCADE,
)
puzzle = models.ForeignKey(
    Puzzle,
    on_delete=models.CASCADE,
)
userAnswer = models.TextField()

datetime = models.DateTimeField(default=datetime.now, blank=True)

class Puzzle(models.Model):
title = models.CharField(max_length=30)
question = models.TextField()
datetime = models.DateTimeField(
    default=datetime.now,
    blank=True)
# image = models.ImageField()
answer = models.TextField(default="answer")
trials = models.IntegerField(
    default=1,
    validators=[MinValueValidator(1)])
subject = models.CharField(
    default="CS",
    max_length=2,
    choices=(
    ("CS", "Computer Science"),
    )
)
</code>```

Edit 2:
Here is also the view in which the query is made

```<code>    puzzle = Puzzle.objects.get(id=puzzleID)
    form = SubmitForm()
    userTrials = len(Submission.objects.filter(user=request.user, puzzle=puzzle))
    if userTrials >= puzzle.trials:
        limitReached = True
    else:
        limitReached = False
    return render(request, "puzzle.html", {
        "puzzle": puzzle,
        "form": form,
        "userTrials": userTrials,
        "remaining": puzzle.trials - userTrials,
        "limitReached": limitReached,
    })
</code>```

答:
Try querying for puzzle, instead of id, as ID will refer to the submission ID, instead of the puzzle id.

Submission.objects.filter(user = request.user, puzzle=puzzleID)

Body:
So I'm trying to query my database for all submissions that have user=request.user and id=12. I know for certain that there are multiple submissions that match this, but filter() only returns one submission. What is wrong with my query?

Thanks

Submission.objects.filter(user=request.user, id=puzzleID)

Edit:
Thank you to all responders. Here is my model for Submission and Puzzle:

class Submission(models.Model):
user = models.ForeignKey(
    User,
    on_delete=models.CASCADE,
)
puzzle = models.ForeignKey(
    Puzzle,
    on_delete=models.CASCADE,
)
userAnswer = models.TextField()

datetime = models.DateTimeField(default=datetime.now, blank=True)

class Puzzle(models.Model):
title = models.CharField(max_length=30)
question = models.TextField()
datetime = models.DateTimeField(
    default=datetime.now,
    blank=True)
# image = models.ImageField()
answer = models.TextField(default="answer")
trials = models.IntegerField(
    default=1,
    validators=[MinValueValidator(1)])
subject = models.CharField(
    default="CS",
    max_length=2,
    choices=(
    ("CS", "Computer Science"),
    )
)

Edit 2:
Here is also the view in which the query is made

    puzzle = Puzzle.objects.get(id=puzzleID)
    form = SubmitForm()
    userTrials = len(Submission.objects.filter(user=request.user, puzzle=puzzle))
    if userTrials >= puzzle.trials:
        limitReached = True
    else:
        limitReached = False
    return render(request, "puzzle.html", {
        "puzzle": puzzle,
        "form": form,
        "userTrials": userTrials,
        "remaining": puzzle.trials - userTrials,
        "limitReached": limitReached,
    })


问:
database datatype performance: int or string
I'm storing phone country codes. They range from 1 to about 300. What's going to be more performant for datatype: int or string? I'm using SQL server 2008 and linq-to-sql.

Thanks.

答: Country codes are strings (notwithstanding that they use only the characters 0..9) and should be stored as such.</p>

ContentLicense: CC BY-SA 2.5


问:
Locating resource for OpenMP + MPI application
I'm currently developing a hybrid program using c++. I'm using both openMP and MPI. However, I don't know how to specify the number of processors and threads for my job. Let's say that I want to use 5 nodes and I want one MPI processor on each node and I want 24 threads per node.

This is how I submit my_job right now:

```<code>qsub -l select=5:ncpus=24:mpiprocs=5 -l place=scatter:exclhost my_job
</code>```

and on my_job script, I'm doing this

```<code>#PBS -l select=5:ncpus=24:mpiprocs=5
export OMP_NUM_THREADS=24
mpic++ -O3 myprogram.cpp -o out -fopenmp -lquadmath -std=gnu++11
mpirun -n 5 ./out
</code>```

However, the performance is very slow, which make me think that there might be a problem with how I'm locating my resources.

Any suggestion?

答:
Thanks Gilles, I also forget to specify the number of processor per node when running the job:

```<code>mpirun -n 5 -ppn 1 ./out
</code>```

Moreover, I have added this line to my_job script:

```<code>export IPATH_NO_CPUAFFINITY=1 // - tells the underlying software not to pin each process to one CPU core, which would effectively disable OpenMP parallelism.
</code>```

both solutions had improved performance "a lot".

Body:
I'm currently developing a hybrid program using c++. I'm using both openMP and MPI. However, I don't know how to specify the number of processors and threads for my job. Let's say that I want to use 5 nodes and I want one MPI processor on each node and I want 24 threads per node.

This is how I submit my_job right now:

qsub -l select=5:ncpus=24:mpiprocs=5 -l place=scatter:exclhost my_job

and on my_job script, I'm doing this

#PBS -l select=5:ncpus=24:mpiprocs=5
export OMP_NUM_THREADS=24
mpic++ -O3 myprogram.cpp -o out -fopenmp -lquadmath -std=gnu++11
mpirun -n 5 ./out

However, the performance is very slow, which make me think that there might be a problem with how I'm locating my resources.

Any suggestion?

Body:
Thanks Gilles, I also forget to specify the number of processor per node when running the job:

mpirun -n 5 -ppn 1 ./out

Moreover, I have added this line to my_job script:

export IPATH_NO_CPUAFFINITY=1 // - tells the underlying software not to pin each process to one CPU core, which would effectively disable OpenMP parallelism.

both solutions had improved performance "a lot".


问:
Python - return intersection of two arrays
I have two arrays and I am trying to return a new array that equals the intersection of my original two arrays. The two original arrays should be of the same length. For example, if I have:

arr1 = np.array([(255, 255, 255), (255, 255, 255)])

arr2 = np.array([(255, 255, 255), (255, 255, 255)])

I should get:

intersectedArr = ([(255, 255, 255), (255, 255, 255])

However, if I have:

arr1 = np.array([(100, 100, 100), (255, 255, 255)])

arr2 = np.array([(255, 255, 255), (255, 255, 255)])

I should get

([(255, 255, 255)])

So far i've tried:

intersectedArr = np.intersect1d(arr1, arr2)

but this returns [255] instead of the expected ([(255, 255, 255)])

Can someone help? Thanks in advance!

Body:
how about a numpy answer?

import numpy as np

arr1 = np.array([(255, 255, 255), (255, 255, 25)])  # changed some to 25
arr2 = np.array([(255, 25, 255), (255, 255, 25)])

arr1[np.where(arr1==arr2)]

array([255, 255, 255, 255,  25])

2nd example

arr1 = np.array([(100, 100, 100), (255, 255, 255)])
arr2 = np.array([(255, 255, 255), (255, 255, 255)])

arr1[np.where(arr1==arr2)]

array([255, 255, 255])