问:
"The transaction log for database is full due to 'LOG_BACKUP'" in a shared host
I have an Asp.Net MVC 5 website with EntityFramework codefirst approach in a shared hosting plan. It uses the open source WebbsitePanel for control panel and its SQL Server panel is somewhat limited. Today when I wanted to edit the database, I encountered this error:

```<code>The transaction log for database 'db_name' is full due to 'LOG_BACKUP'
</code>```

I searched around and found a lot of related answers like this and this or this but the problem is they suggest running a query on the database. I tried running

```<code>db.Database.ExecuteSqlCommand("ALTER DATABASE db_name SET RECOVERY SIMPLE;");
</code>```

with the visual studio (on the HomeController) but I get the following error:

```<code>System.Data.SqlClient.SqlException: ALTER DATABASE statement not allowed within multi-statement transaction.
</code>```

How can I solve my problem? Should I contact the support team (which is a little poor for my host) or can I solve this myself?

答:
In Addition to Ben's Answer, You can try Below Queries as per your need

```<code>USE {database-name};
GO
-- Truncate the log by changing the database recovery model to SIMPLE.
ALTER DATABASE {database-name}
SET RECOVERY SIMPLE;
GO
-- Shrink the truncated log file to 1 MB.
DBCC SHRINKFILE ({database-file-name}, 1);
GO
-- Reset the database recovery model.
ALTER DATABASE {database-name}
SET RECOVERY FULL;
GO
</code>```

Update Credit @cema-sp

To find database file names use below query

```<code>select * from sys.database_files;
</code>```

Body:
I have an Asp.Net MVC 5 website with EntityFramework codefirst approach in a shared hosting plan. It uses the open source WebbsitePanel for control panel and its SQL Server panel is somewhat limited. Today when I wanted to edit the database, I encountered this error:

The transaction log for database 'db_name' is full due to 'LOG_BACKUP'

I searched around and found a lot of related answers like this and this or this but the problem is they suggest running a query on the database. I tried running

db.Database.ExecuteSqlCommand("ALTER DATABASE db_name SET RECOVERY SIMPLE;");

with the visual studio (on the HomeController) but I get the following error:

System.Data.SqlClient.SqlException: ALTER DATABASE statement not allowed within multi-statement transaction.

How can I solve my problem? Should I contact the support team (which is a little poor for my host) or can I solve this myself?

Body:
In Addition to Ben's Answer, You can try Below Queries as per your need

USE {database-name};
GO
-- Truncate the log by changing the database recovery model to SIMPLE.
ALTER DATABASE {database-name}
SET RECOVERY SIMPLE;
GO
-- Shrink the truncated log file to 1 MB.
DBCC SHRINKFILE ({database-file-name}, 1);
GO
-- Reset the database recovery model.
ALTER DATABASE {database-name}
SET RECOVERY FULL;
GO

Update Credit @cema-sp

To find database file names use below query

select * from sys.database_files;


来源: stackexchange

问:
Tricks to manage the available memory in an R session
What tricks do people use to manage the available memory of an interactive R session?  I use the functions below [based on postings by Petr Pikal and David Hinds to the r-help list in 2004] to list (and/or sort) the largest objects and to occassionally rm() some of them. But by far the most effective solution was ... to run under 64-bit Linux with ample memory.

Any other nice tricks folks want to share?  One per post, please.

```<code># improved list of objects
.ls.objects <- function (pos = 1, pattern, order.by,
                        decreasing=FALSE, head=FALSE, n=5) {
    napply <- function(names, fn) sapply(names, function(x)
                                         fn(get(x, pos = pos)))
    names <- ls(pos = pos, pattern = pattern)
    obj.class <- napply(names, function(x) as.character(class(x))[1])
    obj.mode <- napply(names, mode)
    obj.type <- ifelse(is.na(obj.class), obj.mode, obj.class)
    obj.size <- napply(names, object.size)
    obj.dim <- t(napply(names, function(x)
                        as.numeric(dim(x))[1:2]))
    vec <- is.na(obj.dim)[, 1] & (obj.type != "function")
    obj.dim[vec, 1] <- napply(names, length)[vec]
    out <- data.frame(obj.type, obj.size, obj.dim)
    names(out) <- c("Type", "Size", "Rows", "Columns")
    if (!missing(order.by))
        out <- out[order(out[[order.by]], decreasing=decreasing), ]
    if (head)
        out <- head(out, n)
    out
}
# shorthand
lsos <- function(..., n=10) {
    .ls.objects(..., order.by="Size", decreasing=TRUE, head=TRUE, n=n)
}
</code>```

答:
With only 4GB of RAM (running Windows 10, so make that about 2 or more realistically 1GB) I've had to be real careful with the allocation.

I use data.table almost exclusively.

The 'fread' function allows you to subset information by field names on import; only import the fields that are actually needed to begin with. If you're using base R read, null the spurious columns immediately after import.

As 42- suggests, where ever possible I will then subset within the columns immediately after importing the information.

I frequently rm() objects from the environment as soon as they're no longer needed, e.g. on the next line after using them to subset something else, and call gc().

'fread' and 'fwrite' from data.table can be very fast by comparison with base R reads and writes.

As kpierce8 suggests, I almost always fwrite everything out of the environment and fread it back in, even with thousand / hundreds of thousands of tiny files to get through. This not only keeps the environment 'clean' and keeps the memory allocation low but, possibly due to the severe lack of RAM available, R has a propensity for frequently crashing on my computer; really frequently. Having the information backed up on the drive itself as the code progresses through various stages means I don't have to start right from the beginning if it crashes.

As of 2017, I think the fastest SSDs are running around a few GB per second through the M2 port. I have a really basic 50GB Kingston V300 (550MB/s) SSD that I use as my primary disk (has Windows and R on it). I keep all the bulk information on a cheap 500GB WD platter. I move the data sets to the SSD when I start working on them. This, combined with 'fread'ing and 'fwrite'ing everything has been working out great. I've tried using 'ff' but prefer the former. 4K read/write speeds can create issues with this though; backing up a quarter of a million 1k files (250MBs worth) from the SSD to the platter can take hours. As far as I'm aware, there isn't any R package available yet that can automatically optimise the 'chunkification' process; e.g. look at how much RAM a user has, test the read/write speeds of the RAM / all the drives connected and then suggest an optimal 'chunkification' protocol. This could produce some significant workflow improvements / resource optimisations; e.g. split it to ... MB for the ram -> split it to ... MB for the SSD -> split it to ... MB on the platter -> split it to ... MB on the tape. It could sample data sets beforehand to give it a more realistic gauge stick to work from.

A lot of the problems I've worked on in R involve forming combination and permutation pairs, triples etc, which only makes having limited RAM more of a limitation as they will often at least exponentially expand at some point. This has made me focus a lot of attention on the quality as opposed to quantity of information going into them to begin with, rather than trying to clean it up afterwards, and on the sequence of operations in preparing the information to begin with (starting with the simplest operation and increasing the complexity); e.g. subset, then merge / join, then form combinations / permutations etc.

There do seem to be some benefits to using base R read and write in some instances. For instance, the error detection within 'fread' is so good it can be difficult trying to get really messy information into R to begin with to clean it up. Base R also seems to be a lot easier if you're using Linux. Base R seems to work fine in Linux, Windows 10 uses ~20GB of disc space whereas Ubuntu only needs a few GB, the RAM needed with Ubuntu is slightly lower. But I've noticed large quantities of warnings and errors when installing third party packages in (L)Ubuntu. I wouldn't recommend drifting too far away from (L)Ubuntu or other stock distributions with Linux as you can loose so much overall compatibility it renders the process almost pointless (I think 'unity' is due to be cancelled in Ubuntu as of 2017). I realise this won't go down well with some Linux users but some of the custom distributions are borderline pointless beyond novelty (I've spent years using Linux alone).

Hopefully some of that might help others out.

ContentLicense: CC BY-SA 3.0

Body:
What tricks do people use to manage the available memory of an interactive R session?  I use the functions below [based on postings by Petr Pikal and David Hinds to the r-help list in 2004] to list (and/or sort) the largest objects and to occassionally rm() some of them. But by far the most effective solution was ... to run under 64-bit Linux with ample memory.

Any other nice tricks folks want to share?  One per post, please.

# improved list of objects
.ls.objects <- function (pos = 1, pattern, order.by,
                        decreasing=FALSE, head=FALSE, n=5) {
    napply <- function(names, fn) sapply(names, function(x)
                                         fn(get(x, pos = pos)))
    names <- ls(pos = pos, pattern = pattern)
    obj.class <- napply(names, function(x) as.character(class(x))[1])
    obj.mode <- napply(names, mode)
    obj.type <- ifelse(is.na(obj.class), obj.mode, obj.class)
    obj.size <- napply(names, object.size)
    obj.dim <- t(napply(names, function(x)
                        as.numeric(dim(x))[1:2]))
    vec <- is.na(obj.dim)[, 1] & (obj.type != "function")
    obj.dim[vec, 1] <- napply(names, length)[vec]
    out <- data.frame(obj.type, obj.size, obj.dim)
    names(out) <- c("Type", "Size", "Rows", "Columns")
    if (!missing(order.by))
        out <- out[order(out[[order.by]], decreasing=decreasing), ]
    if (head)
        out <- head(out, n)
    out
}
# shorthand
lsos <- function(..., n=10) {
    .ls.objects(..., order.by="Size", decreasing=TRUE, head=TRUE, n=n)
}


问:
how to create explode effect the UIView?
i need explode effect when the view change i.e., explode animation when i move to the next view. i found this type of animation in facebook app when click the icon in the dash board

please help me

答:
hai i finished the explode view this is my code thanks for your help

//Click event for view explode

```<code>  -(IBAction) buttonPressed: (id) sender{
    UIButton *buttonPressed = (UIButton *)sender;
   NSLog(@"buttonTag %d",buttonPressed.tag);
   @try {
    switch (buttonPressed.tag) {
            NSLog(@"Pugal");
        case 0:
            viewController=news;
            break;
        case 1:
            viewController=videoWeb;
            break;
        case 2:
            viewController=photo;
            break;
        case 3:
            viewController=events;
            break;
        case 4:
            viewController=mobileWeb;
            break;

        default:
            break;

    }

}

[self performSelector:@selector(animateTransition:) withObject:[NSNumber numberWithFloat: TIME_FOR_EXPANDING]];
}
</code>```

//animate Transition

```<code>-(void)animateTransition:(NSNumber *)duration {

self.view.userInteractionEnabled=NO;
[[self view] addSubview:viewController.view];
if ((viewController.view.hidden==false) && ([duration floatValue]==TIME_FOR_EXPANDING)) {
    viewController.view.frame=[[UIScreen mainScreen] bounds];
      viewController.view.transform=CGAffineTransformMakeScale(SCALED_DOWN_AMOUNT, SCALED_DOWN_AMOUNT);
}
viewController.view.hidden=false;
if ([duration floatValue]==TIME_FOR_SHRINKING) {
    [UIView beginAnimations:@"animationShrink" context:NULL];
    [UIView setAnimationDuration:[duration floatValue]];
    viewController.view.transform=CGAffineTransformMakeScale(SCALED_DOWN_AMOUNT, SCALED_DOWN_AMOUNT);
}
else {
        [UIView beginAnimations:@"animationExpand" context:NULL];

        [UIView setAnimationDuration:[duration floatValue]];
        viewController.view.transform=CGAffineTransformMakeScale(1, 1);
}
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:@selector(animationDidStop:finished:context:)];
[UIView commitAnimations];
 }
</code>```

//animated stop

```<code>   -(void)animationDidStop:(NSString *)animationID finished:(BOOL)finished context:(void *)context{

self.view.userInteractionEnabled=YES;

if ([animationID isEqualToString:@"animationExpand"]) {

    UINavigationController *navig = [[[UINavigationController alloc] initWithRootViewController:viewController] autorelease];

    [self presentModalViewController:navig animated:NO];
}
else {
    viewController.view.hidden=true;
}
}
</code>```

its work as per my require Thanks

ContentLicense: CC BY-SA 2.5

Body:
hai i finished the explode view this is my code thanks for your help

//Click event for view explode

  -(IBAction) buttonPressed: (id) sender{
    UIButton *buttonPressed = (UIButton *)sender;
   NSLog(@"buttonTag %d",buttonPressed.tag);
   @try {
    switch (buttonPressed.tag) {
            NSLog(@"Pugal");
        case 0:
            viewController=news;
            break;
        case 1:
            viewController=videoWeb;
            break;
        case 2:
            viewController=photo;
            break;
        case 3:
            viewController=events;
            break;
        case 4:
            viewController=mobileWeb;
            break;

        default:
            break;

    }

}

[self performSelector:@selector(animateTransition:) withObject:[NSNumber numberWithFloat: TIME_FOR_EXPANDING]];
}

//animate Transition

-(void)animateTransition:(NSNumber *)duration {

self.view.userInteractionEnabled=NO;
[[self view] addSubview:viewController.view];
if ((viewController.view.hidden==false) && ([duration floatValue]==TIME_FOR_EXPANDING)) {
    viewController.view.frame=[[UIScreen mainScreen] bounds];
      viewController.view.transform=CGAffineTransformMakeScale(SCALED_DOWN_AMOUNT, SCALED_DOWN_AMOUNT);
}
viewController.view.hidden=false;
if ([duration floatValue]==TIME_FOR_SHRINKING) {
    [UIView beginAnimations:@"animationShrink" context:NULL];
    [UIView setAnimationDuration:[duration floatValue]];
    viewController.view.transform=CGAffineTransformMakeScale(SCALED_DOWN_AMOUNT, SCALED_DOWN_AMOUNT);
}
else {
        [UIView beginAnimations:@"animationExpand" context:NULL];

        [UIView setAnimationDuration:[duration floatValue]];
        viewController.view.transform=CGAffineTransformMakeScale(1, 1);
}
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:@selector(animationDidStop:finished:context:)];
[UIView commitAnimations];
 }

