问:
Stop hanging synchronous method
There is a method HTTP_actions.put_import() in XenAPI, which is synchronous and it supports cancellation via its delegate.

I have the following method:

```<code>private void UploadImage(.., Func<bool> isTaskCancelled)
{
    try
    {
        HTTP_actions.put_import(
            cancellingDelegate: () => isTaskCancelled(),
            ...);
    }
    catch (HTTP.CancelledException exception)
    {
    }
}
</code>```

It so happens that in some cases this method HTTP_actions.put_import hangs and doesn't react to isTaskCancelled(). In that case the whole application also hangs.

I can run this method in a separate thread and kill it forcefully once I receive cancellation signal, but this method doesn't always hang and sometimes I want to gracefully cancel this method. Only when this method is really hanging, I want to kill it myself.

What is the best way to handle such situation?

答:
Here is my final implementation (based on Pranay Rana's answer).</p>

```<code>public class XenImageUploader : IDisposable
{
    public static XenImageUploader Create(Session session, IComponentLogger parentComponentLogger)
    {
        var logger = new ComponentLogger(parentComponentLogger, typeof(XenImageUploader));

        var taskHandler = new XenTaskHandler(
            taskReference: session.RegisterNewTask(UploadTaskName, logger),
            currentSession: session);

        return new XenImageUploader(session, taskHandler, logger);
    }

    private XenImageUploader(Session session, XenTaskHandler xenTaskHandler, IComponentLogger logger)
    {
        _session = session;
        _xenTaskHandler = xenTaskHandler;
        _logger = logger;

        _imageUploadingHasFinishedEvent = new AutoResetEvent(initialState: false);

        _xenApiUploadCancellationReactionTime = new TimeSpan();
    }

    public Maybe<string> Upload(
        string imageFilePath,
        XenStorage destinationStorage,
        ProgressToken progressToken,
        JobCancellationToken cancellationToken)
    {
        _logger.WriteDebug("Image uploading has started.");

        var imageUploadingThread = new Thread(() =>
            UploadImageOfVirtualMachine(
                imageFilePath: imageFilePath,
                storageReference: destinationStorage.GetReference(),
                isTaskCancelled: () => cancellationToken.IsCancellationRequested));

        imageUploadingThread.Start();

        using (new Timer(
            callback: _ => WatchForImageUploadingState(imageUploadingThread, progressToken, cancellationToken),
            state: null,
            dueTime: TimeSpan.Zero,
            period: TaskStatusUpdateTime))
        {
            _imageUploadingHasFinishedEvent.WaitOne(MaxTimeToUploadSvm);
        }

        cancellationToken.PerformCancellationIfRequested();

        return _xenTaskHandler.TaskIsSucceded
            ? new Maybe<string>(((string) _xenTaskHandler.Result).GetOpaqueReferenceFromResult())
            : new Maybe<string>();
    }

    public void Dispose()
    {
        _imageUploadingHasFinishedEvent.Dispose();
    }

    private void UploadImageOfVirtualMachine(string imageFilePath, XenRef<SR> storageReference, Func<bool> isTaskCancelled)
    {
        try
        {
            _logger.WriteDebug("Uploading thread has started.");

            HTTP_actions.put_import(
                progressDelegate: progress => { },
                cancellingDelegate: () => isTaskCancelled(),
                timeout_ms: -1,
                hostname: new Uri(_session.Url).Host,
                proxy: null,
                path: imageFilePath,
                task_id: _xenTaskHandler.TaskReference,
                session_id: _session.uuid,
                restore: false,
                force: false,
                sr_id: storageReference);

            _xenTaskHandler.WaitCompletion();

            _logger.WriteDebug("Uploading thread has finished.");
        }
        catch (HTTP.CancelledException exception)
        {
            _logger.WriteInfo("Image uploading has been cancelled.");
            _logger.WriteInfo(exception.ToDetailedString());
        }

        _imageUploadingHasFinishedEvent.Set();
    }

    private void WatchForImageUploadingState(Thread imageUploadingThread, ProgressToken progressToken, JobCancellationToken cancellationToken)
    {
        progressToken.Progress = _xenTaskHandler.Progress;

        if (!cancellationToken.IsCancellationRequested)
        {
            return;
        }

        _xenApiUploadCancellationReactionTime += TaskStatusUpdateTime;

        if (_xenApiUploadCancellationReactionTime >= TimeForXenApiToReactOnCancel)
        {
            _logger.WriteWarning($"XenApi didn't cancel for {_xenApiUploadCancellationReactionTime}.");

            if (imageUploadingThread.IsAlive)
            {
                try
                {
                    _logger.WriteWarning("Trying to forcefully abort uploading thread.");

                    imageUploadingThread.Abort();
                }
                catch (Exception exception)
                {
                    _logger.WriteError(exception.ToDetailedString());
                }
            }

            _imageUploadingHasFinishedEvent.Set();
        }
    }

    private const string UploadTaskName = "Xen image uploading";

    private static readonly TimeSpan TaskStatusUpdateTime = TimeSpan.FromSeconds(1);
    private static readonly TimeSpan TimeForXenApiToReactOnCancel = TimeSpan.FromSeconds(10);
    private static readonly TimeSpan MaxTimeToUploadSvm = TimeSpan.FromMinutes(20);

    private readonly Session _session;
    private readonly XenTaskHandler _xenTaskHandler;
    private readonly IComponentLogger _logger;

    private readonly AutoResetEvent _imageUploadingHasFinishedEvent;

    private TimeSpan _xenApiUploadCancellationReactionTime;
}
</code>```

Title: Stop hanging synchronous method

Body:
There is a method HTTP_actions.put_import() in XenAPI, which is synchronous and it supports cancellation via its delegate.

I have the following method:

private void UploadImage(.., Func<bool> isTaskCancelled)
{
    try
    {
        HTTP_actions.put_import(
            cancellingDelegate: () => isTaskCancelled(),
            ...);
    }
    catch (HTTP.CancelledException exception)
    {
    }
}

It so happens that in some cases this method HTTP_actions.put_import hangs and doesn't react to isTaskCancelled(). In that case the whole application also hangs.

I can run this method in a separate thread and kill it forcefully once I receive cancellation signal, but this method doesn't always hang and sometimes I want to gracefully cancel this method. Only when this method is really hanging, I want to kill it myself.

What is the best way to handle such situation?

Body:
Here is my final implementation (based on Pranay Rana's answer).

public class XenImageUploader : IDisposable
{
    public static XenImageUploader Create(Session session, IComponentLogger parentComponentLogger)
    {
        var logger = new ComponentLogger(parentComponentLogger, typeof(XenImageUploader));

        var taskHandler = new XenTaskHandler(
            taskReference: session.RegisterNewTask(UploadTaskName, logger),
            currentSession: session);

        return new XenImageUploader(session, taskHandler, logger);
    }

    private XenImageUploader(Session session, XenTaskHandler xenTaskHandler, IComponentLogger logger)
    {
        _session = session;
        _xenTaskHandler = xenTaskHandler;
        _logger = logger;

        _imageUploadingHasFinishedEvent = new AutoResetEvent(initialState: false);

        _xenApiUploadCancellationReactionTime = new TimeSpan();
    }

    public Maybe<string> Upload(
        string imageFilePath,
        XenStorage destinationStorage,
        ProgressToken progressToken,
        JobCancellationToken cancellationToken)
    {
        _logger.WriteDebug("Image uploading has started.");

        var imageUploadingThread = new Thread(() =>
            UploadImageOfVirtualMachine(
                imageFilePath: imageFilePath,
                storageReference: destinationStorage.GetReference(),
                isTaskCancelled: () => cancellationToken.IsCancellationRequested));

        imageUploadingThread.Start();

        using (new Timer(
            callback: _ => WatchForImageUploadingState(imageUploadingThread, progressToken, cancellationToken),
            state: null,
            dueTime: TimeSpan.Zero,
            period: TaskStatusUpdateTime))
        {
            _imageUploadingHasFinishedEvent.WaitOne(MaxTimeToUploadSvm);
        }

        cancellationToken.PerformCancellationIfRequested();

        return _xenTaskHandler.TaskIsSucceded
            ? new Maybe<string>(((string) _xenTaskHandler.Result).GetOpaqueReferenceFromResult())
            : new Maybe<string>();
    }

    public void Dispose()
    {
        _imageUploadingHasFinishedEvent.Dispose();
    }

    private void UploadImageOfVirtualMachine(string imageFilePath, XenRef<SR> storageReference, Func<bool> isTaskCancelled)
    {
        try
        {
            _logger.WriteDebug("Uploading thread has started.");

            HTTP_actions.put_import(
                progressDelegate: progress => { },
                cancellingDelegate: () => isTaskCancelled(),
                timeout_ms: -1,
                hostname: new Uri(_session.Url).Host,
                proxy: null,
                path: imageFilePath,
                task_id: _xenTaskHandler.TaskReference,
                session_id: _session.uuid,
                restore: false,
                force: false,
                sr_id: storageReference);

            _xenTaskHandler.WaitCompletion();

            _logger.WriteDebug("Uploading thread has finished.");
        }
        catch (HTTP.CancelledException exception)
        {
            _logger.WriteInfo("Image uploading has been cancelled.");
            _logger.WriteInfo(exception.ToDetailedString());
        }

        _imageUploadingHasFinishedEvent.Set();
    }

    private void WatchForImageUploadingState(Thread imageUploadingThread, ProgressToken progressToken, JobCancellationToken cancellationToken)
    {
        progressToken.Progress = _xenTaskHandler.Progress;

        if (!cancellationToken.IsCancellationRequested)
        {
            return;
        }

        _xenApiUploadCancellationReactionTime += TaskStatusUpdateTime;

        if (_xenApiUploadCancellationReactionTime >= TimeForXenApiToReactOnCancel)
        {
            _logger.WriteWarning($"XenApi didn't cancel for {_xenApiUploadCancellationReactionTime}.");

            if (imageUploadingThread.IsAlive)
            {
                try
                {
                    _logger.WriteWarning("Trying to forcefully abort uploading thread.");

                    imageUploadingThread.Abort();
                }
                catch (Exception exception)
                {
                    _logger.WriteError(exception.ToDetailedString());
                }
            }

            _imageUploadingHasFinishedEvent.Set();
        }
    }

    private const string UploadTaskName = "Xen image uploading";

    private static readonly TimeSpan TaskStatusUpdateTime = TimeSpan.FromSeconds(1);
    private static readonly TimeSpan TimeForXenApiToReactOnCancel = TimeSpan.FromSeconds(10);
    private static readonly TimeSpan MaxTimeToUploadSvm = TimeSpan.FromMinutes(20);

    private readonly Session _session;
    private readonly XenTaskHandler _xenTaskHandler;
    private readonly IComponentLogger _logger;

    private readonly AutoResetEvent _imageUploadingHasFinishedEvent;

    private TimeSpan _xenApiUploadCancellationReactionTime;
}


来源: stackexchange

问:
Insert JSON data to database in Angularjs
Im working on a form which has a dynamic generated fields. My problem is I cant insert data from those generated fields. I tried this thread How to insert json array into mysql database but Its not working for me.

I tried to populate the data when transferred to PHP but got no luck.

DB Connection

```<code><?php
class DbConfig
{
    private $_host = 'localhost';
    private $_username = 'root';
    private $_password = '';
    private $_database = 'machines';

    protected $connection;

    public function __construct()
    {
        if (!isset($this->connection)) {

            $this->connection = new mysqli($this->_host, $this->_username, $this->_password, $this->_database);

            if (!$this->connection) {
                echo 'Cannot connect to database server';
                exit;
            }
        }

        return $this->connection;
    }
}
?>
</code>```

JSON data

```<code>    $scope.columns = [
{"id":1,"brand":"robotworx","tonnage":"200","tableSize":"20x50","pressType":"Kiss Cutting"},
{"id":2,"brand":"fanuc","tonnage":"100","tableSize":"30x60","pressType":"Swing Arm"}

];
</code>```

Controller

```<code>$scope.register=function(){
    $http.post("http://localhost/clickermag/controller/register.php", {
    'company':$scope.company,
    'email':$scope.email,
    'phone':$scope.phone,
    'position':$scope.position,
    'firstName':$scope.firstName,
    'lastName':$scope.lastName,
    'presses':$scope.columns
  })

    .then(function(response){
                    console.log("Data Inserted Successfully");
                },function(error){
                    alert("Sorry! Data Couldn't be inserted!");
                    console.error(error);

                });
        }
</code>```

PHP file

```<code><?php
$data = json_decode(file_get_contents("php://input"));

//including the database connection file
include_once("../classes/Crud.php");

$crud = new Crud();

$company = $data->company;
$email = $data->email;
$phone = $data->phone;
$position = $data->position;
$firstName = $data->firstName;
$lastName = $data->lastName;
$ownedPress = $data->presses;

        //insert data to database
$result = $crud->execute("INSERT INTO users(company, email, phone, position, first_name, last_name) VALUES('$company','$email','$phone','$password','$position','$firstName','$lastName')");

$last_id = $crud->user_id;

foreach($data as $item) {
       $pressesQuery = $crud->execute("INSERT INTO owned_presses(user_id, brand, tonnage, table_size, press_type) VALUES ('$last_id','$item[brand]','$item[tonnage]','$item[tableSize]','$item[pressType]')");
     }

?>
</code>```

I need to put the data from the generated fields to the second query.

答:
First things first, SQL Injection.

Now,

```<code>foreach($data as $item) {
</code>```

Why are you looping through $data, shouldn't you be looping through $ownedPress?

And, I'm not sure how Crud.php is implemented, but I'd assume it'd be:

```<code>$last_id = $result->user_id;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Im working on a form which has a dynamic generated fields. My problem is I cant insert data from those generated fields. I tried this thread How to insert json array into mysql database but Its not working for me.

I tried to populate the data when transferred to PHP but got no luck.

DB Connection

<?php
class DbConfig
{
    private $_host = 'localhost';
    private $_username = 'root';
    private $_password = '';
    private $_database = 'machines';

    protected $connection;

    public function __construct()
    {
        if (!isset($this->connection)) {

            $this->connection = new mysqli($this->_host, $this->_username, $this->_password, $this->_database);

            if (!$this->connection) {
                echo 'Cannot connect to database server';
                exit;
            }
        }

        return $this->connection;
    }
}
?>

JSON data

    $scope.columns = [
{"id":1,"brand":"robotworx","tonnage":"200","tableSize":"20x50","pressType":"Kiss Cutting"},
{"id":2,"brand":"fanuc","tonnage":"100","tableSize":"30x60","pressType":"Swing Arm"}

];

Controller

$scope.register=function(){
    $http.post("http://localhost/clickermag/controller/register.php", {
    'company':$scope.company,
    'email':$scope.email,
    'phone':$scope.phone,
    'position':$scope.position,
    'firstName':$scope.firstName,
    'lastName':$scope.lastName,
    'presses':$scope.columns
  })

    .then(function(response){
                    console.log("Data Inserted Successfully");
                },function(error){
                    alert("Sorry! Data Couldn't be inserted!");
                    console.error(error);

                });
        }

PHP file

<?php
$data = json_decode(file_get_contents("php://input"));

//including the database connection file
include_once("../classes/Crud.php");

$crud = new Crud();

$company = $data->company;
$email = $data->email;
$phone = $data->phone;
$position = $data->position;
$firstName = $data->firstName;
$lastName = $data->lastName;
$ownedPress = $data->presses;

        //insert data to database
$result = $crud->execute("INSERT INTO users(company, email, phone, position, first_name, last_name) VALUES('$company','$email','$phone','$password','$position','$firstName','$lastName')");

$last_id = $crud->user_id;

foreach($data as $item) {
       $pressesQuery = $crud->execute("INSERT INTO owned_presses(user_id, brand, tonnage, table_size, press_type) VALUES ('$last_id','$item[brand]','$item[tonnage]','$item[tableSize]','$item[pressType]')");
     }

?>

I need to put the data from the generated fields to the second query.

Body:
First things first, SQL Injection.

Now,

foreach($data as $item) {

Why are you looping through $data, shouldn't you be looping through $ownedPress?

And, I'm not sure how Crud.php is implemented, but I'd assume it'd be:

$last_id = $result->user_id;


问:
How to use ViewStub in ConstraintLayout?
It seems that when inflating a ViewStub in a ConstraintLayout, the resulting view has lost all its constraints. I guess we can define the constraints for the inflated view using ConstraintSet, but that kind of defeats the purpose of ViewStub.

Is there a good way to do this?

答:
There's a simple solution:

in your ViewStub let the inflatedId attribute  as the same as id

like this:

```<code><ViewStub
    android:id="@+id/pocket_view"
    android:inflatedId="@+id/pocket_view"
    android:layout="@layout/game_pocket_view"
    android:layout_width="@dimen/game_pocket_max_width"
    android:layout_height="@dimen/game_pocket_max_height"
    app:layout_constraintLeft_toLeftOf="@id/avatar_view"
    app:layout_constraintRight_toRightOf="@id/avatar_view"
    app:layout_constraintTop_toTopOf="@id/avatar_view"
    app:layout_constraintBottom_toBottomOf="@id/avatar_view"
    />
</code>```

Body:
There's a simple solution:

in your ViewStub let the inflatedId attribute  as the same as id

like this:

<ViewStub
    android:id="@+id/pocket_view"
    android:inflatedId="@+id/pocket_view"
    android:layout="@layout/game_pocket_view"
    android:layout_width="@dimen/game_pocket_max_width"
    android:layout_height="@dimen/game_pocket_max_height"
    app:layout_constraintLeft_toLeftOf="@id/avatar_view"
    app:layout_constraintRight_toRightOf="@id/avatar_view"
    app:layout_constraintTop_toTopOf="@id/avatar_view"
    app:layout_constraintBottom_toBottomOf="@id/avatar_view"
    />


问:
Does code in methods always get executed?
I have created the implementation of a abstract method of the super class. Does the code in the method always get executed or is there some kind of cache that knows the code will never change?

I want to know if there are performance issues with my code. Is it better to create the map as a member variable and then return it in the method?

```<code>@Override
protected Map<String, Function<Information, String>> getDefinitionMap() {
    final Map<String, Function<Information, String>> map = new LinkedHashMap<>();
    map.put("Name", t -> t.getName());
    map.put("ID", t -> t.getId());
    return map;
}
</code>```

答:
Each time the method getDefinitionMap() is called, a new LinkedHashMap instance is created. There is no "implicit caching".

You can avoid that, if you create the map once, store it in a member variable and return this. You may want to make it unmodifiable so that it cannot be changed by callers. (see java.util.Collections.unmodifiableMap)

Body:
I have created the implementation of a abstract method of the super class. Does the code in the method always get executed or is there some kind of cache that knows the code will never change?

I want to know if there are performance issues with my code. Is it better to create the map as a member variable and then return it in the method?

@Override
protected Map<String, Function<Information, String>> getDefinitionMap() {
    final Map<String, Function<Information, String>> map = new LinkedHashMap<>();
    map.put("Name", t -> t.getName());
    map.put("ID", t -> t.getId());
    return map;
}


问:
regex to match passwords that are greater than 5 characters long and have two consecutive digits
Here's what I have, can someone please tell me where I am wrong?

let sampleWord = "bana12";
let pwRegex = /(?=\w{5})(?=\d{2,})/; // Change this line
let result = pwRegex.test(sampleWord);
console.log(result);```

It works for passwords that contain only letters or only numbers, but not for both.

答:
Use .* before \d{2} since the consecutive digits may occur anywhere in the string. Your current regex should check for two digits to be present at very first.

let sampleWord = "bana12";
let pwRegex = /^(?=\w{5})(?=.*\d{2,})/; // Change this line
console.log( pwRegex.test(sampleWord))```
</div>
</div>
</p>

<p>Note that <code>\w</code> matches only the word characters, so your regex fails if there input string contain 5 non-word characters. So for checking the string length, it's better to use <code>.</code> instead of <code>\w</code>.  </p>

```let pwRegex = /^(?=.{5})(?=.*\d{2,})/;
```

Body:
Here's what I have, can someone please tell me where I am wrong?

let sampleWord = "bana12";
let pwRegex = /(?=\w{5})(?=\d{2,})/; // Change this line
let result = pwRegex.test(sampleWord);
console.log(result);

It works for passwords that contain only letters or only numbers, but not for both.

Body:
Use .* before \d{2} since the consecutive digits may occur anywhere in the string. Your current regex should check for two digits to be present at very first.

let sampleWord = "bana12";
let pwRegex = /^(?=\w{5})(?=.*\d{2,})/; // Change this line
console.log( pwRegex.test(sampleWord))

Note that \w matches only the word characters, so your regex fails if there input string contain 5 non-word characters. So for checking the string length, it's better to use . instead of \w.

let pwRegex = /^(?=.{5})(?=.*\d{2,})/;


问:
iOS changing target name
In iOS project, I changed the target name.
But for building, on the top left (beside stop button), its still showing old target name only... What should I change so that old project name will completely disappear from XCode?</p>

答: Select your target from TARGETS(in left navigation bar) and double click, then rename it.

Title: iOS changing target name


问:
Configuring ALE plugin with Pylint
I'm using ALE with Pylint and pylint-django, but I'm not able to configure it. It shows a linter warning while browsing any file within a Django project:

```<code>no-member: User class has no member objects for below code.
</code>```

on code like the following:

```<code>from django.contrib.auth.models import User

user_list = User.objects.all()
</code>```

答:
After some research I found the solution. If you have installed everything correctly including w0rp's ale, pylint & pylint-django. In your vimrc add the following line & have fun developing web apps using django.
Thanks.

```<code>let g:ale_python_pylint_options = '--load-plugins pylint_django'
</code>```

Title: Configuring ALE plugin with Pylint

Body:
I'm using ALE with Pylint and pylint-django, but I'm not able to configure it. It shows a linter warning while browsing any file within a Django project:

no-member: User class has no member objects for below code.

on code like the following:

from django.contrib.auth.models import User

user_list = User.objects.all()

Body:
After some research I found the solution. If you have installed everything correctly including w0rp's ale, pylint & pylint-django. In your vimrc add the following line & have fun developing web apps using django.
Thanks.

let g:ale_python_pylint_options = '--load-plugins pylint_django'


问:
Comparing integer in int array to a user provided integer
I have a two dimensional array, gridArray[5][7], populated with numbers (only the last row is populated with anything other than 0). I'm taking user input for a column and color, converting the color to a number representation, and then checking it against the rows in the array. If it's in the column the user enters, it should print "Your guess was correct". Instead, it seems to print "Your guess was incorrect", even if the guess was correct. I checked the boolean values, and it's returning false when it should be returning true. I can't figure out why. Here's my code:

```<code>public static void main(String[] args) {
        int[][] gridArray = new int[7][5];

        gridPop(gridArray);

        playFunc(gridArray);

    }

public static void playFunc(int[][] gridArray) {
    char colorGuess = 'N';
    int columnGuess = -1;
    String columnString = "a column to guess";
    boolean correctIncorrectGuess = false;

    System.out.println("Please enter a color to guess (R/B/P/Y/G)");
        colorGuess = charCheck();
            System.out.println("Please enter a column to guess");
            System.out.println("The column # must be between 1 and 5");
                columnGuess = intChecker(columnString);
                    correctIncorrectGuess = checkHat(gridArray, charReturn(colorGuess), columnGuess);
            System.out.println("Your guess was " + boolCorrectString(correctIncorrectGuess));
}

public static boolean checkHat(int[][] gridArray, int color, int column){
    boolean guess = false;
    for (int i = 0; i < gridArray.length; i++) {
        if (gridArray[i][column] == color) {
            guess = true;
        } else {
            guess = false;
        }
    }
    return guess;
}

public static int intChecker(String object) {
    boolean correctInput = false;
    int userInput = 0;

    while (!correctInput) {
        try {
            userInput = scanner.nextInt();
            correctInput = true;
        } catch(InputMismatchException e) {
            System.out.println("I'm sorry, that doesn't seem to be a number");
            System.out.println("Please enter " +object);
            scanner.next();
        }
    }

    return userInput;
}

public static String boolCorrectString(boolean toString) {
    String correctInc = "";
        if (toString) {
            correctInc = "correct";
        } else {
            correctInc = "incorrect";
        }
        return correctInc;
}

public static int charReturn(char color) {
    int colorToInt = -1;
        if (color == 'G') {
            colorToInt =  1;
        } else if (color == 'R') {
            colorToInt =  2;
        } else if (color == 'B') {
            colorToInt =  3;
        } else if (color == 'P') {
            colorToInt =  4;
        } else if (color == 'Y') {
            colorToInt =  5;
        } else if (color == 'g') {
            colorToInt =  1;
        } else if (color == 'r') {
            colorToInt =  2;
        } else if (color == 'b') {
            colorToInt =  3;
        } else if (color == 'p') {
            colorToInt =  4;
        } else if (color == 'y') {
            colorToInt =  5;
        }
return colorToInt;
}

    public static char charCheck() {
        char userInput = 'N';

        userInput =  scanner.next().charAt(0);
            while((userInput != 'G') && (userInput != 'Y') && (userInput != 'B')
            && (userInput != 'R') && (userInput != 'P') && (userInput != 'g') &&
            (userInput != 'y') && (userInput != 'b') && (userInput != 'r') && (userInput != 'p')) {
                System.out.println("Please enter R/B/P/Y/G");
                    userInput =  scanner.next().charAt(0);
            }
            return userInput;
    }
</code>```

I did some testing, and it's gathering the right numbers for the column, the representation of the color, etc. It seems that even when gridArray[i][column] should be the same as the guessed color, the boolean is being returned as false (I tested and it isnt printing incorrectly -- it's actually finding false when it should be true). Why isn't the code comparing the gridArray entry and the color guess correctly? Where does the code break down?

EDIT:
Gridpop method

```<code>public static void gridPop(int[][] gridArray) {
    for (int i=0; i < gridArray[6].length; i++) {
        int randomNum = ThreadLocalRandom.current().nextInt(1, 6);
            gridArray[6][i] = randomNum;
    }
    for (int i=5; i >= 0; i--) {
        for (int j=0; j < gridArray[i].length; j++) {
            gridArray[i][j] = 0;
        }
    }
}
</code>```

EDIT: I'm actually very very dumb. It was an off by one error, as it was checking at the user entered column, not the user entered column -1

答: Put a break after guess = true; and initialize int[][] gridArray with appropriate values; by default this array has zero in all its indexes. Here you are comparing zero with the color's value which is non-zero. so it will always be false.

Body:
I have a two dimensional array, gridArray[5][7], populated with numbers (only the last row is populated with anything other than 0). I'm taking user input for a column and color, converting the color to a number representation, and then checking it against the rows in the array. If it's in the column the user enters, it should print "Your guess was correct". Instead, it seems to print "Your guess was incorrect", even if the guess was correct. I checked the boolean values, and it's returning false when it should be returning true. I can't figure out why. Here's my code:

public static void main(String[] args) {
        int[][] gridArray = new int[7][5];

        gridPop(gridArray);

        playFunc(gridArray);

    }

public static void playFunc(int[][] gridArray) {
    char colorGuess = 'N';
    int columnGuess = -1;
    String columnString = "a column to guess";
    boolean correctIncorrectGuess = false;

    System.out.println("Please enter a color to guess (R/B/P/Y/G)");
        colorGuess = charCheck();
            System.out.println("Please enter a column to guess");
            System.out.println("The column # must be between 1 and 5");
                columnGuess = intChecker(columnString);
                    correctIncorrectGuess = checkHat(gridArray, charReturn(colorGuess), columnGuess);
            System.out.println("Your guess was " + boolCorrectString(correctIncorrectGuess));
}

public static boolean checkHat(int[][] gridArray, int color, int column){
    boolean guess = false;
    for (int i = 0; i < gridArray.length; i++) {
        if (gridArray[i][column] == color) {
            guess = true;
        } else {
            guess = false;
        }
    }
    return guess;
}

public static int intChecker(String object) {
    boolean correctInput = false;
    int userInput = 0;

    while (!correctInput) {
        try {
            userInput = scanner.nextInt();
            correctInput = true;
        } catch(InputMismatchException e) {
            System.out.println("I'm sorry, that doesn't seem to be a number");
            System.out.println("Please enter " +object);
            scanner.next();
        }
    }

    return userInput;
}

public static String boolCorrectString(boolean toString) {
    String correctInc = "";
        if (toString) {
            correctInc = "correct";
        } else {
            correctInc = "incorrect";
        }
        return correctInc;
}

public static int charReturn(char color) {
    int colorToInt = -1;
        if (color == 'G') {
            colorToInt =  1;
        } else if (color == 'R') {
            colorToInt =  2;
        } else if (color == 'B') {
            colorToInt =  3;
        } else if (color == 'P') {
            colorToInt =  4;
        } else if (color == 'Y') {
            colorToInt =  5;
        } else if (color == 'g') {
            colorToInt =  1;
        } else if (color == 'r') {
            colorToInt =  2;
        } else if (color == 'b') {
            colorToInt =  3;
        } else if (color == 'p') {
            colorToInt =  4;
        } else if (color == 'y') {
            colorToInt =  5;
        }
return colorToInt;
}

    public static char charCheck() {
        char userInput = 'N';

        userInput =  scanner.next().charAt(0);
            while((userInput != 'G') && (userInput != 'Y') && (userInput != 'B')
            && (userInput != 'R') && (userInput != 'P') && (userInput != 'g') &&
            (userInput != 'y') && (userInput != 'b') && (userInput != 'r') && (userInput != 'p')) {
                System.out.println("Please enter R/B/P/Y/G");
                    userInput =  scanner.next().charAt(0);
            }
            return userInput;
    }

I did some testing, and it's gathering the right numbers for the column, the representation of the color, etc. It seems that even when gridArray[i][column] should be the same as the guessed color, the boolean is being returned as false (I tested and it isnt printing incorrectly -- it's actually finding false when it should be true). Why isn't the code comparing the gridArray entry and the color guess correctly? Where does the code break down?

EDIT:
Gridpop method

public static void gridPop(int[][] gridArray) {
    for (int i=0; i < gridArray[6].length; i++) {
        int randomNum = ThreadLocalRandom.current().nextInt(1, 6);
            gridArray[6][i] = randomNum;
    }
    for (int i=5; i >= 0; i--) {
        for (int j=0; j < gridArray[i].length; j++) {
            gridArray[i][j] = 0;
        }
    }
}

EDIT: I'm actually very very dumb. It was an off by one error, as it was checking at the user entered column, not the user entered column -1


问:
Regex: Match up to character, abort if contains word
I have a document like

```<code>@ManyToOne
@JoinColumn(name = "p_id_1", referencedColumnName = "id", insertable=false, updateable = false)

@ManyToOne
@JoinColumn(name = "p_id_2", referencedColumnName = "id")
</code>```

I am trying to design a regex that matches from @ManyToOne to ) (excluded) but does not match if the line contains , insertable

After trying around I ended up with @ManyToOne\n.+?(?=, insertable|\)) but this also matches a part of the first lines. What I want it to do is not matching the first two lines and the second two lines only up to the )

As a sidenote: I am using it in a Gradle-Build-Script written in Groovy.

答:
I'd use negative lookarounds to make sure the match breaks on encountering , insertable, and a positive lookahead to exclude the closing bracket, something like:

```<code>@ManyToOne\n((?!, insertable).)*?(?=\))
</code>```

Body:
I have a document like

@ManyToOne
@JoinColumn(name = "p_id_1", referencedColumnName = "id", insertable=false, updateable = false)

@ManyToOne
@JoinColumn(name = "p_id_2", referencedColumnName = "id")

I am trying to design a regex that matches from @ManyToOne to ) (excluded) but does not match if the line contains , insertable

After trying around I ended up with @ManyToOne\n.+?(?=, insertable|\)) but this also matches a part of the first lines. What I want it to do is not matching the first two lines and the second two lines only up to the )

As a sidenote: I am using it in a Gradle-Build-Script written in Groovy.

Body:
I'd use negative lookarounds to make sure the match breaks on encountering , insertable, and a positive lookahead to exclude the closing bracket, something like:

@ManyToOne\n((?!, insertable).)*?(?=\))


问:
I have tried to Get info about redis queue like used_memory
I am trying to calculate metrics for a redis queue in c# using stackexchange.redis.

I need Info like used_memory.....etc

In redis.exe,Just INFO command gives all information..

How to get INFO details in c# using stackexchange.redis.

答: use command INFO  Memory to show memory info only


问:
After getting table results Want to display same as in the UI side as like image attached
SELECT left([Action],CHARINDEX(':',[Action])-1)As Heading,RIGHT([Action],LEN([Action])-CHARINDEX(':',[Action])-1)as Category, Currency, UnitRate, UnitOfMeasure, ChargeAmount, Quantity,istotal_indicator

        FROM (

         SELECT AttributeName

          ,attributevalue , [Action] ,t2.istotal_indicator

         from tbl_ss_orderitems_IC t1 join
       Tbl_ECC_breakdowns t2

```<code>    on t1.[Action]= t2.ECC_Charge_Actiontype
     WHERE AttributeName IN (
       'ChargeAmount'
       ,'Currency'
       ,'Quantity'
       ,'UnitOfMeasure'
       ,'UnitRate'

       )
      --AND [Action] like '%::%'  AND workitemid = 'OS01EWDF00Test_1234'
     ) AS A
    PIVOT
    (
    MAX(AttributeValue)
    FOR AttributeName IN (
       ChargeAmount
       ,Currency
       ,Quantity
       ,UnitOfMeasure
       ,UnitRate
       )
     ) AS PIVOT_1
