问:
Swift 3, function in protocol that return object of class that conforms to a protocol
I've read so many articles about classes and protocols but still didn't found a solution. May be I just didn't understand all of them.

So there's a simple protocol (removed some parts not relevant to the problem):

```<code>protocol InfoObject : NSObjectProtocol
{
    var statusImage: UIImage? {get}

    func viewControllerForItemIndex(_ index: Int?) -> UIViewController?
}
</code>```

But I would like the function viewControllerForItemIndex not only return an object of type UIViewController? but it should conform to the protocol InfoObjectDisplaying (not shown here) as well.

In Objective-C I would write:

```<code>- (UIViewController<InfoObjectDisplaying>*)viewControllerForItemIndex:(NSInteger) index;
</code>```

Is this possible in swift?

答:
I solve this problem like this:

```<code>protocol ScanningMessageViewProtocol: class {
    func showMessage(_ message: String, animated: Bool)
    func showMessage(_ message: String, autoHideAfterDelay time: TimeInterval?, animated: Bool)
    func hideMessage(animated: Bool)
}
extension ScanningMessageViewProtocol where Self: UIView {}

protocol CLScanBarcodeViewControllerDelegate: class {
    func messageViewForScanController(_ controller: CLScanBarcodeViewController) -> ScanningMessageViewProtocol
}
extension CLScanBarcodeViewControllerDelegate where Self: UIViewController {
    func messageViewForScanController(_ controller: CLScanBarcodeViewController?) -> ScanningMessageViewProtocol? { return  nil }
</code>```

}

Use it like this:

```<code>if let messageView = self.delegate?.messageViewForScanController(self) {
        if messageView is UIView {
            self.view.addSubview(messageView as! UIView)
            (messageView as! UIView).translatesAutoresizingMaskIntoConstraints = false
            let size: CGSize = self.view.bounds.size
            let cropSize: CGSize = CGSize(width: size.width * 0.7, height: size.width * 0.7)
            let cropRect = CGRect(x: (size.width - cropSize.width) / 2.0,
                                  y: (size.height - cropSize.height) / 2.0 - distanceToCenterY,
                                  width: cropSize.width,
                                  height: cropSize.height)
            self.view.addConstraint(NSLayoutConstraint(item: messageView, attribute: .leading, relatedBy: .equal, toItem: self.view, attribute: .leading, multiplier: 1, constant: 20))
            self.view.addConstraint(NSLayoutConstraint(item: messageView, attribute: .trailing, relatedBy: .equal, toItem: self.view, attribute: .trailing, multiplier: 1, constant: -20))
            self.view.addConstraint(NSLayoutConstraint(item: messageView, attribute: .top, relatedBy: .equal, toItem: self.view, attribute: .top, multiplier: 1, constant: cropRect.minY + cropRect.height + 30))
            self.view.addConstraint(NSLayoutConstraint(item: messageView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 0, constant: 30))
            messageView.showMessage("this is message", animated: true)
        }
    }
</code>```

Maybe that's not a very elegant way, hope someone could correct the mistakes.

Body:
I've read so many articles about classes and protocols but still didn't found a solution. May be I just didn't understand all of them.

So there's a simple protocol (removed some parts not relevant to the problem):

protocol InfoObject : NSObjectProtocol
{
    var statusImage: UIImage? {get}

    func viewControllerForItemIndex(_ index: Int?) -> UIViewController?
}

But I would like the function viewControllerForItemIndex not only return an object of type UIViewController? but it should conform to the protocol InfoObjectDisplaying (not shown here) as well.

In Objective-C I would write:

- (UIViewController<InfoObjectDisplaying>*)viewControllerForItemIndex:(NSInteger) index;

Is this possible in swift?

Body:
I solve this problem like this:

protocol ScanningMessageViewProtocol: class {
    func showMessage(_ message: String, animated: Bool)
    func showMessage(_ message: String, autoHideAfterDelay time: TimeInterval?, animated: Bool)
    func hideMessage(animated: Bool)
}
extension ScanningMessageViewProtocol where Self: UIView {}

protocol CLScanBarcodeViewControllerDelegate: class {
    func messageViewForScanController(_ controller: CLScanBarcodeViewController) -> ScanningMessageViewProtocol
}
extension CLScanBarcodeViewControllerDelegate where Self: UIViewController {
    func messageViewForScanController(_ controller: CLScanBarcodeViewController?) -> ScanningMessageViewProtocol? { return  nil }

}

Use it like this:

if let messageView = self.delegate?.messageViewForScanController(self) {
        if messageView is UIView {
            self.view.addSubview(messageView as! UIView)
            (messageView as! UIView).translatesAutoresizingMaskIntoConstraints = false
            let size: CGSize = self.view.bounds.size
            let cropSize: CGSize = CGSize(width: size.width * 0.7, height: size.width * 0.7)
            let cropRect = CGRect(x: (size.width - cropSize.width) / 2.0,
                                  y: (size.height - cropSize.height) / 2.0 - distanceToCenterY,
                                  width: cropSize.width,
                                  height: cropSize.height)
            self.view.addConstraint(NSLayoutConstraint(item: messageView, attribute: .leading, relatedBy: .equal, toItem: self.view, attribute: .leading, multiplier: 1, constant: 20))
            self.view.addConstraint(NSLayoutConstraint(item: messageView, attribute: .trailing, relatedBy: .equal, toItem: self.view, attribute: .trailing, multiplier: 1, constant: -20))
            self.view.addConstraint(NSLayoutConstraint(item: messageView, attribute: .top, relatedBy: .equal, toItem: self.view, attribute: .top, multiplier: 1, constant: cropRect.minY + cropRect.height + 30))
            self.view.addConstraint(NSLayoutConstraint(item: messageView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 0, constant: 30))
            messageView.showMessage("this is message", animated: true)
        }
    }

Maybe that's not a very elegant way, hope someone could correct the mistakes.


来源: stackexchange

问:
Unable to add python to PATH
I am very new to python, but it seems like I should be able to activate the python environment by simply typing python. Unfortunately, I keep getting the error "'python' is not recognized as an internal or external command,
operable program or batch file." I can access python through it's path at C:\Python27\python, which works fine, but I can't seem to get the shortcut to work.

Details: I manually installed Python 2.7, and I run Windows 10. I have tried going to the Advanced System Settings to add the PATH manually, but with no result. None of the tutorials or help articles have suggestions for what to do if adding it manually fails. Is there any way I can fix this? It seems like a small thing, but it's really bugging me.

答:
Your PATH variable has double quotes in ("C:\Windows;C:\Windows\System32;C:\Python27") which you should remove and try python command again on command prompt (cmd).

```<code>`C:\ProgramData\Oracle\Java\javapath;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\MiKTeX 2.9\miktex\bin\;C:\Program Files\jEdit;C:\Program Files\Git\cmd;"C:\Windows;C:\Windows\System32;C:\Python27";C:\Python27\Scripts;C:\Users\Maria\AppData\Local\Microsoft\WindowsApps;'
</code>```

Remove double quotes from below ...

```<code>"C:\Windows;C:\Windows\System32;C:\Python27"
</code>```

ContentLicense: CC BY-SA 3.0

Title: Unable to add python to PATH

Body:
Your PATH variable has double quotes in ("C:\Windows;C:\Windows\System32;C:\Python27") which you should remove and try python command again on command prompt (cmd).

`C:\ProgramData\Oracle\Java\javapath;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\MiKTeX 2.9\miktex\bin\;C:\Program Files\jEdit;C:\Program Files\Git\cmd;"C:\Windows;C:\Windows\System32;C:\Python27";C:\Python27\Scripts;C:\Users\Maria\AppData\Local\Microsoft\WindowsApps;'

Remove double quotes from below ...

"C:\Windows;C:\Windows\System32;C:\Python27"


问:
EXC_BAD_ACCESS (SIGSEGV) in WebCore::UserGestureIndicator::processingUserGesture
I have an iOS application built using a UIWebView and HTML5 websockets. The app experiences seemingly random crashes. It has occurred while a user is interacting with it and during longevity tests where no interaction between user and app occurs.

The crash logs all have the following:

```<code>Exception Type:  EXC_BAD_ACCESS (SIGSEGV)
Exception Subtype: KERN_INVALID_ADDRESS at 0x00000000
</code>```

and the thread logs contain:

```<code>Thread XX name:  WebCore: Worker
Thread XX Crashed:
0   WebCore                         0x36c8c7a0 WebCore::UserGestureIndicator::processingUserGesture() + 20
1   WebCore                         0x36d7070a WebCore::DOMTimer::DOMTimer(WebCore::ScriptExecutionContext*, WTF::PassOwnPtr<WebCore::ScheduledAction>, int, bool) + 74
2   WebCore                         0x36d70616 WebCore::DOMTimer::install(WebCore::ScriptExecutionContext*, WTF::PassOwnPtr<WebCore::ScheduledAction>, int, bool) + 46
3   WebCore                         0x3753ae7e WebCore::WorkerContext::setTimeout(WTF::PassOwnPtr<WebCore::ScheduledAction>, int) + 30
4   WebCore                         0x3731ac02 WebCore::JSWorkerContext::setTimeout(JSC::ExecState*) + 194
5   WebCore                         0x37318ff6 WebCore::jsWorkerContextPrototypeFunctionSetTimeout(JSC::ExecState*) + 110
6   JavaScriptCore                  0x2fa9a1d8 llint_native_call_trampoline + 62
7   JavaScriptCore                  0x2faa355a JSC::call(JSC::ExecState*, JSC::JSValue, JSC::CallType, JSC::CallData const&, JSC::JSValue, JSC::ArgList const&) + 66
8   WebCore                         0x36db0b16 WebCore::JSEventListener::handleEvent(WebCore::ScriptExecutionContext*, WebCore::Event*) + 558
9   WebCore                         0x36d6ebba WebCore::EventTarget::fireEventListeners(WebCore::Event*, WebCore::EventTargetData*, WTF::Vector<WebCore::RegisteredEventListener, 1ul, WTF::CrashOnOverflow>&) + 482
10  WebCore                         0x36c6da2a WebCore::EventTarget::fireEventListeners(WebCore::Event*) + 174
11  WebCore                         0x36e28824 WebCore::EventTarget::dispatchEvent(WTF::PassRefPtr<WebCore::Event>) + 60
12  WebCore                         0x3753e596 WebCore::MessageWorkerContextTask::performTask(WebCore::ScriptExecutionContext*) + 222
13  WebCore                         0x3753ec6e WebCore::WorkerRunLoop::runInMode(WebCore::WorkerContext*, WebCore::ModePredicate const&, WebCore::WorkerRunLoop::WaitMode) + 158
14  WebCore                         0x3753eb94 WebCore::WorkerRunLoop::run(WebCore::WorkerContext*) + 60
15  WebCore                         0x37540d64 WebCore::WorkerThread::workerThread() + 432
16  JavaScriptCore                  0x2fa4ba68 WTF::wtfThreadEntryPoint(void*) + 12
17  libsystem_pthread.dylib         0x397b6c5a _pthread_body + 138
18  libsystem_pthread.dylib         0x397b6bca _pthread_start + 98
19  libsystem_pthread.dylib         0x397b4ccc thread_start + 4
</code>```