//animated stop

   -(void)animationDidStop:(NSString *)animationID finished:(BOOL)finished context:(void *)context{

self.view.userInteractionEnabled=YES;

if ([animationID isEqualToString:@"animationExpand"]) {

    UINavigationController *navig = [[[UINavigationController alloc] initWithRootViewController:viewController] autorelease];

    [self presentModalViewController:navig animated:NO];
}
else {
    viewController.view.hidden=true;
}
}

its work as per my require Thanks


问:
Ruby self.name or @name
I have a question about what the best way is to reference a class variable in Ruby.

Here is a class I made:

```<code>class Person
  attr_accessor :name

  def initialize(name)
    @name = name
  end

  def say_name
    puts @name
  end

  def say_name2
    puts self.name
  end

end

bob = Person.new("Bob")

bob.say_name
=> "Bob"

bob.say_name2
=> "Bob"
</code>```

Both of the "say_name" methods seems to work as intended. Why use the @variable vs the self.variable??

答:
attr_accessor :name just creates method name, which returns @name variable, something like

```<code>def name
  @name
end
</code>```

instead of you.

Without attr_accessor both self.name and name will not work and return NoMethodError.
@name will work in all cases.

Title: Ruby self.name or @name

Body:
I have a question about what the best way is to reference a class variable in Ruby.

Here is a class I made:

class Person
  attr_accessor :name

  def initialize(name)
    @name = name
  end

  def say_name
    puts @name
  end

  def say_name2
    puts self.name
  end

end

bob = Person.new("Bob")

bob.say_name
=> "Bob"

bob.say_name2
=> "Bob"

Both of the "say_name" methods seems to work as intended. Why use the @variable vs the self.variable??

Body:
attr_accessor :name just creates method name, which returns @name variable, something like

def name
  @name
end

instead of you.

Without attr_accessor both self.name and name will not work and return NoMethodError.
@name will work in all cases.


问:
Webpack Exclude a specific file
I have this code In my webpack.config.prod.js and I was wondering how do I exclude all json except one in a specific path like src/configs/configs

```<code>exclude: [
  /\.html$/,
  /\.(js|jsx)$/,
  /\.css$/,
  /\.json$/,
  /\.bmp$/,
  /\.gif$/,
  /\.jpe?g$/,
  /\.png$/,
],
loader: require.resolve('file-loader'),
options: {
  name: 'static/media/[name].[hash:8].[ext]',
}

...
</code>```

答:
According to the Webpack documentation, you can do something like this.</p>

```<code>exclude: {
  test: [
    /\.html$/,
    /\.(js|jsx)$/,
    /\.css$/,
    /\.json$/,
    /\.bmp$/,
    /\.gif$/,
    /\.jpe?g$/,
    /\.png$/,
  ],
  exclude: [
    'src/configs/configs/your.json'
  ]
}
</code>```

Title: Webpack Exclude a specific file

Body:
I have this code In my webpack.config.prod.js and I was wondering how do I exclude all json except one in a specific path like src/configs/configs

exclude: [
  /\.html$/,
  /\.(js|jsx)$/,
  /\.css$/,
  /\.json$/,
  /\.bmp$/,
  /\.gif$/,
  /\.jpe?g$/,
  /\.png$/,
],
loader: require.resolve('file-loader'),
options: {
  name: 'static/media/[name].[hash:8].[ext]',
}

...

Body:
According to the Webpack documentation, you can do something like this.

exclude: {
  test: [
    /\.html$/,
    /\.(js|jsx)$/,
    /\.css$/,
    /\.json$/,
    /\.bmp$/,
    /\.gif$/,
    /\.jpe?g$/,
    /\.png$/,
  ],
  exclude: [
    'src/configs/configs/your.json'
  ]
}


问:
Windows batch file to delete .svn files and folders
In order to delete all ".svn" files/folders/subfolders in "myfolder" I use this simple line in a batch file:

```<code>FOR /R myfolder %%X IN (.svn) DO (RD /S /Q "%%X")
</code>```

This works, but if there are no ".svn" files/folders the batch file shows a warning saying: "The system cannot find the file specified."
This warning is very noisy so I was wondering how to make it understand that if it doesn't find any ".svn" files/folders he must skip the RD command.

Usually using wild cards would suffice, but in this case I don't know how to use them, because I don't want to delete files/folders with .svn extension, but I want to delete the files/folders named exactly ".svn", so if I do this:

```<code>FOR /R myfolder %%X IN (*.svn) DO (RD /S /Q "%%X")
</code>```

it would NOT delete files/folders named exactly ".svn" anymore.
I tried also this:

```<code>FOR /R myfolder %%X IN (.sv*) DO (RD /S /Q "%%X")
</code>```

but it doesn't work either, he deletes nothing.

答:
```<code>for /f "tokens=* delims=" %%i in ('dir /s /b /a:d *svn') do (rd /s /q "%%i")
</code>```

Body:
In order to delete all ".svn" files/folders/subfolders in "myfolder" I use this simple line in a batch file:

FOR /R myfolder %%X IN (.svn) DO (RD /S /Q "%%X")

This works, but if there are no ".svn" files/folders the batch file shows a warning saying: "The system cannot find the file specified."
This warning is very noisy so I was wondering how to make it understand that if it doesn't find any ".svn" files/folders he must skip the RD command.

Usually using wild cards would suffice, but in this case I don't know how to use them, because I don't want to delete files/folders with .svn extension, but I want to delete the files/folders named exactly ".svn", so if I do this:

FOR /R myfolder %%X IN (*.svn) DO (RD /S /Q "%%X")

it would NOT delete files/folders named exactly ".svn" anymore.
I tried also this:

FOR /R myfolder %%X IN (.sv*) DO (RD /S /Q "%%X")

but it doesn't work either, he deletes nothing.


问:
MySQL only within the current month?
I have the following MySQL query, and I'm trying to adjust it so it only fetches results which are within the current month (of the current year), I'm guessing you may require more info about my MySQL structure so here it goes - I have a UNIX timestamp generated by PHP's time() stored within the time column (under the referrals table), so with the below setup it would be t2.time.

So my problem is I'm unsure how to proceed, I'm guessing it would be something like adding the following to end of the WHERE clause? => AND t2.time IS WITHIN THE CURRENT MONTH (caps are just on to distinguish problem from rest of query) but i'm not sure how to check if its within the current month.

The MySQL Query:

```<code>SELECT t1.username,
       t1.website,
       SUM(IF(t2.type = 'in', 1, 0))  AS in_count,
       SUM(IF(t2.type = 'out', 1, 0)) AS out_count
FROM   users AS t1
       JOIN referrals AS t2
         ON t1.username = t2.author
WHERE  t1.website != ''
GROUP  BY t1.username,
          t1.website
ORDER  BY in_count DESC
LIMIT  0, 10
</code>```

Appreciate all help! :B

答:
For better performances (--> use index), create an index on your date column and user a "between" in your where clause.</p>

```<code>select ... from my_table where my:date_field between concat(YEAR(CURRENT_DATE()),'-',MONTH(CURRENT_DATE()),'-01')
and adddate(concat(YEAR(CURRENT_DATE()),'-',MONTH(CURRENT_DATE()),'-01'), interval 1 month);
</code>```

Title: MySQL only within the current month?

Body:
I have the following MySQL query, and I'm trying to adjust it so it only fetches results which are within the current month (of the current year), I'm guessing you may require more info about my MySQL structure so here it goes - I have a UNIX timestamp generated by PHP's time() stored within the time column (under the referrals table), so with the below setup it would be t2.time.

So my problem is I'm unsure how to proceed, I'm guessing it would be something like adding the following to end of the WHERE clause? => AND t2.time IS WITHIN THE CURRENT MONTH (caps are just on to distinguish problem from rest of query) but i'm not sure how to check if its within the current month.

The MySQL Query:

SELECT t1.username,
       t1.website,
       SUM(IF(t2.type = 'in', 1, 0))  AS in_count,
       SUM(IF(t2.type = 'out', 1, 0)) AS out_count
FROM   users AS t1
       JOIN referrals AS t2
         ON t1.username = t2.author
WHERE  t1.website != ''
GROUP  BY t1.username,
          t1.website
ORDER  BY in_count DESC
LIMIT  0, 10

Appreciate all help! :B

Body:
For better performances (--> use index), create an index on your date column and user a "between" in your where clause.

select ... from my_table where my:date_field between concat(YEAR(CURRENT_DATE()),'-',MONTH(CURRENT_DATE()),'-01')
and adddate(concat(YEAR(CURRENT_DATE()),'-',MONTH(CURRENT_DATE()),'-01'), interval 1 month);


