问:
How to see source code from github in Visual Studio IDE, but compile with dlls from Nuget?
Nowadays there's a lot of great open source packages and frameworks for all sorts of uses. Let's take for example, ASP.NET Core MVC and Newtonsoft.Json.
Those are shipped in Nuget packages, which are stripped of the source code.
I think many of you can remember a lot of situations in which one would like to see the source code freely available on GitHub (to help debugguing some issue), but was forced to do one of the following:

Be lazy and just forget about it, or continue debugging your issue with a popular library treating it more like a "black box";

Go to the browser, type github.com and search the source code without the mighty advises of the Visual Studio IDE;

Spend 5 minutes, clone the repository to the local drive and look at it with IDE;

Spend even more time while compiling the source code, deinstalling all of the nuget packages of interest from your projects and instead, hooking up directly to all of the freshly compiled assemblies (which are not always one-to-one to Nuget package).

This last option is the most viable, but you're left with a lot of time spent and you can't just push this to your repository or deploy the compiled code anymore. Other developers won't find those relative paths to the dlls and customers may end up with wrong versions of nuget packages baked in the deployment package.

Is there a fifth option which has all the pros of the fourth, but none of the cons? I imagine this being done by an IDE in an isolated fasion, i.e. no modification to my .csproj and package.config files, but the "Go to definition" & "Find all references" features and debugging should work as if I'm hooked up to the real stuff.

Yes, I'm pretty lazy.

答:
as mentioned in one of the comments, there is a VS extension that does this:
Nuget Reference Switcher (select one that matches your VS version to install), for more info, you can read its wiki on github.

here is what I usually do:

git clone the source repository

add the open sourced .sln/.csproj to your own solution:

run nuget reference switcher extension

This is equivalent to your step 4, but a lot less work since the heavy lifting is done by the extension.


来源: stackexchange

问:
Conversion failed when converting the varchar value '0%' to data type int
I'm facing a problem with SQL Server.

I've created a table like this:

```<code>create table Components
(
    pk BIGINT NOT NULL PRIMARY KEY IDENTITY,
    id VARCHAR(50),
    descr VARCHAR(50),
    in_m INT,
    in_iy INT,
    p_fw VARCHAR(5000)
);
</code>```

and I'm trying to insert a couple of values:

```<code>insert into Components (id, descr, in_m, in_iy, p_fw)
values ('FW000_A', '0%', 0, 0, '[0.0,0.0,0.0]'),
       ('FW000_B', '1%', 1, 1, '[1.0,1.0,1.0]');
</code>```

I get the following error:

Msg 245, Level 16, State 1, Line 111

  Conversion failed when converting the varchar value '0%' to data type int.

even though the column descr is correctly defined as varchar(50).

Can anybody help me please? Why is SQL Server trying to convert my strings to int values?

答:
What's missing from your question is that you have more than just the two values lines you've shown, and one of the other ones has an integer literal for the descr column, rather than a string.

This example produces the same error:

```<code>declare @t table (Descr varchar(50) not null)
insert into @t(Descr) values
('0%'),
(12)
</code>```

What I believe happens is that SQL Server first tries to determine the data types for all columns in the values clause. Using data type precedence rules, it observes a varchar literal in one row and an int literal in the other, and so determines that the overall type for this column is int and attempts to perform the conversion that leads to the error.

During this process, it does not use any information about the target table into which the values are going to be placed, including the data types of the columns there.

ContentLicense: CC BY-SA 3.0

Body:
I'm facing a problem with SQL Server.

I've created a table like this:

create table Components
(
    pk BIGINT NOT NULL PRIMARY KEY IDENTITY,
    id VARCHAR(50),
    descr VARCHAR(50),
    in_m INT,
    in_iy INT,
    p_fw VARCHAR(5000)
);

and I'm trying to insert a couple of values:

insert into Components (id, descr, in_m, in_iy, p_fw)
values ('FW000_A', '0%', 0, 0, '[0.0,0.0,0.0]'),
       ('FW000_B', '1%', 1, 1, '[1.0,1.0,1.0]');

I get the following error:

Msg 245, Level 16, State 1, Line 111

  Conversion failed when converting the varchar value '0%' to data type int.

even though the column descr is correctly defined as varchar(50).

Can anybody help me please? Why is SQL Server trying to convert my strings to int values?

Body:
What's missing from your question is that you have more than just the two values lines you've shown, and one of the other ones has an integer literal for the descr column, rather than a string.

This example produces the same error:

declare @t table (Descr varchar(50) not null)
insert into @t(Descr) values
('0%'),
(12)

What I believe happens is that SQL Server first tries to determine the data types for all columns in the values clause. Using data type precedence rules, it observes a varchar literal in one row and an int literal in the other, and so determines that the overall type for this column is int and attempts to perform the conversion that leads to the error.

During this process, it does not use any information about the target table into which the values are going to be placed, including the data types of the columns there.


问:
react-native No bundle URL present
I get the following error when trying to do react-native run-ios (see screenshot below).  I have checked this answer as well as the github thread but neither were helpful.

Any ideas on what to look at or how to make this work? The problem seems to be isolated to ios, as the android emulator works ok.  Looks like maybe it's some sort of bug with the facebook code.

答:
For those still interested i resolved this just by running

```<code>react-native start
</code>```

which starts the packager in the current terminal window and run in other terminal window

```<code>react-native run-ios
</code>```

Title: react-native No bundle URL present

Body:
For those still interested i resolved this just by running

react-native start

which starts the packager in the current terminal window and run in other terminal window

react-native run-ios


问:
Modify for loop to not use delayedexpansion in batch script
In my efforts to understand the for..do loops syntax and their use of %% variables. I have gone through 2 specific examples/implementations where the one for loop does not use DELAYEDEXPANSION and another where it does use DELAYEDEXPANSION with the ! notation. The 1st for loop appears to be compatible with older OSs like the Windows XP whereas the 2nd for loop example does not.

Specifically, the 1st for loop example is taken from this answer (which is related to this) and the 2nd for loop example is taken from this answer.

Modified code for both examples copied below:

1st for loop

```<code>for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a"
set "YY=%dt:~2,2%"
set "YYYY=%dt:~0,4%"
set "MM=%dt:~4,2%"
set "DD=%dt:~6,2%"
set "HH=%dt:~8,2%"
set "Min=%dt:~10,2%"
set "Sec=%dt:~12,2%"
set "datestamp=%YYYY%%MM%%DD%"
set "timestamp=%HH%%Min%%Sec%"
echo datestamp: "%datestamp%"
echo timestamp: "%timestamp%"
</code>```

2nd for loop

```<code>SETLOCAL ENABLEDELAYEDEXPANSION
set "path_of_folder=C:\folderA\folderB"

for /f "skip=5 tokens=1,2,4 delims= " %%a in (
 'dir /ad /tc "%path_of_folder%\."') do IF "%%c"=="." (
  set "dt=%%a"
  set vara=%%a
  set varb=%%b
  echo !vara!, !varb!
  set day=!vara:~0,2!
  echo !day!
)
</code>```

Since I have been reading and seeing issues where delayed expansion (or the ! notation) is not compatible with older OSs (e.g. Windows XP), I would like to see how to write the 2nd loop like the 1st loop; i.e. without the use of DELAYEDEXPANSION.

答:
I explain in detail what aschipfl wrote already absolutely right in his comment.

Both batch files work also on Windows 2000 and Windows XP using also cmd.exe as command processor. The batch files do not work on MS-DOS, Windows 95 and Windows 98 using very limited command.com as command interpreter.

A command can be executed with parameter /? in a command prompt window to get output the help for this command. When in help is written with enabled command extensions it means supported only by cmd.exe on Windows NT based Windows versions and not supported by MS-DOS or Windows 9x using command.com. That means, for example, for /F or if /I or call :Subroutine are not available on Windows 9x, or on Windows NT based Windows with command extensions explicitly disabled. On Windows 9x it is not even possible to use "%~1" or "%~nx1".

The first batch file executes in FOR loop only one command exactly once:

```<code>set "dt=%%a"
</code>```

That command line requires already enabled command extensions. All other commands below are executed after the FOR loop finished. In other words the FOR loop in first batch file does not use a command block to run multiple commands within the FOR loop.

Whenever the Windows command processor detects the beginning of a command block on a command line, it processes the entire command block before executing the command on this command line the first time.

This means for second batch file all variable references using %Variable% are expanded already before the command FOR is executed and then the commands in the command block are executed with the values of the variables as defined above FOR command line. This can be seen by removing @echo off from first line of batch file or change it to @echo ON and run the batch file from within a command prompt window because now it can be seen which command lines respectively entire command blocks defined with ( ... ) are really executed after preprocessing them by the Windows command processor.

So whenever an environment variable is defined or modified within a command block and its value is referenced in same command block it is necessary to use delayed expansion or use workarounds.

One workaround is demonstrated below:

```<code>setlocal EnableExtensions DisableDelayedExpansion
set "FolderPath=%SystemRoot%\System32"

for /F "skip=5 tokens=1,2,4 delims= " %%a in ('dir /AD /TC "%FolderPath%\."') do if "%%c"=="." (
    set "VarA=%%a"
    set "VarB=%%b"
    call echo %%VarA%%, %%VarB%%
    call set "Day=%%VarA:~0,2%%
    call echo %%Day%%
)

endlocal
pause
</code>```

As there is no @echo off at top of this batch code it can be seen on executing the batch file what happens here. Each %% is modified on processing the command block to just %. So executed are the command lines.

```<code>call echo %VarA%, %VarB%
call set "Day=%VarA:~0,2%
call echo %Day%
</code>```

The command CALL is used to process the rest of the line a second time  to run the ECHO and the SET commands with environment variable references replaced by their corresponding values without or with string substitution.

The disadvantage of this solution is that CALL is designed primary for calling a batch file from within a batch file. For that reason the command lines above result in searching first in current directory and next in all directories of environment variable PATH for a file with name echo respectively set with a file extension of environment variable PATHEXT. That file searching behavior causes lots of file system accesses, especially on running those command lines in a FOR loop. If there is really found an executable or script file with file name echo or set, the executable respectively the script interpreter of the script file would be executed instead of the internal command of cmd.exe as usually done on using such a command line. So this solution is inefficient and not fail-safe on execution of the batch file.

Another workaround to avoid delayed expansion is using a subroutine:

```<code>@echo off
setlocal EnableExtensions DisableDelayedExpansion
set "FolderPath=%SystemRoot%\System32"

for /F "skip=5 tokens=1,2,4 delims= " %%a in ('dir /AD /TC "%FolderPath%\."') do if "%%c"=="." call :ProcessCreationDate "%%a" "%%b"

endlocal
pause
exit /B

:ProcessCreationDate
echo %~1, %~2
set "Day=%~1"
set "Day=%Day:~0,2%
echo %Day%
goto :EOF
</code>```