I managed to catch the exception on throw, and from what I can tell it looks to be a framework bug. See attached screenshot.

Most of what I've read seem to indicate that the web view is being dealloced prior to a delegate firing, but nowhere in my code do I dealloc!

Has anyone encountered this or a similar case? Any help is much appreciated!

UPDATE

I have filed a bug report with Apple after contacting developer support. Their engineers confirmed this as being a bug.

答:
In My Case, I have similar issue.

As Many of said, it may cause due to WebView Delegate methods are calling while webview is being deallocated.

In order to fix, we need to set delegate as nil and also stop webview request at specified methods

You have to add below lines of code

```<code>-(void)viewDidUnload{
    [super viewDidUnload];

    webViewRef.delegate = nil;
    [webViewRef stopLoading];

}

-(void)backBtnClicked{

    webViewRef.delegate = nil;
    [webViewRef stopLoading];

}
</code>```

Hope it helps you.

Body:
I have an iOS application built using a UIWebView and HTML5 websockets. The app experiences seemingly random crashes. It has occurred while a user is interacting with it and during longevity tests where no interaction between user and app occurs.

The crash logs all have the following:

Exception Type:  EXC_BAD_ACCESS (SIGSEGV)
Exception Subtype: KERN_INVALID_ADDRESS at 0x00000000

and the thread logs contain:

Thread XX name:  WebCore: Worker
Thread XX Crashed:
0   WebCore                         0x36c8c7a0 WebCore::UserGestureIndicator::processingUserGesture() + 20
1   WebCore                         0x36d7070a WebCore::DOMTimer::DOMTimer(WebCore::ScriptExecutionContext*, WTF::PassOwnPtr<WebCore::ScheduledAction>, int, bool) + 74
2   WebCore                         0x36d70616 WebCore::DOMTimer::install(WebCore::ScriptExecutionContext*, WTF::PassOwnPtr<WebCore::ScheduledAction>, int, bool) + 46
3   WebCore                         0x3753ae7e WebCore::WorkerContext::setTimeout(WTF::PassOwnPtr<WebCore::ScheduledAction>, int) + 30
4   WebCore                         0x3731ac02 WebCore::JSWorkerContext::setTimeout(JSC::ExecState*) + 194
5   WebCore                         0x37318ff6 WebCore::jsWorkerContextPrototypeFunctionSetTimeout(JSC::ExecState*) + 110
6   JavaScriptCore                  0x2fa9a1d8 llint_native_call_trampoline + 62
7   JavaScriptCore                  0x2faa355a JSC::call(JSC::ExecState*, JSC::JSValue, JSC::CallType, JSC::CallData const&, JSC::JSValue, JSC::ArgList const&) + 66
8   WebCore                         0x36db0b16 WebCore::JSEventListener::handleEvent(WebCore::ScriptExecutionContext*, WebCore::Event*) + 558
9   WebCore                         0x36d6ebba WebCore::EventTarget::fireEventListeners(WebCore::Event*, WebCore::EventTargetData*, WTF::Vector<WebCore::RegisteredEventListener, 1ul, WTF::CrashOnOverflow>&) + 482
10  WebCore                         0x36c6da2a WebCore::EventTarget::fireEventListeners(WebCore::Event*) + 174
11  WebCore                         0x36e28824 WebCore::EventTarget::dispatchEvent(WTF::PassRefPtr<WebCore::Event>) + 60
12  WebCore                         0x3753e596 WebCore::MessageWorkerContextTask::performTask(WebCore::ScriptExecutionContext*) + 222
13  WebCore                         0x3753ec6e WebCore::WorkerRunLoop::runInMode(WebCore::WorkerContext*, WebCore::ModePredicate const&, WebCore::WorkerRunLoop::WaitMode) + 158
14  WebCore                         0x3753eb94 WebCore::WorkerRunLoop::run(WebCore::WorkerContext*) + 60
15  WebCore                         0x37540d64 WebCore::WorkerThread::workerThread() + 432
16  JavaScriptCore                  0x2fa4ba68 WTF::wtfThreadEntryPoint(void*) + 12
17  libsystem_pthread.dylib         0x397b6c5a _pthread_body + 138
18  libsystem_pthread.dylib         0x397b6bca _pthread_start + 98
19  libsystem_pthread.dylib         0x397b4ccc thread_start + 4

I managed to catch the exception on throw, and from what I can tell it looks to be a framework bug. See attached screenshot.

Most of what I've read seem to indicate that the web view is being dealloced prior to a delegate firing, but nowhere in my code do I dealloc!

Has anyone encountered this or a similar case? Any help is much appreciated!

UPDATE

I have filed a bug report with Apple after contacting developer support. Their engineers confirmed this as being a bug.

Body:
In My Case, I have similar issue.

As Many of said, it may cause due to WebView Delegate methods are calling while webview is being deallocated.

In order to fix, we need to set delegate as nil and also stop webview request at specified methods

You have to add below lines of code

-(void)viewDidUnload{
    [super viewDidUnload];

    webViewRef.delegate = nil;
    [webViewRef stopLoading];

}

-(void)backBtnClicked{

    webViewRef.delegate = nil;
    [webViewRef stopLoading];

}

Hope it helps you.


问:
Is there a stopwatch in Java?
Is there a stopwatch in Java?

On Google I only found code of stopwatches that don't work - they always return 0 milliseconds.

This code I found doesn't work and I don't see why.

```<code>public class StopWatch {

  private long startTime = 0;
  private long stopTime = 0;
  private boolean running = false;

  public void start() {
    this.startTime = System.currentTimeMillis();
    this.running = true;
  }

  public void stop() {
    this.stopTime = System.currentTimeMillis();
    this.running = false;
  }

  //elaspsed time in milliseconds
  public long getElapsedTime() {
    long elapsed;
    if (running) {
      elapsed = (System.currentTimeMillis() - startTime);
    } else {
      elapsed = (stopTime - startTime);
    }
    return elapsed;
  }

  //elaspsed time in seconds
  public long getElapsedTimeSecs() {
    long elapsed;
    if (running) {
      elapsed = ((System.currentTimeMillis() - startTime) / 1000);
    } else {
      elapsed = ((stopTime - startTime) / 1000);
    }
    return elapsed;
  }
}
</code>```

答:
Try this.

```<code>public class StopWatch {

      private long startTime = 0;
      private long stopTime = 0;

      public StopWatch()
      {
            startTime = System.currentTimeMillis();
      }

      public void start() {
        startTime = System.currentTimeMillis();
      }

      public void stop() {
        stopTime = System.currentTimeMillis();
        System.out.println("StopWatch: " + getElapsedTime() + " milliseconds.");
        System.out.println("StopWatch: " + getElapsedTimeSecs() + " seconds.");
      }

      /**
       * @param process_name
       */
      public void stop(String process_name) {
            stopTime = System.currentTimeMillis();
            System.out.println(process_name + " StopWatch: " + getElapsedTime() + " milliseconds.");
            System.out.println(process_name + " StopWatch: " + getElapsedTimeSecs() + " seconds.");
      }

      //elaspsed time in milliseconds
      public long getElapsedTime() {
          return stopTime - startTime;
      }

      //elaspsed time in seconds
      public double getElapsedTimeSecs() {
        double elapsed;
          elapsed = ((double)(stopTime - startTime)) / 1000;
        return elapsed;
      }
}
</code>```

Usage:

```<code>StopWatch watch = new StopWatch();
// do something
watch.stop();
</code>```

Console:

```<code>StopWatch: 143 milliseconds.
StopWatch: 0.143 seconds.
</code>```

ContentLicense: CC BY-SA 4.0

Title: Is there a stopwatch in Java?

Body:
Is there a stopwatch in Java?

On Google I only found code of stopwatches that don't work - they always return 0 milliseconds.

This code I found doesn't work and I don't see why.

public class StopWatch {

  private long startTime = 0;
  private long stopTime = 0;
  private boolean running = false;

  public void start() {
    this.startTime = System.currentTimeMillis();
    this.running = true;
  }

  public void stop() {
    this.stopTime = System.currentTimeMillis();
    this.running = false;
  }

  //elaspsed time in milliseconds
  public long getElapsedTime() {
    long elapsed;
    if (running) {
      elapsed = (System.currentTimeMillis() - startTime);
    } else {
      elapsed = (stopTime - startTime);
    }
    return elapsed;
  }

  //elaspsed time in seconds
  public long getElapsedTimeSecs() {
    long elapsed;
    if (running) {
      elapsed = ((System.currentTimeMillis() - startTime) / 1000);
    } else {
      elapsed = ((stopTime - startTime) / 1000);
    }
    return elapsed;
  }
}

Body:
Try this.

public class StopWatch {

      private long startTime = 0;
      private long stopTime = 0;

      public StopWatch()
      {
            startTime = System.currentTimeMillis();
      }

      public void start() {
        startTime = System.currentTimeMillis();
      }

      public void stop() {
        stopTime = System.currentTimeMillis();
        System.out.println("StopWatch: " + getElapsedTime() + " milliseconds.");
        System.out.println("StopWatch: " + getElapsedTimeSecs() + " seconds.");
      }

      /**
       * @param process_name
       */
      public void stop(String process_name) {
            stopTime = System.currentTimeMillis();
            System.out.println(process_name + " StopWatch: " + getElapsedTime() + " milliseconds.");
            System.out.println(process_name + " StopWatch: " + getElapsedTimeSecs() + " seconds.");
      }

      //elaspsed time in milliseconds
      public long getElapsedTime() {
          return stopTime - startTime;
      }

      //elaspsed time in seconds
      public double getElapsedTimeSecs() {
        double elapsed;
          elapsed = ((double)(stopTime - startTime)) / 1000;
        return elapsed;
      }
}

Usage:

StopWatch watch = new StopWatch();
// do something
watch.stop();

Console:

StopWatch: 143 milliseconds.
StopWatch: 0.143 seconds.


问:
Learning C# prior to learning ASP.NET MVC?
With only mild programming experience in the past, I was wondering about C# and ASP.NET MVC..

Do you guys think it's a better idea to learn C# before learning ASP.NET MVC?  I've already delved a little into both of these already, but I still need some help deciding.

I think I would be a much stronger MVC user if I had more knowledge of the C# language itself.

What do you guys think?

Thanks!

答: Master C# first, then go to ASP.NET, then learn MVC and other patterns.  Don't bite off more than you can chew, newbie mistake.</p>

ContentLicense: CC BY-SA 2.5


