问:
vertex distortion in shaderlab
I'm rather new to shaderlab with unity. I am trying to distort the vertices so that they are push backwards and towards the camera almost like looking at the camera from a 45 degree angle. I am replicating an effect from a game for fun. This is the code used for the effect

ive tried implenting the code into a shader script like so:

```<code>float4 vert(appdata v){

            float3 position = mul(unity_ObjectToWorld, v.vertex).xyz;

            float y = position.y;
            float z = position.x;

            float3 parentTranslation = ParentMatrix._m30_m31_m32;

            position -= parentTranslation;
            position.z += AlternateLayeringScale;
            position.z -= y;
            position.y += position.z;
            position += parentTranslation + float3(0,parentTranslation.z,0);

            return position;

        }
</code>```

however i get an error stating it cannot convert from float3 to float4, i am not sure how it was implemented

答: The fourth part is 'w' also called the inverse stretching factor. To convert from vec4 to vec3 it's best to do position.xyz / position.w and to put it back in a vec4 you can write return fixed4(position, 1)

Title: vertex distortion in shaderlab

Body:
I'm rather new to shaderlab with unity. I am trying to distort the vertices so that they are push backwards and towards the camera almost like looking at the camera from a 45 degree angle. I am replicating an effect from a game for fun. This is the code used for the effect

ive tried implenting the code into a shader script like so:

float4 vert(appdata v){

            float3 position = mul(unity_ObjectToWorld, v.vertex).xyz;

            float y = position.y;
            float z = position.x;

            float3 parentTranslation = ParentMatrix._m30_m31_m32;

            position -= parentTranslation;
            position.z += AlternateLayeringScale;
            position.z -= y;
            position.y += position.z;
            position += parentTranslation + float3(0,parentTranslation.z,0);

            return position;

        }

however i get an error stating it cannot convert from float3 to float4, i am not sure how it was implemented


来源: stackexchange

问:
Pass data from child to parent component Angular2 (reactive and template driven combined)
being very new to Angular 2 ( and Angular in general ) , I've encountered a situation with my colleague where he decided to go for the template driven approach and me for the reactive driven approach. We've both created components. His being a search product component and mine being a credidcard component.

What does it do and the wish

From a searchbox if you select a creditcard from the dropdownbox my component will be rendered(and validated when a number is being inserted).

I wish to bind the data from my creditcard component ( being the child ) to the model of the SearchProductModel that he defined.
I saw something similar which resembles my problem a bit here is the post (Pass data from child to parent component Angular2).

These are the components and templates

creditcard.component.ts

```<code>@Component({
selector:'creditcard',
templateUrl:'./app/creditcard/creditcard.component.html'
})

export class CreditcardComponent {
creditForm: FormGroup

ccnumber = new FormControl('', [Validators.required, validateCreditcard]);

constructor(fb:FormBuilder){
this.creditForm = fb.group({"ccnumber":this.ccnumber})
}
</code>```

search-product.component.ts

```<code>    @Component({
    selector:'search-product',
    templateUrl:'./app/search/search-product.component.html'
    })

    export class SearchProductComponent{
products: Product[]
model = new SearchProductModel();
searchResult:string;

constructor(private searchProductService: SearchProductService){}

ngOnInit(): void {
this.searchProductService.getProducts().subscribe(products => this.products = products, error => console.log(error));
}

onSubmit(): void {
this.searchProductService.searchProduct(this.model).subscribe(result => this.searchResult = result,
error => console.log(error));;
}
</code>```

search-product.component.html

```<code><form (ngSubmit)="onSubmit()" #searchForm="ngForm" autocomplete="off">
<p>
<md-select placeholder="Product (optioneel)" [(ngModel)]="model.productId" name="product-id" id="product" style="width:250px">
 <md-option *ngFor="let product of products" [value]="product.Id">{{product.Name}}</md-option>
</md-select>
</p>

<div [ngSwitch]="model.productId">
 <p *ngSwitchCase="1">
<creditcard></creditcard>
</p>
<p *ngSwitchDefault>
<md-input-container style="width: 250px">
<input mdInput [(ngModel)]="model.productNumber" name="product-number" id="product-number" required/>
<md-error>productnumber required</md-error>
</md-input-container>

<button md-button type="submit" id="btn-zoek">Search</button>
</form>
</code>```

creditcard.component.html

```<code><form [formGroup]="creditcardForm">
<div class="form-group">
<md-input-container>
 <input mdInput formControlname="creditcardnumber" id="creditcardnumber" name="creditcardnumber"/>
<div *ngIf="creditForm.get('creditcardnumber').dirty && creditcardForm.get('creditcardnumber').hasError('validCreditcard')">Not correct creditcard</div>
</md-input-container>
</div>
</form>
</code>```

As I understand it, the mixed template driven and reactive approach is not advisable so I will be refactoring this in the future. But for now I wonder how I can make it possible for my creditcard input to get into his model.productId ( see the code).
Bear with me, I'm new in this and I'm just having a hard time wrapping my head around it.

Help very much appreciated.

答:
Ok, I made a small mistake that has led me to believe my solution didn't work.
However it did work. I just followed the explanation I've put in the link above.
Added the Emitter in my component and subscribed the other component to the events of mine.
That did the trick. </p>

ContentLicense: CC BY-SA 3.0

Body:
being very new to Angular 2 ( and Angular in general ) , I've encountered a situation with my colleague where he decided to go for the template driven approach and me for the reactive driven approach. We've both created components. His being a search product component and mine being a credidcard component.

What does it do and the wish

From a searchbox if you select a creditcard from the dropdownbox my component will be rendered(and validated when a number is being inserted).

I wish to bind the data from my creditcard component ( being the child ) to the model of the SearchProductModel that he defined.
I saw something similar which resembles my problem a bit here is the post (Pass data from child to parent component Angular2).

These are the components and templates

creditcard.component.ts

@Component({
selector:'creditcard',
templateUrl:'./app/creditcard/creditcard.component.html'
})

export class CreditcardComponent {
creditForm: FormGroup

ccnumber = new FormControl('', [Validators.required, validateCreditcard]);

constructor(fb:FormBuilder){
this.creditForm = fb.group({"ccnumber":this.ccnumber})
}

search-product.component.ts

    @Component({
    selector:'search-product',
    templateUrl:'./app/search/search-product.component.html'
    })

    export class SearchProductComponent{
products: Product[]
model = new SearchProductModel();
searchResult:string;

constructor(private searchProductService: SearchProductService){}

ngOnInit(): void {
this.searchProductService.getProducts().subscribe(products => this.products = products, error => console.log(error));
}

onSubmit(): void {
this.searchProductService.searchProduct(this.model).subscribe(result => this.searchResult = result,
error => console.log(error));;
}

search-product.component.html

<form (ngSubmit)="onSubmit()" #searchForm="ngForm" autocomplete="off">

<md-select placeholder="Product (optioneel)" [(ngModel)]="model.productId" name="product-id" id="product" style="width:250px">
 <md-option *ngFor="let product of products" [value]="product.Id">{{product.Name}}</md-option>
</md-select>

<creditcard></creditcard>

<md-input-container style="width: 250px">
<input mdInput [(ngModel)]="model.productNumber" name="product-number" id="product-number" required/>
<md-error>productnumber required</md-error>
</md-input-container>

<button md-button type="submit" id="btn-zoek">Search</button>
</form>

creditcard.component.html

<form [formGroup]="creditcardForm">

<md-input-container>
 <input mdInput formControlname="creditcardnumber" id="creditcardnumber" name="creditcardnumber"/>

Not correct creditcard

</md-input-container>

</form>

As I understand it, the mixed template driven and reactive approach is not advisable so I will be refactoring this in the future. But for now I wonder how I can make it possible for my creditcard input to get into his model.productId ( see the code).
Bear with me, I'm new in this and I'm just having a hard time wrapping my head around it.

Help very much appreciated.


问:
jquery price not updating on delete
I want to update price on delete button click. When I am clicking on add button it adding the field and updating the price. But on delete button it is only deleting field and price is not updating.      </p>

```<code>$(document).ready(function() {
  $('#add').on('click', function() {

     var maxfld=$('.acmp').length;
     var pricedl=500;

     if(maxfld<10)
     {
     $('#new_ac').append('<div id="" class="acmp">'+(++maxfld)+'  <p>ACCOMPANYING PERSON DETAILS (No access to Scientific Halls)</p><input type="text" name="name" placeholder="Accompany Full Name" required /><input type="text" name="mob" placeholder="Accompany Mobile Number" required /><br />Gender<br /><input name="gender" type="radio" value="male" required="required" /> Male<input name="gender" type="radio" value="female" required="required" /> Female</div>');
     }
     if(maxfld>9)
     {
        alert("Cannot add more accompany");

     }
     var totalp=(pricedl*maxfld);
       $('#amount').html(totalp);

  });

  $('#del').on('click', function() {
    $('.acmp:last-child').remove();
    var newp=totalp/maxfld;
      $('.price').html(newp);

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

答:
You are missing the below variables in delete block

```<code> var maxfld=$('.acmp').length;
 var pricedl=500;
 var totalp=(pricedl*maxfld);
</code>```

May be the below code will work

```<code>$('#del').on('click', function() {
    $('.acmp:last-child').remove();
    var maxfld=$('.acmp').length;
    var pricedl=500;
    var totalp=(pricedl*maxfld);
    var newp=totalp/maxfld;
    $('.price').html(newp);
  });
</code>```

Title: jquery price not updating on delete

Body:
I want to update price on delete button click. When I am clicking on add button it adding the field and updating the price. But on delete button it is only deleting field and price is not updating.

$(document).ready(function() {
  $('#add').on('click', function() {

     var maxfld=$('.acmp').length;
     var pricedl=500;

     if(maxfld<10)
     {
     $('#new_ac').append('
'+(++maxfld)+'
ACCOMPANYING PERSON DETAILS (No access to Scientific Halls)
<input type="text" name="name" placeholder="Accompany Full Name" required /><input type="text" name="mob" placeholder="Accompany Mobile Number" required />
Gender
<input name="gender" type="radio" value="male" required="required" /> Male<input name="gender" type="radio" value="female" required="required" /> Female
');
     }
     if(maxfld>9)
     {
        alert("Cannot add more accompany");

     }
     var totalp=(pricedl*maxfld);
       $('#amount').html(totalp);

  });

  $('#del').on('click', function() {
    $('.acmp:last-child').remove();
    var newp=totalp/maxfld;
      $('.price').html(newp);

  });
});

Body:
You are missing the below variables in delete block

 var maxfld=$('.acmp').length;
 var pricedl=500;
 var totalp=(pricedl*maxfld);

May be the below code will work

$('#del').on('click', function() {
    $('.acmp:last-child').remove();
    var maxfld=$('.acmp').length;
    var pricedl=500;
    var totalp=(pricedl*maxfld);
    var newp=totalp/maxfld;
    $('.price').html(newp);
  });


问:
JVM heap memory
Do we need to mandatory specify JVM heap memory arguments in bat file while calling .jar file?

For example:
start /b "" "jre7\bin\javaw.exe" -Xmx1G -jar XYZ.jar

I have the scenario that in some machine when I explicitly specify the arguments(as above) then Java fatal exception is generated!

enter image description here

Error Message:
"Java virtual machine Launcher:
Error: Could not create Java virtual machine.
Error: A fatal exception has occurred. Program will exit."

But when I remove the arguments then no error is reported.
Please anyone let me know. Thank you.

答:
Xmx is an optional argument that specifies the maximum heap size that can be used by Java. It is not required.

If you specify too large a number, you may get a fatal exception. If you don't specify an option, java chooses the max heap size. You can find the default value of this on linux by running 'java -XX:+PrintFlagsFinal -version | grep MaxHeapSize'

Title: JVM heap memory


问:
knockout in mvc - simple example not working
I got knockout to work before in MVC, but unfortunately I lost the code, and need help figuring it out.

I am trying to simply put an html page in the ~/wwwsource/ folder of my MVC project, and in that page I would like to demo a simple knockout example.

(Eventually, I actually want to use knockout inside MVC Views, using knockout right alongside Razor if possible but first I just would at least like to get a simple working example going, and extend from there.

I tried the following, which worked in JSFiddle but not in Visual Studio:

```<code>        <script src="lib/knockout/dist/knockout.debug.js" type="text/javascript">