</code>```

After excute the query get Table Results data

want to Display same like  In UI side using the result table data records

答: after execute query you have to store result data in an array then using foreach loop you can show row in table format one by one.</p>

Body:
SELECT left([Action],CHARINDEX(':',[Action])-1)As Heading,RIGHT([Action],LEN([Action])-CHARINDEX(':',[Action])-1)as Category, Currency, UnitRate, UnitOfMeasure, ChargeAmount, Quantity,istotal_indicator

        FROM (

         SELECT AttributeName

          ,attributevalue , [Action] ,t2.istotal_indicator

         from tbl_ss_orderitems_IC t1 join
       Tbl_ECC_breakdowns t2

    on t1.[Action]= t2.ECC_Charge_Actiontype
     WHERE AttributeName IN (
       'ChargeAmount'
       ,'Currency'
       ,'Quantity'
       ,'UnitOfMeasure'
       ,'UnitRate'

       )
      --AND [Action] like '%::%'  AND workitemid = 'OS01EWDF00Test_1234'
     ) AS A
    PIVOT
    (
    MAX(AttributeValue)
    FOR AttributeName IN (
       ChargeAmount
       ,Currency
       ,Quantity
       ,UnitOfMeasure
       ,UnitRate
       )
     ) AS PIVOT_1

After excute the query get Table Results data

want to Display same like  In UI side using the result table data records


问:
Django Rest Framework: How to pass extra argument to django serializer?
I have a variable named email in view.

I want to access this in ManageSerializer.

How can I pass this argument in serializer and get there?

views.py

```<code>email = 'xyz@gmail.com'
interviewData = Manage.objects.
    filter(catcher_id = userCheck['id'], acceptation = '1').
    filter(invitation_date__gte = dateToday)[:5];