问:
How to avoid duplicate element entry in C array?
I want some logic which will insert numbers in the array, and at the same time it will check that the current number is already not present in the array. Please help me with the logic.</p>

答:
Code to Remove duplicate Element in an Array

```<code>    #include<stdio.h>
    #include<conio.h>
    void main()
    {
       int a[20], i, j, k, n;
       clrscr();

       printf("\nEnter array size : ");
       scanf("%d",&n);

       printf("\nEnter %d array element : ", n);
       for(i = 0; i < n; i++)
       {
          scanf("%d",&a[i]);
       }

       printf("\nOriginal array is : ");
       for(i=0;i< n;i++)
       {
          printf(" %d",a[i]);
       }

       printf("\nNew array is  : ");
       for(i=0; i < n; i++)
       {
          for(j=i+1; j < n; )
          {
             if(a[j] == a[i])
             {
                for(k=j; k < n;k++)
                {
                   a[k] = a[k+1];
                }
                n--;
             }
             else {
                j++;
             }
          }
       }

       for(i=0; i < n; i++)
       {
          printf("%d ", a[i]);
       }
    getch();
    }
</code>```

Output

Enter array size : 5

Enter 5 array element :  11 13 11 12 13

Original array is :  11 13 11 12 13

New array is :   11 13 12

Body:
Code to Remove duplicate Element in an Array

    #include<stdio.h>
    #include<conio.h>
    void main()
    {
       int a[20], i, j, k, n;
       clrscr();

       printf("\nEnter array size : ");
       scanf("%d",&n);

       printf("\nEnter %d array element : ", n);
       for(i = 0; i < n; i++)
       {
          scanf("%d",&a[i]);
       }

       printf("\nOriginal array is : ");
       for(i=0;i< n;i++)
       {
          printf(" %d",a[i]);
       }

       printf("\nNew array is  : ");
       for(i=0; i < n; i++)
       {
          for(j=i+1; j < n; )
          {
             if(a[j] == a[i])
             {
                for(k=j; k < n;k++)
                {
                   a[k] = a[k+1];
                }
                n--;
             }
             else {
                j++;
             }
          }
       }

       for(i=0; i < n; i++)
       {
          printf("%d ", a[i]);
       }
    getch();
    }

Output

Enter array size : 5

Enter 5 array element :  11 13 11 12 13

Original array is :  11 13 11 12 13

New array is :   11 13 12


问:
Can't show result as select option Codeigniter 3
My Model name mymodel.php

```<code>.....
function all($table,$order)
        {
            $this->db->select('*');
            $this->db->from($table);
            $this->db->order_by($order);
            $query = $this->db->get();
            if ($query->num_rows() == 0) {
                return FALSE;
            } else {
                return $query->result();
            }
        } .....
</code>```

My controller name donate.php

```<code>.....
    function index()
    {
      $data = array(
                        'rekening' => $this->mymodel->all('rekening', 'id_rekening ASC'),
                        );
                    $this->load->view('client/donate/index', $data);
                } .....
</code>```

And this My View in path view/client/donate/index

```<code><?php foreach ($rekening as $rek): ?>
                <option value="<?php echo $rek->id_rekening; ?>" <?php echo set_select('ke_rekening', $rek->id_rekening); ?>><?php echo $rek->bank .' - '. $rek->atas_nama_rekening; ?></option>
              <?php endforeach ?>
</code>```

But why cant show in select option? I use codeigniter 3,
Show image

答:
if I get it correctly is your problem is to get all list or you want to make that option selected which is previously selected?

Here is the solution for adding value to the <option> in the select box. I have also added how to get the pre-selected value selected.

```<code>  In Model:
    $query = $this->db->select('*')
        ->from($table)
        ->order_by($order)
        ->get();

    $your_result_array = $query->result_array();
    return $your_result_array;

    In Controller:

    $data = $this->mymodel->all($data1,$data2);
    $this->load->view('client/donate/index',['data'=>$data]) ;

    Inside Your View:

    <?php

    if(isset($data) && !empty($data)){
        foreach ($data as $single_data){

        ?> <option value="<?= $data['id_rekening] ?>" <?= $your_selected_value_array['your_selected_value'] === $data['id_rekening] ? 'selected':''  ?> > <?= $data['your_other_data_column_name_here] ?> </option> <?php

        }
    }else {

          ?><option> data not found </optiop> <?php
    }
    ?>
</code>```

Body:
My Model name mymodel.php

.....
function all($table,$order)
        {
            $this->db->select('*');
            $this->db->from($table);
            $this->db->order_by($order);
            $query = $this->db->get();
            if ($query->num_rows() == 0) {
                return FALSE;
            } else {
                return $query->result();
            }
        } .....

My controller name donate.php

.....
    function index()
    {
      $data = array(
                        'rekening' => $this->mymodel->all('rekening', 'id_rekening ASC'),
                        );
                    $this->load->view('client/donate/index', $data);
                } .....

And this My View in path view/client/donate/index

<?php foreach ($rekening as $rek): ?>
                <option value="<?php echo $rek->id_rekening; ?>" <?php echo set_select('ke_rekening', $rek->id_rekening); ?>><?php echo $rek->bank .' - '. $rek->atas_nama_rekening; ?></option>
              <?php endforeach ?>

But why cant show in select option? I use codeigniter 3,
Show image

Body:
if I get it correctly is your problem is to get all list or you want to make that option selected which is previously selected?

Here is the solution for adding value to the <option> in the select box. I have also added how to get the pre-selected value selected.

  In Model:
    $query = $this->db->select('*')
        ->from($table)
        ->order_by($order)
        ->get();

    $your_result_array = $query->result_array();
    return $your_result_array;

    In Controller:

    $data = $this->mymodel->all($data1,$data2);
    $this->load->view('client/donate/index',['data'=>$data]) ;

    Inside Your View:

    <?php

    if(isset($data) && !empty($data)){
        foreach ($data as $single_data){

        ?> <option value="<?= $data['id_rekening] ?>" <?= $your_selected_value_array['your_selected_value'] === $data['id_rekening] ? 'selected':''  ?> > <?= $data['your_other_data_column_name_here] ?> </option> <?php

        }
    }else {

          ?><option> data not found </optiop> <?php
    }
    ?>


问:
How to fix ioexception stream closed?
On start up my program gives me the message java.io.IOException: stream closed. It then opens with limited components.

I understand what a stream closed exception is, I just can't figure out how to fix it, in my case. I would really appreciate some help. (I'm sorry about the big chunk of code, but I am not sure what you need to help me)

```<code> try {
    //Defines new file reader and buffered reader
    FileReader file_to_read = new FileReader(path);
    BufferedReader br1 = new BufferedReader(file_to_read);

    //action code

        try {
        //Finds the line number to see the number of cards in each set
        lnr2= new LineNumberReader(new FileReader(new File("C:\\Users\\priceadria\\Desktop\\Words_" + strSetName + ".txt")));
        lnr2.skip(Long.MAX_VALUE);
        strLineNumber2 = String.valueOf(lnr2.getLineNumber());
        lineNumber2 = Integer.parseInt(strLineNumber2);

        //Closes the file reader and buffered reader
        br1.close();
        file_to_read.close();

    } catch (IOException | NumberFormatException e) {
        strLineNumber2 = "0";
    }
        //Adds the set name to the set name array
        lblDeckName[row] = new JLabel (strSetName);

        //Adds all buttons that will be used in the layout into a button array
        JButton aryOptions [][] = new JButton [3][lineNumber];

        //Defines and formats the Add Words button
        JButton btnAddWords = new JButton("Add Words");
        btnAddWords.setOpaque(false);
        btnAddWords.setContentAreaFilled(false);
        btnAddWords.setBorder(null);
        btnAddWords.setBorderPainted(false);

        //Defines and formats the Play button
        JButton btnPlay = new JButton("Play");
        btnPlay.setOpaque(false);
        btnPlay.setContentAreaFilled(false);
        btnPlay.setBorder(null);
        btnPlay.setBorderPainted(false);

        //Defines and formats the Delete Set button
        JButton btnDelete = new JButton("Delete Set");
        btnDelete.setOpaque(false);
        btnDelete.setContentAreaFilled(false);
        btnDelete.setBorder(null);
        btnDelete.setBorderPainted(false);

        //Adds each button to the array based on the number of sets
        aryOptions [0][row] = btnAddWords;
        aryOptions [1][row] = btnPlay;
        aryOptions [2][row] = btnDelete;

        //Formats the GridBagLayout (Spaces are for formatting purposes)
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.gridx = 0;
        gbc.gridy = row;
        layoutBackground.add(lblDeckName[row],gbc);

        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.gridx = 1;
        gbc.gridy = row;
        layoutBackground.add(new JLabel("      "),gbc);

        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.gridx =2;
        gbc.gridy = row;
        layoutBackground.add(new JLabel (strSubjectName),gbc);

        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.gridx = 3;
        gbc.gridy = row;
        layoutBackground.add(new JLabel("                   "),gbc);

        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.gridx = 4;
        gbc.gridy = row;
        layoutBackground.add(new JLabel(strLineNumber2),gbc);

        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.gridx = 5;
        gbc.gridy = row;
        layoutBackground.add(new JLabel("             |  "),gbc);

        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.gridx = 6;
        gbc.gridy = row;
        layoutBackground.add(aryOptions[0][row],gbc);

        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.gridx = 7;
        gbc.gridy = row;
        layoutBackground.add(new JLabel("  |  "),gbc);

        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.gridx = 8;
        gbc.gridy = row;
        layoutBackground.add(aryOptions[1][row],gbc);

        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.gridx = 9;
        gbc.gridy = row;
        layoutBackground.add(new JLabel("  |  "),gbc);

        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.gridx = 10;
        gbc.gridy = row;
        layoutBackground.add(aryOptions[2][row],gbc);

        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.gridx = 11;
        gbc.gridy = row;
        layoutBackground.add(new JLabel("  |"),gbc);

        //Creates an action event for the delete set button
        btnDelete.addActionListener((ActionEvent a) -> {
            //Finds the source of the button that was clicked
            String strSource = String.valueOf(a.getSource());
            String strSourceCut1 = strSource.substring(25,30);

            //Finds the index of the button that was clicked
            String [] aryIndex = strSourceCut1.split(",");
            String strIndex = aryIndex[0];

            try {
                //Defines new file reader and buffered reader
                FileReader file_to_read2 = new FileReader(path);
                BufferedReader br2 = new BufferedReader(file_to_read2);

                //Finds the numerical index of the button that was clicked
                int intIndex = Integer.parseInt(strIndex)/16;

                //Creates a counter to count line numbers
                int counter = 0;

                while((br2.readLine()) != null) {

                    counter ++;
                    if(intIndex == 0) { //If the index is the first option the normal try/catch returns null pointer, so a new try/catch had to be created
                        try {
                            //Finds the name of the set based on what button was clicked
                            String chosenDeck2 = br2.readLine();
                            String [] aryDeleteDeck = chosenDeck2.split(",");
                            deleteDeck = aryDeleteDeck[0];

                            //Closes the buffered reader and file reader
                            br2.close();
                            file_to_read2.close();

                            //Creates the path to the file that needs to be deleted
                            Path p2 = Paths.get("C:\\Users\\priceadria\\Desktop\\Words_" + deleteDeck + ".txt");
                            Files.delete(p2);

                        } catch (IOException e) {
                            JOptionPane.showMessageDialog(null, e);
                        }

                    } else if ( counter == intIndex) {
                        //Reads the deck name based on the button that was clicked
                        String chosenDeck2 = br2.readLine();

                        //Splits the deck name from the subject
                        String [] aryDeleteDeck = chosenDeck2.split(",");
                        deleteDeck = aryDeleteDeck[0];

                        //Closes the buffered reader and file reader
                        br2.close();
                        file_to_read2.close();

                        //Gets the file that needs to be deleted
                        Path p1 = Paths.get("C:\\Users\\priceadria\\Desktop\\Words_" + deleteDeck + ".txt");
                        Files.delete(p1);

                    }
                }
            }
            catch (HeadlessException | IOException | NumberFormatException e) {
                JOptionPane.showMessageDialog(null, e);
            }
        });

        //Creates an action event for the add words button
        btnAddWords.addActionListener((ActionEvent a) -> {
            //Finds the source of the button that was clicked
            String strSource = String.valueOf(a.getSource());
            String strSourceCut1 = strSource.substring(25,30);

            //Finds the index of the button that was clicked
            String [] aryIndex = strSourceCut1.split(",");
            String strIndex = aryIndex[0];

            try {
                //Creates a new file reader and buffered reader
                FileReader file_to_read3 = new FileReader(path);
                BufferedReader br3 = new BufferedReader(file_to_read3);

                //Finds the index value
                int intIndex = Integer.parseInt(strIndex)/16;

                //Creates a counter to count line numbers
                int counter = 0;

                while((br3.readLine()) != null) {
                    //Increases counter value by 1
                    counter ++;
                    if(intIndex == 0)
                    {
                        try {
                            //Reads the set and subject for the
                            String chosenDeck2 = br3.readLine();

                            //Splits the subject from the set
                            String [] aryDeck = chosenDeck2.split(",");
                            chosenDeck = aryDeck[0];

                            //Closes the buffered reader and file reader
                            br3.close();
                            file_to_read3.close();

                        } catch (Exception e) {
                            JOptionPane.showMessageDialog(null, e);
                        }

                    } else if ( counter == intIndex) {
                        String chosenDeck2 = br3.readLine();

                        String [] aryDeck = chosenDeck2.split(",");
                        chosenDeck = aryDeck[0];

                        br3.close();
                        file_to_read3.close();
                    }

                }
            }
            catch (Exception e) {
                JOptionPane.showMessageDialog(null, e);
            }
            //Opens the new words frame
            frmWords s = new frmWords(deckName, newXPoint, newYPoint, chosenDeck);
            s.setVisible(true);
        });
    }

    } catch (Exception e ) {
        JOptionPane.showMessageDialog(null, e);

    }
</code>```

