问:
Delay mouse click 0.5 second
I am using this code to detect mouse position with pyhook in Windows. What I need is to detect mouse click and add delay before execution - scenario: I click with mouse but this click should be 0.5 second delayed (so click should be executed after 0.5 second). Is this possible somehow?</p>

```<code>import pyHook
import pythoncom

def onclick(event):
    print event.Position
    return True

hm = pyHook.HookManager()
hm.SubscribeMouseAllButtonsDown(onclick)
hm.HookMouse()
pythoncom.PumpMessages()
hm.UnhookMouse()
</code>```

答:
Like this :

```<code>import pyHook
import pythoncom
import time
import thread

class _HK :
    def __init__(self):
        self.ev = None
    def run(self,passarg):
        pythoncom.CoInitialize()
        while True :
            if self.ev != None :
                time.sleep(1)
                print self.ev.Position
                self.ev = None

HK = _HK()
s = thread.start_new_thread(HK.run,(None,))

def onclick(event):

    HK.ev = event

    return True

hm = pyHook.HookManager()
hm.SubscribeMouseAllButtonsDown(onclick)
hm.HookMouse()
pythoncom.PumpMessages()
hm.UnhookMouse()
</code>```

Other definitions are invalid if the application is focused on a
  process. Initially the process must be resolved by the system. It can
  then access internal and external components.
  pythoncom.CoInitialize() require for a function or additional process !

I hope it helps(TESTED).

Title: Delay mouse click 0.5 second

Body:
I am using this code to detect mouse position with pyhook in Windows. What I need is to detect mouse click and add delay before execution - scenario: I click with mouse but this click should be 0.5 second delayed (so click should be executed after 0.5 second). Is this possible somehow?

import pyHook
import pythoncom

def onclick(event):
    print event.Position
    return True

hm = pyHook.HookManager()
hm.SubscribeMouseAllButtonsDown(onclick)
hm.HookMouse()
pythoncom.PumpMessages()
hm.UnhookMouse()

Body:
Like this :

import pyHook
import pythoncom
import time
import thread

class _HK :
    def __init__(self):
        self.ev = None
    def run(self,passarg):
        pythoncom.CoInitialize()
        while True :
            if self.ev != None :
                time.sleep(1)
                print self.ev.Position
                self.ev = None

HK = _HK()
s = thread.start_new_thread(HK.run,(None,))

def onclick(event):

    HK.ev = event

    return True

hm = pyHook.HookManager()
hm.SubscribeMouseAllButtonsDown(onclick)
hm.HookMouse()
pythoncom.PumpMessages()
hm.UnhookMouse()

Other definitions are invalid if the application is focused on a
  process. Initially the process must be resolved by the system. It can
  then access internal and external components.
  pythoncom.CoInitialize() require for a function or additional process !

I hope it helps(TESTED).


来源: stackexchange

问:
How do I convert from list to vector this function? (scheme-dr racket)
```<code>(define l1 (list 1 2 3))
(define l2 (list 4 5 6))

(define (concatenar l1 l2)
        (if (null? l1) l2
        (cons (car l1) (concatenar (cdr l1) l2)))
 )
</code>```

My result be a list  '(1 2 3 4 6 7 8 9)

but I want a vector to come out

I know what is done with this function:  vector->list
But I do not know how to implement it

答:
Rename your existing procedure to concatenar-helper and write a wrapper procedure:

(define (concatenar-helper l1 l2)
  (if (null? l1)
      l2
      (cons (car l1) (concatenar-helper (cdr l1) l2))))

(define (concatenar l1 l2)
  (list->vector (concatenar-helper l1 l2)))
```

ContentLicense: CC BY-SA 3.0

Body:
(define l1 (list 1 2 3))
(define l2 (list 4 5 6))

(define (concatenar l1 l2)
        (if (null? l1) l2
        (cons (car l1) (concatenar (cdr l1) l2)))
 )

My result be a list  '(1 2 3 4 6 7 8 9)

but I want a vector to come out

I know what is done with this function:  vector->list
But I do not know how to implement it


问:
"onclick" button in html form not working
```<code><input type="button"
               value="Register"
               onclick="return regformhash(this.form,
                               this.form.username,
                               this.form.email,
                               this.form.password,
                               this.form.confirmpwd);" />
</code>```

<p>When i try to click on that its like no reaction. Just trying to add informations from form, to my php script. </p>

答:
The following is working snippet with your example for username field, add your other input fields and pass those to function.

function regformhash(form, username){
            alert("username:  "+username);

           }
          ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form>
  <input type="text" value= "myUserName" name ="username"/>
  <input type="button" value="Register" onclick=" regformhash(this.form,this.form.username.value);"/>

</form>

          </code>```

Body:
<input type="button"
               value="Register"
               onclick="return regformhash(this.form,
                               this.form.username,
                               this.form.email,
                               this.form.password,
                               this.form.confirmpwd);" />

When i try to click on that its like no reaction. Just trying to add informations from form, to my php script.

Body:
The following is working snippet with your example for username field, add your other input fields and pass those to function.

function regformhash(form, username){
            alert("username:  "+username);

           }

<form>
  <input type="text" value= "myUserName" name ="username"/>
  <input type="button" value="Register" onclick=" regformhash(this.form,this.form.username.value);"/>

</form>


问:
How to load specific image from assets with Swift
I'm new to Swift and I want to load a special image from assets. For example I have:

```<code>image 1 for iphone 4s = green-square@2x.png
image 2 for iphone 5/5s = green-square-Retina@2x.png
image 3 for iphone 6s = green-square@3x.png
</code>```

and I want to load for iphone 6 a specific image like

```<code>self.GSquare = SKSpriteNode(imageNamed: "./Images.xcassets/green-square-Retina@2x.png")
</code>```

Is it possible?

答:
You can easily pick image from asset without UIImage(named: "green-square-Retina").

Instead use the image object directly from bundle.

Start typing the image name and you will get suggestions with actual image from bundle. It is advisable practice and less prone to error.

See this Stackoverflow answer for reference.

Body:
I'm new to Swift and I want to load a special image from assets. For example I have:

image 1 for iphone 4s = green-square@2x.png
image 2 for iphone 5/5s = green-square-Retina@2x.png
image 3 for iphone 6s = green-square@3x.png

and I want to load for iphone 6 a specific image like

self.GSquare = SKSpriteNode(imageNamed: "./Images.xcassets/green-square-Retina@2x.png")

Is it possible?


问:
What is wrong with my loop code?
I wrote a loop code to extract my table files names into a string or an array and meanwhile collect the data into arrays. But I found my code went wrong as only one file was read and repeated in the loop over and over again. I had no idea where my code is wrong and it already took me several hours to look for the problem. Could somebody help me?

```<code>DataCircle      = dir('*-circle.xls');
MeanAreaCircle  = [];
ColonyNumCircle = [];
PlateNameCircle = [];

for zz = 1:numel(DataCircle)
   basefilenamedata1 = DataCircle(w).name;             % generate the base name
   DataName1         = regexprep(basefilenamedata1,'-circle.xls',''); %replace part of the name and the extension
   PlateNameCircle   = [PlateNameCircle DataName1];    % collect the file name into a string
   T1                = readtable(basefilenamedata1);   % read data in
   MeanAreaCircle    = [MeanAreaCircle mean(T1.area)]; % collect the mean for area
end
</code>```

What I got is like this, which is wrong:

```<code>>> PlateNameCircle
PlateNameCircle ='IMG_0813IMG_0813IMG_0813IMG_0813IMG_0813IMG_0813IMG_0813IMG_0813IMG_0813IMG_0813'
>>  MeanAreaCircle
MeanAreaCircle =
   1.0e+03 *
    6.4152    6.4152    6.4152    6.4152    6.4152    6.4152    6.4152    6.4152    6.4152    6.4152
</code>```

My input file list:

```<code>IMG_0809-CC.xls
IMG_0809-circle.xls
IMG_0810-CC.xls
IMG_0810-circle.xls
IMG_0812-CC.xls
IMG_0812-circle.xls
IMG_0813-CC.xls
IMG_0813-circle.xls
</code>```

What I want is a column or a character array or a string like this:

```<code>PlateNameCircle = 'IMG_0809' 'IMG_0810' 'IMG_0811' 'IMG_0812' 'IMG_0813'
</code>```

答:
Issues

1: you're using w to index the name, instead of zz, the loop variable. Apparently, there is a stray variable called w in your workspace, equal to 8. That's why you're always reading the same file, regardless of iteration number.

2: you're not adding a space in the name:

```<code>PlateNameCircle = [PlateNameCircle ' ' DataName1];
</code>```

3: you're adding the same name on each two consecutive iterations:

```<code>PlateNameCircle = 'IMG_0809-CC IMG_0809 IMG_0810-CC IMG_0810 ...'
</code>```

Improvements

vectorize and use cell strings

preallocate instead of grow-on-the-fly

give your variables even-better names (although you already did a pretty good job there already, tbh)

something like:

```<code>filenames       = {D.name};
PlateNameCircle = regexprep(filenames,'-circle.xls',''); %...doubt this is actually what you want, but it *is* what you've written...

MeanAreaCircle  = zeros(numel(filenames),1);
ColonyNumCircle = [];  % <- not used?

for zz = 1:numel(filenames)
   T1 = readtable(filenames{zz});      % read data in
   MeanAreaCircle(zz) = mean(T1.area); % collect the mean for area
end
</code>```

Title: What is wrong with my loop code?

Body:
I wrote a loop code to extract my table files names into a string or an array and meanwhile collect the data into arrays. But I found my code went wrong as only one file was read and repeated in the loop over and over again. I had no idea where my code is wrong and it already took me several hours to look for the problem. Could somebody help me?

DataCircle      = dir('*-circle.xls');
MeanAreaCircle  = [];
ColonyNumCircle = [];
PlateNameCircle = [];

for zz = 1:numel(DataCircle)
   basefilenamedata1 = DataCircle(w).name;             % generate the base name
   DataName1         = regexprep(basefilenamedata1,'-circle.xls',''); %replace part of the name and the extension
   PlateNameCircle   = [PlateNameCircle DataName1];    % collect the file name into a string
   T1                = readtable(basefilenamedata1);   % read data in
   MeanAreaCircle    = [MeanAreaCircle mean(T1.area)]; % collect the mean for area
end

What I got is like this, which is wrong:

>> PlateNameCircle
PlateNameCircle ='IMG_0813IMG_0813IMG_0813IMG_0813IMG_0813IMG_0813IMG_0813IMG_0813IMG_0813IMG_0813'
>>  MeanAreaCircle
MeanAreaCircle =
   1.0e+03 *
    6.4152    6.4152    6.4152    6.4152    6.4152    6.4152    6.4152    6.4152    6.4152    6.4152

My input file list:

IMG_0809-CC.xls
IMG_0809-circle.xls
IMG_0810-CC.xls
IMG_0810-circle.xls
IMG_0812-CC.xls
IMG_0812-circle.xls
IMG_0813-CC.xls
IMG_0813-circle.xls

What I want is a column or a character array or a string like this:

PlateNameCircle = 'IMG_0809' 'IMG_0810' 'IMG_0811' 'IMG_0812' 'IMG_0813'

Body:
Issues

1: you're using w to index the name, instead of zz, the loop variable. Apparently, there is a stray variable called w in your workspace, equal to 8. That's why you're always reading the same file, regardless of iteration number.

2: you're not adding a space in the name:

PlateNameCircle = [PlateNameCircle ' ' DataName1];

3: you're adding the same name on each two consecutive iterations:

PlateNameCircle = 'IMG_0809-CC IMG_0809 IMG_0810-CC IMG_0810 ...'

Improvements

vectorize and use cell strings

preallocate instead of grow-on-the-fly

give your variables even-better names (although you already did a pretty good job there already, tbh)

something like:

filenames       = {D.name};
PlateNameCircle = regexprep(filenames,'-circle.xls',''); %...doubt this is actually what you want, but it *is* what you've written...

MeanAreaCircle  = zeros(numel(filenames),1);
ColonyNumCircle = [];  % <- not used?

for zz = 1:numel(filenames)
   T1 = readtable(filenames{zz});      % read data in
   MeanAreaCircle(zz) = mean(T1.area); % collect the mean for area
end


问:
Quote needed: Preprocessor usage is bad OO practice
I believe, that the usage of preprocessor directives like #if UsingNetwork is bad OO practice - other coworkers do not.
I think, when using an IoC container (e.g. Spring), components can be easily configured if programmed accordingly. In this context either a propery IsUsingNetwork can be set by the IoC container or, if the "using network" implementation behaves differently, another implementation of that interface should be implemented and injected (e.g.: IService, ServiceImplementation, NetworkingServiceImplementation).

Can somebody please provide citations of OO-Gurus or references in books which basically reads "Preprocessor usage is bad OO practice if you try to configure behaviour which should be configured via an IoC container"?

I need this citations to convince coworkers to refactor...

Edit: I do know and agree that using preprocessor directives to change targetplatform specific code during compilation is fine and that is what preprocessor directives are made for. However, I think that runtime-configuration should be used rather than compiletime-configuration to get good designed and testable classes and components. In other words: Using #defines and #if's beyond what they are meant for will lead to difficult to test code and badly designed classes.

Has anybody read something along these lines and can give me so I can refer to?

答:
In c# / VB.NET I would not say its evil.

For example, when debugging windows services, I put the following in Main so that when in Debug mode, I can run the service as an application.

```<code>    <MTAThread()> _
    <System.Diagnostics.DebuggerNonUserCode()> _
    Shared Sub Main()

#If DEBUG Then

        'Starts this up as an application.'

        Dim _service As New DispatchService()
        _service.ServiceStartupMethod(Nothing)
        System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite)

#Else

        'Runs as a service. '

        Dim ServicesToRun() As System.ServiceProcess.ServiceBase
        ServicesToRun = New System.ServiceProcess.ServiceBase() {New DispatchService}
        System.ServiceProcess.ServiceBase.Run(ServicesToRun)

#End If

    End Sub
</code>```

This is configuring the behavior of the application, and is certainly not evil. At the very least, its not as evil as trying to debug a service startup routine.

Please correct me if I read your OP wrong, but it seems that you are complaining about others using a preprocessor when a simple boolean would suffice. If thats the case, dont damn the preprocessors, damn those using them in such fashion.

EDIT:
Re: first comment. I dont get how that example ties in here. The problem is that the preprocessor is being mis-used, not that it is evil.

I'll give you another example. We have an application that does version checking between client and server on startup. In development, we often have different versions and dont want to do a version check. Is this evil?

I guess what I am trying to say is that the preprocessor is not evil, even when changing program behavior. The problem is that someone is misusing it. What is wrong with saying that? Why are you trying to dismiss a language feature?

Much later EDIT: FWIW: i haven't used preprocessor directives for this in a few years. I do use Environment.UserInteractive with a specific arg set ("-c" = Console), and a neat trick I picked up from somewhere here on SO to not block the application but still wait for user input.

```<code>Shared Sub Main(args as string[])
  If (Environment.UserInteractive = True) Then
    'Starts this up as an application.
    If (args.Length > 0 AndAlso args[0].Equals("-c")) Then 'usually a "DeriveCommand" function that returns an enum or something similar
      Dim isRunning As Boolean = true
      Dim _service As New DispatchService()
      _service.ServiceStartupMethod(Nothing)
      Console.WriteLine("Press ESC to stop running")
      While (IsRunning)
        While (Not (Console.KeyAvailable AndAlso (Console.ReadKey(true).Key.Equals(ConsoleKey.Escape) OrElse Console.ReadKey(true).Key.Equals(ConsoleKey.R))))
           Thread.Sleep(1)
         End While
         Console.WriteLine()
         Console.WriteLine("Press ESC to continue running or any other key to continue shutdown.")
         Dim key = Console.ReadKey();
         if (key.Key.Equals(ConsoleKey.Escape))
         {
           Console.WriteLine("Press ESC to load shutdown menu.")
           Continue
         }
         isRunning = false
      End While
      _service.ServiceStopMethod()
    Else
      Throw New ArgumentException("Dont be a double clicker, this needs a console for reporting info and errors")
    End If
  Else

    'Runs as a service. '
    Dim ServicesToRun() As System.ServiceProcess.ServiceBase
    ServicesToRun = New System.ServiceProcess.ServiceBase() {New DispatchService}
    System.ServiceProcess.ServiceBase.Run(ServicesToRun)
  End If
End Sub
</code>```

OwnerDisplayName: tobsen

LastEditorDisplayName: tobsen

Body:
In c# / VB.NET I would not say its evil.

For example, when debugging windows services, I put the following in Main so that when in Debug mode, I can run the service as an application.

    <MTAThread()> _
    <System.Diagnostics.DebuggerNonUserCode()> _
    Shared Sub Main()

#If DEBUG Then

        'Starts this up as an application.'

        Dim _service As New DispatchService()
        _service.ServiceStartupMethod(Nothing)
        System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite)

#Else

        'Runs as a service. '

        Dim ServicesToRun() As System.ServiceProcess.ServiceBase
        ServicesToRun = New System.ServiceProcess.ServiceBase() {New DispatchService}
        System.ServiceProcess.ServiceBase.Run(ServicesToRun)

#End If

    End Sub

This is configuring the behavior of the application, and is certainly not evil. At the very least, its not as evil as trying to debug a service startup routine.

Please correct me if I read your OP wrong, but it seems that you are complaining about others using a preprocessor when a simple boolean would suffice. If thats the case, dont damn the preprocessors, damn those using them in such fashion.

EDIT:
Re: first comment. I dont get how that example ties in here. The problem is that the preprocessor is being mis-used, not that it is evil.

I'll give you another example. We have an application that does version checking between client and server on startup. In development, we often have different versions and dont want to do a version check. Is this evil?

I guess what I am trying to say is that the preprocessor is not evil, even when changing program behavior. The problem is that someone is misusing it. What is wrong with saying that? Why are you trying to dismiss a language feature?

Much later EDIT: FWIW: i haven't used preprocessor directives for this in a few years. I do use Environment.UserInteractive with a specific arg set ("-c" = Console), and a neat trick I picked up from somewhere here on SO to not block the application but still wait for user input.

Shared Sub Main(args as string[])
  If (Environment.UserInteractive = True) Then
    'Starts this up as an application.
    If (args.Length > 0 AndAlso args[0].Equals("-c")) Then 'usually a "DeriveCommand" function that returns an enum or something similar
      Dim isRunning As Boolean = true
      Dim _service As New DispatchService()
      _service.ServiceStartupMethod(Nothing)
      Console.WriteLine("Press ESC to stop running")
      While (IsRunning)
        While (Not (Console.KeyAvailable AndAlso (Console.ReadKey(true).Key.Equals(ConsoleKey.Escape) OrElse Console.ReadKey(true).Key.Equals(ConsoleKey.R))))
           Thread.Sleep(1)
         End While
         Console.WriteLine()
         Console.WriteLine("Press ESC to continue running or any other key to continue shutdown.")
         Dim key = Console.ReadKey();
         if (key.Key.Equals(ConsoleKey.Escape))
         {
           Console.WriteLine("Press ESC to load shutdown menu.")
           Continue
         }
         isRunning = false
      End While
      _service.ServiceStopMethod()
    Else
      Throw New ArgumentException("Dont be a double clicker, this needs a console for reporting info and errors")
    End If
  Else

    'Runs as a service. '
    Dim ServicesToRun() As System.ServiceProcess.ServiceBase
    ServicesToRun = New System.ServiceProcess.ServiceBase() {New DispatchService}
    System.ServiceProcess.ServiceBase.Run(ServicesToRun)
  End If
End Sub

OwnerDisplayName: StingyJack

LastEditorDisplayName: StingyJack


问:
In javascript, when creating properties, which is the right way or better syntax?
properties(keys) can be accessed and set using the dot notation as well as the square brackets. any advice when to use dot prototype syntax</p>

```<code>var myObj = {};
myObj.myProp1 = 'value1'; //works, an expando property
myObj[myProp2] = 'value2'; // FAILS, myProp2 is undefined
myObj["myProp2"] = 'value2'; // works, an expando property
myObj[2010]= 'value'; //note the key is number, still works, an expando property??
myObj.2010 = 'value'; // FAILS. to use dot notation, key must be a string

myObj.prototype.myProp3 = 'value3' // whats the advantage?
</code>```