A subroutine is like another batch file embedded in current batch file.

The command line with exit /B avoids a fall through to the code of the subroutine.

The command line with goto :EOF would not be necessary if the line above is the last line of the batch file. But it is recommended to use it nevertheless in case of more command lines are ever added later below like a second subroutine.

The second batch file is for getting the day on which the specified folder was created. It would be possible to code this batch file without usage of delayed expansion and any workarounds.

```<code>@echo off
setlocal EnableExtensions DisableDelayedExpansion
set "FolderPath=%SystemRoot%\System32"

for /F "skip=5 tokens=1,2,4 delims= " %%a in ('dir /ad /tc "%FolderPath%\." 2^>nul') do if "%%c"=="." set "CreationDate=%%a, %%b" & goto OutputDateAndDay

echo Failed to get creation date of "%FolderPath%"
endlocal
pause
exit /B

:OutputDateAndDay
echo %CreationDate%
set "Day=%CreationDate:~0,2%
echo %Day%
endlocal
pause
</code>```

Once the line of interest with the creation date of specified folder is found, the creation date/time is assigned to an environment variable and the FOR loop is exited with using command GOTO to continue execution on a label below. For the meaning of operator & see single line with multiple commands using Windows batch file.

This solution is better than all other methods because the FOR loop executes the single command line with the three commands IF, SET and GOTO only once which makes this solution the fastest. And it outputs an error message when it was not possible to determine the creation date of the directory because of the directory does not exist at all.

Of course it would be possible to add a GOTO command also on the other solutions to exit FOR loop once the creation date of the directory was determined and output. The last solution is nevertheless the fastest and in my point of view best one for this task.

BTW: All posted batch file examples were tested on Windows XP and produced the expected output.

Body:
In my efforts to understand the for..do loops syntax and their use of %% variables. I have gone through 2 specific examples/implementations where the one for loop does not use DELAYEDEXPANSION and another where it does use DELAYEDEXPANSION with the ! notation. The 1st for loop appears to be compatible with older OSs like the Windows XP whereas the 2nd for loop example does not.

Specifically, the 1st for loop example is taken from this answer (which is related to this) and the 2nd for loop example is taken from this answer.

Modified code for both examples copied below:

1st for loop

for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a"
set "YY=%dt:~2,2%"
set "YYYY=%dt:~0,4%"
set "MM=%dt:~4,2%"
set "DD=%dt:~6,2%"
set "HH=%dt:~8,2%"
set "Min=%dt:~10,2%"
set "Sec=%dt:~12,2%"
set "datestamp=%YYYY%%MM%%DD%"
set "timestamp=%HH%%Min%%Sec%"
echo datestamp: "%datestamp%"
echo timestamp: "%timestamp%"

2nd for loop

SETLOCAL ENABLEDELAYEDEXPANSION
set "path_of_folder=C:\folderA\folderB"

for /f "skip=5 tokens=1,2,4 delims= " %%a in (
 'dir /ad /tc "%path_of_folder%\."') do IF "%%c"=="." (
  set "dt=%%a"
  set vara=%%a
  set varb=%%b
  echo !vara!, !varb!
  set day=!vara:~0,2!
  echo !day!
)

Since I have been reading and seeing issues where delayed expansion (or the ! notation) is not compatible with older OSs (e.g. Windows XP), I would like to see how to write the 2nd loop like the 1st loop; i.e. without the use of DELAYEDEXPANSION.

Body:
I explain in detail what aschipfl wrote already absolutely right in his comment.

Both batch files work also on Windows 2000 and Windows XP using also cmd.exe as command processor. The batch files do not work on MS-DOS, Windows 95 and Windows 98 using very limited command.com as command interpreter.

A command can be executed with parameter /? in a command prompt window to get output the help for this command. When in help is written with enabled command extensions it means supported only by cmd.exe on Windows NT based Windows versions and not supported by MS-DOS or Windows 9x using command.com. That means, for example, for /F or if /I or call :Subroutine are not available on Windows 9x, or on Windows NT based Windows with command extensions explicitly disabled. On Windows 9x it is not even possible to use "%~1" or "%~nx1".

The first batch file executes in FOR loop only one command exactly once:

set "dt=%%a"

That command line requires already enabled command extensions. All other commands below are executed after the FOR loop finished. In other words the FOR loop in first batch file does not use a command block to run multiple commands within the FOR loop.

Whenever the Windows command processor detects the beginning of a command block on a command line, it processes the entire command block before executing the command on this command line the first time.

This means for second batch file all variable references using %Variable% are expanded already before the command FOR is executed and then the commands in the command block are executed with the values of the variables as defined above FOR command line. This can be seen by removing @echo off from first line of batch file or change it to @echo ON and run the batch file from within a command prompt window because now it can be seen which command lines respectively entire command blocks defined with ( ... ) are really executed after preprocessing them by the Windows command processor.

So whenever an environment variable is defined or modified within a command block and its value is referenced in same command block it is necessary to use delayed expansion or use workarounds.

One workaround is demonstrated below:

setlocal EnableExtensions DisableDelayedExpansion
set "FolderPath=%SystemRoot%\System32"

for /F "skip=5 tokens=1,2,4 delims= " %%a in ('dir /AD /TC "%FolderPath%\."') do if "%%c"=="." (
    set "VarA=%%a"
    set "VarB=%%b"
    call echo %%VarA%%, %%VarB%%
    call set "Day=%%VarA:~0,2%%
    call echo %%Day%%
)

endlocal
pause

As there is no @echo off at top of this batch code it can be seen on executing the batch file what happens here. Each %% is modified on processing the command block to just %. So executed are the command lines.

call echo %VarA%, %VarB%
call set "Day=%VarA:~0,2%
call echo %Day%

The command CALL is used to process the rest of the line a second time  to run the ECHO and the SET commands with environment variable references replaced by their corresponding values without or with string substitution.

The disadvantage of this solution is that CALL is designed primary for calling a batch file from within a batch file. For that reason the command lines above result in searching first in current directory and next in all directories of environment variable PATH for a file with name echo respectively set with a file extension of environment variable PATHEXT. That file searching behavior causes lots of file system accesses, especially on running those command lines in a FOR loop. If there is really found an executable or script file with file name echo or set, the executable respectively the script interpreter of the script file would be executed instead of the internal command of cmd.exe as usually done on using such a command line. So this solution is inefficient and not fail-safe on execution of the batch file.

Another workaround to avoid delayed expansion is using a subroutine:

@echo off
setlocal EnableExtensions DisableDelayedExpansion
set "FolderPath=%SystemRoot%\System32"

for /F "skip=5 tokens=1,2,4 delims= " %%a in ('dir /AD /TC "%FolderPath%\."') do if "%%c"=="." call :ProcessCreationDate "%%a" "%%b"

endlocal
pause
exit /B

:ProcessCreationDate
echo %~1, %~2
set "Day=%~1"
set "Day=%Day:~0,2%
echo %Day%
goto :EOF

A subroutine is like another batch file embedded in current batch file.

The command line with exit /B avoids a fall through to the code of the subroutine.

The command line with goto :EOF would not be necessary if the line above is the last line of the batch file. But it is recommended to use it nevertheless in case of more command lines are ever added later below like a second subroutine.

The second batch file is for getting the day on which the specified folder was created. It would be possible to code this batch file without usage of delayed expansion and any workarounds.

@echo off
setlocal EnableExtensions DisableDelayedExpansion
set "FolderPath=%SystemRoot%\System32"

for /F "skip=5 tokens=1,2,4 delims= " %%a in ('dir /ad /tc "%FolderPath%\." 2^>nul') do if "%%c"=="." set "CreationDate=%%a, %%b" & goto OutputDateAndDay

echo Failed to get creation date of "%FolderPath%"
endlocal
pause
exit /B

:OutputDateAndDay
echo %CreationDate%
set "Day=%CreationDate:~0,2%
echo %Day%
endlocal
pause

Once the line of interest with the creation date of specified folder is found, the creation date/time is assigned to an environment variable and the FOR loop is exited with using command GOTO to continue execution on a label below. For the meaning of operator & see single line with multiple commands using Windows batch file.

This solution is better than all other methods because the FOR loop executes the single command line with the three commands IF, SET and GOTO only once which makes this solution the fastest. And it outputs an error message when it was not possible to determine the creation date of the directory because of the directory does not exist at all.

Of course it would be possible to add a GOTO command also on the other solutions to exit FOR loop once the creation date of the directory was determined and output. The last solution is nevertheless the fastest and in my point of view best one for this task.

BTW: All posted batch file examples were tested on Windows XP and produced the expected output.

ContentLicense: CC BY-SA 4.0


问:
How to center image in attributed string?
I have an image that I want to center alongside a bunch of text but even when I set the NSMutableParagraphStyle alignment to center, the line with the image does not center

If anyone could please help me center the line with the image (i.e. first line) that would be great!

Code

```<code>let text = " text next to image is not centered \n\n centered text \n more centered text"
let iconAttachment = textAttachment(fontSize: 14, image: #imageLiteral(resourceName: "icon"))
        let iconString = NSAttributedString(attachment: iconAttachment)
let style = NSMutableParagraphStyle()
        style.alignment = .center
        style.minimumLineHeight = 20

        let attributedText = NSMutableAttributedString()
        attributedText.append(iconString)
        let fullText = NSAttributedString(string: text, attributes: [NSParagraphStyleAttributeName : style])
        attributedText.append(fullText)

private func textAttachment(fontSize: CGFloat, image: UIImage) -> NSTextAttachment {
        let font = UIFont.systemFont(ofSize: fontSize) //set accordingly to your font, you might pass it in the function
        let textAttachment = NSTextAttachment()
            textAttachment.image = image
        let mid = font.descender + font.capHeight
        textAttachment.bounds = CGRect(x: 0, y: font.descender - image.size.height / 2 + mid + 2, width: image.size.width, height: image.size.height).integral
        return textAttachment
    }
</code>```

答:
Here is the code to achieve desire image in center.

```<code>    let text = "\ntext next to image is not centered \n\n centered text \n more centered text"
    let iconAttachment = textAttachment(fontSize: 5, image: #imageLiteral(resourceName: "eye"))
    let iconString = NSAttributedString(attachment: iconAttachment)
    let style = NSMutableParagraphStyle()
    style.alignment = .center
    style.minimumLineHeight = 20

    let attributedText = NSMutableAttributedString()
    attributedText.append(iconString)
    let fullText = NSAttributedString(string: text, attributes: [NSParagraphStyleAttributeName : style])
    attributedText.append(fullText)
    lbl.attributedText = attributedText;
    lbl.numberOfLines = 0
    lbl.lineBreakMode = .byWordWrapping
    lbl.textAlignment = .center
</code>```

Output