问:
How can I display the test name *after* the test using pytest?
Most of the time when I'm using pytest, the output is very, very long. More than a hundred lines. And often times I want this output, I really do. --tb=short isn't really a very good approach. But I don't want to have to scroll back 200 lines in my tmux window to find my test output because that's also super annoying.

What I would love to have is something like this:

```<code>______________________ >>test_my_test_with_a_lot_of_output _______________________
# imagine lots of test output here
______________________ <<test_my_test_with_a_lot_of_output _______________________
</code>```

Is there some flag or setting I can use in py.test to achieve this kind of output?

答:
I couldn't find a simple way to achieve this using hooks. But here is how I would implement this.
It is not an ideal implementation though.

```<code># contest.py
import pytest
import _pytest

class TerminalReporter(_pytest.terminal.TerminalReporter):
    def _gettestname(self, rep):
        # actually "rename" original method for clarity
        return super()._getfailureheadline(rep)

    def _getfailureheadline(self, rep):
        # instead of test name
        # (which is originally printed at the top of report)
        # return prefixed name
        return '>>' + self._gettestname(rep)

    def _outrep_summary(self, rep):
        super()._outrep_summary(rep)
        # after printing test report end, print out test name again
        # XXX: here we hard-code color, so red will be used even for passed tests
        # (if passes logging is enabled)
        # You can add some more logic with analyzing report status
        self.write_sep('_', '<<' + self._gettestname(rep), red=True)

@pytest.hookimpl(trylast=True)
def pytest_configure(config):
    # overwrite original TerminalReporter plugin with our subclass
    # we want this hook to be executed after all other implementations
    # to be able to unregister original plugin
    reporter = TerminalReporter(config)
    config.pluginmanager.unregister(name='terminalreporter')
    config.pluginmanager.register(reporter, 'terminalreporter')
</code>```

For inspiration about extending this approach head to _pytest.terminal.TerinalReporter class sources.

Body:
Most of the time when I'm using pytest, the output is very, very long. More than a hundred lines. And often times I want this output, I really do. --tb=short isn't really a very good approach. But I don't want to have to scroll back 200 lines in my tmux window to find my test output because that's also super annoying.

What I would love to have is something like this:

______________________ >>test_my_test_with_a_lot_of_output _______________________
# imagine lots of test output here
______________________ <<test_my_test_with_a_lot_of_output _______________________

Is there some flag or setting I can use in py.test to achieve this kind of output?

Body:
I couldn't find a simple way to achieve this using hooks. But here is how I would implement this.
It is not an ideal implementation though.

# contest.py
import pytest
import _pytest

class TerminalReporter(_pytest.terminal.TerminalReporter):
    def _gettestname(self, rep):
        # actually "rename" original method for clarity
        return super()._getfailureheadline(rep)

    def _getfailureheadline(self, rep):
        # instead of test name
        # (which is originally printed at the top of report)
        # return prefixed name
        return '>>' + self._gettestname(rep)

    def _outrep_summary(self, rep):
        super()._outrep_summary(rep)
        # after printing test report end, print out test name again
        # XXX: here we hard-code color, so red will be used even for passed tests
        # (if passes logging is enabled)
        # You can add some more logic with analyzing report status
        self.write_sep('_', '<<' + self._gettestname(rep), red=True)

@pytest.hookimpl(trylast=True)
def pytest_configure(config):
    # overwrite original TerminalReporter plugin with our subclass
    # we want this hook to be executed after all other implementations
    # to be able to unregister original plugin
    reporter = TerminalReporter(config)
    config.pluginmanager.unregister(name='terminalreporter')
    config.pluginmanager.register(reporter, 'terminalreporter')

For inspiration about extending this approach head to _pytest.terminal.TerinalReporter class sources.


问:
Can't customize the appearance of EditText select handle / anchor on landscape
I am having a hard time customizing the EditText select handle. I am following this thread:

How to change color / appearance of EditText select handle / anchor?

It looks like pretty straight forward. Yet, I can't get it to work on landscape. Can anyone spot what I am doing wrong? I pretty much pasted the same code on a test activity but the anchor handles' are always the same. I tried using styles as suggested and programmatically. Still I always get the same default blue anchors :(

I am on Nougat not sure if makes any difference.

Test activity:

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setTheme(R.style.MyCustomTheme);
    setContentView(R.layout.activity_main);
    final EditText editText = (EditText) findViewById(R.id.edit1);
    // tried programatically too and no success
    try {
        final Field fEditor = TextView.class.getDeclaredField("mEditor");
        fEditor.setAccessible(true);
        final Object editor = fEditor.get(editText);
        final Field fSelectHandleLeft = editor.getClass().getDeclaredField("mSelectHandleLeft");
        final Field fSelectHandleRight =
                editor.getClass().getDeclaredField("mSelectHandleRight");
        final Field fSelectHandleCenter =
                editor.getClass().getDeclaredField("mSelectHandleCenter");
        fSelectHandleLeft.setAccessible(true);
        fSelectHandleRight.setAccessible(true);
        fSelectHandleCenter.setAccessible(true);
        fSelectHandleLeft.set(editor, ContextCompat.getDrawable(this, R.drawable.small_rect));
        fSelectHandleRight.set(editor, ContextCompat.getDrawable(this, R.drawable.small_rect));
        fSelectHandleCenter.set(editor, ContextCompat.getDrawable(this, R.drawable.small_rect));
    } catch (final Exception e) {
        Log.d("CUSTOM_ANCHORS", e.toString());
    }
}
</code>```

Layout:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <EditText
        android:id="@+id/edit1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:text="Hello World"
        android:textSize="20sp" />

</LinearLayout>
</code>```

My styles:

```<code><!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>

<style name="MyCustomTheme" parent="@style/AppTheme">
    <item name="android:textSelectHandle">@drawable/small_rect</item>
    <item name="android:textSelectHandleLeft">@drawable/small_rect</item>
    <item name="android:textSelectHandleRight">@drawable/small_rect</item>
</style>
</code>```

the drawable (small_rect.xml)

```<code><shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <size
        android:width="20dp"
        android:height="20dp" />
    <gradient
        android:angle="90"
        android:centerColor="#D6D6D6"
        android:endColor="#4B6CD6"
        android:startColor="#6586F0" />
    <corners android:radius="0dp" />
</shape>
</code>```

the result:

答:
The below code works perfectly on Nougat</p>

```<code><EditText
      android:layout_width="match_parent"
      style="@style/MyCustomTheme"
      android:text="@string/app_name"
      android:layout_height="wrap_content" />

<style name="MyCustomTheme" parent="@style/AppTheme">
    <item name="android:textSelectHandle">@android:drawable/arrow_down_float</item>
    <item name="android:textSelectHandleLeft">@android:drawable/arrow_down_float</item>
    <item name="android:textSelectHandleRight">@android:drawable/arrow_down_float</item>
  </style>
</code>```

Body:
I am having a hard time customizing the EditText select handle. I am following this thread:

How to change color / appearance of EditText select handle / anchor?

It looks like pretty straight forward. Yet, I can't get it to work on landscape. Can anyone spot what I am doing wrong? I pretty much pasted the same code on a test activity but the anchor handles' are always the same. I tried using styles as suggested and programmatically. Still I always get the same default blue anchors :(

I am on Nougat not sure if makes any difference.

Test activity:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setTheme(R.style.MyCustomTheme);
    setContentView(R.layout.activity_main);
    final EditText editText = (EditText) findViewById(R.id.edit1);
    // tried programatically too and no success
    try {
        final Field fEditor = TextView.class.getDeclaredField("mEditor");
        fEditor.setAccessible(true);
        final Object editor = fEditor.get(editText);
        final Field fSelectHandleLeft = editor.getClass().getDeclaredField("mSelectHandleLeft");
        final Field fSelectHandleRight =
                editor.getClass().getDeclaredField("mSelectHandleRight");
        final Field fSelectHandleCenter =
                editor.getClass().getDeclaredField("mSelectHandleCenter");
        fSelectHandleLeft.setAccessible(true);
        fSelectHandleRight.setAccessible(true);
        fSelectHandleCenter.setAccessible(true);
        fSelectHandleLeft.set(editor, ContextCompat.getDrawable(this, R.drawable.small_rect));
        fSelectHandleRight.set(editor, ContextCompat.getDrawable(this, R.drawable.small_rect));
        fSelectHandleCenter.set(editor, ContextCompat.getDrawable(this, R.drawable.small_rect));
    } catch (final Exception e) {
        Log.d("CUSTOM_ANCHORS", e.toString());
    }
}

Layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <EditText
        android:id="@+id/edit1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:text="Hello World"
        android:textSize="20sp" />

</LinearLayout>

My styles:

the drawable (small_rect.xml)

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <size
        android:width="20dp"
        android:height="20dp" />
    <gradient
        android:angle="90"
        android:centerColor="#D6D6D6"
        android:endColor="#4B6CD6"
        android:startColor="#6586F0" />
    <corners android:radius="0dp" />
</shape>

the result:

Body:
The below code works perfectly on Nougat

<EditText
      android:layout_width="match_parent"
      style="@style/MyCustomTheme"
      android:text="@string/app_name"
      android:layout_height="wrap_content" />

<style name="MyCustomTheme" parent="@style/AppTheme">
    <item name="android:textSelectHandle">@android:drawable/arrow_down_float</item>
    <item name="android:textSelectHandleLeft">@android:drawable/arrow_down_float</item>
    <item name="android:textSelectHandleRight">@android:drawable/arrow_down_float</item>
  </style>


问:
How long does it take to change a thread's priority in Java?
What I can't find is any statement on whether changing a thread's priority is a costly operation, time-wise. I would like to do it frequently, but if each switch carries a significant time penalty it is probably not worth the trouble. </p>

答:
In the case of Windows, a call to SetThreadPriority to change the priority of a ready to run thread is a system call that will move the thread from it's current priority ready queue to a different priority ready queue, which is more costly than just setting some value in a thread object.

If SetThreadPriority is used to increase the priority of a thread, and if that results in the now higher priority thread preempting a lower priority thread, the preemption occurs at call time, not at the next time slice.

Ready queues are mentioned here:

https://msdn.microsoft.com/en-us/library/windows/desktop/ms682105(v=vs.85).aspx

Context switching related to a priority change is mentioned here: "The following events might require thread dispatching ... A thread’s priority changes, either because of a system service call or because Windows itself changes the priority value." and "Preemption ... a lower-priority thread is preempted when a higher-priority thread becomes ready to run. This situation might occur for a couple of reasons: A higher-priority thread’s wait completes ... A thread priority is increased or decreased." Ready queues are also mentioned: "Windows multiprocessor systems have per-processor dispatcher ready queues"

https://www.microsoftpressstore.com/articles/article.aspx?p=2233328&seqNum=7

I asked about this at MSDN forums. The fourth post agrees with the sequence I mention in the first and third post in this thread:

https://social.msdn.microsoft.com/Forums/en-US/d4d40f9b-bfc9-439f-8a76-71cc5392669f/setthreadpriority-to-higher-priority-is-context-switch-immediate?forum=windowsgeneraldevelopmentissues

In the case of current versions of Linux, run queues indexed by priority were replaced by a red-black tree. Changing a thread's priority would involve removal and reinsertion of a thread object within the red-black tree. Preemption would occur if the thread object is moved sufficiently to the "left" of the red-black tree.