serializer = ManageSerializers(interviewData, many = True)
</code>```

答:
You should pass it in context variable:

```<code>serializer = ManageSerializers(interviewData, many=True, context={'email': email})
</code>```

Docs: Including extra context

Body:
I have a variable named email in view.

I want to access this in ManageSerializer.

How can I pass this argument in serializer and get there?

views.py

email = 'xyz@gmail.com'
interviewData = Manage.objects.
    filter(catcher_id = userCheck['id'], acceptation = '1').
    filter(invitation_date__gte = dateToday)[:5];
serializer = ManageSerializers(interviewData, many = True)

Body:
You should pass it in context variable:

serializer = ManageSerializers(interviewData, many=True, context={'email': email})

Docs: Including extra context


问:
Burger button not centering on navigation bar?
This is my code.

<!DOCTYPE HTML>

        <title>Personal Portfolio</title>
            <meta name="viewport" content="width=device-width, initial-scale=1">

            <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

        <!- Navbar-->

            <button class="navbar-toggler navbar-toggler-right my-sm-0" type="button" data-toggle="collapse" data-target="#mainNav" aria-controls="mainNav" aria-expanded="false" aria-label="Toggle navigation">

            </button>

                        About

                        Portfolio

                        Contact

```

When the window is full size, all the links are center aligned.But when I make the window smaller, the burger icon does not align to the center of the navbar. How do I resolve this?

