问:
Debug C# method at runtime
I am working on an application that should compile and debug C# code on the fly.

A simplified version of the code is included below.

What should be changed in this code to run the generated method step by step and get the state of the variables x and y after each step?

If everything should be changed that is okay, I am happy with any constructive response.

EDIT: to clarify: what I want to do is have my code debug the code that is generated with reflection, not the debug function in Visual Studio.

```<code>string code =
@"
namespace MyNameSpace
{
    public class MyClass
    {
        public static int MyMethod()
        {
            var x = 3;
            var y = 4;
            return x * y;
        }
    }
}";

string namespaceName = "MyNameSpace";
string className = "MyClass";
string methodName = "MyMethod";
string language = "csharp";
string classFullname = namespaceName + "." + className;

CodeDomProvider provider = CodeDomProvider.CreateProvider(language);
CompilerParameters parameters = new CompilerParameters();
CompilerResults results;

parameters.OutputAssembly = "Compiler";

parameters.CompilerOptions = "/t:library";
parameters.GenerateInMemory = true;
parameters.GenerateExecutable = false;
parameters.IncludeDebugInformation = true;

results = provider.CompileAssemblyFromSource(parameters, code);

if (results.Errors.Count != 0)
{
    throw new Exception("Code compilation errors occurred.");
}

var instance = results.CompiledAssembly.CreateInstance(classFullname, false);

// TODO run the method step by step and get the state after each step
</code>```

答:
To debug the generated code you will need the pdb files. To have those while debugging your application, just have to tell the compiler where to save the temporary files. For this you can just add the following line to your parameters:

```<code>parameters.TempFiles = new TempFileCollection(Environment.GetEnvironmentVariable("TEMP"), true);
</code>```

You can then step into the Invokation of your targeted method. The Code could look like this:

```<code>var method = instance?.GetType().GetMethod(methodName);
method?.Invoke(instance, BindingFlags.InvokeMethod, null, null, CultureInfo.CurrentCulture);
</code>```

If you want the Debugger to automatically stop, when entering your "MyMethod", you can modify your string likes this:

```<code>string code =
@"using System.Diagnostics;

namespace MyNameSpace
{
    public class MyClass
    {
        public int MyMethod()
        {
            Debugger.Break();
            var x = 3;
            var y = 4;
            return x * y;
        }
    }
}";
</code>```

Title: Debug C# method at runtime

Body:
I am working on an application that should compile and debug C# code on the fly.

A simplified version of the code is included below.

What should be changed in this code to run the generated method step by step and get the state of the variables x and y after each step?

If everything should be changed that is okay, I am happy with any constructive response.

EDIT: to clarify: what I want to do is have my code debug the code that is generated with reflection, not the debug function in Visual Studio.

string code =
@"
namespace MyNameSpace
{
    public class MyClass
    {
        public static int MyMethod()
        {
            var x = 3;
            var y = 4;
            return x * y;
        }
    }
}";

string namespaceName = "MyNameSpace";
string className = "MyClass";
string methodName = "MyMethod";
string language = "csharp";
string classFullname = namespaceName + "." + className;

CodeDomProvider provider = CodeDomProvider.CreateProvider(language);
CompilerParameters parameters = new CompilerParameters();
CompilerResults results;

parameters.OutputAssembly = "Compiler";

parameters.CompilerOptions = "/t:library";
parameters.GenerateInMemory = true;
parameters.GenerateExecutable = false;
parameters.IncludeDebugInformation = true;

results = provider.CompileAssemblyFromSource(parameters, code);

if (results.Errors.Count != 0)
{
    throw new Exception("Code compilation errors occurred.");
}

var instance = results.CompiledAssembly.CreateInstance(classFullname, false);

// TODO run the method step by step and get the state after each step

Body:
To debug the generated code you will need the pdb files. To have those while debugging your application, just have to tell the compiler where to save the temporary files. For this you can just add the following line to your parameters:

parameters.TempFiles = new TempFileCollection(Environment.GetEnvironmentVariable("TEMP"), true);

You can then step into the Invokation of your targeted method. The Code could look like this:

var method = instance?.GetType().GetMethod(methodName);
method?.Invoke(instance, BindingFlags.InvokeMethod, null, null, CultureInfo.CurrentCulture);

If you want the Debugger to automatically stop, when entering your "MyMethod", you can modify your string likes this:

string code =
@"using System.Diagnostics;

namespace MyNameSpace
{
    public class MyClass
    {
        public int MyMethod()
        {
            Debugger.Break();
            var x = 3;
            var y = 4;
            return x * y;
        }
    }
}";


来源: stackexchange

问:
select2 disable / enabled not working
I have a select element with select2 plugin. Version is 4.0. It works well but i cant change disabled option dynamically.

```<code>$('#list1').select2({
    theme: "bootstrap",
    disabled: true,
    placeholder: "Parsel",
    minimumInputLength: 0,
    allowClear: true,
    closeOnSelect: true,
});
</code>```

As you can see, disabled is true. I cant change disabled option dynamically. It work well if i delete disabled option.

Im using this code for try to change option;

```<code>$("#list1").select2({ disabled : false });
</code>```

or

```<code>$("#list1").select2('enable');
</code>```

How can i change select element's disabled option ?

Thank you all.

答:
Try this for what you need</p>

```<code>$('#list1').select2("enable",true)
</code>```

ContentLicense: CC BY-SA 3.0

Title: select2 disable / enabled not working

Body:
I have a select element with select2 plugin. Version is 4.0. It works well but i cant change disabled option dynamically.

$('#list1').select2({
    theme: "bootstrap",
    disabled: true,
    placeholder: "Parsel",
    minimumInputLength: 0,
    allowClear: true,
    closeOnSelect: true,
});

As you can see, disabled is true. I cant change disabled option dynamically. It work well if i delete disabled option.

Im using this code for try to change option;

$("#list1").select2({ disabled : false });

or

$("#list1").select2('enable');

How can i change select element's disabled option ?

Thank you all.

Body:
Try this for what you need

$('#list1').select2("enable",true)


问:
Does Redux Use Persistent Data Structure?
What type of data structure does redux use for making the data persist in Angular and React.js? I am assuming it uses persistent data structures.</p>

答:
I'm not sure I understand fully your question but

"In computing, a persistent data structure is a data structure that always preserves the previous version of itself when it is modified"

As far as I know redux is just a pattern and there is no persistant data structures associated with, unless you create and bind something yourself (like mongo event sourcing for example).


问:
VS 2017 mouse navigate backward stopped working with ReSharper
I like the VS feature to navigate backwards (e.g. after Ctrl+Click) using mouse back button. Unfortunately this feature stopped working. Literally using mouse back button does nothing. I have found out that navigation works again when I disable ReSharper. However, with enabled ReSharper it does not. Does anyone meet the same issues? I am using ReSharper 2017.2.2 and VS 2017 15.4.4.</p>

答: Microsoft introduced its own Ctrl+Click feature implementation in the latest build of VS2017, try disabling it here Tools | Options | TExt Editor | General | Untick "Enable mouse click to perform Go to Definition" ckeckbox to get the correct behaviour back.


问:
how to convert integer to binary for serial port
I am trying to send a value over serial port. I am unsure how to convert it into the correct format. I tried bin() for binary and format() but it didn't work.

```<code>result = 2
ser.open()
ser.write(b'1')
time.sleep(3)

ser.write(result)                 # wrong format
ser.write("{0:b}".format(result)) # TypeError: unicode strings
                                  # are not supported, please
                                  # encode to bytes: '10'
</code>```

The first write operation sends '1' as binary string. Now I want the variable to be send as binary string as well.

答:
write() method accepts a string parameter. You can convert result to string with str() builtin function like this.

result = str(result)

Python 2:

```<code>result = 2
ser.open()
ser.write(b'1')
time.sleep(3)

ser.write(str(result))
</code>```

Python 3:

You have to encode string in bytes.

```<code>result = 2
ser.open()
ser.write(b'1')
time.sleep(3)

ser.write(str(result).encode('utf-8'))
</code>```

Body:
I am trying to send a value over serial port. I am unsure how to convert it into the correct format. I tried bin() for binary and format() but it didn't work.

result = 2
ser.open()
ser.write(b'1')
time.sleep(3)

ser.write(result)                 # wrong format
ser.write("{0:b}".format(result)) # TypeError: unicode strings
                                  # are not supported, please
                                  # encode to bytes: '10'

The first write operation sends '1' as binary string. Now I want the variable to be send as binary string as well.

Body:
write() method accepts a string parameter. You can convert result to string with str() builtin function like this.

result = str(result)

Python 2:

result = 2
ser.open()
ser.write(b'1')
time.sleep(3)

ser.write(str(result))

Python 3:

You have to encode string in bytes.

result = 2
ser.open()
ser.write(b'1')
time.sleep(3)

ser.write(str(result).encode('utf-8'))


问:
How to install libX11-dev on mac os x sierra
I am working on facial landmarks and therefore I have installed dlib on my mac. When I try to execute a program in Xcode from learnopencv.com, the compiler says:

```<code>error "DLIB_NO_GUI_SUPPORT is defined so you can't use the GUI code. Turn DLIB_NO_GUI_SUPPORT off if you want to use it."
error "Also make sure you have libx11-dev installed on your system"
</code>```

I already installed XQuartz. I don't know what to do anymore. Can anyone help me out here?

答:
I suffered from this error for 3 days and finally fixed with:</p>

```<code>xcode-select --install
</code>```

Body:
I am working on facial landmarks and therefore I have installed dlib on my mac. When I try to execute a program in Xcode from learnopencv.com, the compiler says:

error "DLIB_NO_GUI_SUPPORT is defined so you can't use the GUI code. Turn DLIB_NO_GUI_SUPPORT off if you want to use it."
error "Also make sure you have libx11-dev installed on your system"

I already installed XQuartz. I don't know what to do anymore. Can anyone help me out here?

Body:
I suffered from this error for 3 days and finally fixed with:

xcode-select --install

ContentLicense: CC BY-SA 4.0


问:
symfony 2 - “error The option ”0“ does not exist.”
Im using a2lix/TranslationFormBundle and Im trying to add an EntityType fiedl in.