Note : no change in function

Body:
I have an image that I want to center alongside a bunch of text but even when I set the NSMutableParagraphStyle alignment to center, the line with the image does not center

If anyone could please help me center the line with the image (i.e. first line) that would be great!

Code

let text = " text next to image is not centered \n\n centered text \n more centered text"
let iconAttachment = textAttachment(fontSize: 14, image: #imageLiteral(resourceName: "icon"))
        let iconString = NSAttributedString(attachment: iconAttachment)
let style = NSMutableParagraphStyle()
        style.alignment = .center
        style.minimumLineHeight = 20

        let attributedText = NSMutableAttributedString()
        attributedText.append(iconString)
        let fullText = NSAttributedString(string: text, attributes: [NSParagraphStyleAttributeName : style])
        attributedText.append(fullText)

private func textAttachment(fontSize: CGFloat, image: UIImage) -> NSTextAttachment {
        let font = UIFont.systemFont(ofSize: fontSize) //set accordingly to your font, you might pass it in the function
        let textAttachment = NSTextAttachment()
            textAttachment.image = image
        let mid = font.descender + font.capHeight
        textAttachment.bounds = CGRect(x: 0, y: font.descender - image.size.height / 2 + mid + 2, width: image.size.width, height: image.size.height).integral
        return textAttachment
    }

Body:
Here is the code to achieve desire image in center.

    let text = "\ntext next to image is not centered \n\n centered text \n more centered text"
    let iconAttachment = textAttachment(fontSize: 5, image: #imageLiteral(resourceName: "eye"))
    let iconString = NSAttributedString(attachment: iconAttachment)
    let style = NSMutableParagraphStyle()
    style.alignment = .center
    style.minimumLineHeight = 20

    let attributedText = NSMutableAttributedString()
    attributedText.append(iconString)
    let fullText = NSAttributedString(string: text, attributes: [NSParagraphStyleAttributeName : style])
    attributedText.append(fullText)
    lbl.attributedText = attributedText;
    lbl.numberOfLines = 0
    lbl.lineBreakMode = .byWordWrapping
    lbl.textAlignment = .center

Output

Note : no change in function


问:
set default option in select
```<code><form (ngSubmit)="onSubmit()" #myForm="ngForm">
            <div class="form-group">
                <select name="location" class="form-control" class="selectLocation" [(ngModel)]="nameSelectedVal" (ngModelChange)="onChange($event)">

                    <option *ngFor="let location of locations" [ngValue]="location.code" [disabled]="location.code==0">
                        {{location.city}}
                    </option>

                </select>

                <p class="selectArrow"><button  [disabled]="disableFlag" routerLink="/my-bookride" class="leftArrow">
                <span class="glyphicon glyphicon-arrow-right"></span></button></p>
            </div>
        </form>
</code>```

This is form which i am using to select the option i need to display Select one city as default option when form is loaded

```<code>export class locationComponent
 {
      butDisabled: boolean = true;
    disableFlag:boolean = true;;
       private locations: any;
  constructor() {

        this.locations = [
  {
    "code": 0,
    "city": "Select one city"
  },
  {
    "code": 1,
    "city": "Hyderabad"
  },
  {
    "code": 2,
    "city": "Banglore"
  }
];
  this.nameSelectedVal = this.locations[0];
}

onChange($event) {
    if($event!=="0"){
   this.disableFlag=false;
   } else{
   this.disableFlag=true;
   }
}
}
</code>```

This is were i am giving options to be displayed in HTML View
I have tried using  [ngValue] to set Select one city as default value

答:
Use as it is your HTML :

```<code>                <option *ngFor="let location of locations" [ngValue]="location.code" [disabled]="location.code==0">
                    {{location.city}}
                </option>

            </select>
</code>```

and inside the TS file assign :
this.nameSelectedVal = this.locations[0].code;

it will work.

Title: set default option in select

Body:
<form (ngSubmit)="onSubmit()" #myForm="ngForm">

                <select name="location" class="form-control" class="selectLocation" [(ngModel)]="nameSelectedVal" (ngModelChange)="onChange($event)">

                    <option *ngFor="let location of locations" [ngValue]="location.code" [disabled]="location.code==0">
                        {{location.city}}
                    </option>

                </select>

<button  [disabled]="disableFlag" routerLink="/my-bookride" class="leftArrow">
                </button>

        </form>

This is form which i am using to select the option i need to display Select one city as default option when form is loaded

export class locationComponent
 {
      butDisabled: boolean = true;
    disableFlag:boolean = true;;
       private locations: any;
  constructor() {

        this.locations = [
  {
    "code": 0,
    "city": "Select one city"
  },
  {
    "code": 1,
    "city": "Hyderabad"
  },
  {
    "code": 2,
    "city": "Banglore"
  }
];
  this.nameSelectedVal = this.locations[0];
}

onChange($event) {
    if($event!=="0"){
   this.disableFlag=false;
   } else{
   this.disableFlag=true;
   }
}
}

This is were i am giving options to be displayed in HTML View
I have tried using  [ngValue] to set Select one city as default value

Body:
Use as it is your HTML :

                <option *ngFor="let location of locations" [ngValue]="location.code" [disabled]="location.code==0">
                    {{location.city}}
                </option>

            </select>

and inside the TS file assign :
this.nameSelectedVal = this.locations[0].code;

it will work.


问:
How do I use yii2-dashboard?
I would like to use a dashboard for my system. I found this Yii2-dashboard module. I am not sure if it is like GII where you can create models, CRUD, etc. In short, does yii2-dashboard has a UI like GII? Or should I manually code it? Thanks a lot!</p>

答:
As the docs says, you have to code a little bit: Where do i go now - Yii2 Dashboard

You can start adding panels on to your dashboard using this method

```<code>\Yii::$app->dashboard->addPanel($name,$view,$section);
</code>```

The addPanel() function accepts 3 parameters

```<code>$name; /** name of the panel **/
$view; /** content of the panel **/
$section; /** section where the panel will be displayed**/
</code>```

Title: How do I use yii2-dashboard?

Body:
As the docs says, you have to code a little bit: Where do i go now - Yii2 Dashboard

You can start adding panels on to your dashboard using this method

\Yii::$app->dashboard->addPanel($name,$view,$section);

The addPanel() function accepts 3 parameters

$name; /** name of the panel **/
$view; /** content of the panel **/
$section; /** section where the panel will be displayed**/


问:
ArangoDB Dynamic AQL String Handler
Is it possible to use the aql string handler in ArangoDB to perform a dynamic query? I've tried a number of different ways but it always errors out. For example, I'd like to do something like this:

```<code>let sortExpression = sortByDate ? 'SORT ${date}' : `SORT ${name}`

const result = db._query(aql`
    FOR doc IN tickets
    ${sortExpression}
    RETURN doc
`)
</code>```

This example is very simplified, but I have a more complex situation where something like this would be really handy. Is there a way to make something like this work?

答:
If the query was more complex, and I had real variables to embed, I'd write this like the following:

```<code>let sortProp = sortByDate ? 'date' : 'name';

var query = aql`
    FOR doc IN tickets
       SORT @SORT_PROP@
       RETURN doc`;
query.query = query.query.replace('@SORT_PROP@', sortProp);
var result = db._query(query);
</code>```

Maybe this works for your use case, too.

Title: ArangoDB Dynamic AQL String Handler

Body:
Is it possible to use the aql string handler in ArangoDB to perform a dynamic query? I've tried a number of different ways but it always errors out. For example, I'd like to do something like this:

let sortExpression = sortByDate ? 'SORT ${date}' : `SORT ${name}`

const result = db._query(aql`
    FOR doc IN tickets
    ${sortExpression}
    RETURN doc
`)

This example is very simplified, but I have a more complex situation where something like this would be really handy. Is there a way to make something like this work?

Body:
If the query was more complex, and I had real variables to embed, I'd write this like the following:

let sortProp = sortByDate ? 'date' : 'name';

var query = aql`
    FOR doc IN tickets
       SORT @SORT_PROP@
       RETURN doc`;
query.query = query.query.replace('@SORT_PROP@', sortProp);
var result = db._query(query);

Maybe this works for your use case, too.


问:
Moving EditText input from an Activity to a Fragment of a swipe view
This is the MainActivity upon launch.  The user puts in a number then clicks the button and the Intent brings them to a swipe view with the number they entered.

```<code>public class MainActivity extends AppCompatActivity{
String number;
Button continueButton;
EditText NumberET;

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    continueButton = (Button) findViewById(R.id.ContinueButton);
    NumberET = (EditText) findViewById(R.id.etTotalAmount);
    continueButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            number = NumberET.getText().toString();
            if (number.equals("")) {
                Toast.makeText(getApplicationContext(), "Enter Number", Toast.LENGTH_SHORT).show();
            } else {
                Bundle bundle = new Bundle();
                bundle.putString("AMOUNT_KEY", number);
                FixedCosts fragment = new FixedCosts();
                fragment.setArguments(bundle);
                FragmentTransaction t = getSupportFragmentManager().beginTransaction();
                t.replace(R.id.container, fragment).commit();
                Intent intent = new Intent(MainActivity.this, FragmentActivity.class);
                intent.putExtra("NUMBER", number);
                startActivity(intent);
            }
        }
    });
}
</code>```

In the fragment, I would like to set the text of a textview to display that number.  I cannot get this number to send from this Activity class to the Fragment.  How can I fix this?

Fragment:

```<code>ublic class FixedCosts extends Fragment {
String amount;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fixed_costs_fragment, container, false);
    amount = this.getArguments().getString("AMOUNT_KEY");

    TextView TitletextView = (TextView) view.findViewById(R.id.amountTitle);
    TitletextView.setText(amount);
    return view;}}
</code>```

Here is the FragmentActivity that sets the swipe view:

```<code>public class FragmentActivity extends AppCompatActivity {
public static final String MY_CUSTOM_FRAGMENT_KEY = "I_GOT_THE_KEYS";

String MoneyAmount;

/**
 * The {@link android.support.v4.view.PagerAdapter} that will provide
 * fragments for each of the sections. We use a
 * {@link FragmentPagerAdapter} derivative, which will keep every
 * loaded fragment in memory. If this becomes too memory intensive, it
 * may be best to switch to a
 * {@link android.support.v4.app.FragmentStatePagerAdapter}.
 */
private SectionsPagerAdapter mSectionsPagerAdapter;

/**
 * The {@link ViewPager} that will host the section contents.
 */
private ViewPager mViewPager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.fragment);

    /*MoneyAmount = getIntent().getExtras().getString("AmountMoney");*/

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    // Create the adapter that will return a fragment for each of the three
    // primary sections of the activity.
    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.container);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(mViewPager);

}
private Fragment createCustomFragment(){
    Bundle bundle = new Bundle();
    bundle.putString(MY_CUSTOM_FRAGMENT_KEY, MoneyAmount);

    PlaceholderFragment placeholderFragment = new PlaceholderFragment();
    placeholderFragment.setArguments(bundle);
    return placeholderFragment;
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

/**
 * A placeholder fragment containing a simple view.
 */
public static class PlaceholderFragment extends Fragment {
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
    private static final String ARG_SECTION_NUMBER = "section_number";

    public PlaceholderFragment() {
    }

    /**
     * Returns a new instance of this fragment for the given section
     * number.
     */
    public static PlaceholderFragment newInstance(int sectionNumber, String MoneyAmount) {
        PlaceholderFragment fragment = new PlaceholderFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        args.putString(MY_CUSTOM_FRAGMENT_KEY, MoneyAmount);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, container, false);
        Bundle bundle = getArguments();
        /*String amount = bundle.getString(MY_CUSTOM_FRAGMENT_KEY);
        TextView TitletextView = (TextView) FixedCosts.class.findViewById(R.id.amountTitle);
        TitletextView.setText(amount);*/

        TextView textView = (TextView) rootView.findViewById(R.id.section_label);
        textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
        return rootView;
    }
}

/**
 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
 * one of the sections/tabs/pages.
 */
public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }
    @Override
    public Fragment getItem(int position) {
       switch (position){
           case 0:
               FixedCosts fixedCosts = new FixedCosts();

               return fixedCosts;
       }
        return PlaceholderFragment.newInstance(position + 1, MoneyAmount);
    }
    @Override
    public int getCount() {
        // Show 3 total pages.
        return 3;
    }
    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return "Fixed Costs";
            case 1:
                return "Long term investments";
            case 2:
                return "SECTION 3";
        }
        return null;
    }
}
</code>```

}

答:
Remove activity start code in continueButton.setOnClickListener listener and add view container in same layout for parent activity not in fragment activity:

```<code>public class MainActivity extends AppCompatActivity{
String number;
Button continueButton;
EditText NumberET;

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    continueButton = (Button) findViewById(R.id.ContinueButton);
    NumberET = (EditText) findViewById(R.id.etTotalAmount);
    continueButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            number = NumberET.getText().toString();
            if (amount.equals("")) {
                Toast.makeText(getApplicationContext(), "Enter Number", Toast.LENGTH_SHORT).show();
            } else {
                Bundle bundle = new Bundle();
                bundle.putString("AMOUNT_KEY", number);
                FixedCosts fragment = new FixedCosts();
                fragment.setArguments(bundle);
                FragmentTransaction t = getSupportFragmentManager().beginTransaction();
                t.replace(R.id.container, fragment).commit();
            }
        }
    });
}
</code>```

Hope it will help you.

Body:
This is the MainActivity upon launch.  The user puts in a number then clicks the button and the Intent brings them to a swipe view with the number they entered.

public class MainActivity extends AppCompatActivity{
String number;
Button continueButton;
EditText NumberET;

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    continueButton = (Button) findViewById(R.id.ContinueButton);
    NumberET = (EditText) findViewById(R.id.etTotalAmount);
    continueButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            number = NumberET.getText().toString();
            if (number.equals("")) {
                Toast.makeText(getApplicationContext(), "Enter Number", Toast.LENGTH_SHORT).show();
            } else {
                Bundle bundle = new Bundle();
                bundle.putString("AMOUNT_KEY", number);
                FixedCosts fragment = new FixedCosts();
                fragment.setArguments(bundle);
                FragmentTransaction t = getSupportFragmentManager().beginTransaction();
                t.replace(R.id.container, fragment).commit();
                Intent intent = new Intent(MainActivity.this, FragmentActivity.class);
                intent.putExtra("NUMBER", number);
                startActivity(intent);
            }
        }
    });
}