答:
If you change your CSS from:

```<code>.navbar-toggler-right {
right : 2rem
</code>```

}

to:

```<code>.navbar-toggler-right {
position: absolute;
right: 18rem;
left: 18rem;
top: 3px;
</code>```

}

it will center.

Body:
This is my code.

<!DOCTYPE HTML>

        <title>Personal Portfolio</title>
            <meta name="viewport" content="width=device-width, initial-scale=1">

            <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

        <!- Navbar-->

            <button class="navbar-toggler navbar-toggler-right my-sm-0" type="button" data-toggle="collapse" data-target="#mainNav" aria-controls="mainNav" aria-expanded="false" aria-label="Toggle navigation">

            </button>

                        About

                        Portfolio

                        Contact

When the window is full size, all the links are center aligned.But when I make the window smaller, the burger icon does not align to the center of the navbar. How do I resolve this?

Body:
If you change your CSS from:

.navbar-toggler-right {
right : 2rem

}

to:

.navbar-toggler-right {
position: absolute;
right: 18rem;
left: 18rem;
top: 3px;

}

it will center.


问:
Rails self and association
I have a car and user model.

```<code>User.rb
has_many :cars

Car.rb
belongs_to :user
</code>```

I would like to validate model field in the car model only if its user has mdk_id not nil.

This is how I create car model,

```<code>user = User.where(mdk_id: b["companyid"]).first

car = user.cars.build
</code>```

Then in Car.rb model, I would like to validate model field.

I tried;

```<code>  validates :model if self.user.mdk_id != nil
</code>```

But it gives error;

```<code>undefined method `user' for #<Class:0x007f973a321a58>
</code>```

How can I reference that ?

答:
You can do like these in Car.rb</p>

```<code>validate :validate_user, on: [:create, :update]

def validate_user
  if self.user.mdk_id == nil
    #display error message here
    #such as User's mdk_id cannot be null etc.
  end
end
</code>```

Title: Rails self and association

Body:
I have a car and user model.

User.rb
has_many :cars

Car.rb
belongs_to :user

I would like to validate model field in the car model only if its user has mdk_id not nil.

This is how I create car model,

user = User.where(mdk_id: b["companyid"]).first

car = user.cars.build

Then in Car.rb model, I would like to validate model field.

I tried;

  validates :model if self.user.mdk_id != nil

But it gives error;

undefined method `user' for #<Class:0x007f973a321a58>

How can I reference that ?

Body:
You can do like these in Car.rb

validate :validate_user, on: [:create, :update]