I got this error when i try to build the form  :

```<code> The option "0" does not exist. Known options are: "action", "attr", "auto_initialize", "block_name", "by_reference", "compound", "csrf_field_name", "csrf_message", "csrf_protection", "csrf_provider", "csrf_token_id", "csrf_token_manager", "data", "data_class", "disabled", "empty_data", "error_bubbling", "inherit_data", "intention", "label", "label_attr", "label_format", "mapped", "max_length", "method", "pattern", "post_max_size_message", "property_path", "read_only", "required", "translation_domain", "trim", "virtual"
</code>```

here's my  FormType

```<code> use Symfony\Bridge\Doctrine\Form\Type\EntityType;
 use A2lix\TranslationFormBundle\Form\Type\TranslationsType;

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('tag', TextType::class)
        ->add('translations', TranslationsType::class, [
            'fields' => [
                'promotion' => ['field_type' => EntityType::class, [
                    'class' => 'AdminBundle:Promotion',
                    'choice_label' => 'getName'
                ] ]
            ]
        ])
        ->add('Save', SubmitType::class)
    ;
}
</code>```

When i use the EntityType field outside the TranslationType field, its working . But when i use it within TranslationType, it dont.

Any help would be appreciated

答:
I had a similar error when trying to customize the CKEditor Toolbar within an A2lix form.

The solution was not easy to find. Instead of adding a new array for the options of the class you're integrating like this:

```<code> $builder
    ->add('tag', TextType::class)
    ->add('translations', TranslationsType::class, [
        'fields' => [
            'promotion' => ['field_type' => EntityType::class, [
                'class' => 'AdminBundle:Promotion',
                'choice_label' => 'getName'
            ] ]
        ]
    ])
</code>```

you should try to write it like this (i.e. put the options in the array for 'promotion' directly):

```<code>  $builder
    ->add('tag', TextType::class)
    ->add('translations', TranslationsType::class, [
        'fields' => [
            'promotion' => ['field_type' => EntityType::class,
                'class' => 'AdminBundle:Promotion',
                'choice_label' => 'getName',
            ]
        ]
    ])
</code>```

Body:
Im using a2lix/TranslationFormBundle and Im trying to add an EntityType fiedl in.

I got this error when i try to build the form  :

 The option "0" does not exist. Known options are: "action", "attr", "auto_initialize", "block_name", "by_reference", "compound", "csrf_field_name", "csrf_message", "csrf_protection", "csrf_provider", "csrf_token_id", "csrf_token_manager", "data", "data_class", "disabled", "empty_data", "error_bubbling", "inherit_data", "intention", "label", "label_attr", "label_format", "mapped", "max_length", "method", "pattern", "post_max_size_message", "property_path", "read_only", "required", "translation_domain", "trim", "virtual"

here's my  FormType

 use Symfony\Bridge\Doctrine\Form\Type\EntityType;
 use A2lix\TranslationFormBundle\Form\Type\TranslationsType;

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('tag', TextType::class)
        ->add('translations', TranslationsType::class, [
            'fields' => [
                'promotion' => ['field_type' => EntityType::class, [
                    'class' => 'AdminBundle:Promotion',
                    'choice_label' => 'getName'
                ] ]
            ]
        ])
        ->add('Save', SubmitType::class)
    ;
}

When i use the EntityType field outside the TranslationType field, its working . But when i use it within TranslationType, it dont.

Any help would be appreciated

Body:
I had a similar error when trying to customize the CKEditor Toolbar within an A2lix form.

The solution was not easy to find. Instead of adding a new array for the options of the class you're integrating like this:

 $builder
    ->add('tag', TextType::class)
    ->add('translations', TranslationsType::class, [
        'fields' => [
            'promotion' => ['field_type' => EntityType::class, [
                'class' => 'AdminBundle:Promotion',
                'choice_label' => 'getName'
            ] ]
        ]
    ])

you should try to write it like this (i.e. put the options in the array for 'promotion' directly):

  $builder
    ->add('tag', TextType::class)
    ->add('translations', TranslationsType::class, [
        'fields' => [
            'promotion' => ['field_type' => EntityType::class,
                'class' => 'AdminBundle:Promotion',
                'choice_label' => 'getName',
            ]
        ]
    ])


问:
Elastic Search SQL Server
We are trying to implement free text search using elastic search.

The Plan is to use

OurApplication
    |
  NEST
    |
Elastic Search
    |
?????????????
    |
SQL Server

The database is SQL Server and Create, Update and Delete operations on tables are performed by mutiple applications.

How can I populate and refresh indexes in elastic search ?

I went through River JDBC route, people are saying that it will be depreciated in the further releases ?

If I use River JDBC how can I refresh the indexes when updates happen ?

答:
Best Solution For that JDBC importer

The Java Database Connection (JDBC) importer allows to fetch data from JDBC sources for indexing into Elasticsearch.
The JDBC importer was designed for tabular data. If you have tables with many joins, the JDBC importer is limited in the way to reconstruct deeply nested objects to JSON and process object semantics like object identity. Though it would be possible to extend the JDBC importer with a mapping feature where all the object properties could be specified, the current solution is focused on rather simple tabular data streams.

You can use script file for jdbc database connection and for query.you store the data in index and used this index on application.
You can refresh the index by Setting a cron expression in the parameter schedule enables repeated (or time scheduled).

Example of a schedule parameter:
 "schedule" : "0 0-59 0-23 ? * *"
This executes JDBC importer every minute, every hour, all the days in the week/month/year. and index get fresh data every minute.

Also JDBC importer support mysql, PostgreSQL.
JDBC importer  provide Many feature.

For details :https://github.com/jprante/elasticsear

Title: Elastic Search SQL Server


问:
ASP MVC, EF Code first Unable to load the specified metadata resource (without edmx)
I get the following error when I run my site:

Unable to load the specified metadata resource.

Here is my connection string:

```<code> <add name="Context" connectionString="metadata=res://*/database.csdl|res://*/database.ssdl|res://*/database.msl;provider=System.Data.SqlClient;provider connection string="Server=127.0.0.1,2014;Database=myDbName;User Id=sa;Password=myPassword;multipleactiveresultsets=True;application name=EntityFramework"" providerName="System.Data.EntityClient" />
</code>```

After I looking for a solution I found some answers that doesn't help me to solve this problem, because they say I should apply some changes on .edmx file but I don't have any .edmx file in my project.

My project is code-first and as far as I know code-first project's doesn't have any .edmx file.

I also check related firewall port on server and it's okay.

Here are some solutions that I can't use these to solve this problem:

entity framework Unable to load the specified metadata resource [duplicate]

MetadataException Unable to load the specified metadata resource

Unable to load the specified metadata resource. Scripts != Models

System.Data.MetadataException: Unable to load the specified metadata resource

I use VS17, EF 6.2 and here is my solution structure:

```<code>-- myPrj.web
-- myPrj.Model
-- myPrj.Repository
-- myPrj.Service
</code>```

答:
Your connection string is for a database first context. For code first, you should use a simpler version, which contains only the information to connect to the database (metadata are created dynamically). For your case, try with this:</p>

```<code><add name="Context" connectionString="Server=127.0.0.1,2014;Database=myDbName;User Id=sa;Password=myPassword;multipleactiveresultsets=True;application name=EntityFramework" providerName="System.Data.SqlClient" />
</code>```

Body:
I get the following error when I run my site:

Unable to load the specified metadata resource.

Here is my connection string:

 <add name="Context" connectionString="metadata=res://*/database.csdl|res://*/database.ssdl|res://*/database.msl;provider=System.Data.SqlClient;provider connection string="Server=127.0.0.1,2014;Database=myDbName;User Id=sa;Password=myPassword;multipleactiveresultsets=True;application name=EntityFramework"" providerName="System.Data.EntityClient" />

After I looking for a solution I found some answers that doesn't help me to solve this problem, because they say I should apply some changes on .edmx file but I don't have any .edmx file in my project.

My project is code-first and as far as I know code-first project's doesn't have any .edmx file.

I also check related firewall port on server and it's okay.

Here are some solutions that I can't use these to solve this problem:

entity framework Unable to load the specified metadata resource [duplicate]

MetadataException Unable to load the specified metadata resource

Unable to load the specified metadata resource. Scripts != Models

System.Data.MetadataException: Unable to load the specified metadata resource

I use VS17, EF 6.2 and here is my solution structure:

-- myPrj.web
-- myPrj.Model
-- myPrj.Repository
-- myPrj.Service

Body:
Your connection string is for a database first context. For code first, you should use a simpler version, which contains only the information to connect to the database (metadata are created dynamically). For your case, try with this:

<add name="Context" connectionString="Server=127.0.0.1,2014;Database=myDbName;User Id=sa;Password=myPassword;multipleactiveresultsets=True;application name=EntityFramework" providerName="System.Data.SqlClient" />


问:
I want to have a wait between println to wait for a keypress
I have program where there's text that's being printed. I want to know how I can make it so that the text wait's with printing until I press enter.
Thanks in advance.</p>

答:
At the top of the program, create a Scanner with System.in as its source:

```<code>Scanner scan = new Scanner(System.in);
</code>```

Whenever you want to pause:

```<code>System.out.println("Press ENTER to continue..."); // optional
scan.nextLine();
</code>```

Body:
At the top of the program, create a Scanner with System.in as its source:

Scanner scan = new Scanner(System.in);

Whenever you want to pause:

System.out.println("Press ENTER to continue..."); // optional
scan.nextLine();


问:
Bottom bar navigation and Navigation drawer in same app
I'm using roughike bottom bar navigation in my app.now i,m trying to add navigation drawer also, and use both in my app.when i run my code logcat showing bellow error.how can i fix this?

Log cat error

FATAL EXCEPTION: main java.lang.RuntimeException: Unable to start activity ComponentInfo{com.android.app.testfragments/com.android.app.testfragments.MainActivity}: android.view.InflateException: Binary XML file line #59: Error inflating class com.roughike.bottombar.BottomBar

Activity_main.xml