https://www.ibm.com/developerworks/library/l-completely-fair-scheduler

In response to the comments about the app that "examines a full-speed stream of incoming Bluetooth data packets", the receiving thread should be highest priority, hopefully spending most of its time not running while waiting for the reception of a packet. The high priority packets would be queued up to be processed by another thread just lower in priority than the receiving thread. Multiple processing threads could take advantage of multiple cores if needed.


问:
f.input rows not working Rails 4
Using simple form and f.input on my rails 4 app, however, the row amount is not working. Displays 1 row only.

```<code><%= simple_form_for(@article) do |f| %>
<%= f.error_notification %>

  <%= f.input :whyrating, :input_html => { :rows => 5 } %>

<% end %>
</code>```

also tried without input_html

```<code><%= f.input :whyrating, label:"Why it deserves this rating", :rows => 5 } %>
</code>```

Does anyone no the reason why? I'm sure it's something simple but can't figure it out for the life of me.

答:
You can use input_html attribute of the form input to specify the number of rows. Moreover, in Rails 4+ you can simplify your code such as:</p>

```<code><%= f.input :whyrating, input_html: { rows: "5" } %>
</code>```

Title: f.input rows not working Rails 4

Body:
Using simple form and f.input on my rails 4 app, however, the row amount is not working. Displays 1 row only.

<%= simple_form_for(@article) do |f| %>
<%= f.error_notification %>

  <%= f.input :whyrating, :input_html => { :rows => 5 } %>

<% end %>

also tried without input_html

<%= f.input :whyrating, label:"Why it deserves this rating", :rows => 5 } %>

Does anyone no the reason why? I'm sure it's something simple but can't figure it out for the life of me.

Body:
You can use input_html attribute of the form input to specify the number of rows. Moreover, in Rails 4+ you can simplify your code such as:

<%= f.input :whyrating, input_html: { rows: "5" } %>


问:
Morris JS: "Cannot read property 'match' of undefined" with ajax loaded json
I'm trying to dynamically load JSON data to put in a Morris JS Line, but I keep getting the following error:

```<code>Uncaught TypeError: Cannot read property 'match' of undefined
at Object.b.parseDate (morris.min.js:6)
at c.<anonymous> (morris.min.js:6)
at c.b.Grid.d.setData (morris.min.js:6)
at c.d [as constructor] (morris.min.js:6)
at new c (morris.min.js:6)
at Object.success ((index):232)
at f (jquery.js:1026)
at Object.fireWith [as resolveWith] (jquery.js:1138)
at r (jquery.js:8021)
at XMLHttpRequest.r (jquery.js:8558)
</code>```

I'm making an ajax request using a form and returning data as JSON using the python "json.dumps" function.

```<code>$("#idForm").submit(function(e) {

    var url = "/predict/"; // the script where you handle the form input.

    $.ajax({
           type: "POST",
           url: url,
           data: $("#idForm").serialize(), // serializes the form's elements.
           success: function(json)
           {
                console.log(json);
                var chart = new Morris.Line({
                  // ID of the element in which to draw the chart.
                  element: 'myfirstchart',
                  data: json,
                  // Chart data records -- each entry in this array corresponds to a point on
                  // the chart.
                  // The name of the data record attribute that contains x-values.
                  xkey: 'date',
                  // A list of names of data record attributes that contain y-values.
                  ykeys: ['real', 'predicted'],
                  // Labels for the ykeys -- will be displayed when you hover over the
                  // chart.
                  labels: ['Observed Value', 'Predicted Value']
                });
           }
         });
</code>```

The weird thing is that, if I substitute the "data: json" line with the real JSON (the one given in output by the console.log function, everything works smoothly)

The JSON is the following:

```<code>[
 {
  date: 2016-01-01,
  real: 8,
  predicted: 7
 },
 {
  date: 2016-01-02,
  real: 5,
  predicted: 3
 },
 {
  date: 2016-01-03,
  real: 14,
  predicted: 16
 },
 {
  date: 2016-01-04,
  real: 6,
  predicted: 6
 },
 {
  date: 2016-01-05,
  real: 9,
  predicted: 9
 },
 [...]
 {
  date: 2016-01-27,
  real: 2,
  predicted: 2
 },
 {
  date: 2016-01-28,
  real: 5,
  predicted: 5
 },
 {
  date: 2016-01-29,
  real: 12,
  predicted: 11
 },
 {
  date: 2016-01-30,
  real: 14,
  predicted: 14
 },
 {
  date: 2016-01-31,
  real: 8,
  predicted: 8
 }
</code>```

]

I have tried to parse the JSON again with JQuery, but that gave a parsing error.

Has someone of you encountered this problem?

Thanks a lot

答:
```<code>function line_chart(id) {
    $.ajax({
        type: 'POST',
        async: true,
        dataType: "json",
        url: 'code/content/profile/chart.php',
        data: { user_id: id, type: 'line'},
        success: function(data){
            $('#line').html('');
            Morris.Line({
              element: 'line',
              data: data,
              resize: true,
              xkey: 'period',
              ykeys: ['a', 'b', 'c'],
              lineColors: ['#2577b5', '#293c4d', '#4db6ac'],
              labels: ['Прием', 'Консультация', 'Выдача']
            });
        }
    })
}
</code>```

Body:
I'm trying to dynamically load JSON data to put in a Morris JS Line, but I keep getting the following error:

Uncaught TypeError: Cannot read property 'match' of undefined
at Object.b.parseDate (morris.min.js:6)
at c.<anonymous> (morris.min.js:6)
at c.b.Grid.d.setData (morris.min.js:6)
at c.d [as constructor] (morris.min.js:6)
at new c (morris.min.js:6)
at Object.success ((index):232)
at f (jquery.js:1026)
at Object.fireWith [as resolveWith] (jquery.js:1138)
at r (jquery.js:8021)
at XMLHttpRequest.r (jquery.js:8558)

I'm making an ajax request using a form and returning data as JSON using the python "json.dumps" function.