    // Here's my data model
    var ViewModel = function (first, last) {
        this.firstName = ko.observable(first);
        this.lastName = ko.observable(last);

        this.fullName = ko.pureComputed(function () {
            // Knockout tracks dependencies automatically. It knows that fullName depends on firstName and lastName, because these get called when evaluating fullName.
            return this.firstName() + " " + this.lastName();
        }, this);
    };

    ko.applyBindings(new ViewModel("Planet", "Earth"));
</script>

<p>First name: <input data-bind="value: firstName" /></p>
<p>Last name: <input data-bind="value: lastName" /></p>
<h2>Hello, <span data-bind="text: fullName"> </span>!</h2>
</code>```

答:
You are calling the javascript before the html has been fully rendered. So when ko.applyBindingsis called the html as only partially loaded.

Easiest solution is to wrap the javascript in a document loaded callback using jQuery (which should exist because you're using knockout).

You also have some invalid script tag syntax.  Need to close knockout script tag before starting a new one for the page.

```<code><script src="lib/knockout/dist/knockout.debug.js" type="text/javascript">
</script>

<script type="text/javascript">
// Here's my data model
var ViewModel = function (first, last) {
    this.firstName = ko.observable(first);
    this.lastName = ko.observable(last);

    this.fullName = ko.pureComputed(function () {
        // Knockout tracks dependencies automatically. It knows that fullName depends on firstName and lastName, because these get called when evaluating fullName.
       return this.firstName() + " " + this.lastName();
    }, this);
};

$(document).ready(function(){
    ko.applyBindings(new ViewModel("Planet", "Earth"));
})
</script>

<p>First name: <input data-bind="value: firstName" /></p>
<p>Last name: <input data-bind="value: lastName" /></p>
<h2>Hello, <span data-bind="text: fullName"> </span>!</h2>
</code>```

Body:
I got knockout to work before in MVC, but unfortunately I lost the code, and need help figuring it out.

I am trying to simply put an html page in the ~/wwwsource/ folder of my MVC project, and in that page I would like to demo a simple knockout example.

(Eventually, I actually want to use knockout inside MVC Views, using knockout right alongside Razor if possible but first I just would at least like to get a simple working example going, and extend from there.

I tried the following, which worked in JSFiddle but not in Visual Studio:

First name: <input data-bind="value: firstName" />

Last name: <input data-bind="value: lastName" />

Hello,  !

Body:
You are calling the javascript before the html has been fully rendered. So when ko.applyBindingsis called the html as only partially loaded.

Easiest solution is to wrap the javascript in a document loaded callback using jQuery (which should exist because you're using knockout).

You also have some invalid script tag syntax.  Need to close knockout script tag before starting a new one for the page.

<script src="lib/knockout/dist/knockout.debug.js" type="text/javascript">
</script>

<script type="text/javascript">
// Here's my data model
var ViewModel = function (first, last) {
    this.firstName = ko.observable(first);
    this.lastName = ko.observable(last);

    this.fullName = ko.pureComputed(function () {
        // Knockout tracks dependencies automatically. It knows that fullName depends on firstName and lastName, because these get called when evaluating fullName.
       return this.firstName() + " " + this.lastName();
    }, this);
};

$(document).ready(function(){
    ko.applyBindings(new ViewModel("Planet", "Earth"));
})
</script>

<p>First name: <input data-bind="value: firstName" /></p>
<p>Last name: <input data-bind="value: lastName" /></p>
<h2>Hello, <span data-bind="text: fullName"> </span>!</h2>


问:
OpenCL vector types: Can't access unioned components x,y,z with C++11 enabled
The following C++ OpenCL code compiles fine with g++ -c no_x.cpp:

```<code>// no_x.cpp
#include <CL/cl.h>

void func() {
  cl_double2 xy;
  xy.x = 1.0;
  xy.y = 2.0;
}
</code>```

But with C++-11 enabled the same file gives errors:

```<code>$ g++ -std=c++11 -c no_x.cpp
nox.cpp: In function ‘void func()’:
nox.cpp:7:7: error: ‘union cl_double2’ has no member named ‘x’
    xy.x = 1.0;
       ^
nox.cpp:8:7: error: ‘union cl_double2’ has no member named ‘y’
    xy.y = 2.0;
       ^
</code>```

I can get around it with xy.s[0], xy.s[1] etc, but that's ugly (which is surely why OpenCL provides the .x, .y components). What's up with C++11 that is causing this? Can I in general not compile OpenCL with C++11?

答:
In the OpenCL headers (cl_platform.h, included by cl.h), cl_double2 is defined the following way:

```<code>typedef union
{
    cl_double  CL_ALIGNED(16) s[2];
#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ )
   __extension__ struct{ cl_double  x, y; };
   __extension__ struct{ cl_double s0, s1; };
   __extension__ struct{ cl_double lo, hi; };
#endif
#if defined( __CL_DOUBLE2__)
    __cl_double2     v2;
#endif
}cl_double2;
</code>```

So, if your compiler doesn't use the GNU preprocessor, or if __STRICT_ANSI__ is defined (g++ may define it), you won't be able to access those members.

Body:
The following C++ OpenCL code compiles fine with g++ -c no_x.cpp:

// no_x.cpp
#include <CL/cl.h>

void func() {
  cl_double2 xy;
  xy.x = 1.0;
  xy.y = 2.0;
}

But with C++-11 enabled the same file gives errors:

$ g++ -std=c++11 -c no_x.cpp
nox.cpp: In function ‘void func()’:
nox.cpp:7:7: error: ‘union cl_double2’ has no member named ‘x’
    xy.x = 1.0;
       ^
nox.cpp:8:7: error: ‘union cl_double2’ has no member named ‘y’
    xy.y = 2.0;
       ^

I can get around it with xy.s[0], xy.s[1] etc, but that's ugly (which is surely why OpenCL provides the .x, .y components). What's up with C++11 that is causing this? Can I in general not compile OpenCL with C++11?

Body:
In the OpenCL headers (cl_platform.h, included by cl.h), cl_double2 is defined the following way:

typedef union
{
    cl_double  CL_ALIGNED(16) s[2];
#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ )
   __extension__ struct{ cl_double  x, y; };
   __extension__ struct{ cl_double s0, s1; };
   __extension__ struct{ cl_double lo, hi; };
#endif
#if defined( __CL_DOUBLE2__)
    __cl_double2     v2;
#endif
}cl_double2;

So, if your compiler doesn't use the GNU preprocessor, or if __STRICT_ANSI__ is defined (g++ may define it), you won't be able to access those members.


问:
Why is my DialogFragment not showing the custom layout?
I want to show a DialogFragment with no title, buttons, etc.(i.e, none of what is included in a typical Dialog) but just a ProgressBar spinner on a plain background. For a rough idea, the background's width matches that of the parent and spinner lies at the center of it. For this, I have a custom layout as follows:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent" android:layout_height="match_parent">

    <View
        android:id="@+id/search_progress_alpha_indicator"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginBottom="8dp"
        android:layout_marginLeft="16dp"
        android:layout_marginStart="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginEnd="16dp"
        android:layout_marginTop="8dp"
        app:layout_constraintBottom_toTopOf="@+id/guideline3"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="@+id/guideline2"
        android:background="#00ffffff"/>

    <ProgressBar
        android:id="@+id/search_tutors_progress_bar"
        style="?android:attr/progressBarStyle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:visibility="gone"/>

    <android.support.constraint.Guideline
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/guideline2"
        app:layout_constraintGuide_percent="0.20"
        android:orientation="horizontal"
        tools:layout_editor_absoluteY="126dp"
        tools:layout_editor_absoluteX="0dp" />

    <android.support.constraint.Guideline
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/guideline3"
        app:layout_constraintGuide_percent="0.80"
        android:orientation="horizontal"
        tools:layout_editor_absoluteY="378dp"
        tools:layout_editor_absoluteX="0dp" />

</android.support.constraint.ConstraintLayout>
</code>```

Here, View is the background on top of which the ProgressBar is supposed to spin.

But when I inflate this layout in the DialogFragment, it shows something completely different:

Here is the DialogFragment code:

```<code>public static class SearchIndicatorDialogFragment extends DialogFragment{

        public static String FRAGMENT_TAG = "searchIndDiaFragTag";

        private View alphaSearchIndicator;
        private ProgressBar progressBar;

        @Override
        public void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
        }

        @Nullable
        @Override
        public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

            View dialogRootView = inflater.inflate(R.layout.fragment_search_dialog, container, false);

            // Obtain the ProgressBar
            progressBar = (ProgressBar) dialogRootView.findViewById(R.id.search_tutors_progress_bar);

            // Obtain the Alpha search indicator
            alphaSearchIndicator = dialogRootView.findViewById(R.id.search_progress_alpha_indicator);

            return dialogRootView;
        }

        @Override
        public void onStop() {

            progressBar.setVisibility(View.GONE);

            alphaSearchIndicator.setBackgroundColor(0x00ffffff);

            super.onStop();
        }

        @Override
        public void onResume() {
            progressBar.setVisibility(View.VISIBLE);

            alphaSearchIndicator.setBackgroundColor(0xA6ffffff);

            super.onResume();
        }

    }
</code>```

Why is it not showing my custom layout as intended?

EDIT: As an additional note, The problem in my case is that the background View is supposed to be occupying 60% area of screen(height wise) and for this I have constrained it in between the Guidelines. This is something, I am unable to achieve with other answers to similar questions regarding DialogFragment. Moreover, I would like to know, why does a DialogFragment doesn't display the correct by default in general?

答:
try this

```<code> Window window = yourDialog.getWindow();
 window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
 window.setGravity(Gravity.CENTER);
</code>```

or

```<code>int width = getResources().getDimensionPixelSize(R.dimen.popup_width);
int height =  getResources().getDimensionPixelSize(R.dimen.popup_height);
getDialog().getWindow().setLayout(width, height);
</code>```

Body:
I want to show a DialogFragment with no title, buttons, etc.(i.e, none of what is included in a typical Dialog) but just a ProgressBar spinner on a plain background. For a rough idea, the background's width matches that of the parent and spinner lies at the center of it. For this, I have a custom layout as follows:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent" android:layout_height="match_parent">