What I am finding is that when I am deleting the br1.close() the stream closed error stops, but I can find any reason why? Nothing is using that reader, that I can see. And when I do delete it I get and error saying that the test files are being used by other processes, which I can only presume is br1.

I know this may seem confusing to look at, probably because it is sloppy code, but I would really appreciate some help. I am a high school student.

Thanks :)

答:
When you construct nested Readers as you do, for example,

```<code>    FileReader file_to_read = new FileReader(path);
    BufferedReader br1 = new BufferedReader(file_to_read);
</code>```

, closing the outer one automatically closes the inner one, too.  You do not need to close the inner one yourself, and if you try to do so after closing the outer one, as you do, you will find that it is already closed.

The best solution is to close only the outer one (as opposed to your workaround of closing only the inner one).  You probably don't even need to retain a reference to the inner one -- a more typical idiom would go something like this:

```<code>    BufferedReader br1 = new BufferedReader(new FileReader(path));

    try {
        // ... manipulate br1 ...
    } finally {
        br1.close();
        // no need to explicitly close the inner FileReader
    }
</code>```

You could write that in try-with-resources form if that suits your fancy.

Similar applies to nested Writers, InputStreams, and OutputStreams, too.

Title: How to fix ioexception stream closed?

Body:
On start up my program gives me the message java.io.IOException: stream closed. It then opens with limited components.

I understand what a stream closed exception is, I just can't figure out how to fix it, in my case. I would really appreciate some help. (I'm sorry about the big chunk of code, but I am not sure what you need to help me)

 try {
    //Defines new file reader and buffered reader
    FileReader file_to_read = new FileReader(path);
    BufferedReader br1 = new BufferedReader(file_to_read);

    //action code

        try {
        //Finds the line number to see the number of cards in each set
        lnr2= new LineNumberReader(new FileReader(new File("C:\\Users\\priceadria\\Desktop\\Words_" + strSetName + ".txt")));
        lnr2.skip(Long.MAX_VALUE);
        strLineNumber2 = String.valueOf(lnr2.getLineNumber());
        lineNumber2 = Integer.parseInt(strLineNumber2);

        //Closes the file reader and buffered reader
        br1.close();
        file_to_read.close();

    } catch (IOException | NumberFormatException e) {
        strLineNumber2 = "0";
    }
        //Adds the set name to the set name array
        lblDeckName[row] = new JLabel (strSetName);

        //Adds all buttons that will be used in the layout into a button array
        JButton aryOptions [][] = new JButton [3][lineNumber];

        //Defines and formats the Add Words button
        JButton btnAddWords = new JButton("Add Words");
        btnAddWords.setOpaque(false);
        btnAddWords.setContentAreaFilled(false);
        btnAddWords.setBorder(null);
        btnAddWords.setBorderPainted(false);

        //Defines and formats the Play button
        JButton btnPlay = new JButton("Play");
        btnPlay.setOpaque(false);
        btnPlay.setContentAreaFilled(false);
        btnPlay.setBorder(null);
        btnPlay.setBorderPainted(false);

        //Defines and formats the Delete Set button
        JButton btnDelete = new JButton("Delete Set");
        btnDelete.setOpaque(false);
        btnDelete.setContentAreaFilled(false);
        btnDelete.setBorder(null);
        btnDelete.setBorderPainted(false);

        //Adds each button to the array based on the number of sets
        aryOptions [0][row] = btnAddWords;
        aryOptions [1][row] = btnPlay;
        aryOptions [2][row] = btnDelete;

        //Formats the GridBagLayout (Spaces are for formatting purposes)
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.gridx = 0;
        gbc.gridy = row;
        layoutBackground.add(lblDeckName[row],gbc);

        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.gridx = 1;
        gbc.gridy = row;
        layoutBackground.add(new JLabel("      "),gbc);

        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.gridx =2;
        gbc.gridy = row;
        layoutBackground.add(new JLabel (strSubjectName),gbc);

        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.gridx = 3;
        gbc.gridy = row;
        layoutBackground.add(new JLabel("                   "),gbc);

        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.gridx = 4;
        gbc.gridy = row;
        layoutBackground.add(new JLabel(strLineNumber2),gbc);

        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.gridx = 5;
        gbc.gridy = row;
        layoutBackground.add(new JLabel("             |  "),gbc);

        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.gridx = 6;
        gbc.gridy = row;
        layoutBackground.add(aryOptions[0][row],gbc);

        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.gridx = 7;
        gbc.gridy = row;
        layoutBackground.add(new JLabel("  |  "),gbc);

        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.gridx = 8;
        gbc.gridy = row;
        layoutBackground.add(aryOptions[1][row],gbc);

        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.gridx = 9;
        gbc.gridy = row;
        layoutBackground.add(new JLabel("  |  "),gbc);

        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.gridx = 10;
        gbc.gridy = row;
        layoutBackground.add(aryOptions[2][row],gbc);

        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.gridx = 11;
        gbc.gridy = row;
        layoutBackground.add(new JLabel("  |"),gbc);

        //Creates an action event for the delete set button
        btnDelete.addActionListener((ActionEvent a) -> {
            //Finds the source of the button that was clicked
            String strSource = String.valueOf(a.getSource());
            String strSourceCut1 = strSource.substring(25,30);

            //Finds the index of the button that was clicked
            String [] aryIndex = strSourceCut1.split(",");
            String strIndex = aryIndex[0];

            try {
                //Defines new file reader and buffered reader
                FileReader file_to_read2 = new FileReader(path);
                BufferedReader br2 = new BufferedReader(file_to_read2);

                //Finds the numerical index of the button that was clicked
                int intIndex = Integer.parseInt(strIndex)/16;

                //Creates a counter to count line numbers
                int counter = 0;

                while((br2.readLine()) != null) {

                    counter ++;
                    if(intIndex == 0) { //If the index is the first option the normal try/catch returns null pointer, so a new try/catch had to be created
                        try {
                            //Finds the name of the set based on what button was clicked
                            String chosenDeck2 = br2.readLine();
                            String [] aryDeleteDeck = chosenDeck2.split(",");
                            deleteDeck = aryDeleteDeck[0];

                            //Closes the buffered reader and file reader
                            br2.close();
                            file_to_read2.close();

                            //Creates the path to the file that needs to be deleted
                            Path p2 = Paths.get("C:\\Users\\priceadria\\Desktop\\Words_" + deleteDeck + ".txt");
                            Files.delete(p2);

                        } catch (IOException e) {
                            JOptionPane.showMessageDialog(null, e);
                        }

                    } else if ( counter == intIndex) {
                        //Reads the deck name based on the button that was clicked
                        String chosenDeck2 = br2.readLine();

                        //Splits the deck name from the subject
                        String [] aryDeleteDeck = chosenDeck2.split(",");
                        deleteDeck = aryDeleteDeck[0];

                        //Closes the buffered reader and file reader
                        br2.close();
                        file_to_read2.close();

                        //Gets the file that needs to be deleted
                        Path p1 = Paths.get("C:\\Users\\priceadria\\Desktop\\Words_" + deleteDeck + ".txt");
                        Files.delete(p1);

                    }
                }
            }
            catch (HeadlessException | IOException | NumberFormatException e) {
                JOptionPane.showMessageDialog(null, e);
            }
        });

        //Creates an action event for the add words button
        btnAddWords.addActionListener((ActionEvent a) -> {
            //Finds the source of the button that was clicked
            String strSource = String.valueOf(a.getSource());
            String strSourceCut1 = strSource.substring(25,30);

            //Finds the index of the button that was clicked
            String [] aryIndex = strSourceCut1.split(",");
            String strIndex = aryIndex[0];

            try {
                //Creates a new file reader and buffered reader
                FileReader file_to_read3 = new FileReader(path);
                BufferedReader br3 = new BufferedReader(file_to_read3);

                //Finds the index value
                int intIndex = Integer.parseInt(strIndex)/16;

                //Creates a counter to count line numbers
                int counter = 0;

                while((br3.readLine()) != null) {
                    //Increases counter value by 1
                    counter ++;
                    if(intIndex == 0)
                    {
                        try {
                            //Reads the set and subject for the
                            String chosenDeck2 = br3.readLine();

                            //Splits the subject from the set
                            String [] aryDeck = chosenDeck2.split(",");
                            chosenDeck = aryDeck[0];

                            //Closes the buffered reader and file reader
                            br3.close();
                            file_to_read3.close();

                        } catch (Exception e) {
                            JOptionPane.showMessageDialog(null, e);
                        }

                    } else if ( counter == intIndex) {
                        String chosenDeck2 = br3.readLine();

                        String [] aryDeck = chosenDeck2.split(",");
                        chosenDeck = aryDeck[0];

                        br3.close();
                        file_to_read3.close();
                    }

                }
            }
            catch (Exception e) {
                JOptionPane.showMessageDialog(null, e);
            }
            //Opens the new words frame
            frmWords s = new frmWords(deckName, newXPoint, newYPoint, chosenDeck);
            s.setVisible(true);
        });
    }

    } catch (Exception e ) {
        JOptionPane.showMessageDialog(null, e);

    }