In the fragment, I would like to set the text of a textview to display that number.  I cannot get this number to send from this Activity class to the Fragment.  How can I fix this?

Fragment:

ublic class FixedCosts extends Fragment {
String amount;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fixed_costs_fragment, container, false);
    amount = this.getArguments().getString("AMOUNT_KEY");

    TextView TitletextView = (TextView) view.findViewById(R.id.amountTitle);
    TitletextView.setText(amount);
    return view;}}

Here is the FragmentActivity that sets the swipe view:

public class FragmentActivity extends AppCompatActivity {
public static final String MY_CUSTOM_FRAGMENT_KEY = "I_GOT_THE_KEYS";

String MoneyAmount;

/**
 * The {@link android.support.v4.view.PagerAdapter} that will provide
 * fragments for each of the sections. We use a
 * {@link FragmentPagerAdapter} derivative, which will keep every
 * loaded fragment in memory. If this becomes too memory intensive, it
 * may be best to switch to a
 * {@link android.support.v4.app.FragmentStatePagerAdapter}.
 */
private SectionsPagerAdapter mSectionsPagerAdapter;

/**
 * The {@link ViewPager} that will host the section contents.
 */
private ViewPager mViewPager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.fragment);

    /*MoneyAmount = getIntent().getExtras().getString("AmountMoney");*/

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    // Create the adapter that will return a fragment for each of the three
    // primary sections of the activity.
    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.container);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(mViewPager);

}
private Fragment createCustomFragment(){
    Bundle bundle = new Bundle();
    bundle.putString(MY_CUSTOM_FRAGMENT_KEY, MoneyAmount);

    PlaceholderFragment placeholderFragment = new PlaceholderFragment();
    placeholderFragment.setArguments(bundle);
    return placeholderFragment;
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

/**
 * A placeholder fragment containing a simple view.
 */
public static class PlaceholderFragment extends Fragment {
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
    private static final String ARG_SECTION_NUMBER = "section_number";

    public PlaceholderFragment() {
    }

    /**
     * Returns a new instance of this fragment for the given section
     * number.
     */
    public static PlaceholderFragment newInstance(int sectionNumber, String MoneyAmount) {
        PlaceholderFragment fragment = new PlaceholderFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        args.putString(MY_CUSTOM_FRAGMENT_KEY, MoneyAmount);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, container, false);
        Bundle bundle = getArguments();
        /*String amount = bundle.getString(MY_CUSTOM_FRAGMENT_KEY);
        TextView TitletextView = (TextView) FixedCosts.class.findViewById(R.id.amountTitle);
        TitletextView.setText(amount);*/

        TextView textView = (TextView) rootView.findViewById(R.id.section_label);
        textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
        return rootView;
    }
}

/**
 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
 * one of the sections/tabs/pages.
 */
public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }
    @Override
    public Fragment getItem(int position) {
       switch (position){
           case 0:
               FixedCosts fixedCosts = new FixedCosts();

               return fixedCosts;
       }
        return PlaceholderFragment.newInstance(position + 1, MoneyAmount);
    }
    @Override
    public int getCount() {
        // Show 3 total pages.
        return 3;
    }
    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return "Fixed Costs";
            case 1:
                return "Long term investments";
            case 2:
                return "SECTION 3";
        }
        return null;
    }
}

}

Body:
Remove activity start code in continueButton.setOnClickListener listener and add view container in same layout for parent activity not in fragment activity:

public class MainActivity extends AppCompatActivity{
String number;
Button continueButton;
EditText NumberET;

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    continueButton = (Button) findViewById(R.id.ContinueButton);
    NumberET = (EditText) findViewById(R.id.etTotalAmount);
    continueButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            number = NumberET.getText().toString();
            if (amount.equals("")) {
                Toast.makeText(getApplicationContext(), "Enter Number", Toast.LENGTH_SHORT).show();
            } else {
                Bundle bundle = new Bundle();
                bundle.putString("AMOUNT_KEY", number);
                FixedCosts fragment = new FixedCosts();
                fragment.setArguments(bundle);
                FragmentTransaction t = getSupportFragmentManager().beginTransaction();
                t.replace(R.id.container, fragment).commit();
            }
        }
    });
}

Hope it will help you.


问:
MVVM access Richtextbox flowdocument from VM
I am trying to make a RichTextBox with a FlowDocument that I can insert text at the caret position.  I can add text to the end of the document.  I think I am missing something in my setup to that allows my VM to access the Flowocument or I am setting it up wrong.  If I create a FlowDocument in my VM and try to set my RichTextBox to it I get an error that my MyEditor (RichTextBox) does not exist. I can add text to the RichTextBox using what I call the AddItemBtn from a ListBox so at least that much works.

My question is "How should I set my RichTextBox/FlowDocument up?

XAML code

```<code><Window x:Class="Scripter.Views.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:Scripter.ViewModels"
    xmlns:wpftoolkit="clr-namespace:Xceed.Wpf.Toolkit;assembly=Xceed.Wpf.Toolkit"
    Title="MainWindow" Height="350" Width="725">

<Grid HorizontalAlignment="Stretch">

    <Grid HorizontalAlignment="Stretch" Height="72" Margin="10,14,0,0" VerticalAlignment="Top" Width="auto">
        <WrapPanel HorizontalAlignment="Left" Height="50" Margin="10,0,0,0" VerticalAlignment="Top">

        </WrapPanel>
        <Button x:Name="OpenFilesBtn" Content="Open" HorizontalAlignment="Left" Margin="15,10,0,0" VerticalAlignment="Top" Width="75" Command="{Binding OpenFileBtn}"/>
        <Button x:Name="SavefilesBtn" Content="Save" HorizontalAlignment="Left" Margin="104,10,0,0" VerticalAlignment="Top" Width="75" Command="{Binding SaveFileBtn}"/>
        <TextBlock x:Name="OpenFile" Text="{Binding OpenFile,Mode=OneWay, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Left" Margin="15,37,0,0" VerticalAlignment="Top" Width="353"/>
        <ComboBox x:Name="TipsBtn" SelectedIndex="0" ItemsSource="{Binding Path=Tabs, UpdateSourceTrigger=PropertyChanged}" SelectedItem="{Binding Path=SelectedOption}"  HorizontalAlignment="Left" Margin="538,10,0,0" VerticalAlignment="Top" Width="120"/>
        <Button x:Name="AddItemBtn" Content="Add Item" HorizontalAlignment="Left" Margin="417,10,0,0" VerticalAlignment="Top" Width="100" Command="{Binding AddItemBtn}" CommandParameter="{Binding ElementName=AddItemList,Path=SelectedItem}"/>

    </Grid>
    <Grid Margin="10,100,10,0">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="2*"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <RichTextBox  Grid.Column="0" x:Name="MyEditor" SelectionChanged="MyEditor_SelectionChanged" ScrollViewer.VerticalScrollBarVisibility="Auto" Margin="0" Height="Auto" HorizontalAlignment="Stretch"  VerticalAlignment="Stretch" Width="Auto" IsDocumentEnabled="True" AcceptsTab="True" AcceptsReturn="True" >
            <RichTextBox.Resources>
                <Style TargetType="{x:Type Paragraph}">
                    <Setter Property="Margin" Value="0" ></Setter>
                    <Setter Property="FontSize" Value="15"></Setter>
                </Style>
            </RichTextBox.Resources>
            <FlowDocument >
                <Paragraph >
                    <Run Text="{Binding TestText}" ></Run>
                </Paragraph>
            </FlowDocument>
        </RichTextBox>
        <ListBox x:Name="AddItemList" Grid.Column="1" Width="Auto" Height="Auto" ItemsSource="{Binding Path=OptionsToChoose}" SelectedItem="ItemSelected">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <TextBlock x:Name="TextSelected" Text="{Binding Description}" />
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

    </Grid>
</Grid>
</code>```