    <View
        android:id="@+id/search_progress_alpha_indicator"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginBottom="8dp"
        android:layout_marginLeft="16dp"
        android:layout_marginStart="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginEnd="16dp"
        android:layout_marginTop="8dp"
        app:layout_constraintBottom_toTopOf="@+id/guideline3"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="@+id/guideline2"
        android:background="#00ffffff"/>

    <ProgressBar
        android:id="@+id/search_tutors_progress_bar"
        style="?android:attr/progressBarStyle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:visibility="gone"/>

    <android.support.constraint.Guideline
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/guideline2"
        app:layout_constraintGuide_percent="0.20"
        android:orientation="horizontal"
        tools:layout_editor_absoluteY="126dp"
        tools:layout_editor_absoluteX="0dp" />

    <android.support.constraint.Guideline
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/guideline3"
        app:layout_constraintGuide_percent="0.80"
        android:orientation="horizontal"
        tools:layout_editor_absoluteY="378dp"
        tools:layout_editor_absoluteX="0dp" />

</android.support.constraint.ConstraintLayout>

Here, View is the background on top of which the ProgressBar is supposed to spin.

But when I inflate this layout in the DialogFragment, it shows something completely different:

Here is the DialogFragment code:

public static class SearchIndicatorDialogFragment extends DialogFragment{

        public static String FRAGMENT_TAG = "searchIndDiaFragTag";

        private View alphaSearchIndicator;
        private ProgressBar progressBar;

        @Override
        public void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
        }

        @Nullable
        @Override
        public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

            View dialogRootView = inflater.inflate(R.layout.fragment_search_dialog, container, false);

            // Obtain the ProgressBar
            progressBar = (ProgressBar) dialogRootView.findViewById(R.id.search_tutors_progress_bar);

            // Obtain the Alpha search indicator
            alphaSearchIndicator = dialogRootView.findViewById(R.id.search_progress_alpha_indicator);

            return dialogRootView;
        }

        @Override
        public void onStop() {

            progressBar.setVisibility(View.GONE);

            alphaSearchIndicator.setBackgroundColor(0x00ffffff);

            super.onStop();
        }

        @Override
        public void onResume() {
            progressBar.setVisibility(View.VISIBLE);

            alphaSearchIndicator.setBackgroundColor(0xA6ffffff);

            super.onResume();
        }

    }

Why is it not showing my custom layout as intended?

EDIT: As an additional note, The problem in my case is that the background View is supposed to be occupying 60% area of screen(height wise) and for this I have constrained it in between the Guidelines. This is something, I am unable to achieve with other answers to similar questions regarding DialogFragment. Moreover, I would like to know, why does a DialogFragment doesn't display the correct by default in general?

Body:
try this

 Window window = yourDialog.getWindow();
 window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
 window.setGravity(Gravity.CENTER);

or

int width = getResources().getDimensionPixelSize(R.dimen.popup_width);
int height =  getResources().getDimensionPixelSize(R.dimen.popup_height);
getDialog().getWindow().setLayout(width, height);


问:
formidablepro2pdf checkbox / radio not working
I am using formidablepdfpro in my website and all the pdf mapping are working fine but out of these a radio button with the following label:

Neuanmeldung

Übernahme Übernahme Neuanmeldung mit

Rufnummernportierung

Vertragsverlängerung

Not working properly.
Thanks in advance.

答:
http://www.formidablepro2pdf.com/support/subject/check-boxes-are-not-working/

You can try this.
Regarding Radio Buttons, you MUST name all PDF options the same, and change the PDF Radio Button EXPORT VALUE of each option to match (use copy/paste) each value from the Formidable Form radio button field options. (Again, if the Formidable checkbox value is too long or contains special characters, then use Formidable’s “Separate Values” function)


问:
Stable, open-source Servlet 3.0 container
Are there any JSR-315-capable servlet containers available besides the one in GlassFish 3? Neither Tomcat nor Jetty have stable versions that support the Servlet 3.0 API.</p>

答: Tomcat 7 supports Servlet 3.0</p>

ContentLicense: CC BY-SA 2.5

Body: Tomcat 7 supports Servlet 3.0


问:
Multiple dex files define Lcom/google/firebase/FirebaseException
I encountered a problem with the Firebase integration. First of all, I have added rules to the root-level build.gradle file:

```<code>buildscript {
    repositories {
        maven { url "http://dl.bintray.com/populov/maven" }
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.1.2'
        classpath 'com.google.gms:google-services:3.0.0'
    }
}

allprojects {
    repositories {
        maven { url "http://dl.bintray.com/populov/maven" }
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

And the module Gradle file:

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 24
    buildToolsVersion "24"

    defaultConfig {
        applicationId "com.example.app"
        minSdkVersion 14
        targetSdkVersion 24
        versionCode 2
        versionName "0.9"
    }
    buildTypes {
       ///
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile 'com.google.firebase:firebase-core:9.0.2'
    compile 'com.google.firebase:firebase-crash:9.0.2'
}

apply plugin: 'com.google.gms.google-services'
</code>```

During the build of the project, I get the error:

Error:Error converting bytecode to dex: Cause:
  com.android.dex.DexException: Multiple dex files define
  Lcom/google/firebase/FirebaseException;

Error reason is clear, but I didn't compile any library twice. Should I exclude FirebaseException class from the build process manually? If so, how? Perhaps this is a bug within the Firebase dependencies?

Thanks.

答:
I encountered this error when I was using firebase-ui:2.0.0. I managed to solve it by downgrading to 'com.firebaseui:firebase-ui:1.2.0' and added the following line in Project level build.gradle:

```<code>allprojects {
    repositories {
        jcenter()

        // Add the following
        maven {
            url 'https://maven.fabric.io/public'
        }
    }
}
</code>```

Body:
I encountered a problem with the Firebase integration. First of all, I have added rules to the root-level build.gradle file:

buildscript {
    repositories {
        maven { url "http://dl.bintray.com/populov/maven" }
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.1.2'
        classpath 'com.google.gms:google-services:3.0.0'
    }
}