What I am finding is that when I am deleting the br1.close() the stream closed error stops, but I can find any reason why? Nothing is using that reader, that I can see. And when I do delete it I get and error saying that the test files are being used by other processes, which I can only presume is br1.

I know this may seem confusing to look at, probably because it is sloppy code, but I would really appreciate some help. I am a high school student.

Thanks :)

Body:
When you construct nested Readers as you do, for example,

    FileReader file_to_read = new FileReader(path);
    BufferedReader br1 = new BufferedReader(file_to_read);

, closing the outer one automatically closes the inner one, too.  You do not need to close the inner one yourself, and if you try to do so after closing the outer one, as you do, you will find that it is already closed.

The best solution is to close only the outer one (as opposed to your workaround of closing only the inner one).  You probably don't even need to retain a reference to the inner one -- a more typical idiom would go something like this:

    BufferedReader br1 = new BufferedReader(new FileReader(path));

    try {
        // ... manipulate br1 ...
    } finally {
        br1.close();
        // no need to explicitly close the inner FileReader
    }

You could write that in try-with-resources form if that suits your fancy.

Similar applies to nested Writers, InputStreams, and OutputStreams, too.


问:
Public Properties instead of PRIVATE fields
First just to clarify and avoid unnecessary duplicate tagging, this question is not a duplicate of this one, neither a duplicate of this other one or others I have already searched. Why? they all talk about public fields or private fields WITH the classical C#'s "properties".

My question is why should I write something like this (Public Properties)

```<code>class myClass{

public int AValue{get; set;}
}
</code>```

when I can write instead (Private fields  without any properties involved) (Just classic old C++ style way of writing things)

```<code>class myClass{
private int aValue;
public int getValue{ return aValue;}
public void setValue(int value){ aValue=value;}
</code>```

I am scratching my head, reading many many resources, answers and questions, and no one of them answer this question. They all talk about the advantages over public fiels (which I am not asking about) or about the advantages of the new automatic properties over the old ones (which I am not asking either).

I guess my question is why C# does not use the same way of writing that has worked well in Java or C++ that works well. I don't see any advantage. I would very much appreciate someone teaches me the advantage because afaik is not written anywhere else. (not even in my C# books)

答:
C#'s getter and setter is syntactic sugar, which remove noisy method names (SetValue or GetValue vs just Value) and increase readability of the code.

Readability is much better in consuming code

```<code>// Without properties
var myClass = new MyClass();
myClass.SetAValue(aValue);
myClass.SetBValue(bValue);

//And with properties
var myClass = new MyClass
{
    AValue = aValue,
    BValue = bValue
}
</code>```

Because it is only syntactic sugar - every developer/team are free to not use
it.

Some teams have "rules" that properties should be used only for getting/setting values without any "heavy" logic in getters/setters. And methods should be used for setting or getting values which executes some "heavy" operations.

Body:
First just to clarify and avoid unnecessary duplicate tagging, this question is not a duplicate of this one, neither a duplicate of this other one or others I have already searched. Why? they all talk about public fields or private fields WITH the classical C#'s "properties".

My question is why should I write something like this (Public Properties)

class myClass{

public int AValue{get; set;}
}

when I can write instead (Private fields  without any properties involved) (Just classic old C++ style way of writing things)

class myClass{
private int aValue;
public int getValue{ return aValue;}
public void setValue(int value){ aValue=value;}

I am scratching my head, reading many many resources, answers and questions, and no one of them answer this question. They all talk about the advantages over public fiels (which I am not asking about) or about the advantages of the new automatic properties over the old ones (which I am not asking either).

I guess my question is why C# does not use the same way of writing that has worked well in Java or C++ that works well. I don't see any advantage. I would very much appreciate someone teaches me the advantage because afaik is not written anywhere else. (not even in my C# books)

Body:
C#'s getter and setter is syntactic sugar, which remove noisy method names (SetValue or GetValue vs just Value) and increase readability of the code.

Readability is much better in consuming code

// Without properties
var myClass = new MyClass();
myClass.SetAValue(aValue);
myClass.SetBValue(bValue);

//And with properties
var myClass = new MyClass
{
    AValue = aValue,
    BValue = bValue
}

Because it is only syntactic sugar - every developer/team are free to not use
it.

Some teams have "rules" that properties should be used only for getting/setting values without any "heavy" logic in getters/setters. And methods should be used for setting or getting values which executes some "heavy" operations.


问:
has the wrong number of column. should be 2
I read all topics about this error, but don't understand how i can fix it in my code. Help me please.

```<code>org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [ru/itpark/config/PersistenceConfig.class]: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: A Foreign key refering ru.itpark.model.UserAnswers from ru.itpark.model.TheoreticTask has the wrong number of column. should be 2
</code>```

User class

```<code>@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name="users")
public class User {

    @Id
    //@EmbeddedId
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    @Column
    private String userName;
    @Column
    private String password;
    @Column
    private String name;

    @OneToMany
    @JoinTable(name = "user_answers",
            joinColumns =
            @JoinColumn(name = "user_id"),
            inverseJoinColumns =
            @JoinColumn(name = "id"))
    private List<UserAnswers> userAnswers;

}
</code>```

PracticTask class

```<code>@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name="practic_tasks")
public class PracticTask {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    @Column( name = "theme_id")
    private int themeId;

    @Column
    private String question;

    @Column
    private String answer;

    @OneToMany
    @JoinTable(name = "user_answers",
            joinColumns =
            @JoinColumn(name = "practic_task_last"),
            inverseJoinColumns =
            @JoinColumn(name = "id"))
    private List<UserAnswers> userAnswers;

}
</code>```

Theme class

```<code>    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    @Entity
    @Table(name="themes")
    public class Theme {
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        int id;

        @Column
        private String name;

        @OneToMany
        @JoinTable(name = "practic_tasks",
                joinColumns =
                @JoinColumn(name = "theme_id"),
                inverseJoinColumns =
                @JoinColumn(name = "id"))
        private List<PracticTask> practicTaskList;

        @OneToMany
        @JoinTable(name = "theoretic_tasks",
                joinColumns =
                @JoinColumn(name = "theme_id"),
                inverseJoinColumns =
                @JoinColumn(name = "id"))
        private List<TheoreticTask> theoreticTaskList;

        @OneToMany
        @JoinTable(name = "user_answers",
                joinColumns =
                @JoinColumn(name = "theme_id"),
                inverseJoinColumns =
                @JoinColumn(name = "id"))
        private List<UserAnswers> userAnswers;

    }
</code>```

TheoreticTask class

```<code>@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name="theoretic_tasks")
public class TheoreticTask {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    @Column( name = "theme_id")
    private int themeId;

    @Column
    private String question;

    @Column( name = "first_answer")
    private String firstAnswer;

    @Column( name = "second_answer")
    private String secondAnswer;

    @Column( name = "third_answer")
    private String thirdAnswer;

    @OneToMany
    @JoinTable(name = "user_answers",
            joinColumns =
            @JoinColumn(name = "theoretic_task_last"),
            inverseJoinColumns =
            @JoinColumn(name = "id"))
    private List<UserAnswers> userAnswers;
}
</code>```

UserAnswer class

```<code>@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode
@Table(name = "user_answers")
public class UserAnswers implements Serializable {
    @EmbeddedId
    private UserAnswersPK id;

    @Column(name = "theoretic_task_last")
    private int theoreticTaskLast;

    @Column(name = "practic_task_last")
    private int practicTaskLast;

    @Column(name = "practic_answer_count")
    private int practicAnswerCount;

    @Column(name = "theoretic_answer_count")
    private int theoreticAnswerCount;
}
</code>```

UserAnswerPK class

```<code>@Embeddable
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode
public class UserAnswersPK implements Serializable {
    @Column(name="user_id")
    protected int user_id;
    @Column(name="theme_id")
    protected int theme_id;
}
</code>```

So i read that i need to make JoinColumns but didn't understand.

This is picture of db dependencies

答:
Your mapping has many problems. I think it will be good if you read before doing such relations unless you are learning.

It is always better to define the join mapping on the ManytoOne side rather than the OnetoMany side and I don't think you need a join table based on your database relationship diagram and your join table names.

I will show you mapping relation between UserAnswers and TheoreticTask. You need to change this similarly in all your (1..n) relations.

```<code>@Entity
@Table(name="theoretic_tasks")
public class TheoreticTask {
    // Other Columns and Relations

    @OneToMany(mappedBy="theoreticTask")
    private List<UserAnswers> userAnswers;
}

@Entity
@Table(name = "user_answers")
public class UserAnswers implements Serializable {
    // Other Columns and Relations

    @ManyToOne
    @JoinColumn(name = "theoretic_task_last")
    private TheoreticTask theoreticTask;
}
</code>```

Body:
I read all topics about this error, but don't understand how i can fix it in my code. Help me please.

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [ru/itpark/config/PersistenceConfig.class]: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: A Foreign key refering ru.itpark.model.UserAnswers from ru.itpark.model.TheoreticTask has the wrong number of column. should be 2

User class

@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name="users")
public class User {

    @Id
    //@EmbeddedId
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    @Column
    private String userName;
    @Column
    private String password;
    @Column
    private String name;

    @OneToMany
    @JoinTable(name = "user_answers",
            joinColumns =
            @JoinColumn(name = "user_id"),
            inverseJoinColumns =
            @JoinColumn(name = "id"))
    private List<UserAnswers> userAnswers;

}