def validate_user
  if self.user.mdk_id == nil
    #display error message here
    #such as User's mdk_id cannot be null etc.
  end
end


问:
Java Taking Multiple Line Input
How do I go about taking input that is multiple lines, such as

```<code>4 2 9
1 4 2
9 8 5
</code>```

and placing it into an array of that is big enough to hold each line with no empty positions, or an arraylist. I've tried many ways to do this and cannot find a solution.
For example, if the user copied and pasted the above snippet as input, I want an array or arraylist to hold

```<code>["4 2 9", "1 4 2", "9 8 5"]
</code>```

答:
Try calling nextLine

```<code>Scanner s = new Scanner(System.in);
ArrayList<String> list = new ArrayList<>();
while (s.hasNextLine()) {
    list.add(s.nextLine());
}

System.out.println(list);
</code>```

Note that the scanner will keep prompting for input. To stop this, you need to enter an end of line character. See this answer for how to do this.

Example input/output:

```<code>4 2 9
1 4 2
9 8 5
^D
[4 2 9, 1 4 2, 9 8 5]
</code>```

Title: Java Taking Multiple Line Input

Body:
How do I go about taking input that is multiple lines, such as

4 2 9
1 4 2
9 8 5

and placing it into an array of that is big enough to hold each line with no empty positions, or an arraylist. I've tried many ways to do this and cannot find a solution.
For example, if the user copied and pasted the above snippet as input, I want an array or arraylist to hold

["4 2 9", "1 4 2", "9 8 5"]

Body:
Try calling nextLine

Scanner s = new Scanner(System.in);
ArrayList<String> list = new ArrayList<>();
while (s.hasNextLine()) {
    list.add(s.nextLine());
}

System.out.println(list);

Note that the scanner will keep prompting for input. To stop this, you need to enter an end of line character. See this answer for how to do this.

Example input/output:

4 2 9
1 4 2
9 8 5
^D
[4 2 9, 1 4 2, 9 8 5]


问:
C# Excel interop merge cells in fast way
I want to merge cells and to do it multiple times...
The reason I'm using this merge its because I want more the one table.
and a different number of columns for each table and different size of a column on the another...
The number and the places of the merges are unknown

```<code>    using Microsoft.Office.Interop.Excel;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp111
{
    class Program
    {
        static void Main(string[] args)
        {
            string x = @"C:\Users\hed-b\source\repos\TESTUserFormFromExcel\ConsoleApp111\bin\Debug\TEST.xltm";

            Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application
            {
                DisplayAlerts = false,
                Visible = false,
                ScreenUpdating = false,
            };

            Workbook wb = xlApp.Workbooks.Open(x);
            Worksheet ws = (Worksheet)wb.Worksheets[1];
            if (ws == null)
            {
                Console.WriteLine("Worksheet could not be created. Check that your office installation and project references are correct.");
                return;
            }
            Stopwatch stopWatch = Stopwatch.StartNew();

            for (int i = 2; i <= 10; i++)
            {
                ws.get_Range("A"+i, "B"+i).Merge();

            }
            for (int i = 2; i <= 10; i++)
            {
                ws.get_Range("C" + i, "D" + i).Merge();
            }
            for (int i = 2; i <= 10; i++)
            {
                ws.get_Range("E" + i, "H" + i).Merge();
            }
            Console.WriteLine(stopWatch.ElapsedMilliseconds);

            stopWatch = Stopwatch.StartNew();
            ws.get_Range("A" + 2, "H" + 10).Value2 = new string[10, 5]{
                { "aaaaaaaaaaaaaaaaa","","aaaaaaaaaaaaaaaaa","","aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},
                { "aaaaaaaaaaaaaaaaa","","aaaaaaaaaaaaaaaaa","","aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},
                { "aaaaaaaaaaaaaaaaa","","aaaaaaaaaaaaaaaaa","","aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},
                { "aaaaaaaaaaaaaaaaa","","aaaaaaaaaaaaaaaaa","","aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},
                { "aaaaaaaaaaaaaaaaa","","aaaaaaaaaaaaaaaaa","","aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},
                { "aaaaaaaaaaaaaaaaa","","aaaaaaaaaaaaaaaaa","","aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},
                { "aaaaaaaaaaaaaaaaa","","aaaaaaaaaaaaaaaaa","","aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},
                { "aaaaaaaaaaaaaaaaa","","aaaaaaaaaaaaaaaaa","","aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},
                { "aaaaaaaaaaaaaaaaa","","aaaaaaaaaaaaaaaaa","","aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},
                { "aaaaaaaaaaaaaaaaa","","aaaaaaaaaaaaaaaaa","","aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},
            };

            ws.get_Range("A" + 11, "H" + 15).Value2 = new string[5, 8]{
                { "bbbbb","bbbbb","bbbbb","bbbbb","bbbbb","bbbbb","bbbbb","bbbbb"},
                { "bbbbb","bbbbb","bbbbb","bbbbb","bbbbb","bbbbb","bbbbb","bbbbb"},
                { "bbbbb","bbbbb","bbbbb","bbbbb","bbbbb","bbbbb","bbbbb","bbbbb"},
                { "bbbbb","bbbbb","bbbbb","bbbbb","bbbbb","bbbbb","bbbbb","bbbbb"},
                { "bbbbb","bbbbb","bbbbb","bbbbb","bbbbb","bbbbb","bbbbb","bbbbb"}
            };

            Console.WriteLine(stopWatch.ElapsedMilliseconds);

            xlApp.ScreenUpdating = true;
            xlApp.Visible = true;
        }
    }
}
</code>```

I just looking for better way to do it faster

All these example program merges take about 1724 ms. in my actual program I have much more merges and take more than 5000 ms.
This merges its what take the most of the time...

答:
It'll probably perform better if you execute the merge at once and let Excel handle the multiple ranges you need to merge.

I.e. define a range object which holds the multiple areas and call the Merge on it. It won't merge everything into one big fat cell, but will merge the multiple areas as defined:

```<code>var ranges = String.Empty();

for (int i = 2; i <= 10; i++)
{
    ranges += $"A{i}:B{i},C{i}:D{i},E{i}:H{i},";
}

ws.get_Range(ranges.TrimEnd(',')).Merge();
</code>```