$("#idForm").submit(function(e) {

    var url = "/predict/"; // the script where you handle the form input.

    $.ajax({
           type: "POST",
           url: url,
           data: $("#idForm").serialize(), // serializes the form's elements.
           success: function(json)
           {
                console.log(json);
                var chart = new Morris.Line({
                  // ID of the element in which to draw the chart.
                  element: 'myfirstchart',
                  data: json,
                  // Chart data records -- each entry in this array corresponds to a point on
                  // the chart.
                  // The name of the data record attribute that contains x-values.
                  xkey: 'date',
                  // A list of names of data record attributes that contain y-values.
                  ykeys: ['real', 'predicted'],
                  // Labels for the ykeys -- will be displayed when you hover over the
                  // chart.
                  labels: ['Observed Value', 'Predicted Value']
                });
           }
         });

The weird thing is that, if I substitute the "data: json" line with the real JSON (the one given in output by the console.log function, everything works smoothly)

The JSON is the following:

[
 {
  date: 2016-01-01,
  real: 8,
  predicted: 7
 },
 {
  date: 2016-01-02,
  real: 5,
  predicted: 3
 },
 {
  date: 2016-01-03,
  real: 14,
  predicted: 16
 },
 {
  date: 2016-01-04,
  real: 6,
  predicted: 6
 },
 {
  date: 2016-01-05,
  real: 9,
  predicted: 9
 },
 [...]
 {
  date: 2016-01-27,
  real: 2,
  predicted: 2
 },
 {
  date: 2016-01-28,
  real: 5,
  predicted: 5
 },
 {
  date: 2016-01-29,
  real: 12,
  predicted: 11
 },
 {
  date: 2016-01-30,
  real: 14,
  predicted: 14
 },
 {
  date: 2016-01-31,
  real: 8,
  predicted: 8
 }

]

I have tried to parse the JSON again with JQuery, but that gave a parsing error.

Has someone of you encountered this problem?

Thanks a lot


问:
Find the number of connected objects in a given 2-D binary matrix
Find number of connected objects from a given 2d matrix<br>
 Sample Input & Output1: </p>

```<code>Enter number of rows:
5
Enter number of columns:
5
Enter the matrix:
0 0 0 0 0
1 0 0 1 0
1 0 0 0 1
0 1 0 1 0
0 0 0 0 0
Number of connected objects = 2
</code>```

答:
like this</p>

```<code>#include <stdio.h>
#include <stdlib.h>

typedef int Color;

typedef struct cell {
    char kind;
    Color color;
} Cell;

typedef struct pos {//position
    int h, v;
} Pos, Size;

typedef struct world {
    Size size;
    Cell **cells;
} World;

typedef struct node {
    Pos pos;
    struct node *next;
} Node;

typedef struct stack {
    Node *np;
} Stack;

void push(Stack *s, Pos pos){
    Node *np = malloc(sizeof(*np));
    np->pos = pos;
    np->next = s->np;
    s->np = np;
}
int isEmpty(Stack *s){
    return !s->np;
}

Pos pop(Stack *s){
    Pos ret = s->np->pos;
    Node *next = s->np->next;
    free(s->np);
    s->np = next;
    return ret;
}

World *make_world(Size size, Stack *s);
void ruin(World *w);
void paint(World *w, Pos pos, Color *color);

int main(void){
    int rows, cols;

    puts("Enter number of rows:");
    scanf("%d", &rows);

    puts("Enter number of columns:");
    scanf("%d", &cols);

    Stack land = { NULL };
    World *world = make_world((Size){.v = rows, .h = cols}, &land);

    Color color = 0;
    while(!isEmpty(&land)){//`land` is a position list of `1`
        paint(world, pop(&land), &color);//Paint the same color from the specified position. New location paints another color(do increment color)
    }
    printf("Number of connected objects = %d\n", color);//The number of colors used is the number of connected objects.
    ruin(world);
}

enum { BLANK = 0, LAND = '1', SEA = '0', NONE = -1 };

World *make_world(Size size, Stack *landList){
    World *w = malloc(sizeof(*w));
    w->size = size;
    w->cells = malloc(size.v * sizeof(*w->cells));
    for(int r = 0; r < size.v; ++r){
        w->cells[r] = calloc(size.h, sizeof(**w->cells));
    }
    puts("Enter the matrix:");
    for(int r = 0; r < size.v; ++r){
        for(int c = 0; c < size.h; ++c){
            char ch = 0;
            scanf(" %c", &ch);
            if((w->cells[r][c].kind = ch) == LAND)
                push(landList, (Pos){ .v = r, .h = c});
        }
    }
    return w;
}

void ruin(World *w){
    for(int r = 0; r < w->size.v; ++r)
        free(w->cells[r]);
    free(w->cells);
    free(w);
}

void fill(World *w, Pos pos, Color *color, Cell *neighbor){
    if(pos.h < 0 || pos.v < 0 || pos.h >= w->size.h || pos.v >= w->size.v)//Out of range
        return;
    Cell *cell = &w->cells[pos.v][pos.h];//reduce code
    if(cell->color != BLANK)//Color already painted
        return;
    if(neighbor != NULL){//There are adjacent cells
        if(cell->kind != neighbor->kind){//Do not process unless they are of the same kind
            return;
        }
        cell->color = neighbor->color;//Fill with the color of the adjacent cell
    } else {
        cell->color = ++*color;//The first cell paints a new color.
    }
    //Process my own neighbor cell
    fill(w, (Pos){.v = pos.v-1, .h = pos.h-1}, color, cell);
    fill(w, (Pos){.v = pos.v-1, .h = pos.h  }, color, cell);
    fill(w, (Pos){.v = pos.v-1, .h = pos.h+1}, color, cell);
    fill(w, (Pos){.v = pos.v  , .h = pos.h-1}, color, cell);
//  fill(w, (Pos){.v = pos.v  , .h = pos.h  }, color, cell);//current cell
    fill(w, (Pos){.v = pos.v  , .h = pos.h+1}, color, cell);
    fill(w, (Pos){.v = pos.v+1, .h = pos.h-1}, color, cell);
    fill(w, (Pos){.v = pos.v+1, .h = pos.h  }, color, cell);
    fill(w, (Pos){.v = pos.v+1, .h = pos.h+1}, color, cell);
}

void paint(World *w, Pos pos, Color *color){//wrapper function
    fill(w, pos, color, NULL);
}
</code>```

Body:
Find number of connected objects from a given 2d matrix

 Sample Input & Output1:

Enter number of rows:
5
Enter number of columns:
5
Enter the matrix:
0 0 0 0 0
1 0 0 1 0
1 0 0 0 1
0 1 0 1 0
0 0 0 0 0
Number of connected objects = 2

Body:
like this

#include <stdio.h>
#include <stdlib.h>

typedef int Color;

typedef struct cell {
    char kind;
    Color color;
} Cell;

typedef struct pos {//position
    int h, v;
} Pos, Size;

typedef struct world {
    Size size;
    Cell **cells;
} World;

typedef struct node {
    Pos pos;
    struct node *next;
} Node;

typedef struct stack {
    Node *np;
} Stack;

void push(Stack *s, Pos pos){
    Node *np = malloc(sizeof(*np));
    np->pos = pos;
    np->next = s->np;
    s->np = np;
}
int isEmpty(Stack *s){
    return !s->np;
}

Pos pop(Stack *s){
    Pos ret = s->np->pos;
    Node *next = s->np->next;
    free(s->np);
    s->np = next;
    return ret;
}

World *make_world(Size size, Stack *s);
void ruin(World *w);
void paint(World *w, Pos pos, Color *color);

int main(void){
    int rows, cols;

    puts("Enter number of rows:");
    scanf("%d", &rows);

    puts("Enter number of columns:");
    scanf("%d", &cols);

    Stack land = { NULL };
    World *world = make_world((Size){.v = rows, .h = cols}, &land);

    Color color = 0;
    while(!isEmpty(&land)){//`land` is a position list of `1`
        paint(world, pop(&land), &color);//Paint the same color from the specified position. New location paints another color(do increment color)
    }
    printf("Number of connected objects = %d\n", color);//The number of colors used is the number of connected objects.
    ruin(world);
}

enum { BLANK = 0, LAND = '1', SEA = '0', NONE = -1 };

World *make_world(Size size, Stack *landList){
    World *w = malloc(sizeof(*w));
    w->size = size;
    w->cells = malloc(size.v * sizeof(*w->cells));
    for(int r = 0; r < size.v; ++r){
        w->cells[r] = calloc(size.h, sizeof(**w->cells));
    }
    puts("Enter the matrix:");
    for(int r = 0; r < size.v; ++r){
        for(int c = 0; c < size.h; ++c){
            char ch = 0;
            scanf(" %c", &ch);
            if((w->cells[r][c].kind = ch) == LAND)
                push(landList, (Pos){ .v = r, .h = c});
        }
    }
    return w;
}

void ruin(World *w){
    for(int r = 0; r < w->size.v; ++r)
        free(w->cells[r]);
    free(w->cells);
    free(w);
}

void fill(World *w, Pos pos, Color *color, Cell *neighbor){
    if(pos.h < 0 || pos.v < 0 || pos.h >= w->size.h || pos.v >= w->size.v)//Out of range
        return;
    Cell *cell = &w->cells[pos.v][pos.h];//reduce code
    if(cell->color != BLANK)//Color already painted
        return;
    if(neighbor != NULL){//There are adjacent cells
        if(cell->kind != neighbor->kind){//Do not process unless they are of the same kind
            return;
        }
        cell->color = neighbor->color;//Fill with the color of the adjacent cell
    } else {
        cell->color = ++*color;//The first cell paints a new color.
    }
    //Process my own neighbor cell
    fill(w, (Pos){.v = pos.v-1, .h = pos.h-1}, color, cell);
    fill(w, (Pos){.v = pos.v-1, .h = pos.h  }, color, cell);
    fill(w, (Pos){.v = pos.v-1, .h = pos.h+1}, color, cell);
    fill(w, (Pos){.v = pos.v  , .h = pos.h-1}, color, cell);
//  fill(w, (Pos){.v = pos.v  , .h = pos.h  }, color, cell);//current cell
    fill(w, (Pos){.v = pos.v  , .h = pos.h+1}, color, cell);
    fill(w, (Pos){.v = pos.v+1, .h = pos.h-1}, color, cell);
    fill(w, (Pos){.v = pos.v+1, .h = pos.h  }, color, cell);
    fill(w, (Pos){.v = pos.v+1, .h = pos.h+1}, color, cell);
}

void paint(World *w, Pos pos, Color *color){//wrapper function
    fill(w, pos, color, NULL);
}


问:
Javascript function wait until completion of recursive asynchronous function called within it
Is there a way in Javascript to wait for the completion of another function and it's callback and essentially "pause" the completion of the current function until that time?

Example:

```<code>var doSomething = function(callback) {
  doSomethingElseAsynchronously(doSomething);
  /* Wait until doSomethingElseAsynchronously */
  /* is finished and it's callback has completed */
  return callback();
};
</code>```

答:
What you're thinking of is a current proposal in ES7 know as async functions. Their syntax looks like this:

```<code>async function doSomething() {
    let result = await doThingAsync(); // doThingAsync returns a Promise
    // ... Do things ...
    return result[0]
}
</code>```

async functions return a Promise which resolve with the eventual return value of the function.

Note that async functions have little to no support, and should you choose to use them, you must first transpile your code to ES6 or ES5 using something like Babel

Body:
Is there a way in Javascript to wait for the completion of another function and it's callback and essentially "pause" the completion of the current function until that time?

Example:

var doSomething = function(callback) {
  doSomethingElseAsynchronously(doSomething);
  /* Wait until doSomethingElseAsynchronously */
  /* is finished and it's callback has completed */
  return callback();
};

Body:
What you're thinking of is a current proposal in ES7 know as async functions. Their syntax looks like this:

async function doSomething() {
    let result = await doThingAsync(); // doThingAsync returns a Promise
    // ... Do things ...
    return result[0]
}

async functions return a Promise which resolve with the eventual return value of the function.

Note that async functions have little to no support, and should you choose to use them, you must first transpile your code to ES6 or ES5 using something like Babel


问:
Php include shows code
PROBLEM: When I include a php file on the top of my page, instead of running the script, it shows the code.

If I do a simple echo command on the page it works fine, but including a file does not.

I have Googled the hell out of this question and cannot find a solution that solves the problem. Most of the similar problems I've seen are solved by using longhand php tags instead of shorthand.

The Code

index.php is in the root folder
init.php is in a folder named 'core' which is in the root folder.

Included File: init.php

```<code><?php
session_start();

$GLOABALS['config'] = array (
    'mysql' => array (
        'host'      => '127.0.0.1',
        'username'  => 'root',
        'password'  => '',
        'db'        => 'lr'
    ),
    'remember' => array (
        'cookie_name'       => 'hash',
        'cookie_expiry'     => 604800
    ),
    'session' => array (
        'session_name'      => 'user'
    )
);

spl_autoload_register (function ($class){
    require_once 'classes/' . $class . '.php';
});

require_once 'functions/sanitize.php';
?>
</code>```

Including Page: index.php

```<code><?php include '/core/init.php'?>

<!-- Web Page Stuff -->
</code>```

sanatize.php

```<code>function escape ($string){
return htmlentities ($string, ENT_QUOTES, "UTF-8");
}
</code>```

Why is the php being displayed and not run?

答:
you're missing the

```<code><?php
?>
</code>```

tags in your file to include.

But wow!! So am I to understand that any error with an include during PHP development will shunt the entire library file to the web browser?!!?! So foreign to my concept of full stack programming or cyber-security, where it all would go to a private error log, never exposing the code to the client.

NO WAY IS PHP, NOR APPARENTLY WILL PHP EVER BE MORE SECURE THAN PERL IN MY OPINION!!! So Perl has more server capabilities, it isn't you're missing the willy-nilly 'loose' code that doesn't really require even definitions of variables. Does it dump internal structure code on any error or only on parse errors for instances?!

Title: Php include shows code

Body:
PROBLEM: When I include a php file on the top of my page, instead of running the script, it shows the code.

If I do a simple echo command on the page it works fine, but including a file does not.

I have Googled the hell out of this question and cannot find a solution that solves the problem. Most of the similar problems I've seen are solved by using longhand php tags instead of shorthand.

The Code

index.php is in the root folder
init.php is in a folder named 'core' which is in the root folder.

Included File: init.php

<?php
session_start();

$GLOABALS['config'] = array (
    'mysql' => array (
        'host'      => '127.0.0.1',
        'username'  => 'root',
        'password'  => '',
        'db'        => 'lr'
    ),
    'remember' => array (
        'cookie_name'       => 'hash',
        'cookie_expiry'     => 604800
    ),
    'session' => array (
        'session_name'      => 'user'
    )
);

spl_autoload_register (function ($class){
    require_once 'classes/' . $class . '.php';
});

require_once 'functions/sanitize.php';
?>

Including Page: index.php

<?php include '/core/init.php'?>

sanatize.php

function escape ($string){
return htmlentities ($string, ENT_QUOTES, "UTF-8");
}

Why is the php being displayed and not run?

Body:
you're missing the

<?php
?>

tags in your file to include.

But wow!! So am I to understand that any error with an include during PHP development will shunt the entire library file to the web browser?!!?! So foreign to my concept of full stack programming or cyber-security, where it all would go to a private error log, never exposing the code to the client.

NO WAY IS PHP, NOR APPARENTLY WILL PHP EVER BE MORE SECURE THAN PERL IN MY OPINION!!! So Perl has more server capabilities, it isn't you're missing the willy-nilly 'loose' code that doesn't really require even definitions of variables. Does it dump internal structure code on any error or only on parse errors for instances?!


问:
Unable to Connect to Bluetooth device
This is the piece of code from Standard from Google sample code BluetoothChat.
BluetoothChatService.java

```<code>public void run() {
        Log.i(TAG, "BEGIN mConnectedThread");
        byte[] buffer = new byte[1024];
        int bytes;

        // Keep listening to the InputStream while connected
        while (mState == STATE_CONNECTED) {
            try {
                // Read from the InputStream
                bytes = mmInStream.read(buffer);
                // Send the obtained bytes to the UI Activity
                mHandler.obtainMessage(Constants.MESSAGE_READ, bytes, -1, buffer)
                        .sendToTarget();
            } catch (IOException e) {
                Log.e(TAG, "disconnected", e);
                connectionLost();
                break;
            }
        }
    }
</code>```

As soon as I try to connect the device using

```<code>mChatService.connect(device, false);
</code>```

I get following exception

```<code>java.io.IOException: bt socket closed, read return: -1
at android.bluetooth.BluetoothSocket.read(BluetoothSocket.java:872)
at android.bluetooth.BluetoothInputStream.read(BluetoothInputStream.java:96)
at java.io.InputStream.read(InputStream.java:163)
</code>```

Any help would be appreciated.

答:
I guess the problem is the mmSocket.connect()

Try to get the method createRfcommSocket by reflect.

Here is an example base on Google sample code BluetoothChat.

```<code>            // Make a connection to the BluetoothSocket
            try {
                Thread.sleep(500);
                // This is a blocking call and will only return on a
                // successful connection or an exception
                mmSocket.connect();
                OutputStream os = mmSocket.getOutputStream();
                // Here: connect success
            } catch (Exception e) {
                Log.i(TAG, "Lost 1st try; SPP connect[2]");
                try {
                    mmSocket.close();// close the current socket
                    mmSocket = null;
                    Thread.sleep(500L); // wait for a while
                    mmSocket = (BluetoothSocket) mmDevice.getClass().getMethod("createRfcommSocket", new Class[]{int.class}).invoke(mmDevice, 1); // The key method !
                    mmSocket.connect();
                    OutputStream os = mmSocket.getOutputStream();
                    // Here: connect success
                    synchronized (ESDevice.this) {
                        mSPPConnectThread = null;
                    }
                    connected(mmSocket, mmDevice); // begin connected thread
                } catch (Exception e2) {
                    Log.e(TAG, "Lost 2nd try. Connect fail", e2);
                    connectionFailed();
                    return;
                }
                return;
            }
</code>```

Title: Unable to Connect to Bluetooth device

Body:
This is the piece of code from Standard from Google sample code BluetoothChat.
BluetoothChatService.java

public void run() {
        Log.i(TAG, "BEGIN mConnectedThread");
        byte[] buffer = new byte[1024];
        int bytes;

        // Keep listening to the InputStream while connected
        while (mState == STATE_CONNECTED) {
            try {
                // Read from the InputStream
                bytes = mmInStream.read(buffer);
                // Send the obtained bytes to the UI Activity
                mHandler.obtainMessage(Constants.MESSAGE_READ, bytes, -1, buffer)
                        .sendToTarget();
            } catch (IOException e) {
                Log.e(TAG, "disconnected", e);
                connectionLost();
                break;
            }
        }
    }

As soon as I try to connect the device using

mChatService.connect(device, false);

I get following exception

java.io.IOException: bt socket closed, read return: -1
at android.bluetooth.BluetoothSocket.read(BluetoothSocket.java:872)
at android.bluetooth.BluetoothInputStream.read(BluetoothInputStream.java:96)
at java.io.InputStream.read(InputStream.java:163)

Any help would be appreciated.

Body:
I guess the problem is the mmSocket.connect()

Try to get the method createRfcommSocket by reflect.

Here is an example base on Google sample code BluetoothChat.

            // Make a connection to the BluetoothSocket
            try {
                Thread.sleep(500);
                // This is a blocking call and will only return on a
                // successful connection or an exception
                mmSocket.connect();
                OutputStream os = mmSocket.getOutputStream();
                // Here: connect success
            } catch (Exception e) {
                Log.i(TAG, "Lost 1st try; SPP connect[2]");
                try {
                    mmSocket.close();// close the current socket
                    mmSocket = null;
                    Thread.sleep(500L); // wait for a while
                    mmSocket = (BluetoothSocket) mmDevice.getClass().getMethod("createRfcommSocket", new Class[]{int.class}).invoke(mmDevice, 1); // The key method !
                    mmSocket.connect();
                    OutputStream os = mmSocket.getOutputStream();
                    // Here: connect success
                    synchronized (ESDevice.this) {
                        mSPPConnectThread = null;
                    }
                    connected(mmSocket, mmDevice); // begin connected thread
                } catch (Exception e2) {
                    Log.e(TAG, "Lost 2nd try. Connect fail", e2);
                    connectionFailed();
                    return;
                }
                return;
            }


问:
Pop if X elements in the past Y seconds?
Sorry, kinda new to RX.NET here... I've been able to do a lot of things in RX, but not the main thing I need to do.

I only want the observable to pop if it has received X elements in the past Y seconds. In other words, at any point in time, when a new element is pushed, look back at the past X elements and see if they all occurred within the past Y seconds.

I can't figure out the "look back and count" part.

It seems like Window would be the right operator, due to is slidability, but perhaps I'm biased in my definition of Window. It feels like the closer function is where I'd do that, but I'm not wizard yet.

答:
This function will return the list of x elements that fall within your y timespan.

```<code>public static IObservable<IList<T>> GetFullWindows<T>(this IObservable<T> source, int x, TimeSpan y)
{
    return source
        .Publish(_obs => _obs
            .Window(_obs, _ => Observable.Timer(y))
            .SelectMany(window => window.Take(x).ToList())
            .Where(l => l.Count == x)
        );

}
</code>```

Here's a usage example:

```<code>var obs = Observable.Generate(0, i => i < 20, i => i + 1, i => i, i => TimeSpan.FromMilliseconds((20 - i) * 100));

var b = obs
    .GetFullWindows(4, TimeSpan.FromSeconds(4.5));

b.Subscribe(l => l.Dump()); //using Linqpad
</code>```

The trick is using Buffer or Window with the overlapping window feature. Window works better here, because you can short-circuit it if you have met the count criteria.

Body:
This function will return the list of x elements that fall within your y timespan.

public static IObservable<IList<T>> GetFullWindows<T>(this IObservable<T> source, int x, TimeSpan y)
{
    return source
        .Publish(_obs => _obs
            .Window(_obs, _ => Observable.Timer(y))
            .SelectMany(window => window.Take(x).ToList())
            .Where(l => l.Count == x)
        );

}

Here's a usage example:

var obs = Observable.Generate(0, i => i < 20, i => i + 1, i => i, i => TimeSpan.FromMilliseconds((20 - i) * 100));

var b = obs
    .GetFullWindows(4, TimeSpan.FromSeconds(4.5));

b.Subscribe(l => l.Dump()); //using Linqpad

The trick is using Buffer or Window with the overlapping window feature. Window works better here, because you can short-circuit it if you have met the count criteria.


问:
Attach database with NORECOVERY
Is there a way to attach a SQL Server mdf/ldf files such that the database is in Restoring mode and we can restore log backups on top of it.

I have a hardware array snapshot (crash consistent) that contains the mdf/ldf files. I need to attach these files to another SQL Server instance and then do log restores for a point in time recovery(using stopat)

The CREATE DATABASE .. FOR ATTACH command brings the database online. Log restore cannot be done on an online database.

Is there a way to accomplish this?

答:
No.  Unfortunately.  Vote for the feature here:
DCR - Attach database with NORECOVERY </p>

Title: Attach database with NORECOVERY


问:
Why doesn't `in` search the values when the Series contains strings
It's probably very basic but why does it seem like in doesn't work for Series containing objects or strings?

```<code>>>> import pandas as pd

>>> s = pd.Series(['a', 'b', 'c'])
>>> 'a' in s
False
>>> 'a' in s.astype('S1')
False
</code>```

The Series.__contains__ documentation is rather sparse:

```<code>[In 1]: s.__contains__?
Signature: s.__contains__(key)
Docstring: True if the key is in the info axis
File:      c:\...\lib\site-packages\pandas\core\generic.py
Type:      method
</code>```

My first thought was that in only checks the "index":

```<code>>>> 1 in s
True
</code>```

But then: Why does it (seem to) work with other types:

```<code>>>> 1.2 in pd.Series([1.3, 1.2])
True

>>> 1 in pd.Series([1.3, 1.2])  # also works for index
True
</code>```

I'm not interested in working solutions. I know I can simply use whatever in s.values or np.any(s.eq(whatever)). I would like to know why it behaves that way (or am I missing something?).

答:
It behaves that way because a Series is more like an OrderedDict than a list.

Just like 1 in {0: 5, 1: 10} is True, so is 1 in pd.Series([5, 10]), because the index is RangeIndex(start=0, stop=2, step=1), and the index elements are like the keys.

I see why the case of

```<code>>>> 1.2 in pd.Series([1.3, 1.2])
True
</code>```

could be a little confusing, but it's just a coincidence based on the numbers you've chosen -- the 1.2 is coerced to an int before comparison with either a RangeIndex or an Int64Index, so you're really asking 1 in ser.index.  Personally I don't like this behaviour, but that's what it's doing.

```<code>>>> 1.9 in pd.Series([1.3, 1.2])
True
>>> 1.2 in pd.Series([1.3, 1.2], index=[10, 20])
False
</code>```

To make the coercion even more obvious:

```<code>In [54]: np.inf in pd.Series([1.3, 1.2])
---------------------------------------------------------------------------
OverflowError                             Traceback (most recent call last)
<ipython-input-54-b069ecc5baf6> in <module>()
----> 1 np.inf in pd.Series([1.3, 1.2])

[...]
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.__contains__ (pandas/_libs/index.c:3924)()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.__contains__ (pandas/_libs/hashtable.c:13569)()

OverflowError: cannot convert float infinity to integer
</code>```

Body:
It's probably very basic but why does it seem like in doesn't work for Series containing objects or strings?

>>> import pandas as pd

>>> s = pd.Series(['a', 'b', 'c'])
>>> 'a' in s
False
>>> 'a' in s.astype('S1')
False

The Series.__contains__ documentation is rather sparse:

[In 1]: s.__contains__?
Signature: s.__contains__(key)
Docstring: True if the key is in the info axis
File:      c:\...\lib\site-packages\pandas\core\generic.py
Type:      method

My first thought was that in only checks the "index":

>>> 1 in s
True

But then: Why does it (seem to) work with other types:

>>> 1.2 in pd.Series([1.3, 1.2])
True

>>> 1 in pd.Series([1.3, 1.2])  # also works for index
True

I'm not interested in working solutions. I know I can simply use whatever in s.values or np.any(s.eq(whatever)). I would like to know why it behaves that way (or am I missing something?).

Body:
It behaves that way because a Series is more like an OrderedDict than a list.

Just like 1 in {0: 5, 1: 10} is True, so is 1 in pd.Series([5, 10]), because the index is RangeIndex(start=0, stop=2, step=1), and the index elements are like the keys.

I see why the case of

>>> 1.2 in pd.Series([1.3, 1.2])
True

could be a little confusing, but it's just a coincidence based on the numbers you've chosen -- the 1.2 is coerced to an int before comparison with either a RangeIndex or an Int64Index, so you're really asking 1 in ser.index.  Personally I don't like this behaviour, but that's what it's doing.

>>> 1.9 in pd.Series([1.3, 1.2])
True
>>> 1.2 in pd.Series([1.3, 1.2], index=[10, 20])
False

To make the coercion even more obvious:

In [54]: np.inf in pd.Series([1.3, 1.2])
---------------------------------------------------------------------------
OverflowError                             Traceback (most recent call last)
<ipython-input-54-b069ecc5baf6> in <module>()
----> 1 np.inf in pd.Series([1.3, 1.2])

[...]
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.__contains__ (pandas/_libs/index.c:3924)()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.__contains__ (pandas/_libs/hashtable.c:13569)()

OverflowError: cannot convert float infinity to integer


问:
How to access parent component class in child component
I am trying to style parent component class in child component using css . How to access parent class in the child component in angular 2</p>

答:
I believe if you import the class for the parent component and pass it into the constructor of the child components class you can access the parent from the child.

Mind you if you're trying to do conditional styling of the parent based on the child you may want to look at EventEmitters and Outputs (see this http://learnangular2.com/outputs )


问:
EncryptedXml DecryptDocument method error after .Net framework update
I have an old function written in 2013 that decrypt xml that was encrypted by another program.

The code is realy simple

```<code>        public static void Decrypt(XmlDocument Doc)
    {
        // Check the arguments.
        if (Doc == null)
            throw new ArgumentNullException("Doc");

        // Create a new EncryptedXml object.
        EncryptedXml exml = new EncryptedXml(Doc);

        // Decrypt the XML document.
        exml.DecryptDocument();

    }
</code>```

It worked like a charm until recently that some of our clients started to upgrade their framework to 4.6.2, so the method DecryptDocument() stopped working. Now it throws an exception "The algorithm group '' is invalid". If I remove .net framework 4.6.2 it works again.

The sample code in this link will reproduce the error, it will encrypt successfully then fail to decrypt.

I'm using A3 certificates, pendrive token. Anyone have faced this problem? there is any work around in .net 4.6.2?

Edit 1:

Stacktrace:

at System.Security.Cryptography.CngAlgorithmGroup..ctor(String algorithmGroup)
 at System.Security.Cryptography.CngKey.get_AlgorithmGroup()
 at System.Security.Cryptography.RSACng..ctor(CngKey key)
 at System.Security.Cryptography.X509Certificates.RSACertificateExtensions.GetRSAPrivateKey(X509Certificate2 certificate)
 at System.Security.Cryptography.CngLightup.GetRSAPrivateKey(X509Certificate2 cert)
 at System.Security.Cryptography.Xml.EncryptedXml.DecryptEncryptedKey(EncryptedKey encryptedKey)
 at System.Security.Cryptography.Xml.EncryptedXml.GetDecryptionKey(EncryptedData encryptedData, String symmetricAlgorithmUri)
 at System.Security.Cryptography.Xml.EncryptedXml.DecryptDocument()
 at Criptografar.Program.Decrypt(XmlDocument Doc) in C:\Users\leoka\Documents\Visual Studio 2017\Projects\ConsoleApp4\Criptografar\Program.cs:line 152
 at Criptografar.Program.Main(String[] args) in C:\Users\leoka\Documents\Visual Studio 2017\Projects\ConsoleApp4\Criptografar\Program.cs:line 83

答:
I ran into something very similar today that turned out to be a bug in .NET 4.6.2:
https://github.com/Microsoft/dotnet/issues/341

According to this issue, there are two workarounds:

1) Upgrading the OS to Windows Server 2012R2 or newer, 2) loading the
  user profile.