PracticTask class

@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name="practic_tasks")
public class PracticTask {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    @Column( name = "theme_id")
    private int themeId;

    @Column
    private String question;

    @Column
    private String answer;

    @OneToMany
    @JoinTable(name = "user_answers",
            joinColumns =
            @JoinColumn(name = "practic_task_last"),
            inverseJoinColumns =
            @JoinColumn(name = "id"))
    private List<UserAnswers> userAnswers;

}

Theme class

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    @Entity
    @Table(name="themes")
    public class Theme {
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        int id;

        @Column
        private String name;

        @OneToMany
        @JoinTable(name = "practic_tasks",
                joinColumns =
                @JoinColumn(name = "theme_id"),
                inverseJoinColumns =
                @JoinColumn(name = "id"))
        private List<PracticTask> practicTaskList;

        @OneToMany
        @JoinTable(name = "theoretic_tasks",
                joinColumns =
                @JoinColumn(name = "theme_id"),
                inverseJoinColumns =
                @JoinColumn(name = "id"))
        private List<TheoreticTask> theoreticTaskList;

        @OneToMany
        @JoinTable(name = "user_answers",
                joinColumns =
                @JoinColumn(name = "theme_id"),
                inverseJoinColumns =
                @JoinColumn(name = "id"))
        private List<UserAnswers> userAnswers;

    }

TheoreticTask class

@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name="theoretic_tasks")
public class TheoreticTask {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    @Column( name = "theme_id")
    private int themeId;

    @Column
    private String question;

    @Column( name = "first_answer")
    private String firstAnswer;

    @Column( name = "second_answer")
    private String secondAnswer;

    @Column( name = "third_answer")
    private String thirdAnswer;

    @OneToMany
    @JoinTable(name = "user_answers",
            joinColumns =
            @JoinColumn(name = "theoretic_task_last"),
            inverseJoinColumns =
            @JoinColumn(name = "id"))
    private List<UserAnswers> userAnswers;
}

UserAnswer class

@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode
@Table(name = "user_answers")
public class UserAnswers implements Serializable {
    @EmbeddedId
    private UserAnswersPK id;

    @Column(name = "theoretic_task_last")
    private int theoreticTaskLast;

    @Column(name = "practic_task_last")
    private int practicTaskLast;

    @Column(name = "practic_answer_count")
    private int practicAnswerCount;

    @Column(name = "theoretic_answer_count")
    private int theoreticAnswerCount;
}

UserAnswerPK class

@Embeddable
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode
public class UserAnswersPK implements Serializable {
    @Column(name="user_id")
    protected int user_id;
    @Column(name="theme_id")
    protected int theme_id;
}

So i read that i need to make JoinColumns but didn't understand.

This is picture of db dependencies

Body:
Your mapping has many problems. I think it will be good if you read before doing such relations unless you are learning.

It is always better to define the join mapping on the ManytoOne side rather than the OnetoMany side and I don't think you need a join table based on your database relationship diagram and your join table names.

I will show you mapping relation between UserAnswers and TheoreticTask. You need to change this similarly in all your (1..n) relations.

@Entity
@Table(name="theoretic_tasks")
public class TheoreticTask {
    // Other Columns and Relations

    @OneToMany(mappedBy="theoreticTask")
    private List<UserAnswers> userAnswers;
}

@Entity
@Table(name = "user_answers")
public class UserAnswers implements Serializable {
    // Other Columns and Relations

    @ManyToOne
    @JoinColumn(name = "theoretic_task_last")
    private TheoreticTask theoreticTask;
}


问:
How to save a Array with (Multiple Types) in NSUserDefaults
This is pretty simple but can't seem to find the correct information to solve saving an array like this in User Defaults.

It says it's not a property that NSUser Defaults Excepts.

Code:

```<code>    var notificationList: [(type: String,imageName: String, text: String, date: String, seen: Bool)] = [(type: "Default",imageName: "ClearPartioned", text: "", date: "", seen: true)]

    if (UserDefaults.standard.object(forKey: "notificationList")) == nil { // first time launching

        print("making notification list")

        UserDefaults.standard.set(notificationList, forKey: "notificationList")
        UserDefaults.standard.synchronize()

        print("\(notificationList)")

    } else {

        print("getting saved array")

        notificationList = (UserDefaults.standard.object(forKey: "notificationList") as! [(type: String, imageName: String, text: String, date: String, seen: Bool)])

        print("\(notificationList)")
    }
</code>```

Update:

This is closer but gives error found in this question here. These are the closet answers I have been able to find and there either out dated or crash the system.

Code:

```<code>    if (UserDefaults.standard.object(forKey: "notificationList")) == nil { // first time launching

        print("making notification list")

        let encodedData = NSKeyedArchiver.archivedData(withRootObject: notificationList)
        UserDefaults.standard.set(encodedData, forKey: "notificationList")
        UserDefaults.standard.synchronize()

    } else {

        print("getting saved array")

        notificationList = (UserDefaults.standard.object(forKey: "notificationList") as! [(type: String, imageName: String, text: String, date: String, seen: Bool)])

        print("\(notificationList)")
    }
</code>```

Update 2: This is best answer implementation From Dhiru

Code:

```<code>  if (UserDefaults.standard.object(forKey: "notificationList")) == nil { // first time launching
        print("making notification list")

        let notificationData = NSKeyedArchiver.archivedData(withRootObject: notificationList)
        UserDefaults.standard.set(notificationData, forKey: "notificationList")
        UserDefaults.standard.synchronize()

    } else {

        print("getting saved array")

        let decodedData  = UserDefaults.standard.object(forKey: "notificationList") as! Data
        let notificationList = NSKeyedUnarchiver.unarchiveObject(with: decodedData) as AnyObject

        print("\(notificationList)")
    }
</code>```

Its giving me an error that crashes system

```<code>   *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[_SwiftValue encodeWithCoder:]: unrecognized selector sent to instance 0x1c011f380'
   libc++abi.dylib: terminating with uncaught exception of type NSException
</code>```

Im sure this code would fix it but this is horribly implemented with multiple errors below because I have no clue how to use this code.

Code:

```<code>   func (coder aDecoder: NSCoder) {
        if let notificationList = aDecoder.decodeObjectForKey("notificationList") {
            self.notificationList = notificationList
        }
    }

    func encodeWithCoder(aCoder: NSCoder) {
        if let notificationList = notificationList {
            aCoder.encodeObject(notificationList, forKey: "notificationList")
        }
    }
</code>```

答:
This is how I actually save a Custom Object created in the app in Swift 4.

First, we create 3 protocols for our purpose of saving the custom object in UserDefaults. The logic behind is to convert the Custom Object into a normalized Dictionary/Array form.

This can be applied to any kind of Object which you have created.

The 3 protocols are:

Decoder (Used to decode the dictionary into custom object)

Encoder (Used to encode the custom object into dictionary)

UserDefaultsProtocol (Used to save, delete, update & retrieve the custom object from UserDefault)

Decoder Protocol

```<code>protocol Decoder {
    associatedtype T
    static func decode(dictionary: [String: Any]) -> T
}
</code>```

Encoder Protocol

```<code>protocol Encoder {
    func encode() -> [String: Any]
}
</code>```

UserDefaultsProtocol

```<code>protocol UserDefaultsDelegate: class {
    associatedtype T
    func saveToUserDefaults()
    static func removeFromUserDefaults()
    static func retrieveFromUserDefaults() -> T?
}
</code>```

As per your question, NotificationList Object would look like this

```<code>class NotificationList {
    var type: String = ""
    var imageName: String = ""
    var text: String = ""
    var date: String = ""
    var seen: Bool = false
}
</code>```

Now, you need to confirm all the 3 mentioned protocols to NotificationList. (Swift Best Practice: Use of Extensions & Protocols)

```<code>class NotificationList {
    private struct Constants {
        static let RootKey = "notification_list"
        static let TypeKey = "type"
        static let ImageNameKey = "image_name"
        static let TextKey = "text"
        static let DateKey = "date"
        static let SeenKey = "seen"
    }

    var type: String = ""
    var imageName: String = ""
    var text: String = ""
    var date: String = ""
    var seen: Bool = false

    typealias T = NotificationList
}

extension NotificationList: Encoder {
    func encode() -> [String : Any] {
        return [
            Constants.TypeKey: type,
            Constants.ImageNameKey: imageName,
            Constants.TextKey: text,
            Constants.DateKey: date,
            Constants.SeenKey: seen
        ]
    }
}

extension NotificationList: Decoder {
    static func decode(dictionary: [String: Any]) -> NotificationList {
        let type = dictionary[Constants.TypeKey] as! String
        let imageName = dictionary[Constants.ImageNameKey] as! String
        let text = dictionary[Constants.TextKey] as! String
        let date = dictionary[Constants.DateKey] as! String
        let seen = dictionary[Constants.SeenKey] as! Bool

        let notificationList = NotificationList()
        notificationList.type = type
        notificationList.imageName = imageName
        notificationList.text = text
        notificationList.date = date
        notificationList.seen = seen
        return notificationList
    }
}

extension NotificationList: UserDefaultsDelegate {

    func saveToUserDefaults() {
        UserDefaults.standard.setValue(encode(), forKey: Constants.RootKey)
    }

    static func retrieveFromUserDefaults() -> NotificationList? {
        guard let encodedNotificationList = UserDefaults.standard.dictionary(forKey: Constants.RootKey) else {
            return nil
        }
        return NotificationList.decode(dictionary: encodedNotificationList)
    }

    static func removeFromUserDefaults() {
        UserDefaults.standard.removeObject(forKey: Constants.RootKey)
    }
}
</code>```

How to save NotificationList to UserDefaults?

```<code>var notificationList = NotificationList()
notificationList.type = "Default"
notificationList.imageName = "ClearPartioned"
notificationList.text = ""
notificationList.date = ""
notificationList.seen = true
</code>```

Save to UserDefaults

```<code>notificationList.saveToUserDefaults()
</code>```

Retrieve from UserDefaults

```<code>if let notificationList = NotificationList.retrieveFromUserDefaults() {
      // You will get the instance of notification list saved in UserDefaults
}
</code>```

HOW TO SAVE ARRAY OF NOTIFICATION LIST?

Say notificationLists contains the array of notificationList objects.

```<code>var notificationListsArray = [[String: Any]]()

notificationLists.forEach {
     notificationListsArray.append($0.encode())
}
</code>```

Save that array of dictionary to UserDefaults

```<code>UserDefaults.standard.setValue(notificationListsArray, forValue: "notificationLists")
</code>```

Body:
This is pretty simple but can't seem to find the correct information to solve saving an array like this in User Defaults.

It says it's not a property that NSUser Defaults Excepts.