```<code><android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
 <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
<LinearLayout
            android:id="@+id/container_toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">
 <include
                android:id="@+id/toolbar"
                layout="@layout/toolbar" />
        </LinearLayout>
<FrameLayout
            android:id="@+id/content_frame"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
</LinearLayout>
 <ListView
        android:id="@+id/left_drawer"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:background="#FFFFFF"
        android:choiceMode="singleChoice"
        android:divider="@android:color/darker_gray"
        android:dividerHeight="1dp" />
<FrameLayout
        android:id="@+id/contentContainer"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/bottomBar" />
<com.roughike.bottombar.BottomBar
        android:id="@+id/bottomBar"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:layout_alignParentBottom="true"
        app:bb_tabXmlResource="@xml/bottombar_tabs" />
</android.support.v4.widget.DrawerLayout>
</code>```

答:
Use BottomBar inside CoordinatorLayout as shown below</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main_content"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:fitsSystemWindows="true">

    <!--<include layout="@layout/content_potential_tenant" />-->

    <android.support.design.widget.CoordinatorLayout
        android:id="@+id/coordinator_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <FrameLayout
            android:id="@+id/fragment_frame"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <!--This is where the fragment will be placed-->

        </FrameLayout>

        <com.roughike.bottombar.BottomBar
            android:id="@+id/bottomBar"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:layout_gravity="bottom"
            android:background="@color/navigationItemBackground"
            app:bb_tabXmlResource="@xml/associated_tenant_bottombar_menu"
            app:bb_behavior="underNavbar|shy"/>

    </android.support.design.widget.CoordinatorLayout>

</android.support.v4.widget.DrawerLayout>
</code>```

Body:
I'm using roughike bottom bar navigation in my app.now i,m trying to add navigation drawer also, and use both in my app.when i run my code logcat showing bellow error.how can i fix this?

Log cat error

FATAL EXCEPTION: main java.lang.RuntimeException: Unable to start activity ComponentInfo{com.android.app.testfragments/com.android.app.testfragments.MainActivity}: android.view.InflateException: Binary XML file line #59: Error inflating class com.roughike.bottombar.BottomBar

Activity_main.xml

<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
 <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
<LinearLayout
            android:id="@+id/container_toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">
 <include
                android:id="@+id/toolbar"
                layout="@layout/toolbar" />
        </LinearLayout>
<FrameLayout
            android:id="@+id/content_frame"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
</LinearLayout>
 <ListView
        android:id="@+id/left_drawer"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:background="#FFFFFF"
        android:choiceMode="singleChoice"
        android:divider="@android:color/darker_gray"
        android:dividerHeight="1dp" />
<FrameLayout
        android:id="@+id/contentContainer"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/bottomBar" />
<com.roughike.bottombar.BottomBar
        android:id="@+id/bottomBar"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:layout_alignParentBottom="true"
        app:bb_tabXmlResource="@xml/bottombar_tabs" />
</android.support.v4.widget.DrawerLayout>

Body:
Use BottomBar inside CoordinatorLayout as shown below

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main_content"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:fitsSystemWindows="true">

    <!--<include layout="@layout/content_potential_tenant" />-->

    <android.support.design.widget.CoordinatorLayout
        android:id="@+id/coordinator_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <FrameLayout
            android:id="@+id/fragment_frame"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <!--This is where the fragment will be placed-->

        </FrameLayout>

        <com.roughike.bottombar.BottomBar
            android:id="@+id/bottomBar"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:layout_gravity="bottom"
            android:background="@color/navigationItemBackground"
            app:bb_tabXmlResource="@xml/associated_tenant_bottombar_menu"
            app:bb_behavior="underNavbar|shy"/>

    </android.support.design.widget.CoordinatorLayout>

</android.support.v4.widget.DrawerLayout>


问:
Prevent variables from being rewritten in Makefiles?
I'm learning about Makefiles and application cross-compiling, and I'd like to find a way to prevent variables from being redefined in Makefiles further down the chain.

As an example, I write a top-level Makefile /usr/src/someapp.mk that will...

1) download the application's source code from the web into /usr/src/someapp-1.2.3/

2) untar the source, and

3) run its original /usr/src/someapp-1.2.3/Makefile

Since the original Makefile was written as a stand-alone script, it will unknowningly (re)define the usual suspects (CC, AR/RANLIB, etc.) with local values, effectively erasing the value I chose in the top-level Makefile:

```<code>#My top-level /usr/src/someapp.mk:
all:
    wget someapp-1.2.3.tar.gz
    tar xzvf someapp-1.2.3.tar.gz
    cd someapp-1.2.3 && $(MAKE)

#Original Makefile from www /usr/src/someapp-1.2.3/Makefile:
#RANLIB locally redefined... :-/
RANLIB=ranlib

all:
    $(RANLIB)...
</code>```

I'd like users to be able to download the original source code instead of providing my own, modified version: Is there a way to have "make" either ignore when variables are redefined locally or rewrite them on the fly?

Thank you.

答:
The ?= operator will only define a variable if it is unset.

```<code>VAR ?= value
</code>```

By far the most useful way though is to define variables on the make command line. Such variables become read-only for the duration of the make.

```<code>$ cat Makefile
VAR := hello
$(error [${VAR}])
</code>```

then

```<code>$ make
Makefile:2: *** [hello].  Stop.
</code>```

but

```<code>$ make VAR='value overridden'
Makefile:2: *** [value overridden].  Stop.
</code>```

This suggests your snippet cd someapp-1.2.3 && $(MAKE) becomes $(MAKE) -C someapp-1.2.3 RANLIB=myval.

ContentLicense: CC BY-SA 2.5

Body:
I'm learning about Makefiles and application cross-compiling, and I'd like to find a way to prevent variables from being redefined in Makefiles further down the chain.

As an example, I write a top-level Makefile /usr/src/someapp.mk that will...

1) download the application's source code from the web into /usr/src/someapp-1.2.3/

2) untar the source, and

3) run its original /usr/src/someapp-1.2.3/Makefile

Since the original Makefile was written as a stand-alone script, it will unknowningly (re)define the usual suspects (CC, AR/RANLIB, etc.) with local values, effectively erasing the value I chose in the top-level Makefile:

#My top-level /usr/src/someapp.mk:
all:
    wget someapp-1.2.3.tar.gz
    tar xzvf someapp-1.2.3.tar.gz
    cd someapp-1.2.3 && $(MAKE)

#Original Makefile from www /usr/src/someapp-1.2.3/Makefile:
#RANLIB locally redefined... :-/
RANLIB=ranlib

all:
    $(RANLIB)...

I'd like users to be able to download the original source code instead of providing my own, modified version: Is there a way to have "make" either ignore when variables are redefined locally or rewrite them on the fly?

Thank you.

Body:
The ?= operator will only define a variable if it is unset.

VAR ?= value

By far the most useful way though is to define variables on the make command line. Such variables become read-only for the duration of the make.

$ cat Makefile
VAR := hello
$(error [${VAR}])

then

$ make
Makefile:2: *** [hello].  Stop.

but

$ make VAR='value overridden'
Makefile:2: *** [value overridden].  Stop.

This suggests your snippet cd someapp-1.2.3 && $(MAKE) becomes $(MAKE) -C someapp-1.2.3 RANLIB=myval.


问:
Add UIView to ContentView in a TableViewCell using constraints
I am trying to add cells to UITableView using Constraints. Do you know how. The following just gives:

And says: Height is ambiguous for UIView

Do you know how to add a UIView to ContextView using constraints - note the fixed height in the constraints.

```<code>import UIKit

class ViewController: UITableViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        self.tableView.register(UITableViewCell.self, forCellReuseIdentifier:"Cell")
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 3
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        var cell = tableView.dequeueReusableCell(withIdentifier: "Cell")

        if cell == nil {
            cell = UITableViewCell(style: .default, reuseIdentifier: "Cell")
        }

        let view = UIView(frame: cell!.frame)
        view.translatesAutoresizingMaskIntoConstraints = false
        view.backgroundColor = UIColor.orange

        let constraintTop = NSLayoutConstraint(item: cell!.contentView,
                                               attribute: NSLayoutAttribute.top,
                                               relatedBy: NSLayoutRelation.equal,
                                               toItem: view,
                                               attribute: NSLayoutAttribute.top,
                                               multiplier: 1,
                                               constant: 0)

        let constraintLeading = NSLayoutConstraint(item: cell!.contentView,
                                                   attribute: NSLayoutAttribute.leading,
                                                   relatedBy: NSLayoutRelation.equal,
                                                   toItem: view,
                                                   attribute: NSLayoutAttribute.leading,
                                                   multiplier: 1,
                                                   constant: 0)

        let constraintTrailing = NSLayoutConstraint(item: cell!.contentView,
                                                    attribute: NSLayoutAttribute.trailing,
                                                    relatedBy: NSLayoutRelation.equal,
                                                    toItem: view,
                                                    attribute: NSLayoutAttribute.trailing,
                                                    multiplier: 1,
                                                    constant: 0)

        let constraintHeight = NSLayoutConstraint(item: cell!.contentView,
                                                  attribute: NSLayoutAttribute.height,
                                                  relatedBy: NSLayoutRelation.equal,
                                                  toItem: nil,
                                                  attribute: NSLayoutAttribute.height,
                                                  multiplier: 1, constant: 50) // << Note fixed height

        view.translatesAutoresizingMaskIntoConstraints = false

        cell?.contentView.addSubview(view)
        cell?.contentView.addConstraints([constraintTop, constraintLeading, constraintTrailing, constraintHeight])

        return cell!
    }

}
</code>```

Tried to change constraints to include bottom of the contentView:

```<code>import UIKit