VM code that has the issue

```<code>public ScripterViewModel()
    {
        ScripterModel scripterModel = new ScripterModel();

        ObservableCollection<string> tabsChoice = new ObservableCollection<string>();
        tabsChoice.Add("Tabs");
        tabsChoice.Add("Buttons");
        Tabs = tabsChoice;

        this.OpenFileBtn = new DelegateCommand(chooseFile, canChooseFile).ObservesProperty(() => OpenFile);
        this.SaveFileBtn = new DelegateCommand(saveFile, canSaveFile).ObservesProperty(() => SaveFile);
        this.AddItemBtn = new DelegateCommand<Tabbed>(addItem);

        FlowDocument flowDoc = new FlowDocument();

        Paragraph p = new Paragraph(new Run("new paragraph"));
        flowDoc.Blocks.Add(new Paragraph(new Run("Paragraph 1")));
        flowDoc.Blocks.Add(p);

        //MyEditor = flowDoc;

    }

    public void MyEditor_SelectionChanged(object sender, RoutedEventArgs e)
    {
      // TextRange tempRange = new TextRange(MyEditor.Document.ContentStart, MyEditor.Selection.Start);
        MessageBox.Show("Selection Changed");

    }

    private string _testText;
    public string TestText
    {
        get
        {
            return _testText;
        }

        set
        {
            string _temp;
            _temp = _testText + value;
            SetProperty(ref _testText, value);
        }

    }
</code>```

答:
Hey I am new to WPF and MVVM but I'll give my best to help you. So don't blame me if I'm wrong.

1. Set Window.DataContext

First of all you have to tell your View where it can get the data from.
This can be done by adding this code to your View.xaml:

```<code><Window.DataContext>
    <local:MainViewModel/>
</Window.DataContext>
</code>```

But make sure your namespace variable (here "local") points to your ViewModels.

```<code>xmlns:local="clr-namespace:Client.ViewModel"
</code>```

This for ex. points to my ViewModel folder.

2. Define a OnPropertyChanged method

Your View won't know if you have modified a variable. So you need a method to notify your View about the changes.
First of all implement the interface INotifyPropertyChanged to your ViewModel.

```<code>public class MainViewModel : ViewModelBase, INotifyPropertyChanged
</code>```

Now add this code:

```<code>    public event PropertyChangedEventHandler PropertyChanged;
    public void OnPropertyChanged([CallerMemberName]string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
</code>```

3. Use OnPropertyChanged

So now you have a method to tell your View that a variable has changed but how do you use it?
To explain this to you I'll use your FlowDocument flowDoc.

So let's begin by defining your FlowDocument setting up :

```<code>private FlowDocument _flowDoc;

</code>```

Now lets write a getter & setter for flowDoc:

```<code>    public FlowDocument FlowDoc
    {
        get
        {
            return _flowDoc;
        }
        set
        {
           _flowDoc = value;
        }
    }
</code>```

Now it's time to use our OnPropertyChanged method which we created in 2.
In the setter section you want to add the following Code:

```<code>OnPropertyChanged("variable");
</code>```

Your result should now look like this:

```<code>public FlowDocument FlowDoc
    {
        get
        {
            return _flowDoc;
        }
        set
        {
           _flowDoc = value;
           OnPropertyChanged("FlowDoc");
        }
    }
</code>```

Important: remember to apply this to all your variables!

4. Use MVVM pattern right

In MVVM you have a Model a View and a ViewModel.
The Model is for your data so if possible don't store data in your ViewModel instead use a data class for ex.

You may have a look at this and/or this.

As I said in the beginning I'm new to all of this but i hope it helps
you. Feel free to ask.

Body:
I am trying to make a RichTextBox with a FlowDocument that I can insert text at the caret position.  I can add text to the end of the document.  I think I am missing something in my setup to that allows my VM to access the Flowocument or I am setting it up wrong.  If I create a FlowDocument in my VM and try to set my RichTextBox to it I get an error that my MyEditor (RichTextBox) does not exist. I can add text to the RichTextBox using what I call the AddItemBtn from a ListBox so at least that much works.

My question is "How should I set my RichTextBox/FlowDocument up?

XAML code

<Window x:Class="Scripter.Views.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:Scripter.ViewModels"
    xmlns:wpftoolkit="clr-namespace:Xceed.Wpf.Toolkit;assembly=Xceed.Wpf.Toolkit"
    Title="MainWindow" Height="350" Width="725">

<Grid HorizontalAlignment="Stretch">

    <Grid HorizontalAlignment="Stretch" Height="72" Margin="10,14,0,0" VerticalAlignment="Top" Width="auto">
        <WrapPanel HorizontalAlignment="Left" Height="50" Margin="10,0,0,0" VerticalAlignment="Top">

        </WrapPanel>
        <Button x:Name="OpenFilesBtn" Content="Open" HorizontalAlignment="Left" Margin="15,10,0,0" VerticalAlignment="Top" Width="75" Command="{Binding OpenFileBtn}"/>
        <Button x:Name="SavefilesBtn" Content="Save" HorizontalAlignment="Left" Margin="104,10,0,0" VerticalAlignment="Top" Width="75" Command="{Binding SaveFileBtn}"/>
        <TextBlock x:Name="OpenFile" Text="{Binding OpenFile,Mode=OneWay, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Left" Margin="15,37,0,0" VerticalAlignment="Top" Width="353"/>
        <ComboBox x:Name="TipsBtn" SelectedIndex="0" ItemsSource="{Binding Path=Tabs, UpdateSourceTrigger=PropertyChanged}" SelectedItem="{Binding Path=SelectedOption}"  HorizontalAlignment="Left" Margin="538,10,0,0" VerticalAlignment="Top" Width="120"/>
        <Button x:Name="AddItemBtn" Content="Add Item" HorizontalAlignment="Left" Margin="417,10,0,0" VerticalAlignment="Top" Width="100" Command="{Binding AddItemBtn}" CommandParameter="{Binding ElementName=AddItemList,Path=SelectedItem}"/>

    </Grid>
    <Grid Margin="10,100,10,0">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="2*"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <RichTextBox  Grid.Column="0" x:Name="MyEditor" SelectionChanged="MyEditor_SelectionChanged" ScrollViewer.VerticalScrollBarVisibility="Auto" Margin="0" Height="Auto" HorizontalAlignment="Stretch"  VerticalAlignment="Stretch" Width="Auto" IsDocumentEnabled="True" AcceptsTab="True" AcceptsReturn="True" >
            <RichTextBox.Resources>

            </RichTextBox.Resources>
            <FlowDocument >
                <Paragraph >
                    <Run Text="{Binding TestText}" ></Run>
                </Paragraph>
            </FlowDocument>
        </RichTextBox>
        <ListBox x:Name="AddItemList" Grid.Column="1" Width="Auto" Height="Auto" ItemsSource="{Binding Path=OptionsToChoose}" SelectedItem="ItemSelected">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <TextBlock x:Name="TextSelected" Text="{Binding Description}" />
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

    </Grid>
</Grid>

VM code that has the issue

public ScripterViewModel()
    {
        ScripterModel scripterModel = new ScripterModel();

        ObservableCollection<string> tabsChoice = new ObservableCollection<string>();
        tabsChoice.Add("Tabs");
        tabsChoice.Add("Buttons");
        Tabs = tabsChoice;

        this.OpenFileBtn = new DelegateCommand(chooseFile, canChooseFile).ObservesProperty(() => OpenFile);
        this.SaveFileBtn = new DelegateCommand(saveFile, canSaveFile).ObservesProperty(() => SaveFile);
        this.AddItemBtn = new DelegateCommand<Tabbed>(addItem);

        FlowDocument flowDoc = new FlowDocument();

        Paragraph p = new Paragraph(new Run("new paragraph"));
        flowDoc.Blocks.Add(new Paragraph(new Run("Paragraph 1")));
        flowDoc.Blocks.Add(p);

        //MyEditor = flowDoc;

    }

    public void MyEditor_SelectionChanged(object sender, RoutedEventArgs e)
    {
      // TextRange tempRange = new TextRange(MyEditor.Document.ContentStart, MyEditor.Selection.Start);
        MessageBox.Show("Selection Changed");

    }

    private string _testText;
    public string TestText
    {
        get
        {
            return _testText;
        }

        set
        {
            string _temp;
            _temp = _testText + value;
            SetProperty(ref _testText, value);
        }

    }

Body:
Hey I am new to WPF and MVVM but I'll give my best to help you. So don't blame me if I'm wrong.

1. Set Window.DataContext

First of all you have to tell your View where it can get the data from.
This can be done by adding this code to your View.xaml:

<Window.DataContext>
    <local:MainViewModel/>
</Window.DataContext>

But make sure your namespace variable (here "local") points to your ViewModels.

xmlns:local="clr-namespace:Client.ViewModel"

This for ex. points to my ViewModel folder.

2. Define a OnPropertyChanged method

Your View won't know if you have modified a variable. So you need a method to notify your View about the changes.
First of all implement the interface INotifyPropertyChanged to your ViewModel.

public class MainViewModel : ViewModelBase, INotifyPropertyChanged