Code:

    var notificationList: [(type: String,imageName: String, text: String, date: String, seen: Bool)] = [(type: "Default",imageName: "ClearPartioned", text: "", date: "", seen: true)]

    if (UserDefaults.standard.object(forKey: "notificationList")) == nil { // first time launching

        print("making notification list")

        UserDefaults.standard.set(notificationList, forKey: "notificationList")
        UserDefaults.standard.synchronize()

        print("\(notificationList)")

    } else {

        print("getting saved array")

        notificationList = (UserDefaults.standard.object(forKey: "notificationList") as! [(type: String, imageName: String, text: String, date: String, seen: Bool)])

        print("\(notificationList)")
    }

Update:

This is closer but gives error found in this question here. These are the closet answers I have been able to find and there either out dated or crash the system.

Code:

    if (UserDefaults.standard.object(forKey: "notificationList")) == nil { // first time launching

        print("making notification list")

        let encodedData = NSKeyedArchiver.archivedData(withRootObject: notificationList)
        UserDefaults.standard.set(encodedData, forKey: "notificationList")
        UserDefaults.standard.synchronize()

    } else {

        print("getting saved array")

        notificationList = (UserDefaults.standard.object(forKey: "notificationList") as! [(type: String, imageName: String, text: String, date: String, seen: Bool)])

        print("\(notificationList)")
    }

Update 2: This is best answer implementation From Dhiru

Code:

  if (UserDefaults.standard.object(forKey: "notificationList")) == nil { // first time launching
        print("making notification list")

        let notificationData = NSKeyedArchiver.archivedData(withRootObject: notificationList)
        UserDefaults.standard.set(notificationData, forKey: "notificationList")
        UserDefaults.standard.synchronize()

    } else {

        print("getting saved array")

        let decodedData  = UserDefaults.standard.object(forKey: "notificationList") as! Data
        let notificationList = NSKeyedUnarchiver.unarchiveObject(with: decodedData) as AnyObject

        print("\(notificationList)")
    }

Its giving me an error that crashes system

   *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[_SwiftValue encodeWithCoder:]: unrecognized selector sent to instance 0x1c011f380'
   libc++abi.dylib: terminating with uncaught exception of type NSException

Im sure this code would fix it but this is horribly implemented with multiple errors below because I have no clue how to use this code.

Code:

   func (coder aDecoder: NSCoder) {
        if let notificationList = aDecoder.decodeObjectForKey("notificationList") {
            self.notificationList = notificationList
        }
    }

    func encodeWithCoder(aCoder: NSCoder) {
        if let notificationList = notificationList {
            aCoder.encodeObject(notificationList, forKey: "notificationList")
        }
    }

Body:
This is how I actually save a Custom Object created in the app in Swift 4.

First, we create 3 protocols for our purpose of saving the custom object in UserDefaults. The logic behind is to convert the Custom Object into a normalized Dictionary/Array form.

This can be applied to any kind of Object which you have created.

The 3 protocols are:

Decoder (Used to decode the dictionary into custom object)

Encoder (Used to encode the custom object into dictionary)

UserDefaultsProtocol (Used to save, delete, update & retrieve the custom object from UserDefault)

Decoder Protocol

protocol Decoder {
    associatedtype T
    static func decode(dictionary: [String: Any]) -> T
}

Encoder Protocol

protocol Encoder {
    func encode() -> [String: Any]
}

UserDefaultsProtocol

protocol UserDefaultsDelegate: class {
    associatedtype T
    func saveToUserDefaults()
    static func removeFromUserDefaults()
    static func retrieveFromUserDefaults() -> T?
}

As per your question, NotificationList Object would look like this

class NotificationList {
    var type: String = ""
    var imageName: String = ""
    var text: String = ""
    var date: String = ""
    var seen: Bool = false
}

Now, you need to confirm all the 3 mentioned protocols to NotificationList. (Swift Best Practice: Use of Extensions & Protocols)

class NotificationList {
    private struct Constants {
        static let RootKey = "notification_list"
        static let TypeKey = "type"
        static let ImageNameKey = "image_name"
        static let TextKey = "text"
        static let DateKey = "date"
        static let SeenKey = "seen"
    }

    var type: String = ""
    var imageName: String = ""
    var text: String = ""
    var date: String = ""
    var seen: Bool = false

    typealias T = NotificationList
}

extension NotificationList: Encoder {
    func encode() -> [String : Any] {
        return [
            Constants.TypeKey: type,
            Constants.ImageNameKey: imageName,
            Constants.TextKey: text,
            Constants.DateKey: date,
            Constants.SeenKey: seen
        ]
    }
}

extension NotificationList: Decoder {
    static func decode(dictionary: [String: Any]) -> NotificationList {
        let type = dictionary[Constants.TypeKey] as! String
        let imageName = dictionary[Constants.ImageNameKey] as! String
        let text = dictionary[Constants.TextKey] as! String
        let date = dictionary[Constants.DateKey] as! String
        let seen = dictionary[Constants.SeenKey] as! Bool

        let notificationList = NotificationList()
        notificationList.type = type
        notificationList.imageName = imageName
        notificationList.text = text
        notificationList.date = date
        notificationList.seen = seen
        return notificationList
    }
}

extension NotificationList: UserDefaultsDelegate {

    func saveToUserDefaults() {
        UserDefaults.standard.setValue(encode(), forKey: Constants.RootKey)
    }

    static func retrieveFromUserDefaults() -> NotificationList? {
        guard let encodedNotificationList = UserDefaults.standard.dictionary(forKey: Constants.RootKey) else {
            return nil
        }
        return NotificationList.decode(dictionary: encodedNotificationList)
    }

    static func removeFromUserDefaults() {
        UserDefaults.standard.removeObject(forKey: Constants.RootKey)
    }
}

How to save NotificationList to UserDefaults?

var notificationList = NotificationList()
notificationList.type = "Default"
notificationList.imageName = "ClearPartioned"
notificationList.text = ""
notificationList.date = ""
notificationList.seen = true

Save to UserDefaults

notificationList.saveToUserDefaults()

Retrieve from UserDefaults

if let notificationList = NotificationList.retrieveFromUserDefaults() {
      // You will get the instance of notification list saved in UserDefaults
}

HOW TO SAVE ARRAY OF NOTIFICATION LIST?

Say notificationLists contains the array of notificationList objects.

var notificationListsArray = [[String: Any]]()

notificationLists.forEach {
     notificationListsArray.append($0.encode())
}

Save that array of dictionary to UserDefaults

UserDefaults.standard.setValue(notificationListsArray, forValue: "notificationLists")


问:
How to close modal after form submit event in Angular2?
I want to close modal after form submit event is finished. I've done following things:

<form [formGroup]="alertForm" novalidate (ngSubmit)="save(alertForm.value, alertForm.valid)">

          Available Recipient
          <textarea class="form-control validate" id="recipientLogin" required formControlName="recipientLogin"> </textarea>

          <select class="form-control" id="alert_level" formControlName="alert_level">
            <option  value="0" selected> Emergency </option>
            <option value="1">Major</option>
            <option value="2">Minor</option>
            <option value="3">Information</option>
          </select>

          Subject
          <input type="text" class="form-control validate" id="subject" required formControlName="subject">

          Message
          <textarea class="form-control validate" id="message" required formControlName="message"> </textarea>

          <input type="file" class="form-control" id="media1" />
          <input type="file" class="form-control" id="media2" />
          <input type="file" class="form-control" id="media3" />

          <button type="submit" class="btn btn-default input-field">Send</button>

          <button type="submit" data-dismiss="modal" class="btn btn-default input-field">Close</button>

  </form>```

This triggers save() on form submit but does not close the modal for that I tried data-dismiss="modal" on save button, which block the save() call and close the modal.
I want to complete save() first after that close modal.

答:
Alternatively, on success of your save call you can close the modal via the 'Close' button.

<button #btnId type="submit" />

Which your component can close via this.btnId.click()

Body:
I want to close modal after form submit event is finished. I've done following things:

<form [formGroup]="alertForm" novalidate (ngSubmit)="save(alertForm.value, alertForm.valid)">

          Available Recipient
          <textarea class="form-control validate" id="recipientLogin" required formControlName="recipientLogin"> </textarea>

          <select class="form-control" id="alert_level" formControlName="alert_level">
            <option  value="0" selected> Emergency </option>
            <option value="1">Major</option>
            <option value="2">Minor</option>
            <option value="3">Information</option>
          </select>

          Subject
          <input type="text" class="form-control validate" id="subject" required formControlName="subject">

          Message
          <textarea class="form-control validate" id="message" required formControlName="message"> </textarea>

          <input type="file" class="form-control" id="media1" />
          <input type="file" class="form-control" id="media2" />
          <input type="file" class="form-control" id="media3" />

          <button type="submit" class="btn btn-default input-field">Send</button>

          <button type="submit" data-dismiss="modal" class="btn btn-default input-field">Close</button>

  </form>

This triggers save() on form submit but does not close the modal for that I tried data-dismiss="modal" on save button, which block the save() call and close the modal.
I want to complete save() first after that close modal.


问:
In-app purchase was successful, however, it did not run my code.Why?
I am new to in-app purchase system. I just watched some tutorials, then implemented in-app purchase. However, when my in-app purchase was successful, it did not run my code. Does it have to run the following code?:</p>

```<code>@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == 1001) {
        String purchaseData = data.getStringExtra("INAPP_PURCHASE_DATA");

        if (resultCode == RESULT_OK) {
            try {
                JSONObject jo = new JSONObject(purchaseData);
                String sku = jo.getString(inappid);
                Toast.makeText(
                        MainActivity.this,
                        "You have bought the " + sku
                                + ". Excellent choice,adventurer!",
                        Toast.LENGTH_LONG).show();
                writeInApp("1");
                playGroundMain.bonus_pop_up(R.drawable.rich_big, "\"VIP Монстр\"");
                playGroundMain.reWriteBonus("1", 6);

            } catch (JSONException e) {
                System.out.println("Failed to parse purchase data.");
                e.printStackTrace();
            }
        }
    }
}
</code>```

答:
If you are trying to do a non-consumable inapp purchase the code is fine.

When doing test purchases sometimes the onActivityResult() does not gets called. In a real purchase this may not happen.

To handle the purchase in that case you have to check result code == user already owns this item //resultCode 7, so that the user will not have to pay again in a situation like this.

Body:
I am new to in-app purchase system. I just watched some tutorials, then implemented in-app purchase. However, when my in-app purchase was successful, it did not run my code. Does it have to run the following code?:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == 1001) {
        String purchaseData = data.getStringExtra("INAPP_PURCHASE_DATA");

        if (resultCode == RESULT_OK) {
            try {
                JSONObject jo = new JSONObject(purchaseData);
                String sku = jo.getString(inappid);
                Toast.makeText(
                        MainActivity.this,
                        "You have bought the " + sku
                                + ". Excellent choice,adventurer!",
                        Toast.LENGTH_LONG).show();
                writeInApp("1");
                playGroundMain.bonus_pop_up(R.drawable.rich_big, "\"VIP Монстр\"");
                playGroundMain.reWriteBonus("1", 6);

            } catch (JSONException e) {
                System.out.println("Failed to parse purchase data.");
                e.printStackTrace();
            }
        }
    }
}


问:
Can HTML5 subtitles be positioned with css?
I am using a custom HTML5 app for streaming videos on a local network, and now I am adding subtitles support.

I have around 500 .vtt subtitles converted from .srt. After I converted them from .srt, I noticed they display right at the bottom of the screen, and I'd like them to have a little margin-bottom.

I am able to style the subtitles with css pseudo element ::cue, but only for font size, color, background. Doesn't seem to support any margin, padding or positioning rules.

Before coding a script to modify all the .vtt files to add line:XX% to the cues (that's the only way I found so far to move them), I was wondering if there's a way to position the subtitles without having to modify all the .vtt files.

If I disable my custom controls and tried the default controls instead. When a subtitle is displayed and I put the mouse over the video to show the controls, the subtitle do move up, and when the controls get auto hidden after a few seconds that line of subtitles stay at that place. But the next line move back down. This is the reason I am wondering if they can be moved without editing the .vtt files, since showing the controls move them up, maybe there's a way I can do it programmatically.

So the question is, can .vtt subtitles be positioned using CSS or any other method other than modifying the .vtt files?

This is the basic code I am using for testing:

```<code><video controls autoplay>
    <source src="http://192.168.0.1/video.mp4" type="video/mp4" />
    <track src="http://192.168.0.1/subtitles.vtt" kind="subtitles" srclang="en" label="English" default />