class ViewController: UITableViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        self.tableView.register(UITableViewCell.self, forCellReuseIdentifier:"Cell")
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 3
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        var cell = tableView.dequeueReusableCell(withIdentifier: "Cell")

        if cell == nil {
            cell = UITableViewCell(style: .default, reuseIdentifier: "Cell")
        }

        let view = UIView(frame: cell!.frame)
        view.translatesAutoresizingMaskIntoConstraints = false
        view.backgroundColor = UIColor.orange

        let constraintTop = NSLayoutConstraint(item: cell!.contentView,
                                               attribute: NSLayoutAttribute.top,
                                               relatedBy: NSLayoutRelation.equal,
                                               toItem: view,
                                               attribute: NSLayoutAttribute.top,
                                               multiplier: 1,
                                               constant: 0)

        let constraintLeading = NSLayoutConstraint(item: cell!.contentView,
                                                   attribute: NSLayoutAttribute.leading,
                                                   relatedBy: NSLayoutRelation.equal,
                                                   toItem: view,
                                                   attribute: NSLayoutAttribute.leading,
                                                   multiplier: 1,
                                                   constant: 0)

        let constraintTrailing = NSLayoutConstraint(item: cell!.contentView,
                                                    attribute: NSLayoutAttribute.trailing,
                                                    relatedBy: NSLayoutRelation.equal,
                                                    toItem: view,
                                                    attribute: NSLayoutAttribute.trailing,
                                                    multiplier: 1,
                                                    constant: 0)

        let constraintBottom = NSLayoutConstraint(item: cell!.contentView,
                                                  attribute: NSLayoutAttribute.bottom,
                                                  relatedBy: NSLayoutRelation.equal,
                                                  toItem: view,
                                                  attribute: NSLayoutAttribute.bottom,
                                                  multiplier: 1, constant: 0)

        view.translatesAutoresizingMaskIntoConstraints = false
        cell?.contentView.translatesAutoresizingMaskIntoConstraints = false
        cell?.contentView.addSubview(view)
        cell?.contentView.addConstraints([constraintTop, constraintLeading, constraintTrailing, constraintBottom])

        return cell!
    }

}
</code>```

答:
Well, the solutions is: Read the "Output"!

```<code>Changing the translatesAutoresizingMaskIntoConstraints property of the contentView of a UITableViewCell is not supported and will result in undefined behavior, as this property is managed by the owning UITableViewCell
</code>```

Having the following messed it all up:

cell?.contentView.translatesAutoresizingMaskIntoConstraints = false

Remove this line and it will work.

Body:
I am trying to add cells to UITableView using Constraints. Do you know how. The following just gives:

And says: Height is ambiguous for UIView

Do you know how to add a UIView to ContextView using constraints - note the fixed height in the constraints.

import UIKit

class ViewController: UITableViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        self.tableView.register(UITableViewCell.self, forCellReuseIdentifier:"Cell")
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 3
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        var cell = tableView.dequeueReusableCell(withIdentifier: "Cell")

        if cell == nil {
            cell = UITableViewCell(style: .default, reuseIdentifier: "Cell")
        }

        let view = UIView(frame: cell!.frame)
        view.translatesAutoresizingMaskIntoConstraints = false
        view.backgroundColor = UIColor.orange

        let constraintTop = NSLayoutConstraint(item: cell!.contentView,
                                               attribute: NSLayoutAttribute.top,
                                               relatedBy: NSLayoutRelation.equal,
                                               toItem: view,
                                               attribute: NSLayoutAttribute.top,
                                               multiplier: 1,
                                               constant: 0)

        let constraintLeading = NSLayoutConstraint(item: cell!.contentView,
                                                   attribute: NSLayoutAttribute.leading,
                                                   relatedBy: NSLayoutRelation.equal,
                                                   toItem: view,
                                                   attribute: NSLayoutAttribute.leading,
                                                   multiplier: 1,
                                                   constant: 0)

        let constraintTrailing = NSLayoutConstraint(item: cell!.contentView,
                                                    attribute: NSLayoutAttribute.trailing,
                                                    relatedBy: NSLayoutRelation.equal,
                                                    toItem: view,
                                                    attribute: NSLayoutAttribute.trailing,
                                                    multiplier: 1,
                                                    constant: 0)

        let constraintHeight = NSLayoutConstraint(item: cell!.contentView,
                                                  attribute: NSLayoutAttribute.height,
                                                  relatedBy: NSLayoutRelation.equal,
                                                  toItem: nil,
                                                  attribute: NSLayoutAttribute.height,
                                                  multiplier: 1, constant: 50) // << Note fixed height

        view.translatesAutoresizingMaskIntoConstraints = false

        cell?.contentView.addSubview(view)
        cell?.contentView.addConstraints([constraintTop, constraintLeading, constraintTrailing, constraintHeight])

        return cell!
    }

}

Tried to change constraints to include bottom of the contentView:

import UIKit

class ViewController: UITableViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        self.tableView.register(UITableViewCell.self, forCellReuseIdentifier:"Cell")
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 3
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        var cell = tableView.dequeueReusableCell(withIdentifier: "Cell")

        if cell == nil {
            cell = UITableViewCell(style: .default, reuseIdentifier: "Cell")
        }

        let view = UIView(frame: cell!.frame)
        view.translatesAutoresizingMaskIntoConstraints = false
        view.backgroundColor = UIColor.orange

        let constraintTop = NSLayoutConstraint(item: cell!.contentView,
                                               attribute: NSLayoutAttribute.top,
                                               relatedBy: NSLayoutRelation.equal,
                                               toItem: view,
                                               attribute: NSLayoutAttribute.top,
                                               multiplier: 1,
                                               constant: 0)

        let constraintLeading = NSLayoutConstraint(item: cell!.contentView,
                                                   attribute: NSLayoutAttribute.leading,
                                                   relatedBy: NSLayoutRelation.equal,
                                                   toItem: view,
                                                   attribute: NSLayoutAttribute.leading,
                                                   multiplier: 1,
                                                   constant: 0)

        let constraintTrailing = NSLayoutConstraint(item: cell!.contentView,
                                                    attribute: NSLayoutAttribute.trailing,
                                                    relatedBy: NSLayoutRelation.equal,
                                                    toItem: view,
                                                    attribute: NSLayoutAttribute.trailing,
                                                    multiplier: 1,
                                                    constant: 0)

        let constraintBottom = NSLayoutConstraint(item: cell!.contentView,
                                                  attribute: NSLayoutAttribute.bottom,
                                                  relatedBy: NSLayoutRelation.equal,
                                                  toItem: view,
                                                  attribute: NSLayoutAttribute.bottom,
                                                  multiplier: 1, constant: 0)

        view.translatesAutoresizingMaskIntoConstraints = false
        cell?.contentView.translatesAutoresizingMaskIntoConstraints = false
        cell?.contentView.addSubview(view)
        cell?.contentView.addConstraints([constraintTop, constraintLeading, constraintTrailing, constraintBottom])

        return cell!
    }

}

Body:
Well, the solutions is: Read the "Output"!

Changing the translatesAutoresizingMaskIntoConstraints property of the contentView of a UITableViewCell is not supported and will result in undefined behavior, as this property is managed by the owning UITableViewCell

Having the following messed it all up:

cell?.contentView.translatesAutoresizingMaskIntoConstraints = false

Remove this line and it will work.


问:
Mapping json data in ReactJS
I'm having a hard time mapping data children to a table. What you see in my json data below is an example of one item. I have a map in the Card component (See the render function content) to display as many items as I have independently in a MaterialUI Card. And Each card has also a table. I am mapping the table content with the children (rows) in each item. Because not every item has the same amount of data or same data.

My Cards are being populated just fine with the image, page, and section. But my rows content are not being populated in the table rows (TableRowColumn)

Here is the simplified json with one item:

```<code>exports.administration = [
    {
        id:'1',
        image: '/assets/images/media/christopher-walken.jpg',
        page: '',
        section: 'Test one',
        rows: [
            {
                id:'1.1',
                type: 'STRING',
                name: 'Page1Var1',
                description:'n/a',
                show:'Both',
                label: 'Page1Var1',
                value: 'Test one',
                presentation: 'n/a',
                lines: '1',
                characters: '4096',
            },
        ],

    },
]
</code>```

The database declaration and call

```<code>const TEMPLATEITEMS = require('data/templates.js');
const administrationData = TEMPLATEITEMS['administration'];
</code>```

In my render function:

```<code>{administrationData.map((row, index) => (
    <Card key={index}>
        <CardText>
            <div>
                 //these are working fine
                 <h4>{row.page} / {row.section}</h4>
                 <img src={row.image} alt={row.name} />
            </div>
            <Table>
                <TableBody>
                    //these are not working. I tried several variations as you see below
                    <TableRow id={row.rows.id}>
                        <TableRowColumn> {row.type} </TableRowColumn>
                        <TableRowColumn> {row[index].rows.name} </TableRowColumn>
                        ...
                        <TableRowColumn> {rows.characters} </TableRowColumn>
                    </TableRow>
                </TableBody>
            </Table>
        </CardText>
    </Card>
))}
</code>```

Thank you in advance guys!

答:
```<code>const tableRows = (row) => (
 row.rows.map((r, ix) => <TableRow id={r.id}>
    <TableRowColumn> {r.type} </TableRowColumn>
    <TableRowColumn> {r.name} </TableRowColumn>
    <TableRowColumn> {r.characters} </TableRowColumn>
    </TableRow>
    )
)
</code>```

and then:

```<code><TableBody> {tableRows(row)} </TableBody>
</code>```

Untested, but hopefully not too far off.

Title: Mapping json data in ReactJS

Body:
I'm having a hard time mapping data children to a table. What you see in my json data below is an example of one item. I have a map in the Card component (See the render function content) to display as many items as I have independently in a MaterialUI Card. And Each card has also a table. I am mapping the table content with the children (rows) in each item. Because not every item has the same amount of data or same data.

My Cards are being populated just fine with the image, page, and section. But my rows content are not being populated in the table rows (TableRowColumn)

Here is the simplified json with one item:

exports.administration = [
    {
        id:'1',
        image: '/assets/images/media/christopher-walken.jpg',
        page: '',
        section: 'Test one',
        rows: [
            {
                id:'1.1',
                type: 'STRING',
                name: 'Page1Var1',
                description:'n/a',
                show:'Both',
                label: 'Page1Var1',
                value: 'Test one',
                presentation: 'n/a',
                lines: '1',
                characters: '4096',
            },
        ],

    },
]

The database declaration and call

const TEMPLATEITEMS = require('data/templates.js');
const administrationData = TEMPLATEITEMS['administration'];

In my render function:

{administrationData.map((row, index) => (
    <Card key={index}>
        <CardText>

                 //these are working fine

{row.page} / {row.section}

                <TableBody>
                    //these are not working. I tried several variations as you see below
                    <TableRow id={row.rows.id}>
                        <TableRowColumn> {row.type} </TableRowColumn>
                        <TableRowColumn> {row[index].rows.name} </TableRowColumn>
                        ...
                        <TableRowColumn> {rows.characters} </TableRowColumn>
                    </TableRow>
                </TableBody>

        </CardText>
    </Card>
))}

Thank you in advance guys!

Body:
const tableRows = (row) => (
 row.rows.map((r, ix) => <TableRow id={r.id}>
    <TableRowColumn> {r.type} </TableRowColumn>
    <TableRowColumn> {r.name} </TableRowColumn>
    <TableRowColumn> {r.characters} </TableRowColumn>
    </TableRow>
    )
)

and then:

<TableBody> {tableRows(row)} </TableBody>

Untested, but hopefully not too far off.


问:
Trying to find a set of letters within a string with a loop
I am trying to make a loop that checks all the cells in column A and if it finds that any of them contains the phrase "ISAW" within a string (like 1314_ISAW_STUFF) then it changes the value of the corresponding cell in column G to "COMPLIANT".

I have the following code, the loop works and the Cells.Find option should work but it doesn't activate any cells with matching criteria.

```<code>Sub mytestsub()