Body:
I have an old function written in 2013 that decrypt xml that was encrypted by another program.

The code is realy simple

        public static void Decrypt(XmlDocument Doc)
    {
        // Check the arguments.
        if (Doc == null)
            throw new ArgumentNullException("Doc");

        // Create a new EncryptedXml object.
        EncryptedXml exml = new EncryptedXml(Doc);

        // Decrypt the XML document.
        exml.DecryptDocument();

    }

It worked like a charm until recently that some of our clients started to upgrade their framework to 4.6.2, so the method DecryptDocument() stopped working. Now it throws an exception "The algorithm group '' is invalid". If I remove .net framework 4.6.2 it works again.

The sample code in this link will reproduce the error, it will encrypt successfully then fail to decrypt.

I'm using A3 certificates, pendrive token. Anyone have faced this problem? there is any work around in .net 4.6.2?

Edit 1:

Stacktrace:

at System.Security.Cryptography.CngAlgorithmGroup..ctor(String algorithmGroup)
 at System.Security.Cryptography.CngKey.get_AlgorithmGroup()
 at System.Security.Cryptography.RSACng..ctor(CngKey key)
 at System.Security.Cryptography.X509Certificates.RSACertificateExtensions.GetRSAPrivateKey(X509Certificate2 certificate)
 at System.Security.Cryptography.CngLightup.GetRSAPrivateKey(X509Certificate2 cert)
 at System.Security.Cryptography.Xml.EncryptedXml.DecryptEncryptedKey(EncryptedKey encryptedKey)
 at System.Security.Cryptography.Xml.EncryptedXml.GetDecryptionKey(EncryptedData encryptedData, String symmetricAlgorithmUri)
 at System.Security.Cryptography.Xml.EncryptedXml.DecryptDocument()
 at Criptografar.Program.Decrypt(XmlDocument Doc) in C:\Users\leoka\Documents\Visual Studio 2017\Projects\ConsoleApp4\Criptografar\Program.cs:line 152
 at Criptografar.Program.Main(String[] args) in C:\Users\leoka\Documents\Visual Studio 2017\Projects\ConsoleApp4\Criptografar\Program.cs:line 83