答:
In your case, myObj.prototype.myProp3 = 'value3' should not be used because object literals don't have prototypes. Well they do, but they don't have a prototype property (you'll see that myObj.prototype is undefined).

Prototypes are used on functions to set the default properties for all objects constructed from that function using the new keyword. It is not meant to be used for assigning properties to individual objects.

ContentLicense: CC BY-SA 2.5

Body:
properties(keys) can be accessed and set using the dot notation as well as the square brackets. any advice when to use dot prototype syntax

var myObj = {};
myObj.myProp1 = 'value1'; //works, an expando property
myObj[myProp2] = 'value2'; // FAILS, myProp2 is undefined
myObj["myProp2"] = 'value2'; // works, an expando property
myObj[2010]= 'value'; //note the key is number, still works, an expando property??
myObj.2010 = 'value'; // FAILS. to use dot notation, key must be a string

myObj.prototype.myProp3 = 'value3' // whats the advantage?


问:
How to drop a non-key column without deleting related records with Sequelize Migrations?
I am currently about to learn how to use Sequelize migrations. Therefore I created some example models and migrated them as well. No I tried to delete a column - the migration works fine for that as long as I had no data inserted.

So here are my example models:

```<code>Model1 {id:int, name:string, description:string, fk_model2:int {references Model2:id} }
Model2 {id:int, name:string, description:string, test:string}

Model1toModel2 {id_model1:int, id_model2:int} //not a real model but a table
</code>```

There is a 1:n relation between Model1 and Model2, and an n:m relation, too.
The n:m relation is represented in the database with a table and is created by it's own migration.

Now there is this problem:
I defined a column named test in table Model2 (as shown). After I inserted some example data, I tried to run a migration, which deletes this column. On table Model2 this works just fine.

First try: I used onUpdate: 'cascade', onDelete: 'cascade' in fk_model2-column in table Model1 when creating the tables in a migration file.
So the delete-column migration emptied the Model1 table and the Model1toModel2-table which was created for the n:m relation. That is not what I want.

Second try: I used onUpdate: 'cascade', onDelete: 'restrict'. As expected this gives me ERROR: SQLITE_CONSTRAINT: FOREIGN KEY constraint failed as I now cannot delete Model2-data that is used in Model1. Also this is not what I want.

Question: If I migrate a table, does it delete the whole record and recreates it according to the new conditions defined in the migration file? - so the ON DELETE-Condition fires?

How could I achieve that it just deletes the column test which is not a key value, without touching the tables Model1 and Model1toModel2? (Of course, if the key (& therefore the whole record) in Model2 is deleted, I want the records in Model1toModel2 to be deleted, too, and the 1:n in Model1 to be set NULL or DEFAULT.)

答:
I found the problem/solution here:
How to delete or add column in SQLITE?

Sequelize only pretends to drop a column, instead of this it deletes the data and recreates it afterwards as expected. So this causes the related records to drop or throw SQL-Errors.

Body:
I am currently about to learn how to use Sequelize migrations. Therefore I created some example models and migrated them as well. No I tried to delete a column - the migration works fine for that as long as I had no data inserted.

So here are my example models:

Model1 {id:int, name:string, description:string, fk_model2:int {references Model2:id} }
Model2 {id:int, name:string, description:string, test:string}

Model1toModel2 {id_model1:int, id_model2:int} //not a real model but a table

There is a 1:n relation between Model1 and Model2, and an n:m relation, too.
The n:m relation is represented in the database with a table and is created by it's own migration.

Now there is this problem:
I defined a column named test in table Model2 (as shown). After I inserted some example data, I tried to run a migration, which deletes this column. On table Model2 this works just fine.

First try: I used onUpdate: 'cascade', onDelete: 'cascade' in fk_model2-column in table Model1 when creating the tables in a migration file.
So the delete-column migration emptied the Model1 table and the Model1toModel2-table which was created for the n:m relation. That is not what I want.

Second try: I used onUpdate: 'cascade', onDelete: 'restrict'. As expected this gives me ERROR: SQLITE_CONSTRAINT: FOREIGN KEY constraint failed as I now cannot delete Model2-data that is used in Model1. Also this is not what I want.

Question: If I migrate a table, does it delete the whole record and recreates it according to the new conditions defined in the migration file? - so the ON DELETE-Condition fires?

How could I achieve that it just deletes the column test which is not a key value, without touching the tables Model1 and Model1toModel2? (Of course, if the key (& therefore the whole record) in Model2 is deleted, I want the records in Model1toModel2 to be deleted, too, and the 1:n in Model1 to be set NULL or DEFAULT.)


问:
Overhang notification at bottom of the screen
I am using overhang to display a notification whenever user lands on my website. The notification appears from top of my screen and remains there when I scroll down. I want the same functionality but at the bottom of the screen. Basically, I want the notification to appear at the bottom of the screen rather than top and then remain there even if I scroll down/top. How can I do that?

The code for overhang is as follows:

```<code>$("body").overhang({
  custom: true,
  message: "Upcoming event",
  closeConfirm: true
});
</code>```

Thanks in advance!

答:
Paul answer should work if you can modify overhang CSS file. If you can't, just override that style in your custom CSS, something like:

```<code>body .overhang,
body .overhang-overlay {
    top: auto;
    bottom: 0;
}
</code>```

body is added to make the rule more accurate so it overrides styles from overhang.css without using unnecessary !import directives.

Body:
I am using overhang to display a notification whenever user lands on my website. The notification appears from top of my screen and remains there when I scroll down. I want the same functionality but at the bottom of the screen. Basically, I want the notification to appear at the bottom of the screen rather than top and then remain there even if I scroll down/top. How can I do that?

The code for overhang is as follows:

$("body").overhang({
  custom: true,
  message: "Upcoming event",
  closeConfirm: true
});

Thanks in advance!

Body:
Paul answer should work if you can modify overhang CSS file. If you can't, just override that style in your custom CSS, something like:

body .overhang,
body .overhang-overlay {
    top: auto;
    bottom: 0;
}

body is added to make the rule more accurate so it overrides styles from overhang.css without using unnecessary !import directives.


问:
One line bash command to find N oldest and newest files in a directory
I have the following command:

```<code>files=$(ls -lhrt dirname) && echo $files | head -5 && echo $files | tail -5
</code>```

The idea is to return the oldest and newest 5 files in a directory dirname. This returns the requested data - however, the lines are jumbled together.

Is there a way to better format the output? (or perhaps a better way to write this functionality)?

答:
head an tail together

( Without having to store whole output of previous command into one variable )

Nota: along this, I will use top 4 lines and last 4 lines for sample using seq 1 100.., but top 5 lines and last 5 lines for samples using ls -lhrt dirname.

First way, by using head and tail consecutively

if you try:

```<code>seq 1 100000 | (head -n 4;tail -n 4;)
1
2
3
4
99997
99998
99999
100000
</code>```

Seem do the job, but

```<code>seq 1 1000 | (head -n 4;tail -n 4;)
1
2
3
4
</code>```

Give wrong answer.

This is due to buffering, but bash let you use unbuffered input:

```<code>seq 1 12 | { for i in {1..4};do read foo;echo "$foo";done;tail -n 4 ;}
1
2
3
4
9
10
11
12
</code>```

Finally

For your request, try this:

```<code>{ for i in {1..5};do read foo;echo "$foo";done;tail -n 5;} < <(ls -lhrt dirname)
</code>```

must match your need.

Or by using both together, with help of tee

Just look:

```<code>seq 1 12 | tee > >(tail -n4) >(head -n4)
1
2
3
4
9
10
11
12
</code>```

But this could render strange things on terminal, to prevent this, you could just pipe whole to cat:

```<code>seq 1 12 | tee > >(tail -n4) >(head -n4) | cat
1
2
3
4
9
10
11
12
</code>```

So

```<code>ls -lhrt dirname | tee > >(tail -n5) >(head -n5) | cat
</code>```

must do the job.

Or even, if you wanna play with bash and a big variable:

```<code>files=$(seq 1 12) out='' in=''
for i in {1..4};do
    in+=${files%%$'\n'*}$'\n'
    files=${files#*$'\n'}
    out=${files##*$'\n'}$'\n'${out}
    files=${files%$'\n'*}
done
echo "$in${out%$'\n'}"
1
2
3
4
9
10
11
12
</code>```

Then again:

```<code>files=$(ls -lhrt dirname) out='' in=''
for i in {1..5};do
    in+=${files%%$'\n'*}$'\n'
    files=${files#*$'\n'}
    out=${files##*$'\n'}$'\n'${out}
    files=${files%$'\n'*}
done
echo "$in${out%$'\n'}"
</code>```

But you could use GNU sed

```<code>seq 1 100000 | sed -e ':a;N;4p;5,${s/^[^\n]*\n//;};$!ba;'
1
2
3
4
99997
99998
99999
100000
</code>```

Then

```<code>seq 1 1000 | (head -n 4;tail -n 4;)
1
2
3
4
</code>```0

Body:
I have the following command:

files=$(ls -lhrt dirname) && echo $files | head -5 && echo $files | tail -5

The idea is to return the oldest and newest 5 files in a directory dirname. This returns the requested data - however, the lines are jumbled together.

Is there a way to better format the output? (or perhaps a better way to write this functionality)?

Body:
head an tail together

( Without having to store whole output of previous command into one variable )

Nota: along this, I will use top 4 lines and last 4 lines for sample using seq 1 100.., but top 5 lines and last 5 lines for samples using ls -lhrt dirname.

First way, by using head and tail consecutively

if you try:

seq 1 100000 | (head -n 4;tail -n 4;)
1
2
3
4
99997
99998
99999
100000

Seem do the job, but

seq 1 1000 | (head -n 4;tail -n 4;)
1
2
3
4

Give wrong answer.

This is due to buffering, but bash let you use unbuffered input:

seq 1 12 | { for i in {1..4};do read foo;echo "$foo";done;tail -n 4 ;}
1
2
3
4
9
10
11
12

Finally

For your request, try this:

{ for i in {1..5};do read foo;echo "$foo";done;tail -n 5;} < <(ls -lhrt dirname)

must match your need.

Or by using both together, with help of tee

Just look:

seq 1 12 | tee > >(tail -n4) >(head -n4)
1
2
3
4
9
10
11
12

But this could render strange things on terminal, to prevent this, you could just pipe whole to cat:

seq 1 12 | tee > >(tail -n4) >(head -n4) | cat
1
2
3
4
9
10
11
12

So

ls -lhrt dirname | tee > >(tail -n5) >(head -n5) | cat

must do the job.

Or even, if you wanna play with bash and a big variable:

files=$(seq 1 12) out='' in=''
for i in {1..4};do
    in+=${files%%$'\n'*}$'\n'
    files=${files#*$'\n'}
    out=${files##*$'\n'}$'\n'${out}
    files=${files%$'\n'*}
done
echo "$in${out%$'\n'}"
1
2
3
4
9
10
11
12

Then again:

files=$(ls -lhrt dirname) out='' in=''
for i in {1..5};do
    in+=${files%%$'\n'*}$'\n'
    files=${files#*$'\n'}
    out=${files##*$'\n'}$'\n'${out}
    files=${files%$'\n'*}
done
echo "$in${out%$'\n'}"

But you could use GNU sed

seq 1 100000 | sed -e ':a;N;4p;5,${s/^[^\n]*\n//;};$!ba;'
1
2
3
4
99997
99998
99999
100000

Then

ls -lhrt dirname | sed -e ':a;N;5p;6,${s/^[^\n]*\n//;};$!ba;'


问:
Excel vba to delete a single row until a specific column
I have an excel sheet application in which I need to delete a row from Column 'A' to Column 'M' only, as there are certain data from Column 'N'. A delete statement to delete only that range. For example, if I have data in row 9, I want to delete A9 to M9 and the columns from N9 should not be affected. Similarly, an insert statement to shift cells from A9 to M9 only.

答:
A simple statement to delete the info from A9 to M9

```<code>Sheets("yourSheetName").Range("A9:M9").ClearContents
</code>```

If you move the resulting cells up one row, it's going to throw your data out of sync with what's in N9 to N?, unless it doesn't matter.
To delete AND shift up

```<code>Sub Delete_Range_To_ShiftUp()
   Range("A9:M9").Delete Shift:=xlUp
End Sub
</code>```

To insert a range only (not an entire row) try this

```<code>Sub Insert_Range_To_ShiftDown()
   Range("A9:M9").Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
End Sub
</code>```

Body:
A simple statement to delete the info from A9 to M9

Sheets("yourSheetName").Range("A9:M9").ClearContents

If you move the resulting cells up one row, it's going to throw your data out of sync with what's in N9 to N?, unless it doesn't matter.
To delete AND shift up

Sub Delete_Range_To_ShiftUp()
   Range("A9:M9").Delete Shift:=xlUp
End Sub

To insert a range only (not an entire row) try this

Sub Insert_Range_To_ShiftDown()
   Range("A9:M9").Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
End Sub


问:
select html till i reach a specific class
I have a html like this:

```<code><table>
<tr>
<td>a1</td>
<td>a2</td>

</tr>

<tr>
<td>b1</td>
<td>b2</td>

</tr>

<tr>
<td>c1</td>
<td>c2</td>

</tr>

<tr class="total">
<td>d1</td>
<td>d2</td>

</tr>

<tr>
<td>e1</td>
<td>e2</td>

</tr>

</table>
</code>```

now i want to select only the html till i reach 'total' class, so the hmtl i want jquery to select is:

```<code><tr>
<td>a1</td>
<td>a2</td>

</tr>

<tr>
<td>b1</td>
<td>b2</td>

</tr>

<tr>
<td>c1</td>
<td>c2</td>

</tr>

<tr class="total">
<td>d1</td>
<td>d2</td>

</tr>
</code>```

the code i tried for this was:

```<code>console.log($("table .total").parentsUntil("table").html());
</code>```

but this gives all the tr's (that is, including e1,e2 rows, which i dont want)

if i had gotten the correct html, (ie, till d series), i would perform an action on the each of the tr's to get a perticular value (i mean for ex i want a1, b1, c1, and d1 only, not e1, so i put total class on the d series only).

can anyone help me to get only html till 'total'?

Thanks in advance...

答:
The code below gives you:

```<code>"0": <tr>…</tr>
"1": <tr>…</tr>
"2": <tr>…</tr>
</code>```

console.log($("tr.total").prevUntil("table", "tr"))```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td>a1</td>
    <td>a2</td>
  </tr>
  <tr>
    <td>b1</td>
    <td>b2</td>
  </tr>
  <tr>
    <td>c1</td>
    <td>c2</td>
  </tr>
  <tr class="total">
    <td>d1</td>
    <td>d2</td>
  </tr>
  <tr>
    <td>e1</td>
    <td>e2</td>
  </tr>
</table></code>```

Body:
I have a html like this:

a1
a2

b1
b2

c1
c2

d1
d2

e1
e2

now i want to select only the html till i reach 'total' class, so the hmtl i want jquery to select is:

a1
a2

b1
b2

c1
c2

d1
d2

the code i tried for this was:

console.log($("table .total").parentsUntil("table").html());

but this gives all the tr's (that is, including e1,e2 rows, which i dont want)

if i had gotten the correct html, (ie, till d series), i would perform an action on the each of the tr's to get a perticular value (i mean for ex i want a1, b1, c1, and d1 only, not e1, so i put total class on the d series only).

can anyone help me to get only html till 'total'?

Thanks in advance...

Body:
The code below gives you:

"0": <tr>…</tr>
"1": <tr>…</tr>
"2": <tr>…</tr>

console.log($("tr.total").prevUntil("table", "tr"))

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td>a1</td>
    <td>a2</td>
  </tr>
  <tr>
    <td>b1</td>
    <td>b2</td>
  </tr>
  <tr>
    <td>c1</td>
    <td>c2</td>
  </tr>
  <tr class="total">
    <td>d1</td>
    <td>d2</td>
  </tr>
  <tr>
    <td>e1</td>
    <td>e2</td>
  </tr>
</table>


问:
c++ conversion string- unsigned char
I have a string value:
std::string bl="0x"+"a0"; //where a0 is a heva number. I did add 0x because i want my      vector

```<code>std::vector<unsigned char>vect;
</code>```

vect.push_back(bl.begin(), bl.end()); //error  is not working.

Need help. What to do?
I am working in ubuntu c++ code.

答:
I'm not 100% sure on what you want, because of the contents of your string bl.

Taking you literally:

```<code>std::string bl = "0xA0";
// ^ this is what you meant to write ("0x"+"A0" is actually adding pointers)

std::vector<unsigned char> vect;
vect.insert(vect.begin(), bl.begin(), bl.end());
// ^ you use ranges with .insert not push_back
</code>```

Or you can use the constructor:

```<code>std::string bl = "0xA0";
std::vector<unsigned char> vect(bl.begin(), bl.end());
// ^ you use ranges with the constructor too
</code>```

In both these cases, the vector contains the characters '0', 'x', 'A' and '0'.

Alternatively, you might have meant for the string to contain the single character whose ASCII value is (in hex) 0xA0. If so, "0x"+"a0" is very wrong.

```<code>std::string bl = "\xA0";
std::vector<unsigned char> vect(bl.begin(), bl.end());
</code>```

The vector contains one character, whose ASCII value is 0xA0.

I hope this helps.

Title: c++ conversion string- unsigned char

Body:
I have a string value:
std::string bl="0x"+"a0"; //where a0 is a heva number. I did add 0x because i want my      vector

std::vector<unsigned char>vect;

vect.push_back(bl.begin(), bl.end()); //error  is not working.

Need help. What to do?
I am working in ubuntu c++ code.

Body:
I'm not 100% sure on what you want, because of the contents of your string bl.

Taking you literally:

std::string bl = "0xA0";
// ^ this is what you meant to write ("0x"+"A0" is actually adding pointers)

std::vector<unsigned char> vect;
vect.insert(vect.begin(), bl.begin(), bl.end());
// ^ you use ranges with .insert not push_back

Or you can use the constructor:

std::string bl = "0xA0";
std::vector<unsigned char> vect(bl.begin(), bl.end());
// ^ you use ranges with the constructor too

In both these cases, the vector contains the characters '0', 'x', 'A' and '0'.

Alternatively, you might have meant for the string to contain the single character whose ASCII value is (in hex) 0xA0. If so, "0x"+"a0" is very wrong.

std::string bl = "\xA0";
std::vector<unsigned char> vect(bl.begin(), bl.end());

The vector contains one character, whose ASCII value is 0xA0.

I hope this helps.


问:
Is it possible to apply dynamic style as string in Angular?
I have a  that I want to apply dynamic style to.

Style is stored in a css-like string variable and can be arbitrary e.g.

myStyle = 'color: white; font-weight: bold;'

or

myStyle = 'background-color: red;'

I expected it to work like

but it didn't.

I tried different options but none seem to work for me for different reasons:

I can't put styles in a .css file and use class names because style is coming from server in the form of aforementioned string

Using [style.color] etc. doesn't suit me because I don't know what the style can be

Using [ngStyle] doesn't suit me because it expects object like {'color': 'red', 'font-weight': 'bold'} and I only have string

The reason I have a style stored in a string is because I need to apply it in HTML generated on the server where I simply pass that string to a placeholder variable in a velocity template.

I am almost confident that it can't be done the way I want but probably I am overlooking some solution.

答:
All you need is DomSanitizer and bypassSecurityTrustStyle

Component side :

```<code>import { DomSanitizer } from '@angular/platform-browser';

constructor(private doms : DomSanitizer) {}

newStyle = 'background-color:red';

safeCss(style) {
    return this.doms.bypassSecurityTrustStyle(style);
}
</code>```

Template side :

```<code><p [style]="safeCss(this.newStyle)">
  Start editing to see some magic happen :)
</p>
</code>```

WORKING DEMO

Body:
All you need is DomSanitizer and bypassSecurityTrustStyle

Component side :

import { DomSanitizer } from '@angular/platform-browser';

constructor(private doms : DomSanitizer) {}

newStyle = 'background-color:red';

safeCss(style) {
    return this.doms.bypassSecurityTrustStyle(style);
}

Template side :

<p [style]="safeCss(this.newStyle)">
  Start editing to see some magic happen :)
</p>

WORKING DEMO


问:
Compiled Nashorn output as Java class
Is it possible to convert Nashorn evaluated output of a Javascript into a Java Class file to be invoked later ?
(like JSP --> Java--> Class file)

I have a Javascript file that is used by Nashorn to generate HTML output. The javascript file has different functions per components  to generate the HTML output for each of them. These component functions are invoked dynamically through a "renderServer" function that takes component name and JSON data for that component.

```<code>private ScriptEngine nashorn;
ScriptEngineManager scriptEngineManager = new ScriptEngineManager(null);
        this.nashorn = scriptEngineManager.getEngineByName("nashorn");
         this.nashorn.eval(new FileReader(jsFile);
String compName="myComponent1";// Component 1 name
String jsonData="{....}";// JSON data input for myComponent
String formatted = "JSON.parse('" + jsonData + "')";

String htmlRender = "renderServer(\"" + myComponent1 + "\"," + formatted + ");";

Object finalResult = nashorn.eval(htmlRender);
</code>```

I want to generate the compiled output of the evaluation and invoke the java class like  instead of doing nashorn.eval every time  by passing the component name and input json.
Is it possible to achieve it?

答: No. There is no way to persist bytecode generated by nashorn and use it like a normal Java class. There is an undocumented/unsupported "--persistent-code-cache" to enable disk cache of compiled scripts - but that is still used internally by Nashorn. You can't load those classes by arbitrary class loader and call methods on it from your java code.</p>

Title: Compiled Nashorn output as Java class

Body:
Is it possible to convert Nashorn evaluated output of a Javascript into a Java Class file to be invoked later ?
(like JSP --> Java--> Class file)

I have a Javascript file that is used by Nashorn to generate HTML output. The javascript file has different functions per components  to generate the HTML output for each of them. These component functions are invoked dynamically through a "renderServer" function that takes component name and JSON data for that component.

private ScriptEngine nashorn;
ScriptEngineManager scriptEngineManager = new ScriptEngineManager(null);
        this.nashorn = scriptEngineManager.getEngineByName("nashorn");
         this.nashorn.eval(new FileReader(jsFile);
String compName="myComponent1";// Component 1 name
String jsonData="{....}";// JSON data input for myComponent
String formatted = "JSON.parse('" + jsonData + "')";

String htmlRender = "renderServer(\"" + myComponent1 + "\"," + formatted + ");";

Object finalResult = nashorn.eval(htmlRender);

I want to generate the compiled output of the evaluation and invoke the java class like  instead of doing nashorn.eval every time  by passing the component name and input json.
Is it possible to achieve it?


问:
Multiple files upload in Codeigniter
I want to upload multiple files using single element. So I try this example.

Multiple files upload (Array) with CodeIgniter 2.0

This is my form

```<code><form enctype="multipart/form-data" class="jNice" accept-charset="utf-8" method="post" action="http://xxxx.dev/admin/add_estates">
    <fieldset>
            <label>Title * : </label>
            <input type="text" class="text-long" value="" name="title">

            <label>Description : </label>
            <textarea class="mceEditor" rows="10" cols="40" name="description"></textarea>

            <label>Image : </label>
            <input type="file" multiple="" name="images[]">

            <button class="button-submit" type="submit" name="save" id="">Save</button>
    </fieldset>
</form>
</code>```

This is my controller

```<code>public function add_estates()
{
    $data['page_title'] = "© IDEAL - Administrator - Real State - Add Real Estate";
    $data['main_content'] = 'admin/add_estates';

    if ($this->input->post() !== FALSE) {
        $this->load->library('form_validation');
        $this->form_validation->set_rules('title', 'Career Title', 'trim|required');

        if ($this->form_validation->run() !== FALSE) {

            $title = $this->input->post('title');
            $description = $this->input->post('description');

            if (!empty($_FILES['images']['name'][0])) {
                if ($this->upload_files($title, $_FILES['images']) === FALSE) {
                    $data['error'] = $this->upload->display_errors('<div class="alert alert-danger">', '</div>');
                }
            }

            if (!isset($data['error'])) {
                $this->admin_model->add_estate($title, $description, $image_name);
                $this->session->set_flashdata('suc_msg', 'New real estate added successfully');
                redirect('admin/add_estates');
            }
        }
    }

    $data['suc_msg'] = $this->session->flashdata('suc_msg');

    $this->load->view('layout_admin', $data);
}
</code>```

This is my file upload method

```<code>private function upload_files($title, $files)
{
    $config = array(
        'upload_path'   => './upload/real_estate/',
        'allowed_types' => 'jpg|gif|png',
        'overwrite'     => 1,
    );

    $this->load->library('upload', $config);

    foreach ($files['name'] as $key => $image) {
        $_FILES['images']['name']= $files['name'][$key];
        $_FILES['images']['type']= $files['type'][$key];
        $_FILES['images']['tmp_name']= $files['tmp_name'][$key];
        $_FILES['images']['error']= $files['error'][$key];
        $_FILES['images']['size']= $files['size'][$key];

        $config['file_name'] = $title .'_'. $image;

        $this->upload->initialize($config);

        if ($this->upload->do_upload($image)) {
            $this->upload->data();
        } else {
            return false;
        }
    }

    return true;
}
</code>```

But it give You did not select a file to upload. every time. What is the issue?

答:
```<code>public function index() {

    $user = $this->session->userdata("username");
    $file_path = "./images/" . $user . '/';

    if (isset($_FILES['multipleUpload'])) {

        if (!is_dir('images/' . $user)) {
            mkdir('./images/' . $user, 0777, TRUE);
        }

        $files = $_FILES;
        $cpt = count($_FILES ['multipleUpload'] ['name']);

        for ($i = 0; $i < $cpt; $i ++) {

            $name = time().$files ['multipleUpload'] ['name'] [$i];
            $_FILES ['multipleUpload'] ['name'] = $name;
            $_FILES ['multipleUpload'] ['type'] = $files ['multipleUpload'] ['type'] [$i];
            $_FILES ['multipleUpload'] ['tmp_name'] = $files ['multipleUpload'] ['tmp_name'] [$i];
            $_FILES ['multipleUpload'] ['error'] = $files ['multipleUpload'] ['error'] [$i];
            $_FILES ['multipleUpload'] ['size'] = $files ['multipleUpload'] ['size'] [$i];

            $this->upload->initialize($this->set_upload_options($file_path));
            if(!($this->upload->do_upload('multipleUpload')) || $files ['multipleUpload'] ['error'] [$i] !=0)
            {
                print_r($this->upload->display_errors());
            }
            else
            {
                $this->load->model('uploadModel','um');
                $this->um->insertRecord($user,$name);
            }
        }
    } else {
        $this->load->view('uploadForm');
    }
}

public function set_upload_options($file_path) {
    // upload an image options
    $config = array();
    $config ['upload_path'] = $file_path;
    $config ['allowed_types'] = 'gif|jpg|png';
    return $config;
}
</code>```

Title: Multiple files upload in Codeigniter

Body:
I want to upload multiple files using single element. So I try this example.

Multiple files upload (Array) with CodeIgniter 2.0

This is my form

<form enctype="multipart/form-data" class="jNice" accept-charset="utf-8" method="post" action="http://xxxx.dev/admin/add_estates">
    <fieldset>
            Title * :
            <input type="text" class="text-long" value="" name="title">

            Description :
            <textarea class="mceEditor" rows="10" cols="40" name="description"></textarea>

            Image :
            <input type="file" multiple="" name="images[]">

            <button class="button-submit" type="submit" name="save" id="">Save</button>
    </fieldset>
</form>

This is my controller

public function add_estates()
{
    $data['page_title'] = "© IDEAL - Administrator - Real State - Add Real Estate";
    $data['main_content'] = 'admin/add_estates';

    if ($this->input->post() !== FALSE) {
        $this->load->library('form_validation');
        $this->form_validation->set_rules('title', 'Career Title', 'trim|required');

        if ($this->form_validation->run() !== FALSE) {

            $title = $this->input->post('title');
            $description = $this->input->post('description');

            if (!empty($_FILES['images']['name'][0])) {
                if ($this->upload_files($title, $_FILES['images']) === FALSE) {
                    $data['error'] = $this->upload->display_errors('
', '
');
                }
            }

            if (!isset($data['error'])) {
                $this->admin_model->add_estate($title, $description, $image_name);
                $this->session->set_flashdata('suc_msg', 'New real estate added successfully');
                redirect('admin/add_estates');
            }
        }
    }

    $data['suc_msg'] = $this->session->flashdata('suc_msg');

    $this->load->view('layout_admin', $data);
}

This is my file upload method

private function upload_files($title, $files)
{
    $config = array(
        'upload_path'   => './upload/real_estate/',
        'allowed_types' => 'jpg|gif|png',
        'overwrite'     => 1,
    );

    $this->load->library('upload', $config);

    foreach ($files['name'] as $key => $image) {
        $_FILES['images']['name']= $files['name'][$key];
        $_FILES['images']['type']= $files['type'][$key];
        $_FILES['images']['tmp_name']= $files['tmp_name'][$key];
        $_FILES['images']['error']= $files['error'][$key];
        $_FILES['images']['size']= $files['size'][$key];

        $config['file_name'] = $title .'_'. $image;

        $this->upload->initialize($config);

        if ($this->upload->do_upload($image)) {
            $this->upload->data();
        } else {
            return false;
        }
    }

    return true;
}

But it give You did not select a file to upload. every time. What is the issue?


问:
Datatype of escape sequences in c++
I am still a beginner.

Some of my teachers say that escape sequences are characters while others say they are "special" strings.

What are they exactly?

答:
Escape sequences are used to represent certain special characters within string literals and character literals.

From wikipedia:

Escape sequences are used in the programming languages C and C++, and
  also in many more languages (with some variations) like Java and C#.
  An escape sequence is a sequence of characters that does not represent itself when used inside a character or string literal, but
  is translated into another character or a sequence of characters that
  may be difficult or impossible to represent directly.

In C, all escape sequences consist of two or more characters, the
  first of which is the backslash, \ (called the "Escape character");
  the remaining characters determine the interpretation of the escape
  sequence. For example, \n is an escape sequence that denotes a newline
  character. The remainder of this article focuses on C; other
  programming languages are likely to have different syntax and
  semantics.

From string_literal:

Syntax

```<code>" (unescaped_character|escaped_character)* "  (1)

L " (unescaped_character|escaped_character)* "    (2)

u8 " (unescaped_character|escaped_character)* "   (3) (since C++11)

u " (unescaped_character|escaped_character)* "    (4) (since C++11)

U " (unescaped_character|escaped_character)* "    (5) (since C++11)

prefix(optional) R "delimiter( raw_characters )delimiter" (6) (since C++11)
</code>```

From character_literal:

Syntax

' c-char '    (1)

u8 ' c-char ' (2) (since C++17)

u ' c-char '  (3) (since C++11)

U ' c-char '  (4) (since C++11)

L ' c-char '  (5)

' c-char-sequence '   (6)

where

c-char is either

a character from the basic source character set minus single-quote ('), backslash (), or the newline character,

escape sequence, as defined in escape sequences

universal character name, as defined in escape sequences

c-char-sequence is a sequence of two or more c-chars.

narrow character literal or ordinary character literal, e.g. 'a' or
  '\n' or '\13'. Such literal has type char and the value equal to the
  representation of c-char in the execution character set. If c-char is
  not representable as a single byte in the execution character set, the
  literal has type int and implementation-defined value

Title: Datatype of escape sequences in c++

Body:
Escape sequences are used to represent certain special characters within string literals and character literals.

From wikipedia:

Escape sequences are used in the programming languages C and C++, and
  also in many more languages (with some variations) like Java and C#.
  An escape sequence is a sequence of characters that does not represent itself when used inside a character or string literal, but
  is translated into another character or a sequence of characters that
  may be difficult or impossible to represent directly.

In C, all escape sequences consist of two or more characters, the
  first of which is the backslash, \ (called the "Escape character");
  the remaining characters determine the interpretation of the escape
  sequence. For example, \n is an escape sequence that denotes a newline
  character. The remainder of this article focuses on C; other
  programming languages are likely to have different syntax and
  semantics.

From string_literal:

Syntax

" (unescaped_character|escaped_character)* "  (1)

L " (unescaped_character|escaped_character)* "    (2)

u8 " (unescaped_character|escaped_character)* "   (3) (since C++11)

u " (unescaped_character|escaped_character)* "    (4) (since C++11)

U " (unescaped_character|escaped_character)* "    (5) (since C++11)

prefix(optional) R "delimiter( raw_characters )delimiter" (6) (since C++11)

From character_literal:

Syntax

' c-char '    (1)

u8 ' c-char ' (2) (since C++17)

u ' c-char '  (3) (since C++11)

U ' c-char '  (4) (since C++11)

L ' c-char '  (5)

' c-char-sequence '   (6)

where

c-char is either

a character from the basic source character set minus single-quote ('), backslash (), or the newline character,

escape sequence, as defined in escape sequences

universal character name, as defined in escape sequences

c-char-sequence is a sequence of two or more c-chars.

narrow character literal or ordinary character literal, e.g. 'a' or
  '\n' or '\13'. Such literal has type char and the value equal to the
  representation of c-char in the execution character set. If c-char is
  not representable as a single byte in the execution character set, the
  literal has type int and implementation-defined value


问:
Java / Kotlin generics
i am having a template / generics question.

This is the code i have at the moment

```<code>data class RealmWatcher<T>(
        val results: RealmResults<T>,
        val handler: (RealmResults<T>) -> Unit)
</code>```

And and using this in an Android fragment to listen to specific results and execute actions based on the changes. So lets take this as an example

```<code>private val realmListener = arrayOf(
            RealmWatcher<Notification>(Realm.getDefaultInstance().where(Notification::class.java).equalTo("isNew", true).findAll(),
                                       { n: RealmResults<Notification> ->
                                           // DO STUFF
                                       })
</code>```

I am doing this while start / stop of the fragment

```<code>override fun onResume() {
    super.onResume()
    // start listening and execute
    realmListener.forEach { it.handler(it.results) }
    realmListener.forEach { it.results.addChangeListener(it.handler) }
}

override fun onPause() {
    // stop listening
    realmListener.forEach { it.results.removeChangeListener(it.handler) }
    super.onPause()
}
</code>```

It works only when i am using one type (like Notification above). How should I define that if i want to use different types in the form of

```<code>private val realmListener = arrayOf(
            RealmWatcher<Notification>(Realm.getDefaultInstance().where(Notification::class.java).equalTo("isNew", true).findAll(),
                                       { n: RealmResults<Notification> ->
                                       // TODO STUFF
                                       }),
            RealmWatcher<Project>(Realm.getDefaultInstance().where(Project::class.java).equalTo("isOdd", true).findAll(),
                                       { n: RealmResults<Project> ->
                                         // TODO STUFF
                                       })
                                       )
</code>```

When mixing the types (Notification and Project) I will get a Type mismatch error.

And when defining the

```<code>private val realmListener:Array<RealmWatcher<out Any>>
</code>```

I will also get Type mismatch errors

How can I define the Array to have several different RealmWatcher with different types T?

答:
Doing exactly what you want is going to be tricky, because I don't know of a way to tell the compiler that what you're doing is actually safe. Adding variance, like one of the comments suggests, won't work as T is used in both in and out positions.

However, you could take a different approach. Extend your RealmWatcher like this:

```<code>data class RealmWatcher<T>(
    val results: RealmResults<T>,
    val handler: (RealmResults<T>) -> Unit
) {
    fun attach() {
        handler(results)
        results.addChangeListener(handler)
    }
    fun detach() {
        results.removeChangeListener(handler)
    }
}
</code>```

and then use those two additional functions in your lifecycle callbacks:

```<code>fun onResume() {
    super.onResume()
    // start listening and execute
    realmListener.forEach { it.attach() }
}

fun onPause() {
    // stop listening
    realmListener.forEach { it.detach() }
    super.onPause()
}
</code>```

This will do what you need it to do without creating a problem because of the mixed generic parameters.

Title: Java / Kotlin generics

Body:
i am having a template / generics question.

This is the code i have at the moment

data class RealmWatcher<T>(
        val results: RealmResults<T>,
        val handler: (RealmResults<T>) -> Unit)

And and using this in an Android fragment to listen to specific results and execute actions based on the changes. So lets take this as an example

private val realmListener = arrayOf(
            RealmWatcher<Notification>(Realm.getDefaultInstance().where(Notification::class.java).equalTo("isNew", true).findAll(),
                                       { n: RealmResults<Notification> ->
                                           // DO STUFF
                                       })

I am doing this while start / stop of the fragment

override fun onResume() {
    super.onResume()
    // start listening and execute
    realmListener.forEach { it.handler(it.results) }
    realmListener.forEach { it.results.addChangeListener(it.handler) }
}

override fun onPause() {
    // stop listening
    realmListener.forEach { it.results.removeChangeListener(it.handler) }
    super.onPause()
}

It works only when i am using one type (like Notification above). How should I define that if i want to use different types in the form of

private val realmListener = arrayOf(
            RealmWatcher<Notification>(Realm.getDefaultInstance().where(Notification::class.java).equalTo("isNew", true).findAll(),
                                       { n: RealmResults<Notification> ->
                                       // TODO STUFF
                                       }),
            RealmWatcher<Project>(Realm.getDefaultInstance().where(Project::class.java).equalTo("isOdd", true).findAll(),
                                       { n: RealmResults<Project> ->
                                         // TODO STUFF
                                       })
                                       )

When mixing the types (Notification and Project) I will get a Type mismatch error.

And when defining the

private val realmListener:Array<RealmWatcher<out Any>>

I will also get Type mismatch errors

How can I define the Array to have several different RealmWatcher with different types T?

Body:
Doing exactly what you want is going to be tricky, because I don't know of a way to tell the compiler that what you're doing is actually safe. Adding variance, like one of the comments suggests, won't work as T is used in both in and out positions.

However, you could take a different approach. Extend your RealmWatcher like this:

data class RealmWatcher<T>(
    val results: RealmResults<T>,
    val handler: (RealmResults<T>) -> Unit
) {
    fun attach() {
        handler(results)
        results.addChangeListener(handler)
    }
    fun detach() {
        results.removeChangeListener(handler)
    }
}

and then use those two additional functions in your lifecycle callbacks:

fun onResume() {
    super.onResume()
    // start listening and execute
    realmListener.forEach { it.attach() }
}

fun onPause() {
    // stop listening
    realmListener.forEach { it.detach() }
    super.onPause()
}

This will do what you need it to do without creating a problem because of the mixed generic parameters.


问:
How does imul and idiv really work 8086?
I am trying to figure out how the imul and idiv instructions of the 8086 microprocessor work.

I know this:
1. mul and div are multiplications and division for unsigned numbers
2. imul and idiv, are also multiplications and divisions but for signed numbers

I searched all the web, and what I just wrote above, that's the only info that I've found, but written in different ways.

I have this:

```<code>mov AX, 0FFCEh
idiv AH
</code>```

Because ah it's a byte, AL=AX/AH (the result) and AH=remainder

After the instruction I get AX=0032h, obviously 0 remainder, and the result 32. Can somebody explain how it got to this result ? I need to know how to explain how the instruction works (bit by bit).

Same goes with the imul instruction.

I have:

```<code>mov AX, 0FF10h
imul AL
</code>```

Because AL is a byte, the result of the multiplication will be saved into AX. After the execution of the imul instruction AX=0100h, why isn't it F100h ?

I don't how the CPU actually does mul, div, imul and idiv. If somebody could illustrate for me the differences, would really appreciate it.

Thanks!

答:
idiv part of answer

```<code>mov AX, FFCE
idiv AH
</code>```

AX=FFCE

AH=FF

definition of negative is that their highest ranked bit equals 1, so
FFCE is negative,

because
1111 1111 1100 1110

and processor cannot work with negatives,
we need to have positive, that means we negate this number (or processor does this based on highest ranked bit automaticallly)

```<code>NEG FFCE
</code>```

or

```<code>    1111 1111 1100 1110 =>
=>  0000 0000 0011 0001 +1 =>
=>  0000 0000 0011 0010 =>
=>  0032h
</code>```

then next - AH register is FF - also negative and
we need positive version, we negate

```<code>    1111 1111 =>
=>  0000 0000 +1 =>
=>  0000 0001 =>
=>  01h
</code>```

then when all numbers are positive, we calculate division

32h div 1h, 0h remainder => AL, 32h result => AH

both are negative that means that result is positive and needs no more conversions.

imul part of answer

```<code>mov AX, FF10
imul AL
</code>```

AL=10h

imul/mul uses AL when argument is 8bit (which it is)

so imul AL is same as

```<code>AL * AL => 10h * 10h => 0100h = AX
</code>```

imul part of answer extended

```<code>mov AX, FF10
imul AH
</code>```

AH=FF

AL=10h

so now we have AL * AH => AX

AL = 10h

AH = FF which is negative, we need positive, we negate and get => 01h

multiplication of positives

10h * 01h => 0010h

but as only one of them was negative, we have to negate result,
do not lose starting zeros, or your answer will be incorrect

```<code>0010h => FFEF +1 => FFF0 = AX
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to figure out how the imul and idiv instructions of the 8086 microprocessor work.

I know this:
1. mul and div are multiplications and division for unsigned numbers
2. imul and idiv, are also multiplications and divisions but for signed numbers

I searched all the web, and what I just wrote above, that's the only info that I've found, but written in different ways.

I have this:

mov AX, 0FFCEh
idiv AH

Because ah it's a byte, AL=AX/AH (the result) and AH=remainder

After the instruction I get AX=0032h, obviously 0 remainder, and the result 32. Can somebody explain how it got to this result ? I need to know how to explain how the instruction works (bit by bit).

Same goes with the imul instruction.

I have:

mov AX, 0FF10h
imul AL

Because AL is a byte, the result of the multiplication will be saved into AX. After the execution of the imul instruction AX=0100h, why isn't it F100h ?

I don't how the CPU actually does mul, div, imul and idiv. If somebody could illustrate for me the differences, would really appreciate it.

Thanks!

Body:
idiv part of answer

mov AX, FFCE
idiv AH

AX=FFCE

AH=FF

definition of negative is that their highest ranked bit equals 1, so
FFCE is negative,

because
1111 1111 1100 1110

and processor cannot work with negatives,
we need to have positive, that means we negate this number (or processor does this based on highest ranked bit automaticallly)

NEG FFCE

or

    1111 1111 1100 1110 =>
=>  0000 0000 0011 0001 +1 =>
=>  0000 0000 0011 0010 =>
=>  0032h

then next - AH register is FF - also negative and
we need positive version, we negate

    1111 1111 =>
=>  0000 0000 +1 =>
=>  0000 0001 =>
=>  01h

then when all numbers are positive, we calculate division

32h div 1h, 0h remainder => AL, 32h result => AH

both are negative that means that result is positive and needs no more conversions.

imul part of answer

mov AX, FF10
imul AL

AL=10h

imul/mul uses AL when argument is 8bit (which it is)

so imul AL is same as

AL * AL => 10h * 10h => 0100h = AX

imul part of answer extended

mov AX, FF10
imul AH

AH=FF

AL=10h

so now we have AL * AH => AX

AL = 10h

AH = FF which is negative, we need positive, we negate and get => 01h

multiplication of positives

10h * 01h => 0010h

but as only one of them was negative, we have to negate result,
do not lose starting zeros, or your answer will be incorrect

0010h => FFEF +1 => FFF0 = AX


问:
jQuery: Adding td elements with one class to tr
First of all I have to find the number of cells with one class, this line works.

```<code>var numcells = $('.hidden-td').length
</code>```

And now I have to find the element with the class .placeholder-style I use this line (only one
have this class):

```<code>$(this).find('.placeholder-style')
</code>```

Now I have to add the same number of var numcellslike inside the
with the clase .hidden-td I think this will be with .addClass('hidden-td').

How can I make this?

Thanks

答:
I'm assuming this is the correct structure you're after... if not, post your HTML so I can amend it but either way, this is how you should do it. </p>

```<code>var numcells = $('.hidden-td').length;

var content = $(this).find('.placeholder-style');

for (i = 0; i < numcells; i++) {
    content.append('<td class="hidden-td"></td>');
}
</code>```

Body:
First of all I have to find the number of cells with one class, this line works.

var numcells = $('.hidden-td').length

And now I have to find the element with the class .placeholder-style I use this line (only one
have this class):

$(this).find('.placeholder-style')

Now I have to add the same number of var numcellslike inside the
with the clase .hidden-td I think this will be with .addClass('hidden-td').

How can I make this?

Thanks

Body:
I'm assuming this is the correct structure you're after... if not, post your HTML so I can amend it but either way, this is how you should do it.

var numcells = $('.hidden-td').length;

var content = $(this).find('.placeholder-style');

for (i = 0; i < numcells; i++) {
    content.append('<td class="hidden-td"></td>');
}


问:
Permissions for truncating a table
What permission do I need to GRANT a user, in MSSQL, in order to be able to truncate a table?

I'm trying to grant the minimal set of permissions, but I can't use DELETE, because the table is very large, and I want the operation to be quick.

答:
Don't GRANT, hide...

```<code>CREATE TRIGGER TRG_MyTable_Foo
WITH EXECUTE AS OWNER
INSTEAD OF DELETE
AS
IF CONTEXT_INFO() = 0x9999
BEGIN
    TRUNCATE TABLE MyTable
    SET CONTEXT_INFO 0x00
END
GO

SET CONTEXT_INFO 0x9999
DELETE MyTable WHERE 1=0
</code>```

SET CONTEXT_INFO may be is without any doubt better to separate a normal DELETE from a TRUNCATE TABLE

I haven't tried this...

Edit: changed to use SET CONTEXT_INFO.

Title: Permissions for truncating a table

Body:
Don't GRANT, hide...

CREATE TRIGGER TRG_MyTable_Foo
WITH EXECUTE AS OWNER
INSTEAD OF DELETE
AS
IF CONTEXT_INFO() = 0x9999
BEGIN
    TRUNCATE TABLE MyTable
    SET CONTEXT_INFO 0x00
END
GO

SET CONTEXT_INFO 0x9999
DELETE MyTable WHERE 1=0

SET CONTEXT_INFO may be is without any doubt better to separate a normal DELETE from a TRUNCATE TABLE

I haven't tried this...

Edit: changed to use SET CONTEXT_INFO.


问:
C# restrict a overriding method to return a specific type
I have an abstract class which should have a method returning an instance of a class which should inherit from a base class as well implement an interface.

```<code>public abstract class AbstractClass
{
    abstract [DonotKnowTheType] GetClassInstance() //The Return type should be an instance of a class which implements TestClass and ISample
}

public class ChildClass : AbstractClass
{
    override [DonotKnowTheType] GetClassInstance()
    {
        //Need to return instance of SampleClass in this example. This could vary, this should be an instance of a class which implements TestClass and ISample
    }
}

public class SampleClass : TestClass,ISample
{
    //Implementation
}
</code>```

Please help to achieve this with a good design. Need to restrict developers who writes the overriding method in ChildClass to return only an instance of a class which implements TestClass and ISample. If not, it has to show a compile time error.

答:
You could make your abstract class generic with a contraint on TestClass and ISample:

```<code>public abstract class AbstractClass<T> where T: TestClass, ISample
{
    public abstract T GetClassInstance(); //The Return type should be an instance of a class which implements AbstractClass and ISample
}

public class ChildClass : AbstractClass<SampleClass>
{
    public override SampleClass GetClassInstance()
    {
        //Need to return instance of SampleClass in this example. This could vary, this should be an instance of a class which implements AbstractClass and ISample
        return new SampleClass();
    }
}
</code>```

Body:
I have an abstract class which should have a method returning an instance of a class which should inherit from a base class as well implement an interface.

public abstract class AbstractClass
{
    abstract [DonotKnowTheType] GetClassInstance() //The Return type should be an instance of a class which implements TestClass and ISample
}

public class ChildClass : AbstractClass
{
    override [DonotKnowTheType] GetClassInstance()
    {
        //Need to return instance of SampleClass in this example. This could vary, this should be an instance of a class which implements TestClass and ISample
    }
}

public class SampleClass : TestClass,ISample
{
    //Implementation
}

Please help to achieve this with a good design. Need to restrict developers who writes the overriding method in ChildClass to return only an instance of a class which implements TestClass and ISample. If not, it has to show a compile time error.

Body:
You could make your abstract class generic with a contraint on TestClass and ISample:

public abstract class AbstractClass<T> where T: TestClass, ISample
{
    public abstract T GetClassInstance(); //The Return type should be an instance of a class which implements AbstractClass and ISample
}

public class ChildClass : AbstractClass<SampleClass>
{
    public override SampleClass GetClassInstance()
    {
        //Need to return instance of SampleClass in this example. This could vary, this should be an instance of a class which implements AbstractClass and ISample
        return new SampleClass();
    }
}


问:
VBA - Excel Class Function - Logic
Using VBA to sort through employee course records. I have an Employee class and am trying to identify people individuals who satisfy the condition "has this but not that." I have stepped through the code and all works just fine, except for my condition testing in BlsHasIssue(). Pertinent code:

```<code>'''''''''''''
'clsEmployee'
'''''''''''''
Option Explicit

Private empID As String
Private name As String
Private hasBLSComp As Boolean
Private hasBLSAssignment As Boolean

Public Property Let id(value As String)
    empID = value
End Property

Property Get id() As String
    id = empID
End Property

Public Property Let setName(value As String)
    name = value
End Property

Public Property Get getName() As String
    getName = name
End Property

Public Sub addResusRecord(value As String)  'accepts name of course
    Select Case value
        Case "BLS Assignment":
            hasBLSAssignment = True
        Case "BLS Competency":
            hasBLSComp = True
    End Select
End Sub

Public Function BlsHasIssue() As Boolean
    If hasBLSComp And Not hasBLSAssignment Then
        BlsHasIssue = True
    Else
        BlsHasIssue = False
    End If
End Function

''''''''
'Module'
''''''''
Option Explicit

Const STUDENT_NAME_COL As Integer = 3
Const USER_ID_COL As Integer = 4
Const COURSE_NAME_COL As Integer = 5

Public Function Contains(col As Collection, key As Variant) As Boolean
    Dim obj As Variant
    On Error GoTo err
    Contains = True
    IsObject (col(key))
    Exit Function
err:
    Contains = False
End Function

    Sub ResusCardAudit()

    Dim row As Long
    Dim currEmpID As String
    Dim employees As New Collection
    Dim emp As Object

    For row = 2 To 5 'change to be last row of data
        'Check to see if user exists in collection
        currEmpID = Cells(row, USER_ID_COL).value

        If Not Contains(employees, currEmpID) Then
            'create User and add it to collection
            Set emp = New clsEmployee
            emp.id = currEmpID
            emp.setName = Cells(row, STUDENT_NAME_COL)
            emp.addResusRecord Cells(row, COURSE_NAME_COL)
            employees.Add emp, currEmpID
        Else
            employees.Item(currEmpID).addResusRecord Cells(row, COURSE_NAME_COL)
        End If

    Next row

    'cycle through all employees and determine if any have a comp but not an assignment
    Set emp = New clsEmployee
    row = 2
    For Each emp In employees
        If emp.BlsHasIssue Then

            row = row + 1
        End If
    Next emp

    'if they do, add their details to a new sheet named "Results"

End Sub
</code>```

I have left out the code which properly sets hasBLSComp and hasBLSAssignment. The issue seems to be a logic error when testing emp.BlsHasIssue. The test which has brought me here is when hasBLSComp is True and hasBLSAssignment is False -> BlsHasIssue() results in False.

Note: It is acceptable for hasBLSAssignment to be True and hasBLSComp to be False.

Thoughts?

答:
Thanks for the all of the help. It was an error in my test case--I set the test as the inverse of what I thought I had. This has helped me realize the importance of (valid) multiple test cases before determining something is a problem.

Based on the responses to my question: I will stop hiding the simple logic that tests for an issue in the records and bring it to the module level. I believe this will help me avoid issues moving forward as the code expands.

Title: VBA - Excel Class Function - Logic

Body:
Using VBA to sort through employee course records. I have an Employee class and am trying to identify people individuals who satisfy the condition "has this but not that." I have stepped through the code and all works just fine, except for my condition testing in BlsHasIssue(). Pertinent code:

'''''''''''''
'clsEmployee'
'''''''''''''
Option Explicit

Private empID As String
Private name As String
Private hasBLSComp As Boolean
Private hasBLSAssignment As Boolean

Public Property Let id(value As String)
    empID = value
End Property

Property Get id() As String
    id = empID
End Property

Public Property Let setName(value As String)
    name = value
End Property

Public Property Get getName() As String
    getName = name
End Property

Public Sub addResusRecord(value As String)  'accepts name of course
    Select Case value
        Case "BLS Assignment":
            hasBLSAssignment = True
        Case "BLS Competency":
            hasBLSComp = True
    End Select
End Sub

Public Function BlsHasIssue() As Boolean
    If hasBLSComp And Not hasBLSAssignment Then
        BlsHasIssue = True
    Else
        BlsHasIssue = False
    End If
End Function

''''''''
'Module'
''''''''
Option Explicit

Const STUDENT_NAME_COL As Integer = 3
Const USER_ID_COL As Integer = 4
Const COURSE_NAME_COL As Integer = 5

Public Function Contains(col As Collection, key As Variant) As Boolean
    Dim obj As Variant
    On Error GoTo err
    Contains = True
    IsObject (col(key))
    Exit Function
err:
    Contains = False
End Function

    Sub ResusCardAudit()

    Dim row As Long
    Dim currEmpID As String
    Dim employees As New Collection
    Dim emp As Object

    For row = 2 To 5 'change to be last row of data
        'Check to see if user exists in collection
        currEmpID = Cells(row, USER_ID_COL).value

        If Not Contains(employees, currEmpID) Then
            'create User and add it to collection
            Set emp = New clsEmployee
            emp.id = currEmpID
            emp.setName = Cells(row, STUDENT_NAME_COL)
            emp.addResusRecord Cells(row, COURSE_NAME_COL)
            employees.Add emp, currEmpID
        Else
            employees.Item(currEmpID).addResusRecord Cells(row, COURSE_NAME_COL)
        End If

    Next row

    'cycle through all employees and determine if any have a comp but not an assignment
    Set emp = New clsEmployee
    row = 2
    For Each emp In employees
        If emp.BlsHasIssue Then

            row = row + 1
        End If
    Next emp

    'if they do, add their details to a new sheet named "Results"

End Sub

I have left out the code which properly sets hasBLSComp and hasBLSAssignment. The issue seems to be a logic error when testing emp.BlsHasIssue. The test which has brought me here is when hasBLSComp is True and hasBLSAssignment is False -> BlsHasIssue() results in False.

Note: It is acceptable for hasBLSAssignment to be True and hasBLSComp to be False.

Thoughts?


问:
Proper place to put Postgres JDBC Driver (postgresql-42.1.4.jar) on linux
```<code>import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;

class Demopsql{

Demopsql()
{
    try {
        Class.forName("org.postgresql.Driver");
    } catch (ClassNotFoundException e) {
        System.out.println("Where is your PostgreSQL JDBC Driver? "
                    + "Include in your library path!");
            e.printStackTrace();
            return;
    }
}
</code>```

where should it be paste postgresql-42.1.4.jar or extracted at where?

so that program won't throw class not found exception.

答:
If you are using eclipse, you can follow the method which is written on this post:
Import Libraries in Eclipse?
You will have to put it as an "external jar".

Or you can look at the maven project possibility:
https://maven.apache.org/
You will just have to create a maven project and put a dependency into a file (pom.xml). It will be downloaded when you will do a maven update operation on your project.
I give you the text which should be added to the pom.xml file:

```<code><dependency>
   <groupId>org.postgresql</groupId>
   <artifactId>postgresql</artifactId>
   <version>42.1.4</version>
</dependency>
</code>```

Body:
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;

class Demopsql{

Demopsql()
{
    try {
        Class.forName("org.postgresql.Driver");
    } catch (ClassNotFoundException e) {
        System.out.println("Where is your PostgreSQL JDBC Driver? "
                    + "Include in your library path!");
            e.printStackTrace();
            return;
    }
}

where should it be paste postgresql-42.1.4.jar or extracted at where?

so that program won't throw class not found exception.

Body:
If you are using eclipse, you can follow the method which is written on this post:
Import Libraries in Eclipse?
You will have to put it as an "external jar".

Or you can look at the maven project possibility:
https://maven.apache.org/
You will just have to create a maven project and put a dependency into a file (pom.xml). It will be downloaded when you will do a maven update operation on your project.
I give you the text which should be added to the pom.xml file:

<dependency>
   <groupId>org.postgresql</groupId>
   <artifactId>postgresql</artifactId>
   <version>42.1.4</version>
</dependency>


问:
Clean debug output function?
I want to write an function that will print out error messages/warnings in my program together with the file & line number. There are these two macros in C:

```<code>__FILE__
__LINE__
</code>```

but there's a problem in my opinion... When I'm writing a function like this:

```<code>#include <stdio.h>
#define STRINGIFY(x) #x
#define TOSTRING(x) STRINGIFY(x)
#define AT __FILE__ ":" TOSTRING(__LINE__)
void error(const char *location, const char *msg)
{
#ifdef DEBUG
  printf("Error at %s: %s\n", location, msg);
#endif
}
int main(int , char**)
{
  error(AT, "fake error");
  return 0;
}
</code>```

There are still a lot of useless function calls & trash (the values of __FILE__ and __LINE__ at every call) in the binary file, even if I undefine DEBUG for the release build.
So how can I accomplish this more elegant? I want something like this:

```<code>#include <stdio.h>
#define STRINGIFY(x) #x
#define TOSTRING(x) STRINGIFY(x)
#define AT __FILE__ ":" TOSTRING(__LINE__)
void error(const char *location, const char *msg)
{
  printf("Error at %s: %s\n", location, msg);
}
int main(int , char**)
{
#ifdef DEBUG
  error(AT, "fake error");
#endif
  return 0;
}
</code>```

But not writing #ifdef DEBUG and #endif before and after every function call - that would be too huge for such an task. And remove every  error(AT, "fake error"); call manually isn't really elegant as well...

Any ideas? Maybe inline the function (would not help, wouldn't it)? Some macro or an change of this construct?

答:
Just turn error into a macro:

```<code>#ifdef DEBUG
# define ERROR(l, m) error(l, m)
#else
# define ERROR(l, m)
#endif
</code>```

then, in your functions, write

```<code>ERROR(AT, "fake error");
</code>```

Of course, you could also simplify ERROR and get rid of AT as the first parameter, directly specifying this information in the macro definition.

Title: Clean debug output function?

Body:
I want to write an function that will print out error messages/warnings in my program together with the file & line number. There are these two macros in C:

__FILE__
__LINE__

but there's a problem in my opinion... When I'm writing a function like this:

#include <stdio.h>
#define STRINGIFY(x) #x
#define TOSTRING(x) STRINGIFY(x)
#define AT __FILE__ ":" TOSTRING(__LINE__)
void error(const char *location, const char *msg)
{
#ifdef DEBUG
  printf("Error at %s: %s\n", location, msg);
#endif
}
int main(int , char**)
{
  error(AT, "fake error");
  return 0;
}

There are still a lot of useless function calls & trash (the values of __FILE__ and __LINE__ at every call) in the binary file, even if I undefine DEBUG for the release build.
So how can I accomplish this more elegant? I want something like this:

#include <stdio.h>
#define STRINGIFY(x) #x
#define TOSTRING(x) STRINGIFY(x)
#define AT __FILE__ ":" TOSTRING(__LINE__)
void error(const char *location, const char *msg)
{
  printf("Error at %s: %s\n", location, msg);
}
int main(int , char**)
{
#ifdef DEBUG
  error(AT, "fake error");
#endif
  return 0;
}

But not writing #ifdef DEBUG and #endif before and after every function call - that would be too huge for such an task. And remove every  error(AT, "fake error"); call manually isn't really elegant as well...

Any ideas? Maybe inline the function (would not help, wouldn't it)? Some macro or an change of this construct?

Body:
Just turn error into a macro:

#ifdef DEBUG
# define ERROR(l, m) error(l, m)
#else
# define ERROR(l, m)
#endif

then, in your functions, write

ERROR(AT, "fake error");

Of course, you could also simplify ERROR and get rid of AT as the first parameter, directly specifying this information in the macro definition.


问:
Django - Pass a list item's id/pk to the view with jQuery ajax
Here is my code, shortened for brevity.

HTML Template

```<code>{% for question in questions %}
    <div class="upvote"></div>
{% endfor %}

# lots of code later...

<script>
    $(".upvote").click(function(){
        $.ajax({
            type: "POST",
            url: "{% url 'upvote_for_question' %}",
            data: {
                'question': question
            },
            }
        })
    })
</script>
</code>```

My
 element is an upvote button for a question (think Stack Overflow's upvote button).  As the code shows, every question in question_list has an upvote button.

My question is, when the user presses an upvote button, how do I pass the associated question's pk/id to the view?

答:
One way would be to define url for upvote:

```<code>url(r'^questions/(?P<question_id>\w+)/upvote', views.question_upvote, name='question_upvote')
</code>```

Then use the reverse url functionality in the template and pass url in the data attribute like:

```<code>{% for question in questions %}
    <div class="upvote"
         id="button-{{ question.pk}}"
         data-href="{% url 'question_upvote' question.pk %}">{{ question.upvotes }}
    </div>
{% endfor %}
</code>```

And modify your jQuery to get url from data-href attribute plus add CSRF token, otherwise POST will fail with status 403. Something like:

```<code>$(".upvote").click(function(){
    var postData = {csrfmiddlewaretoken: '{{ csrf_token }}'}
    $.ajax({
        type: "POST",
        url: $(this).attr("data-href"),
        data: postData,
        success: function(new_number_of_upvotes) {
            $(this).html(new_number_of_upvotes)
        }
    })
})
</code>```

Updated view reflecting these changes would be something in the sense of:

```<code>def question_upvote(request, question_id):
    if request.is_ajax() and request.method == 'POST':
        question = get_object_or_404(Questions, pk=question_id)
        question.upvotes += 1
        question.save()
        return HttpResponse(question.upvotes)
    else:
        return HttpResponseRedirect('/')
</code>```

I haven't tested this, but I guess it should work.

Body:
Here is my code, shortened for brevity.

HTML Template

{% for question in questions %}

{% endfor %}

# lots of code later...

My
 element is an upvote button for a question (think Stack Overflow's upvote button).  As the code shows, every question in question_list has an upvote button.

My question is, when the user presses an upvote button, how do I pass the associated question's pk/id to the view?

Body:
One way would be to define url for upvote:

url(r'^questions/(?P<question_id>\w+)/upvote', views.question_upvote, name='question_upvote')

Then use the reverse url functionality in the template and pass url in the data attribute like:

{% for question in questions %}
    <div class="upvote"
         id="button-{{ question.pk}}"
         data-href="{% url 'question_upvote' question.pk %}">{{ question.upvotes }}
    </div>
{% endfor %}

And modify your jQuery to get url from data-href attribute plus add CSRF token, otherwise POST will fail with status 403. Something like:

$(".upvote").click(function(){
    var postData = {csrfmiddlewaretoken: '{{ csrf_token }}'}
    $.ajax({
        type: "POST",
        url: $(this).attr("data-href"),
        data: postData,
        success: function(new_number_of_upvotes) {
            $(this).html(new_number_of_upvotes)
        }
    })
})

Updated view reflecting these changes would be something in the sense of:

def question_upvote(request, question_id):
    if request.is_ajax() and request.method == 'POST':
        question = get_object_or_404(Questions, pk=question_id)
        question.upvotes += 1
        question.save()
        return HttpResponse(question.upvotes)
    else:
        return HttpResponseRedirect('/')

I haven't tested this, but I guess it should work.


答:
Depending on how you enclose the escape sequence, single quote or double quote.

Basically, an escape sequence resembles a single character represented differently in code from what it actually looks like.

```<code>char ch = '\n'; // This is a character
const char *s = "\n"; // This is a string.
</code>```

In the above examples in C, \n represents a newline when inside a string literal or character literal. There will be no more backslashes and Ns when the code is compiled into binary - the compiler has converted the escape sequence to what it resembles.

Sum up:

```<code>\n    // an escape sequence (don't use directly)
'\n'  // a character containing an esc seq
"\n"  // a string containint an esc seq
</code>```

My understanding:

An escape sequence is a sequence (more than 1) of characters written in code, that does not mean what it literally is, but another character. It will be converted to that character after compiling.

Title: Datatype of escape sequences in c++

Body:
I am still a beginner.

Some of my teachers say that escape sequences are characters while others say they are "special" strings.

What are they exactly?

Body:
Depending on how you enclose the escape sequence, single quote or double quote.

Basically, an escape sequence resembles a single character represented differently in code from what it actually looks like.

char ch = '\n'; // This is a character
const char *s = "\n"; // This is a string.

In the above examples in C, \n represents a newline when inside a string literal or character literal. There will be no more backslashes and Ns when the code is compiled into binary - the compiler has converted the escape sequence to what it resembles.

Sum up:

\n    // an escape sequence (don't use directly)
'\n'  // a character containing an esc seq
"\n"  // a string containint an esc seq

My understanding:

An escape sequence is a sequence (more than 1) of characters written in code, that does not mean what it literally is, but another character. It will be converted to that character after compiling.