Dim sh1 As Worksheet
Set sh1 = Worksheets("Sheet1")

Dim i As Integer
sh1.Activate

On Error GoTo MyError
For i = 1 To InStr(ActiveSheet, "ISAW")
    sh1.Cells.Find("ISAW").Activate
    If InStr(ActiveCell, "ISAW") > 0 Then
        ActiveCell.Offset(, 7).Value = "COMPLIANT"
    End If
Next i

MyError:
On Error GoTo -1

End Sub
</code>```

Any help would be appreciated!

I altered the script Tom generously provided as seen below, but it doesn't seem to be working now.

```<code> Sub bugfix()
'QA N/A bugfix'
    Dim fndCell As Range
    Dim FirstAddress As String
    Worksheets("Summary").Unprotect
With Worksheets("Summary")
        .Activate

        On Error GoTo MyError
        Set fndCell = .Column(3).Find(what:="ISAW", lookat:=xlPart)
        If Not fndCell Is Nothing Then
         ' uncomment if you really want to visually track the cells
            'fndCell.Activate
            FirstAddress = fndCell.Address
            Do
                fndCell.Offset(0, 6).Value = "N/A"
                Set fndCell = .Cells.FindNext(fndCell)
            Loop Until fndCell.Address = FirstAddress
        End If
    End With
Exit Sub
MyError:
    On Error GoTo -1
End Sub
</code>```

答:
There's almost never a reason to Activate or use ActiveCell in order to check a certain value, or change another cell's value.
Instead, use fully qualified objects.

Also, using On Error GoTo MyError is not necessary in this case, see code below.

Code

```<code>Sub mytestsub()

Dim sh1 As Worksheet
Dim i As Long, LastRow As Long

Set sh1 = Worksheets("Sheet1")
With sh1
    LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row ' get last row with data in column "A"
    For i = 1 To LastRow
        If InStr(.Range("A" & i).Value2, "ISAW") > 0 Then ' check if current cell in column "A" contains "ISAW"
            .Range("G" & i).Value2 = "COMPLIANT" ' change the value at column "G"
        End If
    Next i
End With

End Sub
</code>```

Body:
I am trying to make a loop that checks all the cells in column A and if it finds that any of them contains the phrase "ISAW" within a string (like 1314_ISAW_STUFF) then it changes the value of the corresponding cell in column G to "COMPLIANT".

I have the following code, the loop works and the Cells.Find option should work but it doesn't activate any cells with matching criteria.

Sub mytestsub()

Dim sh1 As Worksheet
Set sh1 = Worksheets("Sheet1")

Dim i As Integer
sh1.Activate

On Error GoTo MyError
For i = 1 To InStr(ActiveSheet, "ISAW")
    sh1.Cells.Find("ISAW").Activate
    If InStr(ActiveCell, "ISAW") > 0 Then
        ActiveCell.Offset(, 7).Value = "COMPLIANT"
    End If
Next i

MyError:
On Error GoTo -1

End Sub

Any help would be appreciated!

I altered the script Tom generously provided as seen below, but it doesn't seem to be working now.

 Sub bugfix()
'QA N/A bugfix'
    Dim fndCell As Range
    Dim FirstAddress As String
    Worksheets("Summary").Unprotect
With Worksheets("Summary")
        .Activate

        On Error GoTo MyError
        Set fndCell = .Column(3).Find(what:="ISAW", lookat:=xlPart)
        If Not fndCell Is Nothing Then
         ' uncomment if you really want to visually track the cells
            'fndCell.Activate
            FirstAddress = fndCell.Address
            Do
                fndCell.Offset(0, 6).Value = "N/A"
                Set fndCell = .Cells.FindNext(fndCell)
            Loop Until fndCell.Address = FirstAddress
        End If
    End With
Exit Sub
MyError:
    On Error GoTo -1
End Sub

Body:
There's almost never a reason to Activate or use ActiveCell in order to check a certain value, or change another cell's value.
Instead, use fully qualified objects.

Also, using On Error GoTo MyError is not necessary in this case, see code below.

Code

Sub mytestsub()

Dim sh1 As Worksheet
Dim i As Long, LastRow As Long

Set sh1 = Worksheets("Sheet1")
With sh1
    LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row ' get last row with data in column "A"
    For i = 1 To LastRow
        If InStr(.Range("A" & i).Value2, "ISAW") > 0 Then ' check if current cell in column "A" contains "ISAW"
            .Range("G" & i).Value2 = "COMPLIANT" ' change the value at column "G"
        End If
    Next i
End With

End Sub


答:
```<code>{administrationData.map((row, index) => (
    <Card key={index}>
    <CardText>
        <div>
             <h4>{row.page} / {row.section}</h4>
             <img style={styles.image} src={row.image} alt={row.name} />
        </div>
        <Table>
            <TableBody>
                {
                    row.rows.map((item, itemIndex)=>{
                       return(
                           <TableRow id={item.rows.id} index={itemIndex}>
                               <TableRowColumn> {item.type} </TableRowColumn>
                               <TableRowColumn> {item.name}</TableRowColumn>
                               ...
                               <TableRowColumn> {item.characters}</TableRowColumn>
                           </TableRow>
                       );
                    })
                }
            </TableBody>
        </Table>
    </CardText>
  </Card>
))}
</code>```

Title: Mapping json data in ReactJS


问:
windows 7-64bit - win32 api to sacrifice(relegate) administrative privileges for a program
I have a program that creates temporary files. If this program run as administrator with elevated privileges the resulting files cannot be deleted without "elevated" privileges, even if the user is administrator. This forces the user to run the application always with "Run as administrator"

The program does not really need any administrative rights or elevated privileges. Is there a programmatic way to ensure that the application is always run with normal permissions?

答: A manifest can direct Windows to launch the app asInvoker, but if a user right-clicks and chooses Run As Administrator the app will be elevated. I'd be tempted to handle this through user education, but there is something programmatic you can do - it's up to you to decide if it's worth it. You can check to see if you're running elevated (basically IsInRole will say the user is an admin if and only if the app is elevated) and if you're not, launch another process non-elevated (I am sure there are questions here showing that, but here are some blog entries I happened to write linking to ways to do it native and managed) that creates the actual files.</p>


问:
jQuery: how to get the id of a div (with a class named "hidden")
can you help me please ?

I'm searching for a solution to get an id from a hidden div and interact the id in an AJAX query when a click is happened

PHP code :

```<code>while ( $contents_print = mysqli_fetch_array( $req_print ) ) {
echo '
        <div class="post print" id="staggered-test">
            <img src="../00_sources/images/upload/pic_min/' . $contents_print[ 'pic_min' ] . '" alt="' . $contents_print[ 'pic_min' ] . '"/>
                <div class="post-content">
                    <a href="#modal" class="modal-action modal-trigger">Détail</a>
                    <div class="row"><blockquote>' . $contents_print[ 'detail_projet' ] . '</blockquote></div>
                </div>
            <div class="post-content valign-wrapper"><h4 class="header center">' . $contents_print[ 'nom_projet' ] . '</h4></div>
        </div>
    ';

echo '<div class="hidden" id="'.$contents_print[ 'id_projet' ].'"></div>';
}
</code>```

jQuery

```<code>$( document ).ready( function () {
  $(".post").siblings('div:hidden').attr("id").click(function() {
    var url_id = $(this).attr('id');
    //alert(url_id);
  });

  $.ajax({
    url: 'core/libs/contents-services.php?action=getFilterContent&id='+url_id,
    type: "get",
    dataType: "html",
    success: function ( reponse ) {
      $( '#modal' ).html( reponse );
      url_id = reponse.url_id;
    }
  });

  // the "href" attribute of the modal trigger must specify the modal ID that wants to be triggered
  $( '.modal' ).modal();
});
</code>```

May be I'm missing something, my code doesn't work

Please help me. Thanks a lot !

答:
First, change the siblings selector to use the class selection like this:

```<code>.siblings('div.hidden')
</code>```

Next, you are using attr("id") to get the ID of the element, which returns a string, and adding a click event handler to a string, which is also not supported.   You can do the following in one statement; i'm going to do it in two to illustrate it:

```<code>var id = $(".post").siblings('div.hidden').attr("id");
$("#" + id).click(function() {
  ..
});
</code>```

The id variable gets the ID, and then using #ID syntax selection in jQuery to match by ID, a click event can then be applied to the hidden element.

Body:
can you help me please ?

I'm searching for a solution to get an id from a hidden div and interact the id in an AJAX query when a click is happened

PHP code :

while ( $contents_print = mysqli_fetch_array( $req_print ) ) {
echo '

                    Détail

' . $contents_print[ 'detail_projet' ] . '

' . $contents_print[ 'nom_projet' ] . '

    ';

echo '

';
}

jQuery

$( document ).ready( function () {
  $(".post").siblings('div:hidden').attr("id").click(function() {
    var url_id = $(this).attr('id');
    //alert(url_id);
  });

  $.ajax({
    url: 'core/libs/contents-services.php?action=getFilterContent&id='+url_id,
    type: "get",
    dataType: "html",
    success: function ( reponse ) {
      $( '#modal' ).html( reponse );
      url_id = reponse.url_id;
    }
  });

  // the "href" attribute of the modal trigger must specify the modal ID that wants to be triggered
  $( '.modal' ).modal();
});

May be I'm missing something, my code doesn't work

Please help me. Thanks a lot !

Body:
First, change the siblings selector to use the class selection like this:

.siblings('div.hidden')

Next, you are using attr("id") to get the ID of the element, which returns a string, and adding a click event handler to a string, which is also not supported.   You can do the following in one statement; i'm going to do it in two to illustrate it:

var id = $(".post").siblings('div.hidden').attr("id");
$("#" + id).click(function() {
  ..
});

The id variable gets the ID, and then using #ID syntax selection in jQuery to match by ID, a click event can then be applied to the hidden element.


问:
Stereo Display (non head-mounted) option in Unity 2017.2 is not available?
I would like to know the where to enable option for 'Stereo Display (non head-mounted)' in Unity 2017.2. I was using this for nvdia 3D vision stereo and it was present until 2017.1. I have checked with unity's documentation regarding that it does not mention anything about it. This option was available in player settings of unity 2017.1 and 5.6 by enabling Virtual Reality-> And in virtual reality SDK's. Since the VR settings are now moved to XR section in player settings as you can see the below images

.

I cannot seem to find it anymore. Also the Unity's release blog does not mention anything about removing it so not sure where exactly it is. So if anyone has information regarding enabling stereo display in 2017.2 it would be helpful. If also want to know by scripting is it possible to change the player settings to include "Stereo Display" option it as I had scripts for changing player settings for using rendering API like directx11 and openGL while making builds so Iam pretty sure this will also have it but I'm unsure where to look for this and how to add it.

Edit: I use the 'Stereo Display(non head-mounted)' to acieve Active Stereo in my game as the @programmer has mentioned Mock HMD vive has replaced the option of 'Split Stereo Display(non head-mounted)' which I do not want to use as it is SBS and not active stereo. Only the 'Stereo Display(non head-mounted)' option is where I get my Nvdia active glasses working.

答:
The Missing part 'Stereo Display (non head-mounted)' is most probably a bug as I had found a similer thread in Unity forums and got two ways to add stereo sdk to the build. One by turning on

PlayerSettings.stereoscopic3D = true;.

Note:This is deprecated in Unity 2017.2.

Another solution was to add

UnityEditorInternal.VR.VREditor.SetVREnabledDevicesOnTargetGroup(BuildTargetGroup.Standalone,new string[] { "stereo" });

And obviously you will have to turn on virtual reality flag in player settings on. You will see this

Even though it says '(missing from build)' it works when you run the exe.User mikewarren on the linked thread mentioned that this is a bug in unity as it does not display stereo even though it is available which I also think so.
Finally when running unity build you will be able to see stereo3D option if your resolution dialog is enabled. If not try with the command line

-vrmode stereo

which will make the unity render it in stereo mode both worked for me. For now Iam satisfied with this. Hope this helps others also :).

Update: The issue is resolved in the 2017.2.0P2 patch


问:
Setting a timer with different values
I currently am using a single timer. This timer is set so every two seconds it will switch to the next case in the case switch. However I now want to be able to set the timer to a different amount of seconds. I would like to have three or four more different values.
I know I can create new timers and then from that get the event handler for each one however I don't want to do that here.
Is there a way that I can set a single timer to different values?
The code I currently have is listed below: </p>

```<code>Clock = new Timer(2000);
           Clock.Elapsed += Clock_Elapsed;
            Clock.Enabled = true;
            Clock.Start();

 private void Clock_Elapsed(object sender, ElapsedEventArgs e)
        {
            switch (CurrentDevice)
            {
                case (Devices.WSS):
                    if (OurWSS.CurrentComponent != null)
                    {
                        OurRobot.LoadComponent(OurComponent);
                        OurWSS.UnLoad();
                    }
                    CurrentDevice = Devices.Robot
                    break;
                case (Devices.Robot):
                    if (OurRobot.CurrentComponent != null)
                    {
                        OurMachine.LoadComponent(OurComponent);
                        OurRobot.UnLoad();
                    }
                    CurrentDevice = Devices.Machine;
                    break;
                case (Devices.Machine):
                    if (OurMachine.CurrentComponent != null)
                    {
                        OurRobot.LoadComponent(OurComponent);
                        //OurComponent.GetCurrentOperation();
                        OurMachine.UnLoad();
                    }
                    CurrentDevice = Devices.RobotOut;
                    break;
                case (Devices.RobotOut):
                    if (OurRobot.CurrentComponent != null)
                    {
                        OurWSS.LoadComponent(OurComponent);
                        OurRobot.UnLoad();
                    }
                    CurrentDevice = Devices.WSS;
                    break;
            }
        }