问:
Cannot get out of continuation prompt in SQLite
I was practicing some data entry in SQLite and I could not remove myself from the continuation prompt, even when ending with a semicolon.  Here is the code I used.

INSERT INTO quote (name, quote) VALUES('Acolyte of Pain', 'He trained when he was younger to be an acolyte of joy, but things didn't work out like he thought they would.');
...>
...>

After entering more text or ; it continues to show me.

...>

Why is it not working and how can I complete or exit the continuation prompt.

Thanks

答:
You have an unescaped "'" in a string; try:

```<code>INSERT INTO quote (name, quote) VALUES('Acolyte of Pain', 'He trained when he was younger to be an acolyte of joy, but things didn''t work out like he thought they would.');
</code>```

(Note the doubled "''".)

Body:
You have an unescaped "'" in a string; try:

INSERT INTO quote (name, quote) VALUES('Acolyte of Pain', 'He trained when he was younger to be an acolyte of joy, but things didn''t work out like he thought they would.');

(Note the doubled "''".)


问:
Azure Queue Storage Triggered-Webjob - Dequeue Multiple Messages at a time
I have an Azure Queue Storage-Triggered Webjob. The process my webjob performs is to index the data into Azure Search. Best practice for Azure Search is to index multiple items together instead of one at a time, for performance reasons (indexing can take some time to complete).

For this reason, I would like for my webjob to dequeue multiple messages together so I can loop through, process them, and then index them all together into Azure Search.

However I can't figure out how to get my webjob to dequeue more than one at a time. How can this be accomplished?

答:
For this reason, I would like for my webjob to dequeue multiple messages together so I can loop through, process them, and then index them all together into Azure Search.

According to your description, I suggest you could try to use Microsoft.Azure.WebJobs.Extensions.GroupQueueTrigger to achieve your requirement.

This extension will enable you to trigger functions and receive the group of messages instead of a single message like with [QueueTrigger].

More details, you could refer to below code sample and article.

Install:

```<code>Install-Package Microsoft.Azure.WebJobs.Extensions.GroupQueueTrigger
</code>```

Program.cs:

```<code>  static void Main()
        {
            var config = new JobHostConfiguration
            {
                StorageConnectionString = "...",
                DashboardConnectionString = "...."
            };
            config.UseGroupQueueTriggers();
            var host = new JobHost(config);
            host.RunAndBlock();
        }
</code>```

Function.cs:

```<code> //Receive 10 messages at one time
 public static void MyFunction([GroupQueueTrigger("queue3", 10)]List<string> messages)
        {
            foreach (var item in messages)
            {
                Console.WriteLine(item);
            }
        }
</code>```

Result:

How would I get that changed to a GroupQueueTrigger? Is it an easy change?

In my opinion, it is an easy change.

You could follow below steps:

1.Install the package Microsoft.Azure.WebJobs.Extensions.GroupQueueTrigger from Nuget Package manager.

2.Change the program.cs file enable UseGroupQueueTriggers.

3.Change the webjobs functions according to your old triggered function.

Note:The group queue message trigger must use list.

As my code sample shows:

```<code> public static void MyFunction([GroupQueueTrigger("queue3", 10)]List<string> messages)
</code>```

This function will get 10 messages from the "queue3" one time, so in this function you could change the function loop the list of the messages and   process them, then index them all together into Azure Search.

4.Publish your webjobs to azure web apps.

Body:
For this reason, I would like for my webjob to dequeue multiple messages together so I can loop through, process them, and then index them all together into Azure Search.

According to your description, I suggest you could try to use Microsoft.Azure.WebJobs.Extensions.GroupQueueTrigger to achieve your requirement.

This extension will enable you to trigger functions and receive the group of messages instead of a single message like with [QueueTrigger].

More details, you could refer to below code sample and article.

Install:

Install-Package Microsoft.Azure.WebJobs.Extensions.GroupQueueTrigger

Program.cs:

  static void Main()
        {
            var config = new JobHostConfiguration
            {
                StorageConnectionString = "...",
                DashboardConnectionString = "...."
            };
            config.UseGroupQueueTriggers();
            var host = new JobHost(config);
            host.RunAndBlock();
        }

Function.cs:

 //Receive 10 messages at one time
 public static void MyFunction([GroupQueueTrigger("queue3", 10)]List<string> messages)
        {
            foreach (var item in messages)
            {
                Console.WriteLine(item);
            }
        }

Result:

How would I get that changed to a GroupQueueTrigger? Is it an easy change?

In my opinion, it is an easy change.

You could follow below steps:

1.Install the package Microsoft.Azure.WebJobs.Extensions.GroupQueueTrigger from Nuget Package manager.

2.Change the program.cs file enable UseGroupQueueTriggers.

3.Change the webjobs functions according to your old triggered function.

Note:The group queue message trigger must use list.

As my code sample shows:

 public static void MyFunction([GroupQueueTrigger("queue3", 10)]List<string> messages)

This function will get 10 messages from the "queue3" one time, so in this function you could change the function loop the list of the messages and   process them, then index them all together into Azure Search.

4.Publish your webjobs to azure web apps.


问:
prototype and TypeScript Angular 2
I have a button bind to  a function calling another function from a different component to open modal form,  passing as parameters  the costumer name and an icon.

Works fine If It´s is called like:

```<code>@Component({
    selector: 'app-customer',
    templateUrl: './customer.component.html',
    providers: [Items]
})

export class Costumers {
    @Input() customerNane

    Constructor() {}

    openDocs() {
         Items.prototype.OpenDocs(this.customerNane, "fa-book")`;
    }
}
</code>```

But, if i have it on the construtor and call it like:

```<code>constructor(private items: Items) {}

 openDocs() {
    this.items.OpenDocs(this.customerNmane, "fa-book")`;
}
</code>```

Parameters wont't bind.

Much obliged for any explanation!

Update.. items.component.ts

```<code>import { Component } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { MainService } from '../services/main.service'

var JQuery = require('jquery');

@Component({
    selector: 'app-items',
    templateUrl: './items.component.html'

})

export class Items {
    public Title: string;
    public faAny: string;

    vTypeList = [

        {
            vIdType: "",
            vDsType: ""
        }
    ]

    constructor(private http: Http, private mainService: MainService) {

    this.GetItemsType();
    }

    GetItemsType() {

        this.http.get('/Items/GetItemsType')
            .subscribe(data => {
                var ObjTp = JSON.parse(data.json());
                for (var i in ObjTp) {
                    if (ObjTp[i] != null) {
                        this.vTypeList.push(ObjTp[i]);
                    }
                }

            });

    }

    OpenDocs(pTitle: string, pFaAny: string) {

        this.Title = pTitle;
        this.faAny = pFaAny;
        JQuery('#docs').modal('show');

    }

    private CloseDocs() {

            JQuery('#docs').css("display", "none");
            JQuery('#docs').modal('hide');

        }

    }
</code>```

and the bind its two way

```<code> <h4 ng-model="Title" ><i class="fa {{faAny}}"></i> Add some list: {{Title}}</h4>
</code>```

答:
Parameters wont't bind.

Use an arrow function. Change

```<code>openDocs() {
    this.items.OpenDocs(this.customerNmane, "fa-book");
}
</code>```

to

```<code>openDocs = () => {
    this.items.OpenDocs(this.customerNmane, "fa-book");
}
</code>```

Why

Cause arrow functions ensure correct this.

More

https://basarat.gitbooks.io/typescript/docs/arrow-functions.html

Title: prototype and TypeScript Angular 2

Body:
I have a button bind to  a function calling another function from a different component to open modal form,  passing as parameters  the costumer name and an icon.

Works fine If It´s is called like:

@Component({
    selector: 'app-customer',
    templateUrl: './customer.component.html',
    providers: [Items]
})

export class Costumers {
    @Input() customerNane

    Constructor() {}

    openDocs() {
         Items.prototype.OpenDocs(this.customerNane, "fa-book")`;
    }
}

But, if i have it on the construtor and call it like:

constructor(private items: Items) {}

 openDocs() {
    this.items.OpenDocs(this.customerNmane, "fa-book")`;
}

Parameters wont't bind.

Much obliged for any explanation!

Update.. items.component.ts

import { Component } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { MainService } from '../services/main.service'

var JQuery = require('jquery');

@Component({
    selector: 'app-items',
    templateUrl: './items.component.html'

})

export class Items {
    public Title: string;
    public faAny: string;

    vTypeList = [

        {
            vIdType: "",
            vDsType: ""
        }
    ]

    constructor(private http: Http, private mainService: MainService) {

    this.GetItemsType();
    }

    GetItemsType() {

        this.http.get('/Items/GetItemsType')
            .subscribe(data => {
                var ObjTp = JSON.parse(data.json());
                for (var i in ObjTp) {
                    if (ObjTp[i] != null) {
                        this.vTypeList.push(ObjTp[i]);
                    }
                }

            });

    }

    OpenDocs(pTitle: string, pFaAny: string) {

        this.Title = pTitle;
        this.faAny = pFaAny;
        JQuery('#docs').modal('show');

    }

    private CloseDocs() {

            JQuery('#docs').css("display", "none");
            JQuery('#docs').modal('hide');

        }

    }

and the bind its two way

 Add some list: {{Title}}

Body:
Parameters wont't bind.

Use an arrow function. Change

openDocs() {
    this.items.OpenDocs(this.customerNmane, "fa-book");
}

to

openDocs = () => {
    this.items.OpenDocs(this.customerNmane, "fa-book");
}

Why

Cause arrow functions ensure correct this.

More

https://basarat.gitbooks.io/typescript/docs/arrow-functions.html


问:
Upgrading Django Version: Best Practice
I've pretty big code base written on Django 1.5, it's about time to upgrade to the newest version (1.11.2) as many stuff don't work well.

I'm wondering if it's best to upgrade step by step: 1.5->1.6->1.7...
or just jump to 1.11.2

what method should be better and make the (hard) process easier? as my project has many dependencies?

Also what are good practices to do? I'm using virtualenv and aware of this Django article about upgrading

答:
I my case about: Data

I am using SQLite and i am sure that, the lastest version can kill you if you have only 1 conflict.

python manage.py makemigrations  and so on had so many chance in it's method.

And if you change Python from 2x to 3x, it is a new case too =))