Now add this code:

    public event PropertyChangedEventHandler PropertyChanged;
    public void OnPropertyChanged([CallerMemberName]string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

3. Use OnPropertyChanged

So now you have a method to tell your View that a variable has changed but how do you use it?
To explain this to you I'll use your FlowDocument flowDoc.

So let's begin by defining your FlowDocument setting up :

private FlowDocument _flowDoc;

Now lets write a getter & setter for flowDoc:

    public FlowDocument FlowDoc
    {
        get
        {
            return _flowDoc;
        }
        set
        {
           _flowDoc = value;
        }
    }

Now it's time to use our OnPropertyChanged method which we created in 2.
In the setter section you want to add the following Code:

OnPropertyChanged("variable");

Your result should now look like this:

public FlowDocument FlowDoc
    {
        get
        {
            return _flowDoc;
        }
        set
        {
           _flowDoc = value;
           OnPropertyChanged("FlowDoc");
        }
    }

Important: remember to apply this to all your variables!

4. Use MVVM pattern right

In MVVM you have a Model a View and a ViewModel.
The Model is for your data so if possible don't store data in your ViewModel instead use a data class for ex.

You may have a look at this and/or this.

As I said in the beginning I'm new to all of this but i hope it helps
you. Feel free to ask.


问:
how do I set the right view on my controller
I was able to insert data through jquery ajax using modal but the problem is i get a different view

This is my AjaxCrudController

```<code>public function store(Request $request) {
    //
    $create = Post::create($request->all());
    return response()->json($create);
}
</code>```

I want to view the page were my table is to see my added post it's on my ajax-crud-2.blade.php how do i get to this view?

答:
You have to do following,

Define Route:

```<code>Route::get('ajax/crud/2','AjaxCrudController@getAjaxCrud2');
</code>```

Make function:

```<code>public function getAjaxCrud2(){
     $data = Post::all();
     return view('ajax-crud-2',compact('data'));
}
</code>```

Now, when ajax call returns success then you have to redirect to route ajax/crud/2.

Body:
I was able to insert data through jquery ajax using modal but the problem is i get a different view

This is my AjaxCrudController

public function store(Request $request) {
    //
    $create = Post::create($request->all());
    return response()->json($create);
}

I want to view the page were my table is to see my added post it's on my ajax-crud-2.blade.php how do i get to this view?

Body:
You have to do following,

Define Route:

Route::get('ajax/crud/2','AjaxCrudController@getAjaxCrud2');

Make function:

public function getAjaxCrud2(){
     $data = Post::all();
     return view('ajax-crud-2',compact('data'));
}

Now, when ajax call returns success then you have to redirect to route ajax/crud/2.


问:
Add a number after a string, if it already exists
I'm working on a script that checks if the url already exists in the database, and if yes adds an additional -1 or -2 etc etc at the end. I found this script

But it 'd need to to check it again after adding-1. Since it may be already existing. How can I do that? I tired i this way

```<code>        $query = mysql_query("SELECT * FROM posts WHERE url='$url'");

        while ( $query ) {

            $result = mysql_fetch_assoc($query);
            $url = $result['url'];
            $urlnew = $result['url'];
            $oldurl = $url;
            $first = 1;
            $separator = '-';

            while ( $urlnew == $url ) {

                $url = preg_match('/(.+)'.$separator.'([0-9]+)$/', $urlnew, $match);

                $urlnew = isset($match[2]) ? $match[1].$separator.($match[2] + 1) : $url.$separator.$first;

                $first++;

            }
        $url = $urlnew;
        }
</code>```

The new code above works just fine. But it checks only once. How can I make it to check untill it dose not exists in the DB?

tried adding a new sql query at the bottom after $url -$urlnew but it only breaks the function.

EDIT

Here's the correct script :D

```<code>$query = mysql_query("SELECT * FROM posts WHERE url LIKE '%".$url."%'");

if ( $query ) {

    while ( $result = mysql_fetch_assoc($query) ) {

        $url = $result['url'];
        $urlnew = $result['url'];
        $first = 1;
        $separator = '-';

        while ( $urlnew == $url ) {

            preg_match('/(.+)'.$separator.'([0-9]+)$/', $urlnew, $match);

            $urlnew = isset($match[2]) ? $match[1].$separator.($match[2] + 1) :$url.$separator.$first;

            $first++;

        }

    }
}

$url = $urlnew;
</code>```

答:
Here's what I used for my needs</p>

```<code>function checkLink($link, $counter=1){
    global $connect;
    $newLink = $link;
    do{
        $checkLink = mysqli_query($connect, "SELECT id FROM table WHERE link = '$newLink'");
        if(mysqli_num_rows($checkLink) > 0){
            $newLink = $link.'-'.$counter;
            $counter++;
        } else {
            break;
        }
    } while(1);

    return $newLink;
}

$link = 'www.example.com';
$uniquelink = checkLink($link);
</code>```

Body:
I'm working on a script that checks if the url already exists in the database, and if yes adds an additional -1 or -2 etc etc at the end. I found this script

But it 'd need to to check it again after adding-1. Since it may be already existing. How can I do that? I tired i this way

        $query = mysql_query("SELECT * FROM posts WHERE url='$url'");

        while ( $query ) {

            $result = mysql_fetch_assoc($query);
            $url = $result['url'];
            $urlnew = $result['url'];
            $oldurl = $url;
            $first = 1;
            $separator = '-';

            while ( $urlnew == $url ) {

                $url = preg_match('/(.+)'.$separator.'([0-9]+)$/', $urlnew, $match);

                $urlnew = isset($match[2]) ? $match[1].$separator.($match[2] + 1) : $url.$separator.$first;

                $first++;

            }
        $url = $urlnew;
        }

The new code above works just fine. But it checks only once. How can I make it to check untill it dose not exists in the DB?

tried adding a new sql query at the bottom after $url -$urlnew but it only breaks the function.

EDIT

Here's the correct script :D

$query = mysql_query("SELECT * FROM posts WHERE url LIKE '%".$url."%'");

if ( $query ) {

    while ( $result = mysql_fetch_assoc($query) ) {

        $url = $result['url'];
        $urlnew = $result['url'];
        $first = 1;
        $separator = '-';

        while ( $urlnew == $url ) {

            preg_match('/(.+)'.$separator.'([0-9]+)$/', $urlnew, $match);

            $urlnew = isset($match[2]) ? $match[1].$separator.($match[2] + 1) :$url.$separator.$first;

            $first++;

        }

    }
}

$url = $urlnew;

Body:
Here's what I used for my needs

function checkLink($link, $counter=1){
    global $connect;
    $newLink = $link;
    do{
        $checkLink = mysqli_query($connect, "SELECT id FROM table WHERE link = '$newLink'");
        if(mysqli_num_rows($checkLink) > 0){
            $newLink = $link.'-'.$counter;
            $counter++;
        } else {
            break;
        }
    } while(1);

    return $newLink;
}

$link = 'www.example.com';
$uniquelink = checkLink($link);


问:
XMLHttpRequest cannot load and Response for preflight has invalid HTTP status code 405
I am using ionic framework and angularjs I use chrome for viewing my logs but here i am doing a login page I am trying to post the user entered data to serve but i am getting this error like .

```<code> OPTIONS http://aflaree.com/qrcodeservice/Service1.svc/login
</code>```

and this one is next error XMLHttpRequest cannot load  http://aflaree.com/qrcodeservice/Service1.svc/login Response for preflight has invalid HTTP status code 405
   after reading some blog i figure there is a CORS extention from from which allows ajax request i tried that also but i am not able to find why this two error is appearing. here is my code

https://plnkr.co/edit/Dz0aFsLqoQcnCxht00z3?p=preview

my code work fine in device but I am getting error in chrome if any one knows why please help me

答: For iOS devices, also check the protocol used. Using HTTPS instead of HTTP solved the issue for me.</p>

Body:
I am using ionic framework and angularjs I use chrome for viewing my logs but here i am doing a login page I am trying to post the user entered data to serve but i am getting this error like .

 OPTIONS http://aflaree.com/qrcodeservice/Service1.svc/login

and this one is next error XMLHttpRequest cannot load  http://aflaree.com/qrcodeservice/Service1.svc/login Response for preflight has invalid HTTP status code 405
   after reading some blog i figure there is a CORS extention from from which allows ajax request i tried that also but i am not able to find why this two error is appearing. here is my code

https://plnkr.co/edit/Dz0aFsLqoQcnCxht00z3?p=preview

my code work fine in device but I am getting error in chrome if any one knows why please help me


问:
Create and use multiple database for single application
I am creating a system which will have multiple customer. right now i am using same database and table for all customer but i think it'll slow down fetching of record when i'll have hundreds of customer's data in same database.
so should i create separate database for each new registered customer dynamically by executing scripts from code? (will use master database to manage all user's connectionstrings)

I'm using entity framework. so same will be possible using EF? will it cause any problem?

答:
May be you can use ABP framework to handle multiple database with entity framework.
ABP will help you to auto register repositories into IocContainer by adding attribute of all your DBContext (Each DBContext connect to a DB) as following:</p>

```<code>[AutoRepositoryTypes(
typeof(IRepository<>),
typeof(IRepository<,>),
typeof(SimpleTaskSystemEfRepositoryBase<>),
typeof(SimpleTaskSystemEfRepositoryBase<,>)
)]
public class SimpleTaskSystemDbContext : AbpDbContext
{
     ...
}
</code>```

Body:
May be you can use ABP framework to handle multiple database with entity framework.
ABP will help you to auto register repositories into IocContainer by adding attribute of all your DBContext (Each DBContext connect to a DB) as following:

[AutoRepositoryTypes(
typeof(IRepository<>),
typeof(IRepository<,>),
typeof(SimpleTaskSystemEfRepositoryBase<>),
typeof(SimpleTaskSystemEfRepositoryBase<,>)
)]
public class SimpleTaskSystemDbContext : AbpDbContext
{
     ...
}


问:
NavigableMap throwing unwanted exception
From java docs of NavigableMap :firstKey() of Navigable map

Returns a key-value mapping associated with the least key in this map, or null if the map is empty.

However, when i run the following program i am getting NoSuchElementException

```<code> public class Test1 {
        public static void main(String a[]) {
            NavigableMap<Object, Object> map = new TreeMap<>();
            Object obj = map.firstKey();
        }
    }
</code>```

I am not sure if i am missing something here, Please let me know why it is behaving like this?

答:
```<code>returns null if there is no key
</code>```

That is for value with key. But you are asking key itself.

K firstKey()

Returns:
      the first (lowest) key currently in this map

Throws:
      NoSuchElementException - if this map is empty

Body:
From java docs of NavigableMap :firstKey() of Navigable map

Returns a key-value mapping associated with the least key in this map, or null if the map is empty.

However, when i run the following program i am getting NoSuchElementException

 public class Test1 {
        public static void main(String a[]) {
            NavigableMap<Object, Object> map = new TreeMap<>();
            Object obj = map.firstKey();
        }
    }

I am not sure if i am missing something here, Please let me know why it is behaving like this?

Body:
returns null if there is no key

That is for value with key. But you are asking key itself.

K firstKey()

Returns:
      the first (lowest) key currently in this map

Throws:
      NoSuchElementException - if this map is empty


问:
Reverse Engineer a .pyo python file
I have 2 .pyo python files that I can convert to .py source files, but they don't compile perfectly as hinted by decompyle's verify.

Therefore looking at the source code, I can tell that config.pyo  simply had variables in in an array:

ADMIN_USERIDS = [116901,
 141,
 349244,
 39,
 1159488]

I would like to take the original .pyo and disassembly or whatever I need to do inorder to change one of these IDs.

Or....

in model.pyo the source indicates a

if (productsDeveloperId != self.getUserId()):

All I would want to do is hex edit the != to be a == .....Simple with a windows exe program but I can't find a good python disassembler anywhere.

Any suggestions are welcomed...I am new to reading bytecode and new to python as well.

答:
Very recently I've developed tools that should help with this sort of thing. Some of the stuff is still very much alpha, but with some work you could have used it here.

There are several disassemblers around and they generally appear in the decompiler. The one I am partial to of course is the one I wrote called xdis because it gives the most information about what is in the bytecode file. There is also one called pycdas written in C++ and is in the project that has the pycdc decompiler. So that part is not new.

Also, as you indicate you used a decompiler but it wasn't perfect. Hopefully in later versions called uncompyle6 these bugs have been addressed. But if not, file a github issue.

Ok. So now onto what is new. Recently I've modified the disassembler to make it amenable to modification and have written an Python assembler to store it back into the pyc bytecode format. This stuff is still in alpha; find it at http://github.com/rocky/python-xasm .

So with that you could make the simple changes to the constants and the condition tests.

So now let me go into the condition test since you asked about that specifically and it hasn't been fully answered here.

Consider this simple Python code:

```<code>  ___file__ == '__main'
</code>```

Let's disassemble that with pydisasm:

```<code>...
# Constants:
#    0: '__main'
#    1: None
# Names:
#    0: ___file__
  1:           0 LOAD_NAME                 0 (___file__)
               3 LOAD_CONST                0 ('__main')
               6 COMPARE_OP                2 (==)
               9 POP_TOP
              10 LOAD_CONST                1 (None)
              13 RETURN_VALUE
</code>```

Ok. so we see that the == is the operand of a COMPARE_OP
instructions which is encoded as 2.

Looking at the doc for this https://docs.python.org/3.6/library/dis.html#opcode-COMPARE_OP  (this is for Python 3.6, but it's the same across pretty much all Python versions) there is the marginally helpful explanation:

```<code>The operation name can be found in cmp_op[opname].
</code>```

But for the secret decoder ring information you'll have to go to the
Python source code for opcode.py which you probably have on your disk somewhere, but here's a link: https://github.com/python/cpython/blob/master/Lib/opcode.py#L24 where we have

```<code> cmp_op = ('<', '<=', '==', '!=', '>', '>=', 'in', 'not in', 'is', ...
</code>```

And you'll see that while == is 2, != is 3.

As for changing the constant [116901, 141, 349244, 39, 1159488] that would appear in my disassembler in the section called Constants and you'd basically change the numbers there and then run the assembler.

OwnerDisplayName: Brian

ContentLicense: CC BY-SA 2.5

Title: Reverse Engineer a .pyo python file

Body:
Very recently I've developed tools that should help with this sort of thing. Some of the stuff is still very much alpha, but with some work you could have used it here.

There are several disassemblers around and they generally appear in the decompiler. The one I am partial to of course is the one I wrote called xdis because it gives the most information about what is in the bytecode file. There is also one called pycdas written in C++ and is in the project that has the pycdc decompiler. So that part is not new.

Also, as you indicate you used a decompiler but it wasn't perfect. Hopefully in later versions called uncompyle6 these bugs have been addressed. But if not, file a github issue.

Ok. So now onto what is new. Recently I've modified the disassembler to make it amenable to modification and have written an Python assembler to store it back into the pyc bytecode format. This stuff is still in alpha; find it at http://github.com/rocky/python-xasm .

So with that you could make the simple changes to the constants and the condition tests.

So now let me go into the condition test since you asked about that specifically and it hasn't been fully answered here.

Consider this simple Python code:

  ___file__ == '__main'

Let's disassemble that with pydisasm:

...
# Constants:
#    0: '__main'
#    1: None
# Names:
#    0: ___file__
  1:           0 LOAD_NAME                 0 (___file__)
               3 LOAD_CONST                0 ('__main')
               6 COMPARE_OP                2 (==)
               9 POP_TOP
              10 LOAD_CONST                1 (None)
              13 RETURN_VALUE

Ok. so we see that the == is the operand of a COMPARE_OP
instructions which is encoded as 2.

Looking at the doc for this https://docs.python.org/3.6/library/dis.html#opcode-COMPARE_OP  (this is for Python 3.6, but it's the same across pretty much all Python versions) there is the marginally helpful explanation:

The operation name can be found in cmp_op[opname].

But for the secret decoder ring information you'll have to go to the
Python source code for opcode.py which you probably have on your disk somewhere, but here's a link: https://github.com/python/cpython/blob/master/Lib/opcode.py#L24 where we have

 cmp_op = ('<', '<=', '==', '!=', '>', '>=', 'in', 'not in', 'is', ...

And you'll see that while == is 2, != is 3.

As for changing the constant [116901, 141, 349244, 39, 1159488] that would appear in my disassembler in the section called Constants and you'd basically change the numbers there and then run the assembler.


问:
How to get a table name from a column value in sqlite?
I have indexed a series of tables in a column named title in a custom made index_table. I want to select a particular table using the column value from index_table.

My query:

```<code>SELECT * FROM (SELECT title FROM index_table WHERE rowid = 1);
</code>```

This line SELECT title FROM index_table WHERE rowid = 1 contains the name of the table from which I want to SELECT *.

However this code does not work. It returns only the selected column value from the index_table.

How can I select table from a value in a column?

答:
You cannot do what you're trying to do in any RDMS that I'm familiar with. Neither column, nor table names can be set via variables or subqueries. You have two ways to handle this:

Use two steps in your application logic. One to get the table name, the second builds the query and executes it.

Use some join trickery. It's hard to build a query for you without the schema available, but something like what I have below should do the equivalent.

select
    title_table.*
from
    title_table
    join index_table
        on title_table.id = index_table.id
where
    index_table.rowid = 1
```

Body:
I have indexed a series of tables in a column named title in a custom made index_table. I want to select a particular table using the column value from index_table.

My query:

SELECT * FROM (SELECT title FROM index_table WHERE rowid = 1);

This line SELECT title FROM index_table WHERE rowid = 1 contains the name of the table from which I want to SELECT *.

However this code does not work. It returns only the selected column value from the index_table.

How can I select table from a value in a column?


问:
How can client send a value to server using SignalR and the server update a model?
If I want to update a model/DB using SignalR, how is this achieved? (The other way around, i.e. from Server to Client is explained in many tutorials, but this way?)

So say we have a simple Model

```<code>public class User
{
    public int UserID { get; set; }

    public string UserName { get; set; }

}
</code>```

And the corresponding View has an input field for the name. The hub is something like

```<code>public class UserHub : Hub
{
    public void UpdateName(string value)
    {
        // now what?

        Clients.All.updateTheViewIfNecessary(string newValue);

    }
}
</code>```

Edit
How do I update the model, i.e. how do I achieve the same result as in the regular CRUD edit controller

```<code>db.Entry(user).State = EntityState.Modified;
db.SaveChanges();
</code>```

答:
Call the server function to pass the values like shown in the javascript below.

I have also include the sample html table containing list of users to call server function against each button click

            <input type="button" value="User 1" />
            <button type="button" value="2" title="User 2">User 2</button>
            <input type="button" value="User 3" />
            <input type="button" value="User 4" />

var userId, userName, strOtherVal;
userId = 1; // sample values
userName = 'ali';
strOtherVal = 'admin';

         $(function () {
            $("#tblData tr td button,input").click(function (event) {

                 myHub.server.sendData(userId, userName, strOtherVal)
                    .fail(function (error) {
                        console.log('error sending data: ' + error)
                    });

            });
        });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script></code>```

On the server side your function will look like this

```<code> public void sendData(int userId, string userName, string strOtherVal)
        {
            //create model
            var UserModel = new User() { UserID = userId, UserName = userName, OtherVal = strOtherVal };

            //here call your function to check or post this model to db

        }

 public class User
    {
        public int UserID { get; set; }

        public string UserName { get; set; }

        public string OtherVal { get; set; }
    }
</code>```

Body:
If I want to update a model/DB using SignalR, how is this achieved? (The other way around, i.e. from Server to Client is explained in many tutorials, but this way?)

So say we have a simple Model

public class User
{
    public int UserID { get; set; }

    public string UserName { get; set; }

}

And the corresponding View has an input field for the name. The hub is something like

public class UserHub : Hub
{
    public void UpdateName(string value)
    {
        // now what?

        Clients.All.updateTheViewIfNecessary(string newValue);

    }
}

Edit
How do I update the model, i.e. how do I achieve the same result as in the regular CRUD edit controller

db.Entry(user).State = EntityState.Modified;
db.SaveChanges();

Body:
Call the server function to pass the values like shown in the javascript below.

I have also include the sample html table containing list of users to call server function against each button click

    <table id="tblData">
        <tr>
            <td><input type="button" value="User 1" /> </td>
            <td><button type="button" value="2" title="User 2">User 2</button></td>
            <td><input type="button" value="User 3" /></td>
            <td><input type="button" value="User 4" /></td>
        </tr>
    </table>

var userId, userName, strOtherVal;
userId = 1; // sample values
userName = 'ali';
strOtherVal = 'admin';

         $(function () {
            $("#tblData tr td button,input").click(function (event) {

                 myHub.server.sendData(userId, userName, strOtherVal)
                    .fail(function (error) {
                        console.log('error sending data: ' + error)
                    });

            });
        });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>

On the server side your function will look like this

 public void sendData(int userId, string userName, string strOtherVal)
        {
            //create model
            var UserModel = new User() { UserID = userId, UserName = userName, OtherVal = strOtherVal };

            //here call your function to check or post this model to db

        }

 public class User
    {
        public int UserID { get; set; }

        public string UserName { get; set; }

        public string OtherVal { get; set; }
    }


问:
pass template URL in $compile
I have a scenario where I need to pass the template URL path in $compile instead of the template like below.

```<code>function addSubmenu() {
    scope.subMenuAdded = true;
    scope.subMenuVisible = true;
    scope.menuItemClickHandler = function(menuItem) {
        menuController.itemClickHandler.call(menuController, menuItem);
    };
    $compile('<apt-expandable-menu data-menu="menuItem.children" data-on-menu-item-click="menuItemClickHandler" ng-if="subMenuVisible"></apt-expandable-menu>')(scope, function(cloned){
        element.append(cloned);
    });
}
</code>```

Instead of the actual template in $compile I need to pass the template URL like below.

```<code>function addSubmenu() {
    scope.subMenuAdded = true;
    scope.subMenuVisible = true;
    scope.menuItemClickHandler = function(menuItem) {
        menuController.itemClickHandler.call(menuController, menuItem);
    };
    $compile('./expandableMenuChildItem.template.html')(scope, function(cloned){
        element.append(cloned);
    });
}
</code>```

and in expandableMenuChildItem.template.html:

```<code><apt-expandable-menu data-menu="menuItem.children" data-on-menu-item-click="menuItemClickHandler" ng-if="subMenuVisible"></apt-expandable-menu>
</code>```

but it is throwing me an error:

angular.js:14199 Error: Syntax error, unrecognized expression: ./expandableMenuChildItem.template.html

Any help would be appreciated.

答:
You could use the $templateRequest service. Like so:</p>

```<code>$templateRequest('nameOfTemplate.html').then(function(template){
    $compile(template)(scope, ..);
});
</code>```

Title: pass template URL in $compile

Body:
I have a scenario where I need to pass the template URL path in $compile instead of the template like below.

function addSubmenu() {
    scope.subMenuAdded = true;
    scope.subMenuVisible = true;
    scope.menuItemClickHandler = function(menuItem) {
        menuController.itemClickHandler.call(menuController, menuItem);
    };
    $compile('<apt-expandable-menu data-menu="menuItem.children" data-on-menu-item-click="menuItemClickHandler" ng-if="subMenuVisible"></apt-expandable-menu>')(scope, function(cloned){
        element.append(cloned);
    });
}

Instead of the actual template in $compile I need to pass the template URL like below.

function addSubmenu() {
    scope.subMenuAdded = true;
    scope.subMenuVisible = true;
    scope.menuItemClickHandler = function(menuItem) {
        menuController.itemClickHandler.call(menuController, menuItem);
    };
    $compile('./expandableMenuChildItem.template.html')(scope, function(cloned){
        element.append(cloned);
    });
}

and in expandableMenuChildItem.template.html:

<apt-expandable-menu data-menu="menuItem.children" data-on-menu-item-click="menuItemClickHandler" ng-if="subMenuVisible"></apt-expandable-menu>

but it is throwing me an error:

angular.js:14199 Error: Syntax error, unrecognized expression: ./expandableMenuChildItem.template.html

Any help would be appreciated.

Body:
You could use the $templateRequest service. Like so:

$templateRequest('nameOfTemplate.html').then(function(template){
    $compile(template)(scope, ..);
});


问:
Extract results from a list in R
I have a list called bag. It is the result of a number of regression methods from mlr package (Pseudo-)code is shown below. I want to extract the aggregated performance results from it for each Task. For instance, how can I access to both "Aggr. perf" values from $visc.1$regr.rpart and $visc.2$regr.rpart.  I can access them individually, but I think there must be a simpler approach.

```<code>> class(bag)

[1] "list"
</code>```

Code producing bag (dataset is not included):

```<code>library('mlr')
dataset = read.csv("dataset.csv")
regr.task = makeRegrTask(id = "dataset", data = dataset, target = "target")
# feature reduction
fv = generateFilterValuesData(regr.task)

# resampling description
rdesc = makeResampleDesc("Holdout")

####################
bag = NULL
####################

for (i in 1:2)
{

  cols = c(order(fv$data$randomForestSRC.rfsrc, decreasing = TRUE)[1:i], ncol(dataset))
  dataset.ig = dataset[, cols]
  iid = paste(c("dataset", i), collapse = ".")
  regr.task = makeRegrTask(id = iid,
                           data = dataset.ig,
                           target = "dataset")

  # learners
  lrns = list(
    "regr.bcart"
    ,"regr.fnn"
    ,"regr.rpart"
  )

      set.seed(0, "L'Ecuyer")
      bmr = benchmark(lrns, regr.task, rdesc, show.info = FALSE)

      #########################
      bag = c(bag, bmr)
      #########################
}
</code>```

MWC:

```<code>for (i in seq(1,42,3))
{
    print (bag[i]$results)
}
</code>```

Output:

```<code>$visc.1
$visc.1$regr.bcart
Resample Result
Task: visc.1
Learner: regr.bcart
Aggr perf: mse.test.mean=5.14e+03
Runtime: 0.181672

$visc.1$regr.cforest
Resample Result
Task: visc.1
Learner: regr.cforest
Aggr perf: mse.test.mean=4.92e+03
Runtime: 0.103091

$visc.1$regr.fnn
Resample Result
Task: visc.1
Learner: regr.fnn
Aggr perf: mse.test.mean=2.44e+03
Runtime: 0.0151947

$visc.1$regr.mars
Resample Result
Task: visc.1
Learner: regr.mars
Aggr perf: mse.test.mean=3.77e+03
Runtime: 0.0163326

$visc.1$regr.rpart
Resample Result
Task: visc.1
Learner: regr.rpart
Aggr perf: mse.test.mean=4.77e+03
Runtime: 0.0265007

$visc.2
$visc.2$regr.bcart
Resample Result
Task: visc.2
Learner: regr.bcart
Aggr perf: mse.test.mean=5.14e+03
Runtime: 0.177014

$visc.2$regr.cforest
Resample Result
Task: visc.2
Learner: regr.cforest
Aggr perf: mse.test.mean=4.95e+03
Runtime: 0.115235

$visc.2$regr.fnn
Resample Result
Task: visc.2
Learner: regr.fnn
Aggr perf: mse.test.mean=3.25e+03
Runtime: 0.0116491

$visc.2$regr.mars
Resample Result
Task: visc.2
Learner: regr.mars
Aggr perf: mse.test.mean=2.67e+03
Runtime: 0.0153017

$visc.2$regr.rpart
Resample Result
Task: visc.2
Learner: regr.rpart
Aggr perf: mse.test.mean=4.77e+03
Runtime: 0.0252295
</code>```

EDIT:
I have also saved dput(bag[1:2]) here.

Title: Extract results from a list in R

Body:
I have a list called bag. It is the result of a number of regression methods from mlr package (Pseudo-)code is shown below. I want to extract the aggregated performance results from it for each Task. For instance, how can I access to both "Aggr. perf" values from $visc.1$regr.rpart and $visc.2$regr.rpart.  I can access them individually, but I think there must be a simpler approach.

> class(bag)

[1] "list"

Code producing bag (dataset is not included):

library('mlr')
dataset = read.csv("dataset.csv")
regr.task = makeRegrTask(id = "dataset", data = dataset, target = "target")
# feature reduction
fv = generateFilterValuesData(regr.task)

# resampling description
rdesc = makeResampleDesc("Holdout")

####################
bag = NULL
####################

for (i in 1:2)
{

  cols = c(order(fv$data$randomForestSRC.rfsrc, decreasing = TRUE)[1:i], ncol(dataset))
  dataset.ig = dataset[, cols]
  iid = paste(c("dataset", i), collapse = ".")
  regr.task = makeRegrTask(id = iid,
                           data = dataset.ig,
                           target = "dataset")

  # learners
  lrns = list(
    "regr.bcart"
    ,"regr.fnn"
    ,"regr.rpart"
  )

      set.seed(0, "L'Ecuyer")
      bmr = benchmark(lrns, regr.task, rdesc, show.info = FALSE)

      #########################
      bag = c(bag, bmr)
      #########################
}

MWC:

for (i in seq(1,42,3))
{
    print (bag[i]$results)
}

Output:

$visc.1
$visc.1$regr.bcart
Resample Result
Task: visc.1
Learner: regr.bcart
Aggr perf: mse.test.mean=5.14e+03
Runtime: 0.181672

$visc.1$regr.cforest
Resample Result
Task: visc.1
Learner: regr.cforest
Aggr perf: mse.test.mean=4.92e+03
Runtime: 0.103091

$visc.1$regr.fnn
Resample Result
Task: visc.1
Learner: regr.fnn
Aggr perf: mse.test.mean=2.44e+03
Runtime: 0.0151947

$visc.1$regr.mars
Resample Result
Task: visc.1
Learner: regr.mars
Aggr perf: mse.test.mean=3.77e+03
Runtime: 0.0163326

$visc.1$regr.rpart
Resample Result
Task: visc.1
Learner: regr.rpart
Aggr perf: mse.test.mean=4.77e+03
Runtime: 0.0265007

$visc.2
$visc.2$regr.bcart
Resample Result
Task: visc.2
Learner: regr.bcart
Aggr perf: mse.test.mean=5.14e+03
Runtime: 0.177014

$visc.2$regr.cforest
Resample Result
Task: visc.2
Learner: regr.cforest
Aggr perf: mse.test.mean=4.95e+03
Runtime: 0.115235

$visc.2$regr.fnn
Resample Result
Task: visc.2
Learner: regr.fnn
Aggr perf: mse.test.mean=3.25e+03
Runtime: 0.0116491

$visc.2$regr.mars
Resample Result
Task: visc.2
Learner: regr.mars
Aggr perf: mse.test.mean=2.67e+03
Runtime: 0.0153017

$visc.2$regr.rpart
Resample Result
Task: visc.2
Learner: regr.rpart
Aggr perf: mse.test.mean=4.77e+03
Runtime: 0.0252295

EDIT:
I have also saved dput(bag[1:2]) here.

Body:
creating a list from mtcars columns as per bag example above.

io <-list(mtcars$mpg, mtcars$cyl, mtcars$disp)
names(io) <- c("mpg","cyl","disp")
class(io)
[1] "list"

io
$mpg
 [1] 21.0 21.0 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 17.8 16.4 17.3 15.2 10.4 10.4 14.7 32.4 30.4 33.9 21.5
[22] 15.5 15.2 13.3 19.2 27.3 26.0 30.4 15.8 19.7 15.0 21.4

$cyl
 [1] 6 6 4 6 8 6 8 4 4 6 6 8 8 8 8 8 8 4 4 4 4 8 8 8 8 4 4 4 8 6 8 4

$disp
 [1] 160.0 160.0 108.0 258.0 360.0 225.0 360.0 146.7 140.8 167.6 167.6 275.8 275.8 275.8 472.0 460.0 440.0
[18]  78.7  75.7  71.1 120.1 318.0 304.0 350.0 400.0  79.0 120.3  95.1 351.0 145.0 301.0 121.0

For implementing MWC:

req_rows <- seq(1,length(io$mpg),3)
req_rows
[1]  1  4  7 10 13 16 19 22 25 28 31

# rather than using loop, use this
io$mpg[io_seq]
[1] 21.0 21.4 14.3 19.2 17.3 10.4 30.4 15.5 19.2 30.4 15.0


问:
Walkthrough with tab view controller
I have been attempting to create a walkthrough for my app although I also have a tab view controller which is the initial view controller. I have been able to identify when a user is opening the app for the first time, but when I make the walkthrough view controller initial, I get a Sigbart error. This is because I set up my tabbar in the app delegate.

Is there a way to possibly keep the tab bar VC the initial and hide the first VC if it is the users first time opening the app?

Is there another way of doing it?

答: I dont know the code to check of its the flrst time a user opens an app, but why dont you make that check on your tab bar controller? And then lf lt ls the first time, you just change the root vc to the tutorial vc. When they are done with the tutorial you just change back the root vc to the tab bar. </p>

Title: Walkthrough with tab view controller