</code>```

答:
If you limit usage to multiply of a second you could try creating a counter, increase it in every tick and than check if is time to execute a method:</p>

```<code>    long seconds;

    private void Clock_Elapsed(object sender, ElapsedEventArgs e)
    {
        seconds++;
        ExecAction1Second(); -- action taht executes every second
        if (seconds % 2 == 0)
            ExecAction2Seconds(); -- action taht executes every 2 seconds
        if (seconds % 3 == 0)
            ExecAction3Seconds(); -- action taht executes every 3 seconds
    }
</code>```

Title: Setting a timer with different values

Body:
I currently am using a single timer. This timer is set so every two seconds it will switch to the next case in the case switch. However I now want to be able to set the timer to a different amount of seconds. I would like to have three or four more different values.
I know I can create new timers and then from that get the event handler for each one however I don't want to do that here.
Is there a way that I can set a single timer to different values?
The code I currently have is listed below:

Clock = new Timer(2000);
           Clock.Elapsed += Clock_Elapsed;
            Clock.Enabled = true;
            Clock.Start();

 private void Clock_Elapsed(object sender, ElapsedEventArgs e)
        {
            switch (CurrentDevice)
            {
                case (Devices.WSS):
                    if (OurWSS.CurrentComponent != null)
                    {
                        OurRobot.LoadComponent(OurComponent);
                        OurWSS.UnLoad();
                    }
                    CurrentDevice = Devices.Robot
                    break;
                case (Devices.Robot):
                    if (OurRobot.CurrentComponent != null)
                    {
                        OurMachine.LoadComponent(OurComponent);
                        OurRobot.UnLoad();
                    }
                    CurrentDevice = Devices.Machine;
                    break;
                case (Devices.Machine):
                    if (OurMachine.CurrentComponent != null)
                    {
                        OurRobot.LoadComponent(OurComponent);
                        //OurComponent.GetCurrentOperation();
                        OurMachine.UnLoad();
                    }
                    CurrentDevice = Devices.RobotOut;
                    break;
                case (Devices.RobotOut):
                    if (OurRobot.CurrentComponent != null)
                    {
                        OurWSS.LoadComponent(OurComponent);
                        OurRobot.UnLoad();
                    }
                    CurrentDevice = Devices.WSS;
                    break;
            }
        }

Body:
If you limit usage to multiply of a second you could try creating a counter, increase it in every tick and than check if is time to execute a method:

    long seconds;

    private void Clock_Elapsed(object sender, ElapsedEventArgs e)
    {
        seconds++;
        ExecAction1Second(); -- action taht executes every second
        if (seconds % 2 == 0)
            ExecAction2Seconds(); -- action taht executes every 2 seconds
        if (seconds % 3 == 0)
            ExecAction3Seconds(); -- action taht executes every 3 seconds
    }


问:
How can I set the text color of an NSButton via Interface Builder?
There are several questions about how to set the text color programmatically.  That's all fine, but there's got to be a way to do it via Interface Builder also.

The "Show Fonts" box works for changing the size of the button text, but Xcode ignores any color changes made using the widget there, and the Attributes Inspector for NSButton doesn't have a color picker...

答:
I've no idea why this is missing still from NSButton. But here is the replacement class in Swift 4:

```<code>import Cocoa

class TextButton: NSButton {
    @IBInspectable open var textColor: NSColor = NSColor.black
    @IBInspectable open var textSize: CGFloat = 10

    public override init(frame frameRect: NSRect) {
        super.init(frame: frameRect)
    }

    public required init?(coder: NSCoder) {
        super.init(coder: coder)
    }

    override func awakeFromNib() {
        let titleParagraphStyle = NSMutableParagraphStyle()
        titleParagraphStyle.alignment = alignment

        let attributes: [NSAttributedStringKey : Any] = [.foregroundColor: textColor, .font: NSFont.systemFont(ofSize: textSize), .paragraphStyle: titleParagraphStyle]
        self.attributedTitle = NSMutableAttributedString(string: self.title, attributes: attributes)
    }
}
</code>```

Body:
I've no idea why this is missing still from NSButton. But here is the replacement class in Swift 4:

import Cocoa

class TextButton: NSButton {
    @IBInspectable open var textColor: NSColor = NSColor.black
    @IBInspectable open var textSize: CGFloat = 10

    public override init(frame frameRect: NSRect) {
        super.init(frame: frameRect)
    }

    public required init?(coder: NSCoder) {
        super.init(coder: coder)
    }

    override func awakeFromNib() {
        let titleParagraphStyle = NSMutableParagraphStyle()
        titleParagraphStyle.alignment = alignment

        let attributes: [NSAttributedStringKey : Any] = [.foregroundColor: textColor, .font: NSFont.systemFont(ofSize: textSize), .paragraphStyle: titleParagraphStyle]
        self.attributedTitle = NSMutableAttributedString(string: self.title, attributes: attributes)
    }
}


问:
Find nearest points in a vector
Given a sorted vector with a number of values, as in the following example:

```<code>std::vector<double> f;
f.pushback(10);
f.pushback(100);
f.pushback(1000);
f.pushback(10000);
</code>```

I'm looking for the most elegant way to retrieve for any double d the two values that are immediately adjacent to it. For example, given the value "45", I'd like this to return "10" and "100".

I was looking at lower_bound and upper_bound, but they don't do what I want. Can you help?

EDIT: I've decided to post my own anser, as it is somewhat a composite of all the helpful answers that I got in this thread. I've voted up those answers which I thought were most helpful.

Thanks everyone,

Dave

答:
I wrote up this little function, which seems to fit the more general case you wanted. I haven't tested it totally, but I did write a little test code (included).</p>

```<code>#include <algorithm>
#include <iostream>
#include <vector>