allprojects {
    repositories {
        maven { url "http://dl.bintray.com/populov/maven" }
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

And the module Gradle file:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 24
    buildToolsVersion "24"

    defaultConfig {
        applicationId "com.example.app"
        minSdkVersion 14
        targetSdkVersion 24
        versionCode 2
        versionName "0.9"
    }
    buildTypes {
       ///
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile 'com.google.firebase:firebase-core:9.0.2'
    compile 'com.google.firebase:firebase-crash:9.0.2'
}

apply plugin: 'com.google.gms.google-services'

During the build of the project, I get the error:

Error:Error converting bytecode to dex: Cause:
  com.android.dex.DexException: Multiple dex files define
  Lcom/google/firebase/FirebaseException;

Error reason is clear, but I didn't compile any library twice. Should I exclude FirebaseException class from the build process manually? If so, how? Perhaps this is a bug within the Firebase dependencies?

Thanks.

Body:
I encountered this error when I was using firebase-ui:2.0.0. I managed to solve it by downgrading to 'com.firebaseui:firebase-ui:1.2.0' and added the following line in Project level build.gradle:

allprojects {
    repositories {
        jcenter()

        // Add the following
        maven {
            url 'https://maven.fabric.io/public'
        }
    }
}


问:
Uncaught ReferenceError: moment is not defined while using moment in laravel with vue js
im using laravel 5 and i installed moment js through npm install command. im trying to use it in one of my views with vue js. but no matter what i do i get error "moment is not defined" and if i use require, i get "require is not defined" below is the script section of my view.
`

```<code><script>
    var order = new Vue({
        el: '#create_order',

        data: {
            moment: moment,
            event_id: '',
            event_type: '',
            ticket_types: [],
            time_slots: [],
            current_timeslots: [],
            start_date: null,
            end_date: null
        },

        methods: {
            moment: function (date) {
                return moment(date);
            },`
</code>```

im beginner at this so please be as explanatory as possible, thanks.

答:
You should import moment library before starting to use it.

You can try code below

```<code><script>
   import moment from 'moment'
   var order = new Vue({
   ...
</code>```

Body:
You should import moment library before starting to use it.

You can try code below

<script>
   import moment from 'moment'
   var order = new Vue({
   ...


问:
Generate date range in between 2 dates
for the last couple of hours I have been breaking my head over this.

I want to create a result set which contains a series of dates like this:

```<code>2011-07-05
2011-07-04
2011-07-03
2011-07-02
2011-07-01
2011-06-30
2011-06-29
2011-06-28
...
</code>```

Ideally between 2 dates given. But If I can say the last 30 days or the last 100 days from now that would be fine also.

Normally I would this with a CTE like this

```<code>;WITH Dates AS
(
    SELECT CONVERT(DATE, GETDATE()) [Date]
    UNION ALL
    SELECT DATEADD(DAY,-1, [Date])
    FROM Dates
    WHERE [Date] > DATEADD(DAY, -30, CONVERT(DATE, GETDATE()))
)
SELECT [Date]
</code>```

But I am not allowed to use any statements that can't be executed in a subquery. The program I am using executes queries like this:

```<code>Select *
From (
    TheQuery
) as t1
</code>```

This means I can't use declares, no stored procedures, no CTEs..

Is there any way I can obtain the dataset I need with these limitations?

I am using azure SQL

答:
Well, I think the easiest way is to create calendar table and in subquery just select dates between dates.
You can do this by this query:

```<code>CREATE TABLE dbo.Calendar ([Date] date)
DECLARE @startDate date, @endDate date

SET @startDate = '2000-01-01'
SET @endDate = '2020-12-31'

WHILE @startDate <= @endDate
BEGIN
INSERT INTO dbo.Calendar
SELECT @startDate

SET @startDate = DATEADD(DD,1,@startDate)
END
</code>```

Selecting dates:

```<code>Select *
From dbo.Calendar WHERE [Date] BETWEEN @date1 AND @date2
</code>```

Title: Generate date range in between 2 dates

Body:
for the last couple of hours I have been breaking my head over this.

I want to create a result set which contains a series of dates like this:

2011-07-05
2011-07-04
2011-07-03
2011-07-02
2011-07-01
2011-06-30
2011-06-29
2011-06-28
...

Ideally between 2 dates given. But If I can say the last 30 days or the last 100 days from now that would be fine also.

Normally I would this with a CTE like this

;WITH Dates AS
(
    SELECT CONVERT(DATE, GETDATE()) [Date]
    UNION ALL
    SELECT DATEADD(DAY,-1, [Date])
    FROM Dates
    WHERE [Date] > DATEADD(DAY, -30, CONVERT(DATE, GETDATE()))
)
SELECT [Date]

But I am not allowed to use any statements that can't be executed in a subquery. The program I am using executes queries like this:

Select *
From (
    TheQuery
) as t1

This means I can't use declares, no stored procedures, no CTEs..

Is there any way I can obtain the dataset I need with these limitations?

I am using azure SQL

Body:
Well, I think the easiest way is to create calendar table and in subquery just select dates between dates.
You can do this by this query:

CREATE TABLE dbo.Calendar ([Date] date)
DECLARE @startDate date, @endDate date

SET @startDate = '2000-01-01'
SET @endDate = '2020-12-31'

WHILE @startDate <= @endDate
BEGIN
INSERT INTO dbo.Calendar
SELECT @startDate

SET @startDate = DATEADD(DD,1,@startDate)
END

Selecting dates:

Select *
From dbo.Calendar WHERE [Date] BETWEEN @date1 AND @date2


问:
how can i connect multiple devices with bluetooth technology using c#
I try to connect more than two devices to one device using Bluetooth, what's the best way if I program in c# ?

```<code>public BluetoothDeviceInfo[] DiscoverDevices();
</code>```

答:
You can get the number of available devices and then loop through the List of all devices using the BluetoothClient class:

```<code>int maxDevices = 10;
List<Device> devices = new List<Device>();
BluetoothClient bc = new BluetoothClient();
BluetoothDeviceInfo[] array = bc.DiscoverDevices(maxDevices);
int count = array.Length;
for (int i = 0; i < count; i++)
{
    Device device = new Device(array[i]);
    devices.Add(device);

    // the variable device will now hold a detected BT device.
    // Now you can connect to the device:
    bc.Connect(new BluetoothEndPoint((BluetoothAddress)adres,service));

    // Send a message to the device
    System.Net.Sockets.NetworkStream stream = bc.GetStream();
    StreamWriter streamWriter = new StreamWriter(stream);
    streamWriter.WriteLine("! 0 200 200 210 1");
}
// the variable devices will now hold an array of all detected BT devices.
</code>```

Note: DiscoverDevices takes about 20-30 seconds to complete.

Body:
I try to connect more than two devices to one device using Bluetooth, what's the best way if I program in c# ?

public BluetoothDeviceInfo[] DiscoverDevices();

Body:
You can get the number of available devices and then loop through the List of all devices using the BluetoothClient class:

int maxDevices = 10;
List<Device> devices = new List<Device>();
BluetoothClient bc = new BluetoothClient();
BluetoothDeviceInfo[] array = bc.DiscoverDevices(maxDevices);
int count = array.Length;
for (int i = 0; i < count; i++)
{
    Device device = new Device(array[i]);
    devices.Add(device);

    // the variable device will now hold a detected BT device.
    // Now you can connect to the device:
    bc.Connect(new BluetoothEndPoint((BluetoothAddress)adres,service));

    // Send a message to the device
    System.Net.Sockets.NetworkStream stream = bc.GetStream();
    StreamWriter streamWriter = new StreamWriter(stream);
    streamWriter.WriteLine("! 0 200 200 210 1");
}
// the variable devices will now hold an array of all detected BT devices.

Note: DiscoverDevices takes about 20-30 seconds to complete.


问:
script in xcode to change values at build time
I have source code of app iOS project. I want make it multiple branded app. For e.g. I want to change the value of a Variable, app icon, bundle identifier, display name at build time.

How can i do this?

答:
you can create multiple schemes like we have default debug/release in xcode project to have as a brand type.
multiple schemes

Add User-defined variables in build setting.Then you can change values in schemes.See screenshots for example.
user defined variables

OR
  Simply create multiple targets having different icon images & display name.


问:
Does assigning objects to null in Java impact garbage collection?
Does assigning an unused object reference to null in Java improve the garbage collection process in any measurable way?

My experience with Java (and C#) has taught me that is often counter intuitive to try and outsmart the virtual machine or JIT compiler, but I've seen co-workers use this method and I am curious if this is a good practice to pick up or one of those voodoo programming superstitions?

答:
Typically, no.

But like all things: it depends. The GC in Java these days is VERY good and everything should be cleaned up very shortly after it is no longer reachable. This is just after leaving a method for local variables, and when a class instance is no longer referenced for fields.

You only need to explicitly null if you know it would remain referenced otherwise. For example an array which is kept around. You may want to null the individual elements of the array when they are no longer needed.

For example, this code from ArrayList:

```<code>public E remove(int index) {
    RangeCheck(index);

    modCount++;
    E oldValue = (E) elementData[index];

    int numMoved = size - index - 1;
    if (numMoved > 0)
         System.arraycopy(elementData, index+1, elementData, index,
             numMoved);
    elementData[--size] = null; // Let gc do its work

    return oldValue;
}
</code>```

Also, explicitly nulling an object will not cause an object to be collected any sooner than if it just went out of scope naturally as long as no references remain.

Both:

```<code>void foo() {
   Object o = new Object();
   /// do stuff with o
}
</code>```

and:

```<code>void foo() {
   Object o = new Object();
   /// do stuff with o
   o = null;
}
</code>```

Are functionally equivalent.

OwnerDisplayName: nemo

LastEditorDisplayName: nemo

Body:
Typically, no.

But like all things: it depends. The GC in Java these days is VERY good and everything should be cleaned up very shortly after it is no longer reachable. This is just after leaving a method for local variables, and when a class instance is no longer referenced for fields.

You only need to explicitly null if you know it would remain referenced otherwise. For example an array which is kept around. You may want to null the individual elements of the array when they are no longer needed.

For example, this code from ArrayList:

public E remove(int index) {
    RangeCheck(index);

    modCount++;
    E oldValue = (E) elementData[index];

    int numMoved = size - index - 1;
    if (numMoved > 0)
         System.arraycopy(elementData, index+1, elementData, index,
             numMoved);
    elementData[--size] = null; // Let gc do its work

    return oldValue;
}

Also, explicitly nulling an object will not cause an object to be collected any sooner than if it just went out of scope naturally as long as no references remain.

Both:

void foo() {
   Object o = new Object();
   /// do stuff with o
}

and:

void foo() {
   Object o = new Object();
   /// do stuff with o
   o = null;
}

Are functionally equivalent.

OwnerDisplayName: tweakt

LastEditorDisplayName: tweakt


问:
What are the best practices to encrypt passwords stored in MySql using PhP?
I am seeking advice on how to securely store passwords in MySQL using PHP.

Overlooking the limitations of PHP itself, I want to know more about salting, hashing, and encrypting these bad boys.

Obviously people will continue to use weak passwords unless forced to do otherwise, but it's how I am storing them that is important to me. My user's passwords are far more important to me than the database itself, and as such I want to keep them in such a way that it will be painstaking and monotonous for any script kiddie trying reverse. Obviously with due diligence just about anything can be defeated, but I wouldn't mind making this particularly bothersome.

There are two scenarios we are looking at.

The kiddie has a complete copy of the database.

The kiddie has a complete copy of the PHP used to craft the password, and the database.

Any and all advice on this topic is graciously appreciated.

答:
Use bcrypt. If someone has the user table of your database, then they can use brute force/rainbow tables/etc to their heart's content. Even with salt, if you're using MD5 or some other fast-hashing algorithm (which aren't designed to solve this problem, by the way); it's just a matter of time before it can be cracked.

Any well-known and widely-supported hashing algorithm is going to have this same basic "flaw" (if you can call it that; it's really by definition). The difference is that bcrypt is slow as molasses when performing the hashing operation, rendering a brute force attack much less effective.

For an absolutely great discussion on the merits of bcrypt, the dangers of other approaches, and the difficulty of password security in general, read this thread. It has lots of comments by many people that are much more knowledgeable about this sort of thing than I am, and it should hopefully help you understand more of the issues at stake.


问:
PHP: MYSQLI Change Order By Style

Hi, i want to get data from chat table like this:

```<code>6
7
8
</code>```

My Code show like this:

```<code>8
7
6
</code>```

Code:

```<code>"SELECT * FROM `chat` WHERE
    `chat-code` = 'vm1mxo3dpi9gzuo' AND (`user_1` = '1' OR `user_2` = '1')
     ORDER BY id DESC LIMIT 3"
</code>```

答:
Try to read what will happens if you use DESC or ASC statements. https://dev.mysql.com/doc/refman/5.7/en/sorting-rows.html
Hope it will help you.</p>

Title: PHP: MYSQLI Change Order By Style

Body:
Hi, i want to get data from chat table like this:

6
7
8

My Code show like this:

8
7
6

Code:

"SELECT * FROM `chat` WHERE
    `chat-code` = 'vm1mxo3dpi9gzuo' AND (`user_1` = '1' OR `user_2` = '1')
     ORDER BY id DESC LIMIT 3"


问:
NSMutableDictionary returning null
I created an NSMutableDictionary in NSObject class like

```<code>@property (nonatomic, strong) NSMutableDictionary<NSNumber *, NSString *> *requestComments;
</code>```

and saved the data in this variable when comes through API.

But when I am sending the key to get the value it is returning null every time.

To get the value I am doing like this

```<code>NSLog(@"%@",dataManager.requestComments[serviceRequest.RequestId]);
// serviceRequest.RequestId is returning NSNumber.
</code>```

the output I'm getting is "(null)"

if I use to like this then it returns a value

```<code>NSLog(@"%@",[dataManager.requestComments valueForKey:@"30221"]);
</code>```

Why it is returning null in the above case.

答:
Based on your question, this should work

```<code>NSLog(@"%@",dataManager.requestComments[[serviceRequest.RequestId stringValue]]);
</code>```

Because you gave the key as NSString and you are expecting it to return based on an NSNumber. You need to look at the code which you are using to store this dictionary.

Update

You have mentioned that key is of NSNumber type. But you are passing a string in valueForKey and getting a valid object back. You should check how you are forming this dictionary from API response.

Title: NSMutableDictionary returning null

Body:
I created an NSMutableDictionary in NSObject class like

@property (nonatomic, strong) NSMutableDictionary<NSNumber *, NSString *> *requestComments;

and saved the data in this variable when comes through API.

But when I am sending the key to get the value it is returning null every time.

To get the value I am doing like this

NSLog(@"%@",dataManager.requestComments[serviceRequest.RequestId]);
// serviceRequest.RequestId is returning NSNumber.

the output I'm getting is "(null)"

if I use to like this then it returns a value

NSLog(@"%@",[dataManager.requestComments valueForKey:@"30221"]);

Why it is returning null in the above case.

Body:
Based on your question, this should work

NSLog(@"%@",dataManager.requestComments[[serviceRequest.RequestId stringValue]]);

Because you gave the key as NSString and you are expecting it to return based on an NSNumber. You need to look at the code which you are using to store this dictionary.

Update

You have mentioned that key is of NSNumber type. But you are passing a string in valueForKey and getting a valid object back. You should check how you are forming this dictionary from API response.


问:
JavaAgent on Java 9
Prior to java 9, the monitoring JavaAgent were loaded into the JVM by boostrapClassloader so that the monitored applications could access them

With Java 9 modular architecture, only java.base module gets loaded in Bootstrap classloader and so, Java agent can access only classes inside java.base?
It can't access anything outside java.base by default?

What is required to be changed inside javaAgent in order to access other modules like java.sql?

答:
Here's a link the java.lang.instrument package description in the JDK 9 EA builds:

http://download.java.net/java/jdk9/docs/api/java/lang/instrument/package-summary.html

The section "Loading agent classes and the modules/classes available to the agent class" should help with the discussion here.

As regards the java.sql module then it is one of several "non-core" modules that are no longer defined to the boot loader. Moving these modules to the platform class loader means they can run with reduced permissions and so helps with the overall security of the platform. This should be completely transparent to applications and libraries on the class path and should only be noticeable by code that (a) runs with -Xbootclasspath/a, (b) creates a custom class with null as the parent, and (c) agent supporting classes added to the boot class loader search with the Boot-Class-Path attribute or the appendToBootstrapClassLoaderSearch API.

Title: JavaAgent on Java 9


问:
Android background task with main class
I've run in to one little problem while working with the android API, this is it:

Is possible to make a BACKGROUND TASK (always running like a alarmtimer) that can read from common settings, I have problems with this since the main task gets unloaded when the app is closed (task keeps running but all the commands return null)

Is it even possible? if so, how?

Even more important, in my main class i have SyncMaster = new SyncMaster(this); and is there a way to talk to it via my background task?

答: may be you should consider using a Service.</p>

Title: Android background task with main class


问:
storing huge amounts of data in mongo
I am working on a front end system for a radius server.

The radius server will pass updates to the system every 180 seconds. Which means if I have about 15,000 clients that would be around 7,200,000 entries per day...Which is a lot.

I am trying to understand what the best possible way to store and retrieve this data will be. Obviously as time goes on, this will become substantial. Will MongoDB handle this? Typical document is not much, something this

```<code>{
 id: 1
 radiusId: uniqueId
 start: 2017-01-01 14:23:23
 upload: 102323
 download: 1231556
}
</code>```

However, there will be MANY of these records. I guess this is something similar to the way that SNMP NMS servers handle data which as far as I know they use RRD to do this.

Currently in my testing I just push every document into a single collection. So I am asking,

A) Is Mongo the right tool for the job and
B) Is there a better/more preferred/more optimal way to store the data

EDIT:

OK, so just incase someone comes across this and needs some help.

I ran it for a while in mongo, I was really not satisfied with performance. We can chalk this up to the hardware I was running on, perhaps my level of knowledge or the framework I was using. However I found a solution that works very well for me. InfluxDB pretty much handles all of this right out of the box, its a time series database which is effectively the data I am trying to store (https://github.com/influxdata/influxdb). Performance for me has been like night & day. Again, could all be my fault, just updating this.

EDIT 2:

So after a while I think I figured out why I never got the performance I was after with Mongo. I am using sailsjs as framework and it was searching by id using regex, which obviously has a huge performance hit. I will eventually try migrate back to Mongo instead of influx and see if its better.

答:
15,000 clients updating every 180 seconds = ~83 insertions / sec. That's not a huge load even for a moderately sized DB server, especially given the very small size of the records you're inserting.

I think MongoDB will do fine with that load (also, to be honest, almost any modern SQL DB would probably be able to keep up as well). IMHO, the key points to consider are these:

Hardware: make sure you have enough RAM. This will primarily depend on how many indexes you define, and how many queries you're doing. If this is primarily a log that will rarely be read, then you won't need much RAM for your working set (although you'll need enough for your indexes). But if you're also running queries then you'll need much more resources

If you are running extensive queries, consider setting up a replica set. That way, your master server can be reserved for writing data, ensuring reliability, while your slaves can be configured to serve your queries without affecting the write reliability.

Regarding the data structure, I think that's fine, but it'll really depend on what type of queries you wish to run against it. For example, if most queries use the radiusId to reference another table and pull in a bunch of data for each record, then you might want to consider denormalizing some of that data. But again, that really depends on the queries you run.

If you're really concerned about managing the write load reliably, consider using the Mongo front-end only to manage the writes, and then dumping the data to a data warehouse backend to run queries on. You can partially do this by running a replica set like I mentioned above, but the disadvantage of a replica set is that you can't restructure the data. The data in each member of the replica set is exactly the same (hence the name, replica set :-) Oftentimes, the best structure for writing data (normalized, small records) isn't the best structure for reading data (denormalized, large records with all the info and joins you need already done). If you're running a bunch of complex queries referencing a bunch of other tables, using a true data warehouse for the querying part might be better.

As your write load increases, you may consider sharding. I'm assuming the RadiusId points to each specific server among a pool of Radius servers. You could potentially shard on that key, which would split the writes based on which server is sending the data. Thus, as you increase your radius servers, you can increase your mongo servers proportionally to maintain write reliability. However, I don't think you need to do this right away as I bet one reasonably provisioned server should be able to manage the load you've specified.

Anyway, those are my preliminary suggestions.

Title: storing huge amounts of data in mongo

Body:
I am working on a front end system for a radius server.

The radius server will pass updates to the system every 180 seconds. Which means if I have about 15,000 clients that would be around 7,200,000 entries per day...Which is a lot.

I am trying to understand what the best possible way to store and retrieve this data will be. Obviously as time goes on, this will become substantial. Will MongoDB handle this? Typical document is not much, something this

{
 id: 1
 radiusId: uniqueId
 start: 2017-01-01 14:23:23
 upload: 102323
 download: 1231556
}

However, there will be MANY of these records. I guess this is something similar to the way that SNMP NMS servers handle data which as far as I know they use RRD to do this.

Currently in my testing I just push every document into a single collection. So I am asking,

A) Is Mongo the right tool for the job and
B) Is there a better/more preferred/more optimal way to store the data

EDIT:

OK, so just incase someone comes across this and needs some help.

I ran it for a while in mongo, I was really not satisfied with performance. We can chalk this up to the hardware I was running on, perhaps my level of knowledge or the framework I was using. However I found a solution that works very well for me. InfluxDB pretty much handles all of this right out of the box, its a time series database which is effectively the data I am trying to store (https://github.com/influxdata/influxdb). Performance for me has been like night & day. Again, could all be my fault, just updating this.

EDIT 2:

So after a while I think I figured out why I never got the performance I was after with Mongo. I am using sailsjs as framework and it was searching by id using regex, which obviously has a huge performance hit. I will eventually try migrate back to Mongo instead of influx and see if its better.


问:
hide tab bar in view with push
I have a tabBar + NavigationViewController. The Tab bar has collection view  with cells(Say view1) and with cells a push seague is implemented to another view(Say view2).

In view2 I want to have a navBar but no tab bar.

I tried

self.tabBarController?.tabBar.hidden = true,

it worked fine for view2 but when I went back to view1 by back button the tab was still hidden( even after in view1 class I added self.tabBarController?.tabBar.hidden = false in viewDidLoad func).

How can i make the tab bar reappear in view1?

I'm working in swift.

答:
if you want to hide TabBarController Bottom Bar :  #Swift 3

In YourViewController :  in ViewDidLoad() method

```<code>self.tabBarController?.tabBar.isHidden = false
</code>```

Title: hide tab bar in view with push

Body:
if you want to hide TabBarController Bottom Bar :  #Swift 3

In YourViewController :  in ViewDidLoad() method

self.tabBarController?.tabBar.isHidden = false


问:
Cordova Error: Your ios platform does not have Api.js
I'm trying to build a cordova ios app but not having much luck and getting strange errors.

Using this version of Cordova with older version of cordova-ios is
deprecated. Upgrade to cordova-ios@4.0.0 or newer.

Error: Your ios platform does not have Api.js

The first warning says my cordov-ios version is old, which is strange as this is my output:

```<code>$ cordova --version
7.0.1

$ cordova platform version ios

Installed platforms:
  ios 4.4.0
Available platforms:
  android ~6.2.2
  blackberry10 ~3.8.0 (deprecated)
  browser ~4.1.0
  osx ~4.0.1
  webos ~3.7.0
</code>```

So I clearly have the latest versions necessary.

And then the Api.js error. What is causing this?

Error: Your ios platform does not have Api.js

Any ideas?

答: use cordova@6.0 solved the problem</p>

Body:
I'm trying to build a cordova ios app but not having much luck and getting strange errors.

Using this version of Cordova with older version of cordova-ios is
deprecated. Upgrade to cordova-ios@4.0.0 or newer.

Error: Your ios platform does not have Api.js

The first warning says my cordov-ios version is old, which is strange as this is my output:

$ cordova --version
7.0.1

$ cordova platform version ios

Installed platforms:
  ios 4.4.0
Available platforms:
  android ~6.2.2
  blackberry10 ~3.8.0 (deprecated)
  browser ~4.1.0
  osx ~4.0.1
  webos ~3.7.0

So I clearly have the latest versions necessary.

And then the Api.js error. What is causing this?

Error: Your ios platform does not have Api.js

Any ideas?

Body: use cordova@6.0 solved the problem


问:
Video accessibility
our clients gave us a video that is mostly B-roll so they are saying they do not need to add captions to make is ADA compliant, but I'm not sure that is true. I know for images, if it's purely decorative you just leave your alt tag empty, but does the same rule apply to videos? Or do they still need to have captions describing what is going on in the video even though it's mainly decorative?</p>

答:
According to WCAG

1.2.3 Audio Description or Media Alternative (Prerecorded): An alternative for time-based media or audio description of the prerecorded video content is provided for synchronized media, except when the media is a media alternative for text and is clearly labeled as such. (Level A)

The video may be secondary but screenreader users or hard of hearing people for instance have the right to access the description of what happens in the video (i.e. audio-description). If nothing happens in the video, I would really wonder why people want to publish such video.

Title: Video accessibility


问:
Can we send notification globally without using firebase?
Can we create rest services for sending a notification to Android app without using Firebase Cloud Messaging / Google Cloud Messaging or other cloud messenger tool? If yes, how's that possible? I have searched for the same but couldn't get the appropriate result. The result I get in that REST services are combined with cloud messenger tool, but I want to create services through which I could easily send notification without open Cloud Messenger console.

code to handle data from php

```<code>    private void handleNotification(String message) {
    Log.e(TAG, "===========================messaging 4=======" );

    if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) {

        Intent intent= new Intent(this,MainActivity.class);
        intent.putExtra("message",message);
        intent.putExtra("imageUrl",imageUrl);
        intent.putExtra("time_stamp",timeStamp);

        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        LocalBroadcastManager.getInstance(this).sendBroadcast(intent);

        final PendingIntent pendingIntent = PendingIntent.getActivity(
                this, 0, intent, PendingIntent.FLAG_ONE_SHOT);

        Uri notificationSound= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        NotificationCompat.Builder notifiBuilder=new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("NOTIFICATION !!")
                .setContentText(message)
                .setAutoCancel(true)
                .setSound(notificationSound)
                .setContentIntent(pendingIntent) ;

        NotificationManager notificationManager=
                ( NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(0,notifiBuilder.build());

        Intent pushNotification = new Intent(Config.PUSH_NOTIFICATION);
        pushNotification.putExtra("message", message);
        LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);

        // play notification sound
       /* NotificationUtils notificationUtils = new NotificationUtils(getApplicationContext());

       notificationUtils.playNotificationSound();*/

    }
}

private void handleDataMessage(JSONObject json) {
    Log.e(TAG, "===========================messaging 4=======" );
    Log.e(TAG, "push json: " + json.toString());

    try {
        JSONObject data = json.getJSONObject("data");

        String title = data.getString("title");
        String message = data.getString("message");
       boolean isBackground = data.getBoolean("is_background");
        String imageUrl = data.getString("image");
       String timestamp = data.getString("timestamp");
      JSONObject payload = data.getJSONObject("payload");

        Log.e(TAG, "title: " + title);
        Log.e(TAG, "message: " + message);
       Log.e(TAG, "isBackground: " + isBackground);
        Log.e(TAG, "payload: " + payload.toString());
        Log.e(TAG, "imageUrl: " + imageUrl);
        Log.e(TAG, "timestamp: " + timestamp);

        if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) {
            // app is in foreground, broadcast the push message

            Intent intent= new Intent(this,MainActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
            final PendingIntent pendingIntent = PendingIntent.getActivity(
                    this, 0, intent, PendingIntent.FLAG_ONE_SHOT);

            Uri notificationSound= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

            NotificationCompat.Builder notifiBuilder=new NotificationCompat.Builder(this)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle("NOTIFICATION data message!!")
                    .setContentText(message)
                    .addAction(R.mipmap.ic_accept,"ACCEPT",pendingIntent)
                    .addAction(R.mipmap.ic_decline,"DECLINE",pendingIntent)
                    .setAutoCancel(true)
                    .setSound(notificationSound)
                    .setContentIntent(pendingIntent) ;

            NotificationManager notificationManager=
                    ( NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

            notificationManager.notify(0,notifiBuilder.build());

            Intent pushNotification = new Intent(Config.PUSH_NOTIFICATION);
            pushNotification.putExtra("message", message);
            LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);

            // play notification sound

        } else {
            // app is in background, show the notification in notification tray

            Intent resultIntent = new Intent(getApplicationContext(), MainActivity.class);
            resultIntent.putExtra("message", message);

            // check for image attachment
            if (TextUtils.isEmpty(imageUrl)) {
                showNotificationMessage(getApplicationContext(), title, message, resultIntent);
            } else {
                // image is present, show notification with image
                showNotificationMessageWithBigImage(getApplicationContext(), title, message, resultIntent, imageUrl);
            }
        }
    } catch (JSONException e) {
        Log.e(TAG, "Json Exception: " + e.getMessage());
    } catch (Exception e) {
        Log.e(TAG, "Exception: " + e.getMessage());
    }
}
</code>```

答:
Since GCM uses simple TCP connection you can do it by urself.

All you need is single TCP Server and TCP client on every device you need.

Will be almost the same, but it will consume more battery.

Body:
Can we create rest services for sending a notification to Android app without using Firebase Cloud Messaging / Google Cloud Messaging or other cloud messenger tool? If yes, how's that possible? I have searched for the same but couldn't get the appropriate result. The result I get in that REST services are combined with cloud messenger tool, but I want to create services through which I could easily send notification without open Cloud Messenger console.

code to handle data from php

    private void handleNotification(String message) {
    Log.e(TAG, "===========================messaging 4=======" );

    if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) {

        Intent intent= new Intent(this,MainActivity.class);
        intent.putExtra("message",message);
        intent.putExtra("imageUrl",imageUrl);
        intent.putExtra("time_stamp",timeStamp);

        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        LocalBroadcastManager.getInstance(this).sendBroadcast(intent);

        final PendingIntent pendingIntent = PendingIntent.getActivity(
                this, 0, intent, PendingIntent.FLAG_ONE_SHOT);

        Uri notificationSound= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        NotificationCompat.Builder notifiBuilder=new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("NOTIFICATION !!")
                .setContentText(message)
                .setAutoCancel(true)
                .setSound(notificationSound)
                .setContentIntent(pendingIntent) ;

        NotificationManager notificationManager=
                ( NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(0,notifiBuilder.build());

        Intent pushNotification = new Intent(Config.PUSH_NOTIFICATION);
        pushNotification.putExtra("message", message);
        LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);

        // play notification sound
       /* NotificationUtils notificationUtils = new NotificationUtils(getApplicationContext());

       notificationUtils.playNotificationSound();*/

    }
}

private void handleDataMessage(JSONObject json) {
    Log.e(TAG, "===========================messaging 4=======" );
    Log.e(TAG, "push json: " + json.toString());

    try {
        JSONObject data = json.getJSONObject("data");

        String title = data.getString("title");
        String message = data.getString("message");
       boolean isBackground = data.getBoolean("is_background");
        String imageUrl = data.getString("image");
       String timestamp = data.getString("timestamp");
      JSONObject payload = data.getJSONObject("payload");

        Log.e(TAG, "title: " + title);
        Log.e(TAG, "message: " + message);
       Log.e(TAG, "isBackground: " + isBackground);
        Log.e(TAG, "payload: " + payload.toString());
        Log.e(TAG, "imageUrl: " + imageUrl);
        Log.e(TAG, "timestamp: " + timestamp);

        if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) {
            // app is in foreground, broadcast the push message

            Intent intent= new Intent(this,MainActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
            final PendingIntent pendingIntent = PendingIntent.getActivity(
                    this, 0, intent, PendingIntent.FLAG_ONE_SHOT);

            Uri notificationSound= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

            NotificationCompat.Builder notifiBuilder=new NotificationCompat.Builder(this)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle("NOTIFICATION data message!!")
                    .setContentText(message)
                    .addAction(R.mipmap.ic_accept,"ACCEPT",pendingIntent)
                    .addAction(R.mipmap.ic_decline,"DECLINE",pendingIntent)
                    .setAutoCancel(true)
                    .setSound(notificationSound)
                    .setContentIntent(pendingIntent) ;

            NotificationManager notificationManager=
                    ( NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

            notificationManager.notify(0,notifiBuilder.build());

            Intent pushNotification = new Intent(Config.PUSH_NOTIFICATION);
            pushNotification.putExtra("message", message);
            LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);

            // play notification sound

        } else {
            // app is in background, show the notification in notification tray

            Intent resultIntent = new Intent(getApplicationContext(), MainActivity.class);
            resultIntent.putExtra("message", message);

            // check for image attachment
            if (TextUtils.isEmpty(imageUrl)) {
                showNotificationMessage(getApplicationContext(), title, message, resultIntent);
            } else {
                // image is present, show notification with image
                showNotificationMessageWithBigImage(getApplicationContext(), title, message, resultIntent, imageUrl);
            }
        }
    } catch (JSONException e) {
        Log.e(TAG, "Json Exception: " + e.getMessage());
    } catch (Exception e) {
        Log.e(TAG, "Exception: " + e.getMessage());
    }
}


问:
Bean instance is not getting loaded
I need a help regarding dependency injection.

I hava a bean class which is having a object reference of JdbcTemplate and I am using @Autowired to
create instance of that object. But that object is not getting loaded and as a result NullPointerException is thrown
from setCustName() method.

Please help

Bean Class :

```<code>class CustomerBean {

    private String custName;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public void setCustName(String custName) {
    this.custName = custName;
    jdbcTemplate.update(query);
    }
}
</code>```

XML :

```<code><bean id="myjdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource" />
 </bean>

 <bean id="custBean" class="com.test.CustomerBean">
        <property name="custName" value="John" />
 </bean>
</code>```

Stacktrace:

```<code>PropertyAccessException 1: org.springframework.beans.MethodInvocationException: Property 'custName' threw exception; nested exception is java.lang.NullPointerException
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:334)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:108)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1419)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1160)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:293)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
</code>```

答:
Add @Component annotation to the bean class which contains beans that can be autowired.

After adding the above @Component annotation on beans, we need to tell spring to scan these respective beans and load all the autowired dependencies. This can be done by declaring the following XMLconfiguration

<context:component-scan base-packages="<your_package_names>"/>

for example if my package structure is com.mycompany

<context:component-scan base-packages="com.mycompany"/>

Title: Bean instance is not getting loaded

Body:
I need a help regarding dependency injection.

I hava a bean class which is having a object reference of JdbcTemplate and I am using @Autowired to
create instance of that object. But that object is not getting loaded and as a result NullPointerException is thrown
from setCustName() method.

Please help

Bean Class :

class CustomerBean {

    private String custName;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public void setCustName(String custName) {
    this.custName = custName;
    jdbcTemplate.update(query);
    }
}

XML :

<bean id="myjdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource" />
 </bean>

 <bean id="custBean" class="com.test.CustomerBean">
        <property name="custName" value="John" />
 </bean>

Stacktrace:

PropertyAccessException 1: org.springframework.beans.MethodInvocationException: Property 'custName' threw exception; nested exception is java.lang.NullPointerException
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:334)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:108)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1419)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1160)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:293)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)


问:
Remove the cells below the selected one from the UITableView Swift 3
Here I am trying to remove the remaining objects after the selected one of an array when a particular row is selected from the UITableView.

Here is my sample array:

```<code>var myArray = ["rahul","rahib","suhail","alex","siya"]
</code>```

If I select myArray[2] the remaining elements after "suhail" should be deleted and the final array have to be ["rahul","rahib","suhail"].

Here is my try but it only remove one object:

```<code>var selectedIndex = indexPath.row
myArray.remove(at: selectedIndex+1)
</code>```

Thanks in advance!

答:
Change let to var for myArray

```<code>var myArray = ["rahul","rahib","suhail","alex","siya"]
</code>```

Use removeSubrange(_:) method to remove remaining item from the array

```<code>myArray.removeSubrange(indexPath.row..<myArray.count)
</code>```

Body:
Here I am trying to remove the remaining objects after the selected one of an array when a particular row is selected from the UITableView.

Here is my sample array:

var myArray = ["rahul","rahib","suhail","alex","siya"]

If I select myArray[2] the remaining elements after "suhail" should be deleted and the final array have to be ["rahul","rahib","suhail"].

Here is my try but it only remove one object:

var selectedIndex = indexPath.row
myArray.remove(at: selectedIndex+1)

Thanks in advance!

Body:
Change let to var for myArray

var myArray = ["rahul","rahib","suhail","alex","siya"]

Use removeSubrange(_:) method to remove remaining item from the array

myArray.removeSubrange(indexPath.row..<myArray.count)


问:
how to create array of random normalize number?
i want to create a matrix that each row of the matrix have 7 real random number in [0,1]  and the sum of number in each rows  should be equal to 1.
this matrix have 100 rows and 7 columns. how can i do it?
 at first ,i create an array with 1 row and 7 columns. then write the code as bellow. i try normal the number in the rows but sum of each row became more than 1.how can i fix it? thank for taking your time.</p>

```<code>a = rand(1,7);
for i=1:7
a(i) = a(i)/sum(a);
end
sum(a)
</code>```

答:
The problem is that by using a for-loop, you're changing the sum of the vector every loop iteration. You should take advantage of MATLAB's ability to act on whole matrices at once:</p>

```<code>a = rand(1,7);
a = a./sum(a);
</code>```

Body:
i want to create a matrix that each row of the matrix have 7 real random number in [0,1]  and the sum of number in each rows  should be equal to 1.
this matrix have 100 rows and 7 columns. how can i do it?
 at first ,i create an array with 1 row and 7 columns. then write the code as bellow. i try normal the number in the rows but sum of each row became more than 1.how can i fix it? thank for taking your time.

a = rand(1,7);
for i=1:7
a(i) = a(i)/sum(a);
end
sum(a)

Body:
The problem is that by using a for-loop, you're changing the sum of the vector every loop iteration. You should take advantage of MATLAB's ability to act on whole matrices at once:

a = rand(1,7);
a = a./sum(a);


问:
Need help on React Js
I am new to React Js and my code is not working. Please have a look below:

This is my script file Main.jsx. This file is compiled by react and output is put in main.js file under 'dist' folder.

```<code>var react = require("react"),
reactDom = require("react-dom");
var myComponent = react.createClass({
    render: function () {
        return <div><h4>I am rendered by react.</h4></div>;
    }
});

reactDom.render(<myComponent />, document.getElementById("basicDiv"));
</code>```

It is Index.html

```<code><html>
<head>
    <base href="./" />
    <title>App title</title>
    <script src="node_modules/react/dist/react.js"></script>
    <script src="node_modules/react/dist/react-with-addons.js"></script>
    <script src="node_modules/react-dom/dist/react-dom.js"></script>
</head>

<body>
    <div id="basicDiv"></div>

    <!-- React compiled code is in dist folder and is accessible -->
    <script src="dist/main.js"></script>
</body>

</html>
</code>```

When I run the index.html file in browser the Output is blank screen. Please see the below screenshot of chrome dev tools inspector window:

The content of 'myComponent' is not rendered in browser. I have seen many tutorials with the same code but it is not working... don't know why.

Please help on this and if possible, provide me some sample code / tutorials for latest releases also. Thanks in advance

Update

Please note that I have included React library reference in my HTML file which makes me to freely use "React" or "react" as a variable name while importing React in my script files. Taking "React" (with capital R) as variable name is not mandatory here in this case.

Final Update

So the solution (as answered by Damien Leroux) is to make the react component variable-name starting with a capital letter. 'var myComponent' must be 'var MyComponent' or 'var Mycomponent'.

答:
```<code>import React from 'react'
import './Aboutus.css'
import Header from '../Home/Header/Header.jsx'
import Footer from '../Home/Footer/Footer.jsx'

var stylesheader = {
  paddingTop: 50,
  textAlign:'center',
  color: '#204871'
};

var stylehead = {
  paddingLeft: 200,
  paddingRight:200,
  paddingTop:20,
  color: '#204871'
};

var styles = {
  paddingTop: 120, paddingLeft:20,
  color: '#128bea',
  fontSize: 26
};

var style1 = {
  paddingTop:100,
  color: '#204871'
};

class Aboutus extends React.Component {

    render() {

  var title = "we are a team";

  var leadership = [
  {
    "name":"abc",
    "department":"abc",
    "phone":"abc",
    "email":"abc"
  },
  {
     "name":"abc",
    "department":"abc",
    "phone":"abc",
    "email":"abc"
  }
  ];

  var business = [
  {
     "name":"abc",
    "department":"abc",
    "email":"abc"
  },
  {
       "name":"abc",
    "department":"abc",
    "email":"abc"
  },
  ];

  var algorithm = [
  {
       "name":"abc",
    "department":"abc",
    "email":"abc"
  },
  {
       "name":"abc",
    "department":"abc",
    "email":"abc"
  },
  {
      "name":"abc",
    "department":"abc",
    "email":"abc"
  },
  {
       "name":"abc",
    "department":"abc",
    "email":"abc"
  }
  ];

   var developer = [
  {
      "name":"abc",
    "department":"abc",
    "email":"abc"
  },
  {
       "name":"abc",
    "department":"abc",
    "email":"abc"
  },
  {
      "name":"abc",
    "department":"abc",
    "email":"abc"
  }
  ];

     var row1=leadership.map(row => {
                              return <div className="column">
                                       <div className="card">
                                          <div className="container">
                                              <h2>{row.name}</h2>
                                              <p>{row.department}</p>
                                              <p>{row.phone}</p>
                                              <p>{row.email}</p>
                                          </div>
                                        </div>
                                      </div>
                              });

      var row2=business.map(row => {
                              return <div className="column">
                                       <div className="card">
                                          <div className="container">
                                              <h2>{row.name}</h2>
                                              <p>{row.department}</p>
                                              <p>{row.email}</p>
                                          </div>
                                        </div>
                                      </div>
                              });

       var row3=algorithm.map(row => {
                              return <div className="column">
                                       <div className="card">
                                          <div className="container">
                                              <h2>{row.name}</h2>
                                              <p>{row.department}</p>
                                              <p>{row.email}</p>
                                          </div>
                                        </div>
                                      </div>
                              });

       var row4=developer.map(row => {
                              return <div className="column">
                                       <div className="card">
                                          <div className="container">
                                              <h2>{row.name}</h2>
                                              <p>{row.department}</p>
                                              <p>{row.email}</p>
                                          </div>
                                        </div>
                                      </div>
                              });

      return (

         <div className="home-component">

                <div className="home-header">
                <Header/>
                </div>

                <div className="home-content" >
                            <h1 style={stylesheader}> Meet the team </h1>
                            <h2 style={stylehead}>{title}</h2>

                            <h2 style={styles}> Leadership </h2>
                            <div className="row" style={style1}>
                              {row1}
                            </div>

                            <h2 style={styles}> Business Development </h2>
                            <div className="row" style={style1}>
                             {row2}
                            </div>

                            <h2 style={styles}> Algorithm Development </h2>
                            <div className="row" style={style1} >
                             {row3}
                            </div>

                            <h2 style={styles}>Software Development </h2>
                             <div className="row" style={style1} >
                              {row4}
                             </div>
                </div>

                <Footer/>

         </div>
    );

    }
}

export default Aboutus;
</code>```

Title: Need help on React Js

Body:
I am new to React Js and my code is not working. Please have a look below:

This is my script file Main.jsx. This file is compiled by react and output is put in main.js file under 'dist' folder.

var react = require("react"),
reactDom = require("react-dom");
var myComponent = react.createClass({
    render: function () {
        return

I am rendered by react.

;
    }
});

reactDom.render(<myComponent />, document.getElementById("basicDiv"));

It is Index.html

    <base href="./" />
    <title>App title</title>

When I run the index.html file in browser the Output is blank screen. Please see the below screenshot of chrome dev tools inspector window:

The content of 'myComponent' is not rendered in browser. I have seen many tutorials with the same code but it is not working... don't know why.

Please help on this and if possible, provide me some sample code / tutorials for latest releases also. Thanks in advance

Update

Please note that I have included React library reference in my HTML file which makes me to freely use "React" or "react" as a variable name while importing React in my script files. Taking "React" (with capital R) as variable name is not mandatory here in this case.

Final Update

So the solution (as answered by Damien Leroux) is to make the react component variable-name starting with a capital letter. 'var myComponent' must be 'var MyComponent' or 'var Mycomponent'.


问:
Java - Empty XML nodes
I am trying to create an XML file and when I am running this code, it is successfully creating XML file, but with empty nodes. My data is not parsing. This is the code -

```<code>public class xml {

    public static void main(String[] args) {
        List<String> headers = new ArrayList<String>(5);

        File file = new File("C:/Users/Admin/Desktop/data.csv");
        BufferedReader reader = null;

        try {

            DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder domBuilder = domFactory.newDocumentBuilder();

            Document newDoc = domBuilder.newDocument();
            // Root element
            Element rootElement = newDoc.createElement("root");
            newDoc.appendChild(rootElement);

            reader = new BufferedReader(new FileReader(file));
            int line = 0;

            String text = null;
            while ((text = reader.readLine()) != null) {

                StringTokenizer st = new StringTokenizer(text, "?", false);
                String[] rowValues = new String[st.countTokens()];
                int index = 0;
                while (st.hasMoreTokens()) {

                    String next = st.nextToken();
                    rowValues[index++] = next;

                }

                // String[] rowValues = text.split(",");

                if (line == 0) { // Header row
                    for (String col : rowValues) {
                        headers.add(col);
                    }
                } else { // Data row
                    Element rowElement = newDoc.createElement("row");
                    rootElement.appendChild(rowElement);

                    for (int col = 0; col < headers.size(); col++) {
                        String header = headers.get(col);
                        String value = null;

                        if (col < rowValues.length) {
                            value = rowValues[col];
                        } else {
                            // ?? Default value
                            value = " ";
                        }

                        System.out.println(header + " " + value);

                    }
                }
                line++;
            }

            try {

                TransformerFactory tranFactory = TransformerFactory.newInstance();
                Transformer aTransformer = tranFactory.newTransformer();
                aTransformer.setOutputProperty(OutputKeys.INDENT, "yes");
                aTransformer.setOutputProperty(OutputKeys.METHOD, "xml");
                aTransformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

                Source src = new DOMSource(newDoc);
                Result result = new StreamResult(new File("C:/Users/Admin/Desktop/data.xml"));

                aTransformer.transform(src, result);
                System.out.println("File creation successfully!");

            } catch (Exception exp) {
                exp.printStackTrace();
            } finally {
                try {

                } catch (Exception e1) {
                }
                try {

                } catch (Exception e1) {
                }
            }
        } catch (Exception e1) {
            e1.printStackTrace();
        }

    }
}
</code>```

Anything I did wrong, not able to recognized the mistake.

EDIT :-

Sample csv file and the output:-

```<code> Symbol,Open,High,Low,Last Traded Price,Change
"NIFTY 50","9,645.90","9,650.65","9,600.95","9,609.30","-5.70"
"RELIANCE","1,390.00","1,414.20","1,389.00","1,407.55","26.50"
"BPCL","647.70","665.00","645.95","660.10","10.75"
"ADANIPORTS","368.50","373.80","368.00","372.25","4.25"
"ONGC","159.50","161.75","159.35","160.80","1.70"
</code>```

output:-

```<code><?xml version="1.0" encoding="UTF-8" standalone="no"?>
<root>
    <row>"NIFTY 50","9,645.90","9,650.65","9,600.95","9,609.30","-5.70"</row>
    <row>"RELIANCE","1,390.00","1,414.20","1,389.00","1,407.55","26.50"</row>
    <row>"BPCL","647.70","665.00","645.95","660.10","10.75"</row>
    <row>"ADANIPORTS","368.50","373.80","368.00","372.25","4.25"</row>
    <row>"ONGC","159.50","161.75","159.35","160.80","1.70"</row>
</root>
</code>```

答: You don't user the variable value. So you should add a line, for example, rowElement.setTextContent(value); before the line System.out.println(header + " " + value);.

Title: Java - Empty XML nodes

Body:
I am trying to create an XML file and when I am running this code, it is successfully creating XML file, but with empty nodes. My data is not parsing. This is the code -

public class xml {

    public static void main(String[] args) {
        List<String> headers = new ArrayList<String>(5);

        File file = new File("C:/Users/Admin/Desktop/data.csv");
        BufferedReader reader = null;

        try {

            DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder domBuilder = domFactory.newDocumentBuilder();

            Document newDoc = domBuilder.newDocument();
            // Root element
            Element rootElement = newDoc.createElement("root");
            newDoc.appendChild(rootElement);

            reader = new BufferedReader(new FileReader(file));
            int line = 0;

            String text = null;
            while ((text = reader.readLine()) != null) {

                StringTokenizer st = new StringTokenizer(text, "?", false);
                String[] rowValues = new String[st.countTokens()];
                int index = 0;
                while (st.hasMoreTokens()) {

                    String next = st.nextToken();
                    rowValues[index++] = next;

                }

                // String[] rowValues = text.split(",");

                if (line == 0) { // Header row
                    for (String col : rowValues) {
                        headers.add(col);
                    }
                } else { // Data row
                    Element rowElement = newDoc.createElement("row");
                    rootElement.appendChild(rowElement);

                    for (int col = 0; col < headers.size(); col++) {
                        String header = headers.get(col);
                        String value = null;

                        if (col < rowValues.length) {
                            value = rowValues[col];
                        } else {
                            // ?? Default value
                            value = " ";
                        }

                        System.out.println(header + " " + value);

                    }
                }
                line++;
            }

            try {

                TransformerFactory tranFactory = TransformerFactory.newInstance();
                Transformer aTransformer = tranFactory.newTransformer();
                aTransformer.setOutputProperty(OutputKeys.INDENT, "yes");
                aTransformer.setOutputProperty(OutputKeys.METHOD, "xml");
                aTransformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

                Source src = new DOMSource(newDoc);
                Result result = new StreamResult(new File("C:/Users/Admin/Desktop/data.xml"));

                aTransformer.transform(src, result);
                System.out.println("File creation successfully!");

            } catch (Exception exp) {
                exp.printStackTrace();
            } finally {
                try {

                } catch (Exception e1) {
                }
                try {

                } catch (Exception e1) {
                }
            }
        } catch (Exception e1) {
            e1.printStackTrace();
        }

    }
}

Anything I did wrong, not able to recognized the mistake.

EDIT :-

Sample csv file and the output:-

 Symbol,Open,High,Low,Last Traded Price,Change
"NIFTY 50","9,645.90","9,650.65","9,600.95","9,609.30","-5.70"
"RELIANCE","1,390.00","1,414.20","1,389.00","1,407.55","26.50"
"BPCL","647.70","665.00","645.95","660.10","10.75"
"ADANIPORTS","368.50","373.80","368.00","372.25","4.25"
"ONGC","159.50","161.75","159.35","160.80","1.70"

output:-

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<root>
    <row>"NIFTY 50","9,645.90","9,650.65","9,600.95","9,609.30","-5.70"</row>
    <row>"RELIANCE","1,390.00","1,414.20","1,389.00","1,407.55","26.50"</row>
    <row>"BPCL","647.70","665.00","645.95","660.10","10.75"</row>
    <row>"ADANIPORTS","368.50","373.80","368.00","372.25","4.25"</row>
    <row>"ONGC","159.50","161.75","159.35","160.80","1.70"</row>
</root>