Body:
I want to merge cells and to do it multiple times...
The reason I'm using this merge its because I want more the one table.
and a different number of columns for each table and different size of a column on the another...
The number and the places of the merges are unknown

    using Microsoft.Office.Interop.Excel;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp111
{
    class Program
    {
        static void Main(string[] args)
        {
            string x = @"C:\Users\hed-b\source\repos\TESTUserFormFromExcel\ConsoleApp111\bin\Debug\TEST.xltm";

            Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application
            {
                DisplayAlerts = false,
                Visible = false,
                ScreenUpdating = false,
            };

            Workbook wb = xlApp.Workbooks.Open(x);
            Worksheet ws = (Worksheet)wb.Worksheets[1];
            if (ws == null)
            {
                Console.WriteLine("Worksheet could not be created. Check that your office installation and project references are correct.");
                return;
            }
            Stopwatch stopWatch = Stopwatch.StartNew();

            for (int i = 2; i <= 10; i++)
            {
                ws.get_Range("A"+i, "B"+i).Merge();

            }
            for (int i = 2; i <= 10; i++)
            {
                ws.get_Range("C" + i, "D" + i).Merge();
            }
            for (int i = 2; i <= 10; i++)
            {
                ws.get_Range("E" + i, "H" + i).Merge();
            }
            Console.WriteLine(stopWatch.ElapsedMilliseconds);

            stopWatch = Stopwatch.StartNew();
            ws.get_Range("A" + 2, "H" + 10).Value2 = new string[10, 5]{
                { "aaaaaaaaaaaaaaaaa","","aaaaaaaaaaaaaaaaa","","aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},
                { "aaaaaaaaaaaaaaaaa","","aaaaaaaaaaaaaaaaa","","aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},
                { "aaaaaaaaaaaaaaaaa","","aaaaaaaaaaaaaaaaa","","aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},
                { "aaaaaaaaaaaaaaaaa","","aaaaaaaaaaaaaaaaa","","aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},
                { "aaaaaaaaaaaaaaaaa","","aaaaaaaaaaaaaaaaa","","aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},
                { "aaaaaaaaaaaaaaaaa","","aaaaaaaaaaaaaaaaa","","aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},
                { "aaaaaaaaaaaaaaaaa","","aaaaaaaaaaaaaaaaa","","aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},
                { "aaaaaaaaaaaaaaaaa","","aaaaaaaaaaaaaaaaa","","aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},
                { "aaaaaaaaaaaaaaaaa","","aaaaaaaaaaaaaaaaa","","aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},
                { "aaaaaaaaaaaaaaaaa","","aaaaaaaaaaaaaaaaa","","aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},
            };

            ws.get_Range("A" + 11, "H" + 15).Value2 = new string[5, 8]{
                { "bbbbb","bbbbb","bbbbb","bbbbb","bbbbb","bbbbb","bbbbb","bbbbb"},
                { "bbbbb","bbbbb","bbbbb","bbbbb","bbbbb","bbbbb","bbbbb","bbbbb"},
                { "bbbbb","bbbbb","bbbbb","bbbbb","bbbbb","bbbbb","bbbbb","bbbbb"},
                { "bbbbb","bbbbb","bbbbb","bbbbb","bbbbb","bbbbb","bbbbb","bbbbb"},
                { "bbbbb","bbbbb","bbbbb","bbbbb","bbbbb","bbbbb","bbbbb","bbbbb"}
            };

            Console.WriteLine(stopWatch.ElapsedMilliseconds);

            xlApp.ScreenUpdating = true;
            xlApp.Visible = true;
        }
    }
}

I just looking for better way to do it faster

All these example program merges take about 1724 ms. in my actual program I have much more merges and take more than 5000 ms.
This merges its what take the most of the time...

Body:
It'll probably perform better if you execute the merge at once and let Excel handle the multiple ranges you need to merge.

I.e. define a range object which holds the multiple areas and call the Merge on it. It won't merge everything into one big fat cell, but will merge the multiple areas as defined:

var ranges = String.Empty();

for (int i = 2; i <= 10; i++)
{
    ranges += $"A{i}:B{i},C{i}:D{i},E{i}:H{i},";
}

ws.get_Range(ranges.TrimEnd(',')).Merge();


问:
WordPress Parse error: syntax error, unexpected T_FUNCTION
I am importing a Wordpress site for somebody and I am getting the white screen. In WP_DEBUG it is giving me this error:

Parse error: syntax error, unexpected T_FUNCTION in /wp-content/plugins/edit-guests.php on line 5

Here is the code surrounding line 5:

```<code>    <?php
/*
 * Plugin Name: iThemes Exchange Change Guest Customer Email
 */
add_action( 'add_meta_boxes_it_exchange_tran', function () {
    add_meta_box(
        'it-exchange-change-guest-customer-email',
        'Change Guest Customer Email ADdress',
        function ( $post ) {
            if ( ! $post ) {
                return;
            }
</code>```

Line 5 is the line that starts with "add_action".

I am sure this is a novice's mistake, but any help is greatly appreciated, thank you so much!

答:
Put this correct code after you can check it,

add_action( 'add_meta_boxes_it_exchange_tran',
function () {
    add_meta_box( 'it-exchange-change-guest-customer-email',    'Change Guest Customer Email ADdress',
        function ( $post ) {
            if ( ! $post ) {
                return;
            }}
);});```

Body:
I am importing a Wordpress site for somebody and I am getting the white screen. In WP_DEBUG it is giving me this error:

Parse error: syntax error, unexpected T_FUNCTION in /wp-content/plugins/edit-guests.php on line 5

Here is the code surrounding line 5:

    <?php
/*
 * Plugin Name: iThemes Exchange Change Guest Customer Email
 */
add_action( 'add_meta_boxes_it_exchange_tran', function () {
    add_meta_box(
        'it-exchange-change-guest-customer-email',
        'Change Guest Customer Email ADdress',
        function ( $post ) {
            if ( ! $post ) {
                return;
            }

Line 5 is the line that starts with "add_action".

I am sure this is a novice's mistake, but any help is greatly appreciated, thank you so much!


问:
How to replace all list values in every column in a dataframe
If I have a dataframe, which has columns like below:

```<code>a1 <- c("Hello", "World")
b1 <- c("[1, 2]", "[1,2,3]")
c1 <- c("[1, 2, 3, 3]", "[1, 4, 5, 6]")
d1 <- c("[]", "[1]")

data <- data.frame(a1, b1, c1, d1)
</code>```

I want to replace all the columns which have list values with its the length of the list instead. I tried using some apply functions, but could not get it to work.

答:
You can do like this</p>

```<code>a1 <- c("Hello", "World")
b1 <- c("[1, 2]", "[1,2,3]")
c1 <- c("[1, 2, 3, 3]", "[1, 4, 5, 6]")
d1 <- c("[]", "[1]")
data <- data.frame(a1, b1, c1, d1, stringsAsFactors = F)

data <- data.frame(apply(data,2,function(x) gsub(pattern = "\\[", "", x)), stringsAsFactors = F)
data <- data.frame(apply(data,2,function(x) gsub(pattern = "\\]", "", x)), stringsAsFactors = F)

data$b1 <- unlist(lapply(strsplit(data$b1, ","), length))
data$c1 <- unlist(lapply(strsplit(data$c1, ","), length))
data$d1 <- unlist(lapply(strsplit(data$d1, ","), length))

data

     a1 b1 c1 d1
1 Hello  2  4  0
2 World  3  4  1
</code>```

Body:
If I have a dataframe, which has columns like below:

a1 <- c("Hello", "World")
b1 <- c("[1, 2]", "[1,2,3]")
c1 <- c("[1, 2, 3, 3]", "[1, 4, 5, 6]")
d1 <- c("[]", "[1]")

data <- data.frame(a1, b1, c1, d1)

I want to replace all the columns which have list values with its the length of the list instead. I tried using some apply functions, but could not get it to work.

Body:
You can do like this

a1 <- c("Hello", "World")
b1 <- c("[1, 2]", "[1,2,3]")
c1 <- c("[1, 2, 3, 3]", "[1, 4, 5, 6]")
d1 <- c("[]", "[1]")
data <- data.frame(a1, b1, c1, d1, stringsAsFactors = F)

data <- data.frame(apply(data,2,function(x) gsub(pattern = "\\[", "", x)), stringsAsFactors = F)
data <- data.frame(apply(data,2,function(x) gsub(pattern = "\\]", "", x)), stringsAsFactors = F)

data$b1 <- unlist(lapply(strsplit(data$b1, ","), length))
data$c1 <- unlist(lapply(strsplit(data$c1, ","), length))
data$d1 <- unlist(lapply(strsplit(data$d1, ","), length))

data

     a1 b1 c1 d1
1 Hello  2  4  0
2 World  3  4  1


问:
jQuery UI toggle for scale effect not working as expected
On my site, (I can't share URL here, you'd need to login to see there), I'm using my required jQuery UI animation properly. But when I tested the same code again in localhost, it just doesn't work:

I have added the fiddle:

If you try the fiddle, it works perfectly, but when I run the exactly same code, I see following behavior:

Page is loaded:

Click on button, the bell resizes to 0 and hides.

Click again, instead of resizing back to 100% with animation, it quickly resizes to 100% ( without animantion), then again resizes to 0% (with animantion) instead of 100%. Just after the animation, it again resizes to 100%. So, it is finally shown, but there's some wrong / repeatetion that I don't understand.

Here's the approx. 'timeline' of 2nd point to get an idea:

Time  - action

0% - Click

0.1% - Image resizes to 100% from 0% (no animation);

0.2% (say) - Image resizes to 0% from 100% (with animation);

99.1% (say) - Image resizes to 100% from 0% (no animation);

100% - done

This repeats when you keep clicking.

Correct behaviour (as happening in fiddle):

Click on button, the bell resizes to 0 and hides with animantion.

Click again, the bell resizes to 100% and is shown again with animation.

PS:

When I wrote individual jQuery (.show('scale', 2000) and .hide('scale', 2000)), things were working everywhere.

EDIT 1:

When I further tested with other effects like clip, drop it didn't cause any issue. So I think problem is with scale effect

$(document).ready(function(){
  $(document).on("click", "button", function(){
    $("#nbutton .b1").toggle("scale", 2000);
   });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>  #nbutton{
            height: 60px;
            width: 60px;
            border-radius: 50px;
            position: fixed;
            right: 40px;
            bottom: 30px;
            border: none;
            color: white;
            box-shadow: 0 0 10px 0 rgba(0,0,0,0.3);
            cursor: pointer;
            z-index: 100;
        }
        .nbutton{
            width: 60px;
            height: 60px;
            position: absolute;
        }
        .b1{
            z-index: 2;
            background-image: url('https://test.roadcast.co.in/app/assets/img/bell.png');
            background-size: contain;
            background-repeat: no-repeat;
        }
        .b2{
            z-index: 1;
            background-image: url('https://test.roadcast.co.in/app/assets/img/bellcross.png');
            background-size: contain;
            background-repeat: no-repeat;
            transition: transform 0.400s ease;
            transform: rotateZ(-45deg);
        }</code>```

<button>Click</button>```

答:
You can either use JQuery animate() with step or multiple animate() like as follow.there you need to calculate you ease respect for duration.

```<code>$(document).ready(function(){
  $(document).on("click", "button", function(){
        if($("#nbutton .b1").css('display') =='block')
        {
          var div = $("#nbutton .b1");

          div.animate({height: '60px',width: '60px'}, 200);
          div.animate({height: '0px',width: '0px',margin:'50%'}, 200);
          div.animate({height: '60px',width: '60px',margin:'0%'}, 1600);
          div.animate({height: '0px',width: '0px',margin:'50%'}, 200);
          div.animate({height: '60px',width: '60px',margin:'0%'},200);
          $("#nbutton .b1").css('display','none');
        }
        else
        {
          $("#nbutton .b1").css('display','block');
          div.animate({height: '0px',width: '0px',margin:'50%'}, 1000);

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

Body:
On my site, (I can't share URL here, you'd need to login to see there), I'm using my required jQuery UI animation properly. But when I tested the same code again in localhost, it just doesn't work:

I have added the fiddle:

If you try the fiddle, it works perfectly, but when I run the exactly same code, I see following behavior:

Page is loaded:

Click on button, the bell resizes to 0 and hides.

Click again, instead of resizing back to 100% with animation, it quickly resizes to 100% ( without animantion), then again resizes to 0% (with animantion) instead of 100%. Just after the animation, it again resizes to 100%. So, it is finally shown, but there's some wrong / repeatetion that I don't understand.

Here's the approx. 'timeline' of 2nd point to get an idea:

Time  - action

0% - Click

0.1% - Image resizes to 100% from 0% (no animation);

0.2% (say) - Image resizes to 0% from 100% (with animation);

99.1% (say) - Image resizes to 100% from 0% (no animation);

100% - done

This repeats when you keep clicking.

Correct behaviour (as happening in fiddle):

Click on button, the bell resizes to 0 and hides with animantion.

Click again, the bell resizes to 100% and is shown again with animation.

PS:

When I wrote individual jQuery (.show('scale', 2000) and .hide('scale', 2000)), things were working everywhere.

EDIT 1:

When I further tested with other effects like clip, drop it didn't cause any issue. So I think problem is with scale effect

$(document).ready(function(){
  $(document).on("click", "button", function(){
    $("#nbutton .b1").toggle("scale", 2000);
   });
});

  #nbutton{
            height: 60px;
            width: 60px;
            border-radius: 50px;
            position: fixed;
            right: 40px;
            bottom: 30px;
            border: none;
            color: white;
            box-shadow: 0 0 10px 0 rgba(0,0,0,0.3);
            cursor: pointer;
            z-index: 100;
        }
        .nbutton{
            width: 60px;
            height: 60px;
            position: absolute;
        }
        .b1{
            z-index: 2;
            background-image: url('https://test.roadcast.co.in/app/assets/img/bell.png');
            background-size: contain;
            background-repeat: no-repeat;
        }
        .b2{
            z-index: 1;
            background-image: url('https://test.roadcast.co.in/app/assets/img/bellcross.png');
            background-size: contain;
            background-repeat: no-repeat;
            transition: transform 0.400s ease;
            transform: rotateZ(-45deg);
        }

<button>Click</button>

Body:
You can either use JQuery animate() with step or multiple animate() like as follow.there you need to calculate you ease respect for duration.

$(document).ready(function(){
  $(document).on("click", "button", function(){
        if($("#nbutton .b1").css('display') =='block')
        {
          var div = $("#nbutton .b1");

          div.animate({height: '60px',width: '60px'}, 200);
          div.animate({height: '0px',width: '0px',margin:'50%'}, 200);
          div.animate({height: '60px',width: '60px',margin:'0%'}, 1600);
          div.animate({height: '0px',width: '0px',margin:'50%'}, 200);
          div.animate({height: '60px',width: '60px',margin:'0%'},200);
          $("#nbutton .b1").css('display','none');
        }
        else
        {
          $("#nbutton .b1").css('display','block');
          div.animate({height: '0px',width: '0px',margin:'50%'}, 1000);

        }
       });
});


问:
Scrollable CardView with RecyclerView inside
I would like to implement a screen where I have a Card view containing a RecyclerView.

The CardView should of the same height of the content of the recycler view, this means that if the RecyclerView has few item, I should see the bottom corners and the bottom shadow of the card but if the RecyclerView has many items, the Card view should "scroll" with the RecyclerView to have the bottom corners and shadow of the cardview at the bottom of the RecylerView.

Here what it should look like when the RecyclerView is at top :

When the user begins to scroll, the top corners disappear with the RecyclerView scrolling :

And finally, when the user reaches the bottom of the RecyclerView, the bottom corners and the shadow of the CardView appears :

From now, I managed to have a working implementation by putting the RecyclerView inside the CardView and the CardView inside a NestedScrollView but this breaks the fling gesture...

```<code><android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:clipChildren="false"
    android:id="@+id/containerLayout"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:orientation="vertical"
    tools:ignore="MissingPrefix">

    <android.support.v4.widget.NestedScrollView
        android:clipToPadding="false"
        android:layout_height="match_parent"
        android:layout_width="match_parent"
        android:paddingBottom="16dp"
        android:paddingLeft="85dp"
        android:paddingRight="85dp"
        android:paddingTop="16dp">

        <android.support.v7.widget.CardView
            android:layout_height="wrap_content"
            android:layout_width="match_parent"
            app:cardBackgroundColor="?android:attr/windowBackground">

            <android.support.v7.widget.RecyclerView
                android:id="@+id/recyclerView"
                android:layout_height="wrap_content"
                android:layout_width="match_parent"/>
        </android.support.v7.widget.CardView>
    </android.support.v4.widget.NestedScrollView>
</android.support.design.widget.CoordinatorLayout>
</code>```

Do you have any hints or idea on how I could implement such design ? I guess that CoordinatorLayout could help me but I couldn't find anything ...

Thank you

答:
it's just a simple line of code

```<code>recycler.setNestedScrollingEnabled(false);
</code>```

and don't forget to make cardview height to wrap_content

Body:
I would like to implement a screen where I have a Card view containing a RecyclerView.

The CardView should of the same height of the content of the recycler view, this means that if the RecyclerView has few item, I should see the bottom corners and the bottom shadow of the card but if the RecyclerView has many items, the Card view should "scroll" with the RecyclerView to have the bottom corners and shadow of the cardview at the bottom of the RecylerView.

Here what it should look like when the RecyclerView is at top :

When the user begins to scroll, the top corners disappear with the RecyclerView scrolling :

And finally, when the user reaches the bottom of the RecyclerView, the bottom corners and the shadow of the CardView appears :

From now, I managed to have a working implementation by putting the RecyclerView inside the CardView and the CardView inside a NestedScrollView but this breaks the fling gesture...

<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:clipChildren="false"
    android:id="@+id/containerLayout"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:orientation="vertical"
    tools:ignore="MissingPrefix">

    <android.support.v4.widget.NestedScrollView
        android:clipToPadding="false"
        android:layout_height="match_parent"
        android:layout_width="match_parent"
        android:paddingBottom="16dp"
        android:paddingLeft="85dp"
        android:paddingRight="85dp"
        android:paddingTop="16dp">

        <android.support.v7.widget.CardView
            android:layout_height="wrap_content"
            android:layout_width="match_parent"
            app:cardBackgroundColor="?android:attr/windowBackground">

            <android.support.v7.widget.RecyclerView
                android:id="@+id/recyclerView"
                android:layout_height="wrap_content"
                android:layout_width="match_parent"/>
        </android.support.v7.widget.CardView>
    </android.support.v4.widget.NestedScrollView>
</android.support.design.widget.CoordinatorLayout>

Do you have any hints or idea on how I could implement such design ? I guess that CoordinatorLayout could help me but I couldn't find anything ...

Thank you

Body:
it's just a simple line of code

recycler.setNestedScrollingEnabled(false);

and don't forget to make cardview height to wrap_content


问:
Google calendar API. Saying 403 error(insufficient permission)

```<code>{
  "error": {
    "errors": [
      {
        "domain": "global",
        "reason": "insufficientPermissions",
        "message": "Insufficient Permission"
      }
    ],
    "code": 403,
    "message": "Insufficient Permission"
  }
}
</code>```

While inserting new event into google calendar.

答:
After some effort, I got the solution. I needed to delete all my previous credentials saved.

Example : I needed to delete ->.credentials/calendar-php-quickstart.json

where .credentials is a directory.

Body:
{
  "error": {
    "errors": [
      {
        "domain": "global",
        "reason": "insufficientPermissions",
        "message": "Insufficient Permission"
      }
    ],
    "code": 403,
    "message": "Insufficient Permission"
  }
}

While inserting new event into google calendar.


问:
How to run a foreground scheduled task in ASP.NET MVC?
I've this code in my ASP.NET MVC application to share a value across the application.

```<code>public static class Global
{
    public static string Token { get; private set; };

    public static void LoadFromFile()
    {
        // loads Token value from a settings file
    }
}
</code>```

What I want to do is to run LoadFromFile method once a day to update the Token value.

I can't use a separate background task like in HangFire, since I want to update the value for current running application.

How can I do it? thanks.

Update:
Mates who think this is a duplicate, please read the question. I want to update the shared value in current running application. changing it in in a separate  background task won't change it for current application.

答:
I had faced similar requirement once, here is the trick I used

```<code>    private static DateTime lastRunAt;
    private static object loadingTokenLock = new object();

    private static bool TokenUpdateNeeded
    {
        get
        {
            return DateTime.UtcNow.DayOfYear != lastRunAt.DayOfYear;
        }
    }

    public static void TryLoadToken()
    {
        if (TokenUpdateNeeded)
            lock (loadingTokenLock)
                if (TokenUpdateNeeded)
                    LoadFromFile();
    }

    public static void LoadFromFile()
    {
        // loads Token value from a settings file
        lastRunAt = DateTime.UtcNow;
    }

    void Session_Start(object sender, EventArgs e)
    {
        TryLoadToken();
    }
</code>```

I can't remember the exact coding, but the idea was to update the Token upon the first request of the day.

The problem is if your application have not been visit for more than a day, the Token will not be updated. So we defined a task in Windows Task Scheduler to visit the site once everyday

Body:
I've this code in my ASP.NET MVC application to share a value across the application.

public static class Global
{
    public static string Token { get; private set; };

    public static void LoadFromFile()
    {
        // loads Token value from a settings file
    }
}

What I want to do is to run LoadFromFile method once a day to update the Token value.

I can't use a separate background task like in HangFire, since I want to update the value for current running application.

How can I do it? thanks.

Update:
Mates who think this is a duplicate, please read the question. I want to update the shared value in current running application. changing it in in a separate  background task won't change it for current application.

Body:
I had faced similar requirement once, here is the trick I used

    private static DateTime lastRunAt;
    private static object loadingTokenLock = new object();

    private static bool TokenUpdateNeeded
    {
        get
        {
            return DateTime.UtcNow.DayOfYear != lastRunAt.DayOfYear;
        }
    }

    public static void TryLoadToken()
    {
        if (TokenUpdateNeeded)
            lock (loadingTokenLock)
                if (TokenUpdateNeeded)
                    LoadFromFile();
    }

    public static void LoadFromFile()
    {
        // loads Token value from a settings file
        lastRunAt = DateTime.UtcNow;
    }

    void Session_Start(object sender, EventArgs e)
    {
        TryLoadToken();
    }

I can't remember the exact coding, but the idea was to update the Token upon the first request of the day.

The problem is if your application have not been visit for more than a day, the Token will not be updated. So we defined a task in Windows Task Scheduler to visit the site once everyday


答:
You can pass a proc to the if option like this:

```<code>validates :model, presence: true, if: proc { |car| car.user.mdk_id? }
</code>```

(I assumed you need to validate presence of the field, you can change the validation if you need).

Please, check out the rails guides on this topic.

Title: Rails self and association

Body:
You can pass a proc to the if option like this:

validates :model, presence: true, if: proc { |car| car.user.mdk_id? }

(I assumed you need to validate presence of the field, you can change the validation if you need).

Please, check out the rails guides on this topic.


问:
'RAISERROR' must be declared
```<code>CREATE TRIGGER x AFTER INSERT ON itemtype
FOR EACH ROW
DECLARE
    minn itemtype.PRICE%type;
BEGIN
select MIN(itemtype.PRICE) into minn from itemtype;
IF (:new.PRICE > minn*4) then RAISERROR('Custom text');
END IF;
END;
/
</code>```

I'm trying to create a trigger that raises an error when I try to insert a new entry into the itemtype with itemtype.PRICE column value is greater than 4 times the current low priced item on the table.

I get these compilation errors when I try to create the trigger.

```<code>LINE/COL ERROR
-------- --------------------------------------------------------------
5/31     PL/SQL: Statement ignored
5/31     PLS-00201: identifier 'RAISERROR' must be declared
</code>```

I have also tried

```<code>    CREATE TRIGGER x AFTER INSERT ON itemtype
    FOR EACH ROW
    DECLARE
        minn itemtype.PRICE%type;
    BEGIN
    select MIN(itemtype.PRICE) into minn from itemtype;
    if (:new.PRICE > minn*4) then raise_application_error(-20010,'Too Expensive');
    END IF;
    END;
    /
</code>```

which complies, but when i try to insert a new entry into the table I get theses errors saying my trigger fails.

```<code>    SQL> insert into itemtype(ITEMNUM,NAME,PICTURE,PRICE,BELONGSTO ) VALUES ('A11','The who knows','',10.99,'P');
    insert into itemtype(ITEMNUM,NAME,PICTURE,PRICE,BELONGSTO ) VALUES ('A11','The who knows','',10.99,'P')
                *
    ERROR at line 1:
    ORA-04091: table USERNAME.ITEMTYPE is mutating, trigger/function may not see it
    ORA-06512: at "USERNAME.X", line 5
    ORA-04088: error during execution of trigger 'USERNAME.X'
</code>```

答:
Try use PRAGMA AUTONOMOUS_TRANSACTION in trigger.

Look my answer on this question:
SQL trigger on delete mutating table

Title: 'RAISERROR' must be declared

Body:
CREATE TRIGGER x AFTER INSERT ON itemtype
FOR EACH ROW
DECLARE
    minn itemtype.PRICE%type;
BEGIN
select MIN(itemtype.PRICE) into minn from itemtype;
IF (:new.PRICE > minn*4) then RAISERROR('Custom text');
END IF;
END;
/

I'm trying to create a trigger that raises an error when I try to insert a new entry into the itemtype with itemtype.PRICE column value is greater than 4 times the current low priced item on the table.

I get these compilation errors when I try to create the trigger.

LINE/COL ERROR
-------- --------------------------------------------------------------
5/31     PL/SQL: Statement ignored
5/31     PLS-00201: identifier 'RAISERROR' must be declared

I have also tried

    CREATE TRIGGER x AFTER INSERT ON itemtype
    FOR EACH ROW
    DECLARE
        minn itemtype.PRICE%type;
    BEGIN
    select MIN(itemtype.PRICE) into minn from itemtype;
    if (:new.PRICE > minn*4) then raise_application_error(-20010,'Too Expensive');
    END IF;
    END;
    /

which complies, but when i try to insert a new entry into the table I get theses errors saying my trigger fails.

    SQL> insert into itemtype(ITEMNUM,NAME,PICTURE,PRICE,BELONGSTO ) VALUES ('A11','The who knows','',10.99,'P');
    insert into itemtype(ITEMNUM,NAME,PICTURE,PRICE,BELONGSTO ) VALUES ('A11','The who knows','',10.99,'P')
                *
    ERROR at line 1:
    ORA-04091: table USERNAME.ITEMTYPE is mutating, trigger/function may not see it
    ORA-06512: at "USERNAME.X", line 5
    ORA-04088: error during execution of trigger 'USERNAME.X'


问:
How to activate combobox on first click (Datagridview)
In winforms, you need to click the combobox twice to properly activate it - the first time to focus it, the second time to actually get the dropdown list.

How do I change this behavior so that it activates on the very first click?

This is for DATAGRIDVIEW combobox.

答:
I changed only the EditMode property of the datagridview to EditOnEnter and it's working perfectly.

```<code>EditMode  = EditOnEnter
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I changed only the EditMode property of the datagridview to EditOnEnter and it's working perfectly.

EditMode  = EditOnEnter


问:
Scrollview with React Native isn't scrolling
I am currently working on a react native project which requires me to make a profile page.  Im trying to use scrollview to render an image with words underneath it.  Here is my code:

```<code>// @flow

import React, { Component } from 'react';
import { Dimensions } from 'react-native';
import {
  View,
  Text,
  Image,
  TouchableOpacity,
  ScrollView,
  TouchableWithoutFeedback,
  FlatList,
} from 'react-native';

//import PictureScroller from './PictureScroller';
//import TaggButton from './TaggButton';
import styles from './styles';

//import PropTypes from 'prop-types';

type Props = {
  images: Object,
  name: String,
}

const Profile = (props: Props) => {

    return (
      <ScrollView style={styles.scrollView} contentContainerStyle={{flex:1}}>
        <Image source={props.images}/>
        <Text style={styles.name}>props.name</Text>
      </ScrollView>
      );
    }

export default Profile;
</code>```

Please let me know if I should include additional code.

答:
The contentContainerStyle flex:1 is the problem here.

Just remove contentContainerStyle or change flex:1 in contentContainerStyle to flexGrow:1. You should be able to scroll.

Body:
I am currently working on a react native project which requires me to make a profile page.  Im trying to use scrollview to render an image with words underneath it.  Here is my code:

// @flow

import React, { Component } from 'react';
import { Dimensions } from 'react-native';
import {
  View,
  Text,
  Image,
  TouchableOpacity,
  ScrollView,
  TouchableWithoutFeedback,
  FlatList,
} from 'react-native';

//import PictureScroller from './PictureScroller';
//import TaggButton from './TaggButton';
import styles from './styles';

//import PropTypes from 'prop-types';

type Props = {
  images: Object,
  name: String,
}

const Profile = (props: Props) => {

    return (
      <ScrollView style={styles.scrollView} contentContainerStyle={{flex:1}}>
        <Image source={props.images}/>
        <Text style={styles.name}>props.name</Text>
      </ScrollView>
      );
    }

export default Profile;

Please let me know if I should include additional code.


问:
3 threads to print alternate values in sequence
I am trying to create an implementation where multiple threads print alternate values of sequence. So here thread1 will print 1,4,7 thread2 will print 2,5,8 thread3 will print 3,6,9. I am using Atomic integer and modulo function.

Below implementation works fine in the sense that first thread prints 1,4,7 while second prints 2,5,8 and third prints 3,6,9 but problem is that sequence is not maintained i.e output can be like 1,3,2,4,5,7,8,6,9 while i want sequence to be maintained as proper threads shld print those values.
One condition is i don't want to use synchronize. [Just for learning purpose]

```<code>import java.util.concurrent.atomic.AtomicInteger;

public class ThreeThreadsOrderedLockLess {

    AtomicInteger sharedOutput = new AtomicInteger(0);

    public static void main(String args[]) {

        ThreeThreadsOrderedLockLess t = new ThreeThreadsOrderedLockLess();

        ThreadTasks t1 = t.new ThreadTasks(0);
        ThreadTasks t2 = t.new ThreadTasks(1);
        ThreadTasks t3 = t.new ThreadTasks(2);

        Thread ts1 = new Thread(t1);
        Thread ts2 = new Thread(t2);
        Thread ts3 = new Thread(t3);
        ts1.start();
        ts2.start();
        ts3.start();

    }

    private class ThreadTasks implements Runnable {

        private final int threadPosition;

        public ThreadTasks(int threadPosition) {
            super();

            this.threadPosition = threadPosition;
        }

        @Override
        public void run() {

            while (sharedOutput.get() < 9) {

                if (sharedOutput.get() % 3 == this.threadPosition) {

                    System.out.println("Printing output for Thread: "
                            + this.threadPosition + "  "
                            + sharedOutput.incrementAndGet());
                }
            }

        }
    }

}
</code>```

答:
```<code>public class PrintThreadsInSerial {
    public static void main(String[] args) {
    Thread t = new Thread(new Job());
    t.start();
    }
}

class Job implements Runnable {
    @Override
    public void run() {
     while (true) {
        for (int i = 1; i <= 3; i++) {
         System.out.println(i);
        }
     }
    }
}
</code>```

Body:
I am trying to create an implementation where multiple threads print alternate values of sequence. So here thread1 will print 1,4,7 thread2 will print 2,5,8 thread3 will print 3,6,9. I am using Atomic integer and modulo function.

Below implementation works fine in the sense that first thread prints 1,4,7 while second prints 2,5,8 and third prints 3,6,9 but problem is that sequence is not maintained i.e output can be like 1,3,2,4,5,7,8,6,9 while i want sequence to be maintained as proper threads shld print those values.
One condition is i don't want to use synchronize. [Just for learning purpose]

import java.util.concurrent.atomic.AtomicInteger;

public class ThreeThreadsOrderedLockLess {

    AtomicInteger sharedOutput = new AtomicInteger(0);

    public static void main(String args[]) {

        ThreeThreadsOrderedLockLess t = new ThreeThreadsOrderedLockLess();

        ThreadTasks t1 = t.new ThreadTasks(0);
        ThreadTasks t2 = t.new ThreadTasks(1);
        ThreadTasks t3 = t.new ThreadTasks(2);

        Thread ts1 = new Thread(t1);
        Thread ts2 = new Thread(t2);
        Thread ts3 = new Thread(t3);
        ts1.start();
        ts2.start();
        ts3.start();

    }

    private class ThreadTasks implements Runnable {

        private final int threadPosition;

        public ThreadTasks(int threadPosition) {
            super();

            this.threadPosition = threadPosition;
        }

        @Override
        public void run() {

            while (sharedOutput.get() < 9) {

                if (sharedOutput.get() % 3 == this.threadPosition) {

                    System.out.println("Printing output for Thread: "
                            + this.threadPosition + "  "
                            + sharedOutput.incrementAndGet());
                }
            }

        }
    }

}