template <class RandomAccessIt, class Container, class T>
std::pair<RandomAccessIt, RandomAccessIt> bracket_range(RandomAccessIt begin, RandomAccessIt end, Container& c, T val)
{
    typename Container::iterator first;
    typename Container::iterator second;

    first = std::find(begin, end, val);
    //Find the first value after this by iteration
    second = first;
    if (first == begin){ // Found the first element, so set this to end to indicate no lower values
    first = end;
    }
    else if (first != end && first != begin) --first; //Set this to the first value before the found one, if the value was found
    while (second != end && *second == val) ++second;
    return std::make_pair(first,second);
}

int main(int argc, _TCHAR* argv[])
{
    std::vector<int> values;
    std::pair<std::vector<int>::iterator, std::vector<int>::iterator> vals;

    for (int i = 1; i < 9; ++i) values.push_back(i);

    for (int i = 0; i < 10; ++i){
        vals = bracket_range(values.begin(), values.end(),values, i);
        if (vals.first == values.end() && vals.second == values.end()){ // Not found at all
            std::cout << i << " is not in the container." << std::endl;
        }
        else if (vals.first == values.end()){ // No value lower
            std::cout << i << ": " << "None Lower," << *(vals.second) << std::endl;
        }
        else if (vals.second == values.end()) { // No value higher
            std::cout << i << ": " << *(vals.first) << ", None Higher" << std::endl;
        }
        else{
        std::cout << i << ": " << *(vals.first) << "," << *(vals.second) << std::endl;
        }
    }
    return 0;
}
</code>```

OwnerDisplayName: Dave Van den Eynde

Title: Find nearest points in a vector

Body:
Given a sorted vector with a number of values, as in the following example:

std::vector<double> f;
f.pushback(10);
f.pushback(100);
f.pushback(1000);
f.pushback(10000);

I'm looking for the most elegant way to retrieve for any double d the two values that are immediately adjacent to it. For example, given the value "45", I'd like this to return "10" and "100".

I was looking at lower_bound and upper_bound, but they don't do what I want. Can you help?

EDIT: I've decided to post my own anser, as it is somewhat a composite of all the helpful answers that I got in this thread. I've voted up those answers which I thought were most helpful.

Thanks everyone,

Dave

LastEditorDisplayName: Dave Van den Eynde

Body:
I wrote up this little function, which seems to fit the more general case you wanted. I haven't tested it totally, but I did write a little test code (included).

#include <algorithm>
#include <iostream>
#include <vector>

template <class RandomAccessIt, class Container, class T>
std::pair<RandomAccessIt, RandomAccessIt> bracket_range(RandomAccessIt begin, RandomAccessIt end, Container& c, T val)
{
    typename Container::iterator first;
    typename Container::iterator second;

    first = std::find(begin, end, val);
    //Find the first value after this by iteration
    second = first;
    if (first == begin){ // Found the first element, so set this to end to indicate no lower values
    first = end;
    }
    else if (first != end && first != begin) --first; //Set this to the first value before the found one, if the value was found
    while (second != end && *second == val) ++second;
    return std::make_pair(first,second);
}

int main(int argc, _TCHAR* argv[])
{
    std::vector<int> values;
    std::pair<std::vector<int>::iterator, std::vector<int>::iterator> vals;

    for (int i = 1; i < 9; ++i) values.push_back(i);

    for (int i = 0; i < 10; ++i){
        vals = bracket_range(values.begin(), values.end(),values, i);
        if (vals.first == values.end() && vals.second == values.end()){ // Not found at all
            std::cout << i << " is not in the container." << std::endl;
        }
        else if (vals.first == values.end()){ // No value lower
            std::cout << i << ": " << "None Lower," << *(vals.second) << std::endl;
        }
        else if (vals.second == values.end()) { // No value higher
            std::cout << i << ": " << *(vals.first) << ", None Higher" << std::endl;
        }
        else{
        std::cout << i << ": " << *(vals.first) << "," << *(vals.second) << std::endl;
        }
    }
    return 0;
}

OwnerDisplayName: Harper Shelby


问:
canActivate Dependant on Parent Route Resolve
I have routes setup like so:

```<code>export const APP_ROUTES: Routes = [
    {
        path: '',
        resolve: {
            user: CurrentUserResolver
        },
        children: [
            {
                path: ':sectionKey',
                canActivate: [SectionAccessGuard],
                children: [
                    {
                        path: 'dashboard',
                        component: DashboardComponent
                    }
                ]
            }
        ]
    }
]
</code>```

Where the parent route will retrieve the user via a HTTP call, and I'd like my sub-route :sectionKey to only be activated if the current user has access to it.  The issue is, it appears my canActivate SectionAccessGuard is called prior to the snapshot being fully populated:

```<code>@Injectable()
export default class SectionAccessGuard implements CanActivate {
    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
        console.log(route.data);
        console.log(route);
        return true;
    }
}
</code>```

In the console, the first entry will have nothing; however, the 2nd entry will eventually have the user field populated.

I know the canActivate method can return an Observable<boolean> as well, but I don't see any hooks on how to wait until the resolve completes.

What am I missing here?  I feel like this should be pretty straight forward.  I'm currently using angular v4.0.0-rc.2

答:
It's been about 8 months since I posted this so I'll give an update on where we ended up:

Storing data in the router through resolves started to become very awkward depending on where the component was (this.route.parent.parent.parent.data.user), so we're no longer using resolves, and instead using NgRx to store that kind of information.

Our guards then are in charge of triggering the fetching of the data, as well as waiting until it's complete.  Something like this:

```<code>@Injectable()
export class AuthenticationGuard implements CanActivate {
    constructor(private router: Router, private store: Store<ApplicationState>) { }

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
        this.store.dispatch(new AuthenticateAction());

        return this.store
            .select('auth')
            .filter((s) => !!s && !s.authenticating)
            .map((s) => s.authenticated)
            .take(1);
    }
}
</code>```

Where there are a couple flags in the state (authenticating and authenticated) that tell the guard where we're at in the process.

Body:
I have routes setup like so:

export const APP_ROUTES: Routes = [
    {
        path: '',
        resolve: {
            user: CurrentUserResolver
        },
        children: [
            {
                path: ':sectionKey',
                canActivate: [SectionAccessGuard],
                children: [
                    {
                        path: 'dashboard',
                        component: DashboardComponent
                    }
                ]
            }
        ]
    }
]

Where the parent route will retrieve the user via a HTTP call, and I'd like my sub-route :sectionKey to only be activated if the current user has access to it.  The issue is, it appears my canActivate SectionAccessGuard is called prior to the snapshot being fully populated:

@Injectable()
export default class SectionAccessGuard implements CanActivate {
    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
        console.log(route.data);
        console.log(route);
        return true;
    }
}

In the console, the first entry will have nothing; however, the 2nd entry will eventually have the user field populated.

I know the canActivate method can return an Observable<boolean> as well, but I don't see any hooks on how to wait until the resolve completes.

What am I missing here?  I feel like this should be pretty straight forward.  I'm currently using angular v4.0.0-rc.2

Body:
It's been about 8 months since I posted this so I'll give an update on where we ended up:

Storing data in the router through resolves started to become very awkward depending on where the component was (this.route.parent.parent.parent.data.user), so we're no longer using resolves, and instead using NgRx to store that kind of information.

Our guards then are in charge of triggering the fetching of the data, as well as waiting until it's complete.  Something like this:

@Injectable()
export class AuthenticationGuard implements CanActivate {
    constructor(private router: Router, private store: Store<ApplicationState>) { }

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
        this.store.dispatch(new AuthenticateAction());

        return this.store
            .select('auth')
            .filter((s) => !!s && !s.authenticating)
            .map((s) => s.authenticated)
            .take(1);
    }
}

Where there are a couple flags in the state (authenticating and authenticated) that tell the guard where we're at in the process.


问:
UINavigationBar slides away instead of staying on place
I created demo project to show the problem.

We have two view controllers inside UINavigationController.

MainViewController which is the root.

```<code>class MainViewController: UIViewController {

    lazy var button: UIButton = {
        let button = UIButton()
        button.setTitle("Detail", for: .normal)
        return button
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        navigationItem.title = "Main"
        view.backgroundColor = .blue
        view.addSubview(button)
        button.translatesAutoresizingMaskIntoConstraints = false
        button.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        button.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
        button.widthAnchor.constraint(equalToConstant: 150).isActive = true
        button.heightAnchor.constraint(equalToConstant: 42).isActive = true
        button.addTarget(self, action: #selector(buttonTapped(_:)), for: .touchUpInside)
    }

    @objc func buttonTapped(_ sender: UIButton) {
        navigationController?.pushViewController(DetailViewController(), animated: true)
    }
}
</code>```

And DetailViewController which is pushed.

```<code>class DetailViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.setNavigationBarHidden(true, animated: animated)
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        navigationController?.setNavigationBarHidden(false, animated: animated)
    }
}
</code>```

As you can see I want to hide UINavigationBar in DetailViewController:

Question

The problem is that, UINavigationBar slides away instead of stay of his place together with whole MainViewController. How can I change that behavior and keep pop gesture?

答:
The following code is hacking.

```<code>override func viewDidAppear(_ animated: Bool) {
    UIView.animate(withDuration: 0) {
        self.navigationController?.setNavigationBarHidden(false, animated: false)
    }
}
</code>```

Do not write this bizarre code, as suggested by @sagarbhut in his post (in this thread).

You have two choices.

Hack

Do not hack.

Use convenience functions like this one

https://developer.apple.com/documentation/uikit/uiview/1622562-transition

Create a custom segue, if you are using storyboards.

https://www.appcoda.com/custom-segue-animations/

Implement the UIViewControllerAnimatedTransitioning protocol

https://developer.apple.com/documentation/uikit/uiviewcontrolleranimatedtransitioning

You can get some great results but I'm afraid you will need to work hard. There are numerous tutorials online that discuss how to implement the above.

Body:
I created demo project to show the problem.

We have two view controllers inside UINavigationController.

MainViewController which is the root.

class MainViewController: UIViewController {

    lazy var button: UIButton = {
        let button = UIButton()
        button.setTitle("Detail", for: .normal)
        return button
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        navigationItem.title = "Main"
        view.backgroundColor = .blue
        view.addSubview(button)
        button.translatesAutoresizingMaskIntoConstraints = false
        button.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        button.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
        button.widthAnchor.constraint(equalToConstant: 150).isActive = true
        button.heightAnchor.constraint(equalToConstant: 42).isActive = true
        button.addTarget(self, action: #selector(buttonTapped(_:)), for: .touchUpInside)
    }

    @objc func buttonTapped(_ sender: UIButton) {
        navigationController?.pushViewController(DetailViewController(), animated: true)
    }
}

And DetailViewController which is pushed.

class DetailViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.setNavigationBarHidden(true, animated: animated)
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        navigationController?.setNavigationBarHidden(false, animated: animated)
    }
}

As you can see I want to hide UINavigationBar in DetailViewController:

Question

The problem is that, UINavigationBar slides away instead of stay of his place together with whole MainViewController. How can I change that behavior and keep pop gesture?

Body:
The following code is hacking.

override func viewDidAppear(_ animated: Bool) {
    UIView.animate(withDuration: 0) {
        self.navigationController?.setNavigationBarHidden(false, animated: false)
    }
}

Do not write this bizarre code, as suggested by @sagarbhut in his post (in this thread).

You have two choices.

Hack

Do not hack.

Use convenience functions like this one

https://developer.apple.com/documentation/uikit/uiview/1622562-transition

Create a custom segue, if you are using storyboards.

https://www.appcoda.com/custom-segue-animations/

Implement the UIViewControllerAnimatedTransitioning protocol

https://developer.apple.com/documentation/uikit/uiviewcontrolleranimatedtransitioning

You can get some great results but I'm afraid you will need to work hard. There are numerous tutorials online that discuss how to implement the above.


问:
AngularJs - .success is not a function after minification
I'm using angularJS(v1.5.7) in my MVC application. During the development, we used the syntax bellow to make ajax calling::

$http({
  method: 'GET',
  url: "",
  params: { }
}).success(function (data) {
  ...
}).finally(function () {
  ...
});```