</video>
<style>
    video::cue {
        font-size:100%;
        color:white;
    }
</style>
</code>```

答: You can give the line-height to the ::cue, but the problem with it is if subtitle goes into multiple lines then the gap between the lines increases.

Body:
I am using a custom HTML5 app for streaming videos on a local network, and now I am adding subtitles support.

I have around 500 .vtt subtitles converted from .srt. After I converted them from .srt, I noticed they display right at the bottom of the screen, and I'd like them to have a little margin-bottom.

I am able to style the subtitles with css pseudo element ::cue, but only for font size, color, background. Doesn't seem to support any margin, padding or positioning rules.

Before coding a script to modify all the .vtt files to add line:XX% to the cues (that's the only way I found so far to move them), I was wondering if there's a way to position the subtitles without having to modify all the .vtt files.

If I disable my custom controls and tried the default controls instead. When a subtitle is displayed and I put the mouse over the video to show the controls, the subtitle do move up, and when the controls get auto hidden after a few seconds that line of subtitles stay at that place. But the next line move back down. This is the reason I am wondering if they can be moved without editing the .vtt files, since showing the controls move them up, maybe there's a way I can do it programmatically.

So the question is, can .vtt subtitles be positioned using CSS or any other method other than modifying the .vtt files?

This is the basic code I am using for testing:

<video controls autoplay>
    <source src="http://192.168.0.1/video.mp4" type="video/mp4" />
    <track src="http://192.168.0.1/subtitles.vtt" kind="subtitles" srclang="en" label="English" default />
</video>


问:
Feature are incompatible with given information in evaluate() using tf.contrib.learn.SVM
Code is as follows:

```<code>def svm_tf(file):
    X,Y,training_size, index = process_data(file)
    def input_fn():
        return {
              'example_id': tf.constant(index[:training_size]),
              'multi_dim_feature': tf.constant(X[:training_size].values.tolist()),
        }, tf.constant(Y[:training_size])

    feature_columns = [tf.contrib.layers.real_valued_column("multi_dim_feature",dimension=4)]
    svm = learn.SVM(feature_columns=feature_columns,
                    l1_regularization=0.0,
                    l2_regularization=1.0,
                    example_id_column='example_id')
    svm.fit(input_fn=input_fn,steps=50)

    def test_input():
        return{
        'example_id': tf.constant(index[training_size:]),
        'features': tf.constant(X[training_size:].values.tolist())
        }, tf.constant(Y[training_size:])

    accuracy = svm.evaluate(input_fn=test_input,steps=1)['accuracy']
    print('\nAccuracy :{0:f}\n'.format(accuracy))
</code>```

However, when I run the program, it runs into error as follows:

```<code>Traceback (most recent call last):
  File "subscriber.py", line 84, in <module>
    svm_tf(file)
  File "subscriber.py", line 75, in svm_tf
    accuracy = svm.evaluate(input_fn=test_input,steps=1)['accuracy']
  File "/home/annie/.local/lib/python2.7/site-packages/tensorflow/python/util/deprecation.py", line 289, in new_func
    return func(*args, **kwargs)
  File "/home/annie/.local/lib/python2.7/site-packages/tensorflow/contrib/learn/python/learn/estimators/estimator.py", line 543, in evaluate
    log_progress=log_progress)
  File "/home/annie/.local/lib/python2.7/site-packages/tensorflow/contrib/learn/python/learn/estimators/estimator.py", line 827, in _evaluate_model
    self._check_inputs(features, labels)
  File "/home/annie/.local/lib/python2.7/site-packages/tensorflow/contrib/learn/python/learn/estimators/estimator.py", line 757, in _check_inputs
    (str(features), str(self._features_info)))
ValueError: Features are incompatible with given information. Given features: {'example_id': <tf.Tensor 'Const:0' shape=(1000,) dtype=string>, 'features': <tf.Tensor 'Const_1:0' shape=(1000, 4) dtype=float32>}, required signatures: {'example_id': TensorSignature(dtype=tf.string, shape=TensorShape([Dimension(4000)]), is_sparse=False), 'multi_dim_feature': TensorSignature(dtype=tf.float32, shape=TensorShape([Dimension(4000), Dimension(4)]), is_sparse=False)}.
</code>```

I cannot find any relevant questions online and therefore is very lost
Please help! Thanks in advance

答: In your test_input function, replace features with multi_dim_features.

Body:
Code is as follows:

def svm_tf(file):
    X,Y,training_size, index = process_data(file)
    def input_fn():
        return {
              'example_id': tf.constant(index[:training_size]),
              'multi_dim_feature': tf.constant(X[:training_size].values.tolist()),
        }, tf.constant(Y[:training_size])

    feature_columns = [tf.contrib.layers.real_valued_column("multi_dim_feature",dimension=4)]
    svm = learn.SVM(feature_columns=feature_columns,
                    l1_regularization=0.0,
                    l2_regularization=1.0,
                    example_id_column='example_id')
    svm.fit(input_fn=input_fn,steps=50)

    def test_input():
        return{
        'example_id': tf.constant(index[training_size:]),
        'features': tf.constant(X[training_size:].values.tolist())
        }, tf.constant(Y[training_size:])

    accuracy = svm.evaluate(input_fn=test_input,steps=1)['accuracy']
    print('\nAccuracy :{0:f}\n'.format(accuracy))

However, when I run the program, it runs into error as follows:

Traceback (most recent call last):
  File "subscriber.py", line 84, in <module>
    svm_tf(file)
  File "subscriber.py", line 75, in svm_tf
    accuracy = svm.evaluate(input_fn=test_input,steps=1)['accuracy']
  File "/home/annie/.local/lib/python2.7/site-packages/tensorflow/python/util/deprecation.py", line 289, in new_func
    return func(*args, **kwargs)
  File "/home/annie/.local/lib/python2.7/site-packages/tensorflow/contrib/learn/python/learn/estimators/estimator.py", line 543, in evaluate
    log_progress=log_progress)
  File "/home/annie/.local/lib/python2.7/site-packages/tensorflow/contrib/learn/python/learn/estimators/estimator.py", line 827, in _evaluate_model
    self._check_inputs(features, labels)
  File "/home/annie/.local/lib/python2.7/site-packages/tensorflow/contrib/learn/python/learn/estimators/estimator.py", line 757, in _check_inputs
    (str(features), str(self._features_info)))
ValueError: Features are incompatible with given information. Given features: {'example_id': <tf.Tensor 'Const:0' shape=(1000,) dtype=string>, 'features': <tf.Tensor 'Const_1:0' shape=(1000, 4) dtype=float32>}, required signatures: {'example_id': TensorSignature(dtype=tf.string, shape=TensorShape([Dimension(4000)]), is_sparse=False), 'multi_dim_feature': TensorSignature(dtype=tf.float32, shape=TensorShape([Dimension(4000), Dimension(4)]), is_sparse=False)}.

I cannot find any relevant questions online and therefore is very lost
Please help! Thanks in advance


答:
Possible solution:

O(n^2) algorithm, where you do a linear search O(n) to check if the number is present in the array or not for all the n elements.

For each element (n elements):

O(n): Search

O(1): Insertion

O(n^2) algorithm, when you insert in sorted array.

For each element (n elements):

O(log n): Binary search

O(n): Shift and Insertion

Though there are advanced data structures (more in C++ STL) but you will need more than just a array. Because insertion is costly in array(Insertion in a specific position).

Other data structures which might help: BST (AVL-BST, Splay Trees, ... other balanced Trees structures).

In C++: sets is exactly what you want. sets is implemented as tree in STL.

Title: How to avoid duplicate element entry in C array?

Body: I want some logic which will insert numbers in the array, and at the same time it will check that the current number is already not present in the array. Please help me with the logic.


问:
jquery autocomplete - can it be set up so that the drop down shows up on focus?

Possible Duplicate:

  jQuery autocomplete UI- I'd like it to start the search onfocus without the user having to type anything

I noticed the question

jQuery autocomplete UI- I'd like it to start the search onfocus without the user having to type anything.

I have the same question and the I get the same problems with the solution.

Basically, I'm trying to force the jquery autocomplete UI to execute on focus and not require the user to press any key or enter any value.

thanks

答:
What version of jQueryUI are you using? According to the documentation for autocomplete, the way you referenced should work:

("search" method documentation)

...If no value argument is specified, the current input's value is used. Can be called with an empty string and minLength: 0 to display all items.

I've posted an example here that works for me in FF/Chrome: http://jsfiddle.net/andrewwhitaker/B38Hj/.  Let me know if you see any weird behavior.

```<code>$("input").focus(function() {
    $(this).autocomplete("search");
});
</code>```

The example uses jQuery UI 1.8.5 and jQuery 1.4.4.

Body:
What version of jQueryUI are you using? According to the documentation for autocomplete, the way you referenced should work:

("search" method documentation)

...If no value argument is specified, the current input's value is used. Can be called with an empty string and minLength: 0 to display all items.

I've posted an example here that works for me in FF/Chrome: http://jsfiddle.net/andrewwhitaker/B38Hj/.  Let me know if you see any weird behavior.

$("input").focus(function() {
    $(this).autocomplete("search");
});

The example uses jQuery UI 1.8.5 and jQuery 1.4.4.