Title: Upgrading Django Version: Best Practice


问:
Java toString() using reflection?
I was writing a toString() for a class in Java the other day by manually writing out each element of the class to a String and it occurred to me that using reflection it might be possible to create a generic toString() method that could work on ALL classes. I.E. it would figure out the field names and values and send them out to a String.

Getting the field names is fairly simple, here is what a co-worker came up with:

```<code>public static List initFieldArray(String className) throws ClassNotFoundException {

    Class c = Class.forName(className);
    Field field[] = c.getFields();
    List<String> classFields = new ArrayList(field.length);

    for (int i = 0; i < field.length; i++) {
        String cf = field[i].toString();
        classFields.add(cf.substring(cf.lastIndexOf(".") + 1));
    }

    return classFields;
}
</code>```

Using a factory I could reduce the performance overhead by storing the fields once, the first time the toString() is called. However finding the values could be a lot more expensive.

Due to the performance of reflection this may be more hypothetical then practical. But I am interested in the idea of reflection and how I can use it to improve my everyday programming.

答: If you're using Eclipse, you may also have a look at JUtils toString generator, which does it statically (generating the method in your source code).</p>

OwnerDisplayName: nemo

Title: Java toString() using reflection?

Body:
I was writing a toString() for a class in Java the other day by manually writing out each element of the class to a String and it occurred to me that using reflection it might be possible to create a generic toString() method that could work on ALL classes. I.E. it would figure out the field names and values and send them out to a String.

Getting the field names is fairly simple, here is what a co-worker came up with:

public static List initFieldArray(String className) throws ClassNotFoundException {

    Class c = Class.forName(className);
    Field field[] = c.getFields();
    List<String> classFields = new ArrayList(field.length);

    for (int i = 0; i < field.length; i++) {
        String cf = field[i].toString();
        classFields.add(cf.substring(cf.lastIndexOf(".") + 1));
    }

    return classFields;
}

Using a factory I could reduce the performance overhead by storing the fields once, the first time the toString() is called. However finding the values could be a lot more expensive.

Due to the performance of reflection this may be more hypothetical then practical. But I am interested in the idea of reflection and how I can use it to improve my everyday programming.

OwnerDisplayName: Olivier


问:
Durandal JS knockout Deferred updates
I am having an issue when enabling deferred updates in the knockout library. I have implemented Jquery datatables as a component, when navigating to a view that has this component i can see the following methods being called in order.
Getview>Activate>Attach

everything works as expected

But if i press f5 and refresh the page rather than navigating to it from another page it breaks and the following methods are called

Getview>Activate>Attach>Getview>Activate>Attach>Detach>Detach (not sure why its called twice in the end)
and it breaks, no table shows on the UI at all as it does not render from what i can tell, i think it has something to do with durandal transitions and there being a difference between navigating to a page and refreshing a page kinda grasping at straws tho.

This is a minimal class that replicates the problem for me, note i dont have an HTML file for this component i want to use the getView method to pass in some dynamic HTML from JQueryDT

I created a quick sample project with the bare minimum needed to replicate the problem.
https://bitbucket.org/dchosking1988/deferred-update-example

If you pull that and run it you will see that the "hello world" will disappear when you refresh the page but it wont if you navigate between tabs.

the general steps i used to replicate the issue are

1) download sample project

2) add test component (see repo above for the sample file)

3) enable deferred updates

4) disable view caching

4) try compose new instance of the component

Edits to give more info

*This is not a JQuery Datatable problem, it is replicated with the following

So you dont have to download the gitRepo, this is the code i can replicate the problem with in the sample project following the above steps.

```<code>define([],
function () {
    var test = function () {
        var self = this;

        var defaultViewHtml = '<div> <h1>Hello World</h1></div>';
        var currentView = null;

        self.getView = function () {
            console.log('GetView');
            if (!currentView) {
                currentView = $(defaultViewHtml)[0];
            }
            return currentView;
        };

        self.activate = function (activateOptions) {
            console.log('Activate');
        };

        self.attached = function (view, parent, settings) {
            console.log('Attatched');
        };

        self.detached = function (view, parent) {
            console.log('Detatched');
        };
    };

    return test;
});
</code>```

Then Add this HTML to the index.html, also dont forget to create an instance of the class in the index.js

```<code> <div class="whiteRow">
    <div class="container">
        <div class="row">
            <div class="col-md-12">
                <div data-bind="compose: { model: test }"></div>
            </div>
        </div>
    </div>
</div>
</code>```

答:
This is occurred because it call code twice and second called the currentView stay empty in test.js, I commented the stretch where you set the currentView and code work.

```<code>self.getView = function () {
               console.log('GetView');
               //if (!currentView) {
               //    currentView = $(defaultViewHtml)[0];
               //}
               return currentView;
               };
</code>```

-

```<code><div class="whiteRow">
    <div class="container">
        <div class="row">
            <div class="col-md-12">
                <div data-bind="compose: { model: test }"></div>
            </div>
        </div>
    </div>
</div>
</code>```

Title: Durandal JS knockout Deferred updates

Body:
I am having an issue when enabling deferred updates in the knockout library. I have implemented Jquery datatables as a component, when navigating to a view that has this component i can see the following methods being called in order.
Getview>Activate>Attach

everything works as expected

But if i press f5 and refresh the page rather than navigating to it from another page it breaks and the following methods are called

Getview>Activate>Attach>Getview>Activate>Attach>Detach>Detach (not sure why its called twice in the end)
and it breaks, no table shows on the UI at all as it does not render from what i can tell, i think it has something to do with durandal transitions and there being a difference between navigating to a page and refreshing a page kinda grasping at straws tho.

This is a minimal class that replicates the problem for me, note i dont have an HTML file for this component i want to use the getView method to pass in some dynamic HTML from JQueryDT

I created a quick sample project with the bare minimum needed to replicate the problem.
https://bitbucket.org/dchosking1988/deferred-update-example

If you pull that and run it you will see that the "hello world" will disappear when you refresh the page but it wont if you navigate between tabs.

the general steps i used to replicate the issue are

1) download sample project

2) add test component (see repo above for the sample file)

3) enable deferred updates

4) disable view caching

4) try compose new instance of the component

Edits to give more info

*This is not a JQuery Datatable problem, it is replicated with the following

So you dont have to download the gitRepo, this is the code i can replicate the problem with in the sample project following the above steps.

define([],
function () {
    var test = function () {
        var self = this;

        var defaultViewHtml = '

Hello World

';
        var currentView = null;

        self.getView = function () {
            console.log('GetView');
            if (!currentView) {
                currentView = $(defaultViewHtml)[0];
            }
            return currentView;
        };

        self.activate = function (activateOptions) {
            console.log('Activate');
        };

        self.attached = function (view, parent, settings) {
            console.log('Attatched');
        };

        self.detached = function (view, parent) {
            console.log('Detatched');
        };
    };

    return test;
});

Then Add this HTML to the index.html, also dont forget to create an instance of the class in the index.js

Body:
This is occurred because it call code twice and second called the currentView stay empty in test.js, I commented the stretch where you set the currentView and code work.

self.getView = function () {
               console.log('GetView');
               //if (!currentView) {
               //    currentView = $(defaultViewHtml)[0];
               //}
               return currentView;
               };

-

<div class="whiteRow">
    <div class="container">
        <div class="row">
            <div class="col-md-12">
                <div data-bind="compose: { model: test }"></div>
            </div>
        </div>
    </div>
</div>