When I published my application on the server, I'm using bundle to minify my javascript files.

After that, I'm geting the error: ".success is not a function"

Does anybody knows why this issue happen only when I minify the files?

答:
Try using the following syntax  </p>

```<code>.then(function(success)){
    ...
}, function(error){
    ...
});
</code>```

<p>As once answered here for more information.
$http.get(...).success is not a function the angular team deprecated success as a function itself in favour of using .then() and passing in first a success function, and a second optional error function passed in. </p>

Body:
I'm using angularJS(v1.5.7) in my MVC application. During the development, we used the syntax bellow to make ajax calling::

$http({
  method: 'GET',
  url: "",
  params: { }
}).success(function (data) {
  ...
}).finally(function () {
  ...
});

When I published my application on the server, I'm using bundle to minify my javascript files.

After that, I'm geting the error: ".success is not a function"

Does anybody knows why this issue happen only when I minify the files?

Body:
Try using the following syntax

.then(function(success)){
    ...
}, function(error){
    ...
});

As once answered here for more information.
$http.get(...).success is not a function the angular team deprecated success as a function itself in favour of using .then() and passing in first a success function, and a second optional error function passed in.


问:
Syntax Error after cut and paste SQL Stored Procedure
I have checked all things in related to internet all are same as they say i just cant understand what is wrong, Please help me early.

```<code>//stored procedure
    DELIMITER $$

    DROP PROCEDURE IF EXISTS `manoj`.`SP_inserttbluserregistration` $$
    CREATE DEFINER=`root`@`syits04-pc` PROCEDURE
    `SP_inserttbluserregistration`(IN FIRSTNAME1 varchar(500),IN LASTNAME1
    varchar(500),IN EMAIL1 varchar(500),IN USERTYPE1 integer,IN USERNAME1
    varchar(500),IN PASSWORD1 varchar(500),IN STATUS1 INTEGER,IN UPDATESTATUS1
    INTEGER,IN DELETESTATUS1 INTEGER)
    BEGIN
    insert into
  tbluserregistration(FIRSTNAME,LASTNAME,EMAIL,USERTYPE,USERNAME,PASSWORD,STATUS,UPDATESTATUS,DELETESTATUS) VALUES(FIRSTNAME1,LASTNAME1,EMAIL1,USERTYPE1,USERNAME1,PASSWORD1,STATUS1,UPDATESTATUS1,DELETESTATUS1);
END $$
</code>```

DELIMITER ;

// this is code of c#

```<code>MySqlCommand cmdi = new MySqlCommand("SP_inserttbluserregistration", GetConnection.GetConnectionOpen());
                    cmd.CommandType = System.Data.CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("FIRSTNAME1", FIRSTNAME);
                    cmd.Parameters["FIRSTNAME1"].Direction = ParameterDirection.Input;
                    cmd.Parameters.AddWithValue("LASTNAME1", LASTNAME);
                    cmd.Parameters["LASTNAME1"].Direction = ParameterDirection.Input;
                    cmd.Parameters.AddWithValue("USERTYPE1", USERTYPE);
                    cmd.Parameters["USERTYPE1"].Direction = ParameterDirection.Input;
                    cmd.Parameters.AddWithValue("EMAIL1", EMAIL);
                    cmd.Parameters["EMAIL1"].Direction = ParameterDirection.Input;
                    cmd.Parameters.AddWithValue("USERNAME1", USERNAME);
                    cmd.Parameters["USERNAME1"].Direction = ParameterDirection.Input;
                    cmd.Parameters.AddWithValue("PASSWORD1", PASSWORD);
                    cmd.Parameters["PASSWORD1"].Direction = ParameterDirection.Input;
                    cmd.Parameters.AddWithValue("STATUS1", 0);
                    cmd.Parameters["STATUS1"].Direction = ParameterDirection.Input;
                    cmd.Parameters.AddWithValue("UPDATESTATUS1", 0);
                    cmd.Parameters["UPDATESTATUS1"].Direction = ParameterDirection.Input;
                    cmd.Parameters.AddWithValue("DELETESTATUS1", 0);
                    cmd.Parameters["DELETESTATUS1"].Direction = ParameterDirection.Input;
                    object isInserted = cmdi.ExecuteNonQuery();
                    if (isInserted != null)
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
</code>```

ERROR

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SP_inserttbluserregistration' at line 1

答: Your quote marks (`) are wrong. Sometimes when you cut and paste, the incorrect characters are used. Try replace all the (') characters with (') instead of (`) </p>

Body:
I have checked all things in related to internet all are same as they say i just cant understand what is wrong, Please help me early.

//stored procedure
    DELIMITER $$

    DROP PROCEDURE IF EXISTS `manoj`.`SP_inserttbluserregistration` $$
    CREATE DEFINER=`root`@`syits04-pc` PROCEDURE
    `SP_inserttbluserregistration`(IN FIRSTNAME1 varchar(500),IN LASTNAME1
    varchar(500),IN EMAIL1 varchar(500),IN USERTYPE1 integer,IN USERNAME1
    varchar(500),IN PASSWORD1 varchar(500),IN STATUS1 INTEGER,IN UPDATESTATUS1
    INTEGER,IN DELETESTATUS1 INTEGER)
    BEGIN
    insert into
  tbluserregistration(FIRSTNAME,LASTNAME,EMAIL,USERTYPE,USERNAME,PASSWORD,STATUS,UPDATESTATUS,DELETESTATUS) VALUES(FIRSTNAME1,LASTNAME1,EMAIL1,USERTYPE1,USERNAME1,PASSWORD1,STATUS1,UPDATESTATUS1,DELETESTATUS1);
END $$

DELIMITER ;

// this is code of c#

MySqlCommand cmdi = new MySqlCommand("SP_inserttbluserregistration", GetConnection.GetConnectionOpen());
                    cmd.CommandType = System.Data.CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("FIRSTNAME1", FIRSTNAME);
                    cmd.Parameters["FIRSTNAME1"].Direction = ParameterDirection.Input;
                    cmd.Parameters.AddWithValue("LASTNAME1", LASTNAME);
                    cmd.Parameters["LASTNAME1"].Direction = ParameterDirection.Input;
                    cmd.Parameters.AddWithValue("USERTYPE1", USERTYPE);
                    cmd.Parameters["USERTYPE1"].Direction = ParameterDirection.Input;
                    cmd.Parameters.AddWithValue("EMAIL1", EMAIL);
                    cmd.Parameters["EMAIL1"].Direction = ParameterDirection.Input;
                    cmd.Parameters.AddWithValue("USERNAME1", USERNAME);
                    cmd.Parameters["USERNAME1"].Direction = ParameterDirection.Input;
                    cmd.Parameters.AddWithValue("PASSWORD1", PASSWORD);
                    cmd.Parameters["PASSWORD1"].Direction = ParameterDirection.Input;
                    cmd.Parameters.AddWithValue("STATUS1", 0);
                    cmd.Parameters["STATUS1"].Direction = ParameterDirection.Input;
                    cmd.Parameters.AddWithValue("UPDATESTATUS1", 0);
                    cmd.Parameters["UPDATESTATUS1"].Direction = ParameterDirection.Input;
                    cmd.Parameters.AddWithValue("DELETESTATUS1", 0);
                    cmd.Parameters["DELETESTATUS1"].Direction = ParameterDirection.Input;
                    object isInserted = cmdi.ExecuteNonQuery();
                    if (isInserted != null)
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }

ERROR

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SP_inserttbluserregistration' at line 1