问:
IndexError: list index out of range (bimbam.py)
So I wanted to decompile a game using:

Python 2.7.15, Microsoft Visual C++ Compiler Package for Python 2.7, Cython 0.21.2 and the anaconda-master package.

I'm doing this on Windows 8.1 Build 9600 just so you know.

I followed this guide: (https://www.youtube.com/watch?v=lK_DDFpvlFw) But at 20:56 I get an error of bimbam.py (the tool to decompile the game). I reinstalled everything, used different versions, changed directories, followed other guides and used older anaconda-master packages but I can't get rid of the error. I think I know what the error means: "there is nothing in the place where something should be" or  "the script wants to access a variable/path which doesn't exist".

```<code>Traceback (most recent call last):
  File "C:\Users\Gabriel\Desktop\AnacondaDecompiler-master\tools\bimbam.py", lin
e 72, in <module>
    main()
  File "C:\Users\Gabriel\Desktop\AnacondaDecompiler-master\tools\bimbam.py", lin
e 38, in main
    input = sys.argv[1]
IndexError: list index out of range
</code>```

答:
It seems you need to configure an argument that your program will use.
input = sys.argv[1] caused the index error meaning that there is no argument passed.

Can you run the program with a matching argument?
in example python bimbam.py <filename>

Body:
So I wanted to decompile a game using:

Python 2.7.15, Microsoft Visual C++ Compiler Package for Python 2.7, Cython 0.21.2 and the anaconda-master package.

I'm doing this on Windows 8.1 Build 9600 just so you know.

I followed this guide: (https://www.youtube.com/watch?v=lK_DDFpvlFw) But at 20:56 I get an error of bimbam.py (the tool to decompile the game). I reinstalled everything, used different versions, changed directories, followed other guides and used older anaconda-master packages but I can't get rid of the error. I think I know what the error means: "there is nothing in the place where something should be" or  "the script wants to access a variable/path which doesn't exist".

Traceback (most recent call last):
  File "C:\Users\Gabriel\Desktop\AnacondaDecompiler-master\tools\bimbam.py", lin
e 72, in <module>
    main()
  File "C:\Users\Gabriel\Desktop\AnacondaDecompiler-master\tools\bimbam.py", lin
e 38, in main
    input = sys.argv[1]
IndexError: list index out of range


来源: stackexchange

问:
Install a list of software via apt using a list variable
While it's possible to install a list of software the following way:

```<code>- name: Install what I want
  apt:
    name:
      - docker
      - nmap
</code>```

Is it also possible to use a variable that contains a list of software names instead? Like so:

```<code>vars:
  my_list:
    - docker
    - nmap

- name: Install what I want
  apt:
    name: "{{ my_list }}"
</code>```

答:
I last ansible version you can use next syntax:</p>

```<code>vars:
  my_list: [docker, nmap]

tasks:
  - name: Install APPS
    apt:
      name: "{{ my_list }}"
      state: present
      update_cache: yes
</code>```

ContentLicense: CC BY-SA 4.0

Body:
While it's possible to install a list of software the following way:

- name: Install what I want
  apt:
    name:
      - docker
      - nmap

Is it also possible to use a variable that contains a list of software names instead? Like so:

vars:
  my_list:
    - docker
    - nmap

- name: Install what I want
  apt:
    name: "{{ my_list }}"

Body:
I last ansible version you can use next syntax:

vars:
  my_list: [docker, nmap]

tasks:
  - name: Install APPS
    apt:
      name: "{{ my_list }}"
      state: present
      update_cache: yes


问:
open a PDF file with automatically replaced Fonts
I am not a programmer, but a normal user who uses Linux.

I want to use Ghostscript to DISPLAY Pdf files, not to CREATE Pdf files. (I have never used Ghostscript until now).

But I want Ghostscript to automatically replace all fonts with other fonts when I open the PDF. No matter if the fonts are embedded or not.

With which fonts should the fonts be replaced?
Answer: I want to create a list of fonts, that I want to be available for replacement.

But which of these fonts on the list should be used?
Answer: The one that best matches the metric of the font to be replaced.

Is it possible to do this somehow?

答:
You can't get Ghostscript to do what you are asking. If a PDF file contains fonts Ghostscript will use those fonts, it will only substitute if it cannot find an embedded font.

The reason for this is simple; the font embedded in the PDF file is the correct font. It's Metrics are correct, and the mapping form character code to the appropriate glyph selector in the font will be correct.

It's also a non-trivial problem to select from a list of fonts the one which 'best matches the metrics of the font to be replaced'. What characteristics should be considered ? How should those be determined ?

When a font is not embedded then Ghostscript will consult its own list of fonts and CIDFonts. Both of these lists can be customised, the documentation is here

But since a substitute font is always going to be a compromise, you can't tell Ghostscript not to use the embedded fonts in a PDF. Well technically you could, by modifying the PDF interpreter, but you say you aren't a programmer, so I doubt you will want to try that.


问:
Uncaught Error: [$injector:modulerr] error while working with angular js
I am trying to create a simple regisration form which will in the end tell me whether I have registered or not . But I am stuck with this error .
This is my app.js file

```<code>    (function (){
    'use strict';
     angular.module('modulemain',[]).controller('ModuleController',ModuleController);

     ModuleController.$inject=['$scope'];

    function ModuleController($scope){
    $scope.fname='';
    $scope.lname='';
    $scope.mname='';
    $scope.email='';
    $scope.password='';
    $scope.confirm='';
    $scope.msg='';
    $scope.msg1='';

    $scope.submission=function(){
      if($scope.password!=$scope.confirm){
        $scope.msg="Password did not matched";
        $scope.msg1="Try Entering Password";
      }
      else{
        $scope.msg="Registration Successful";
        $scope.msg1="Welcome $scope.fname";
      }

    };

  };

});
</code>```

And this is my index.html file

```<code><!DOCTYPE html>
<html lang="en" dir="ltr" ng-app='app'>
<head>
   <title>Registration</title>
   <meta name="viewport" content="width=device-width, initial-scale=1">
   <script type="text/javascript" src="angular.min.js"></script>
   <script type="text/javascript" src='app.js'></script>

</head>
<body>
<div class="form" ng-controller="ModuleController">
  First Name: <input type="text" id="fname" placeholder="Enter First name" ng-model="fname"><br>
  Middle Name: <input type="text" id="mname" placeholder="Enter middle name" ng-model="mname"><br>
  Last Name :<input type="text" id="lname" placeholder="Enter last name" ng-model="lname"><br>
  Email: <input type="email" id="email" placeholder="Enter Email address" ng-model="email"><br>
  Password: <input type="password" id="pass" placeholder="Enter password" ng-model="password"><br>
  Confirm Password: <input type="password" id="c_pass" placeholder="Re-enter the password" ng-
  model="confirm"><br>

  <button type="submit" ng-click="submit()"> Submit</button>
  <br><br>
  <div>
    {{msg}}<br>
    {{msg1}}
  </div>
 </div>
</body>
</code>```

And I am getting following error

```<code>angular.min.js:7 Uncaught Error: [$injector:modulerr] http://errors.angula

at angular.min.js:7
at angular.min.js:43
at r (angular.min.js:8)
at g (angular.min.js:42)
at fb (angular.min.js:46)
at c (angular.min.js:22)
at Uc (angular.min.js:22)
at Ae (angular.min.js:21)
at angular.min.js:348
at HTMLDocument.b (angular.min.js:38)
</code>```

Can anyone help me with this ?? I am new to Angular Js .

答:
```<code>(function (angular) {
    'use strict';
    angular.module('modulemain',[]).controller('ModuleController',ModuleController);

    ModuleController.$inject=['$scope'];

    function ModuleController($scope){
        $scope.fname='';
        $scope.lname='';
        $scope.mname='';
        $scope.email='';
        $scope.password='';
        $scope.confirm='';
        $scope.msg='';
        $scope.msg1='';

        $scope.submission=function(){
            if($scope.password!=$scope.confirm){
                $scope.msg="Password did not matched";
                $scope.msg1="Try Entering Password";
            } else {
                $scope.msg="Registration Successful";
                $scope.msg1="Welcome $scope.fname";
            }
        };
    };
})(angular);
</code>```

Body:
I am trying to create a simple regisration form which will in the end tell me whether I have registered or not . But I am stuck with this error .
This is my app.js file

    (function (){
    'use strict';
     angular.module('modulemain',[]).controller('ModuleController',ModuleController);

     ModuleController.$inject=['$scope'];

    function ModuleController($scope){
    $scope.fname='';
    $scope.lname='';
    $scope.mname='';
    $scope.email='';
    $scope.password='';
    $scope.confirm='';
    $scope.msg='';
    $scope.msg1='';

    $scope.submission=function(){
      if($scope.password!=$scope.confirm){
        $scope.msg="Password did not matched";
        $scope.msg1="Try Entering Password";
      }
      else{
        $scope.msg="Registration Successful";
        $scope.msg1="Welcome $scope.fname";
      }

    };

  };

});

And this is my index.html file

<!DOCTYPE html>

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

  First Name: <input type="text" id="fname" placeholder="Enter First name" ng-model="fname">

  Middle Name: <input type="text" id="mname" placeholder="Enter middle name" ng-model="mname">

  Last Name :<input type="text" id="lname" placeholder="Enter last name" ng-model="lname">

  Email: <input type="email" id="email" placeholder="Enter Email address" ng-model="email">

  Password: <input type="password" id="pass" placeholder="Enter password" ng-model="password">

  Confirm Password: <input type="password" id="c_pass" placeholder="Re-enter the password" ng-
  model="confirm">

  <button type="submit" ng-click="submit()"> Submit</button>

    {{msg}}

    {{msg1}}

And I am getting following error

angular.min.js:7 Uncaught Error: [$injector:modulerr] http://errors.angula

at angular.min.js:7
at angular.min.js:43
at r (angular.min.js:8)
at g (angular.min.js:42)
at fb (angular.min.js:46)
at c (angular.min.js:22)
at Uc (angular.min.js:22)
at Ae (angular.min.js:21)
at angular.min.js:348
at HTMLDocument.b (angular.min.js:38)

Can anyone help me with this ?? I am new to Angular Js .


问:
create repetition of elements multidimentional
I am trying to create a repetition of elements given array like this [1,2,10] to get the result by size n, if size n equals 2 the result is [ [1,1], [1,2], [1,10], [2,2], [2, 10], [10, 10] ]
i am trying to recursion it without any magic function javascript , just do push and pop :),
here is my code

```<code>
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function t(arr, length,  i = 0, result = []) {
  let final = []
  if( result.length == length){
    final.push(result)
    console.log(final)
    return
  }

  let j = i;
  while( j < arr.length ) {
    result.push(arr[j])
    // console.log(result)
    t(arr, length, j, result)

    result.pop()
    j++
  }
  return final
}

function k() {
  const arr = [1,2,10]
  const l = 2
  return t(arr, l)
}

console.log( "finall result ===> " , k())</code>```

```

the final result is an empty array, though on condition above I push result to array empty of final,
is there any wrong in my code?

expected result : [ [1,1], [1,2], [1,10], [2,2], [2, 10], [10, 10] ]

答:
You could take a recursive approach and iterate the array without mutating the array.

function getCombinations(array, n) {
    function iter(index, right) {
        if (right.length === n) {
            result.push(right);
            return;
        }
        while (index < array.length) {
            iter(index, [...right, array[index]]);
            index++;
        }
    }

    var result = [];
    iter(0, []);
    return result;
}

console.log(getCombinations([1, 2, 10], 2));```

Body:
I am trying to create a repetition of elements given array like this [1,2,10] to get the result by size n, if size n equals 2 the result is [ [1,1], [1,2], [1,10], [2,2], [2, 10], [10, 10] ]
i am trying to recursion it without any magic function javascript , just do push and pop :),
here is my code

function t(arr, length,  i = 0, result = []) {
  let final = []
  if( result.length == length){
    final.push(result)
    console.log(final)
    return
  }

  let j = i;
  while( j < arr.length ) {
    result.push(arr[j])
    // console.log(result)
    t(arr, length, j, result)

    result.pop()
    j++
  }
  return final
}

function k() {
  const arr = [1,2,10]
  const l = 2
  return t(arr, l)
}

console.log( "finall result ===> " , k())

the final result is an empty array, though on condition above I push result to array empty of final,
is there any wrong in my code?

expected result : [ [1,1], [1,2], [1,10], [2,2], [2, 10], [10, 10] ]


问:
Typescript property as string, how do I get the interface
Why do I get this error? How do I give languages an interface when its a object literal in another external module?

Element implicitly has an any type because expression of type string can't be used to index type { en: { title: string; }; es: { title: string; }; fi: { title: string; }; }.

No index signature with a parameter of type string was found on type { en: { title: string; }; es: { title: string; }; fi: { title: string; }; }.ts(7053)

export const languages = {
  en: {
    title: "English"
  },
  es: {
    title: "Español"
  },
  fi: {
    title: "Suomalainen"
  }
}
```

<pre class="lang-js prettyprint-override"><code>import React from 'react';
import { languages } from './utils/languageData'

interface IProps {
  lang: string
}

function LanguageSelect(props: IProps) {
  const { lang } = props

  const getText = (langId: string, propVal: string): string => {
    const result = languages[langId][propVal]
    const txt = result ? 'error' : result
    return txt
  }

  return (
    <div className="LanguageSelect" data-test="languageSelect-box">
      <div className="languageArea">{getText(lang, 'title')}</div>
    </div>
  );
}

export default LanguageSelect;
</code>```

答:
You can make your type check stricter all the way up to the component props.

export const languages = {
  en : {
    title: "English"
  },
  es: {
    title: "Español"
  },
  fi: {
    title: "Suomalainen"
  }
};
export type LanguageKeys = keyof typeof languages;

```

<p>and then:</p>

<pre class="lang-js prettyprint-override"><code>    import React from 'react';
    import { languages, LanguageKeys } from './utils/languageData'

    interface IProps {
      lang: LanguageKeys
    }

    function LanguageSelect(props: IProps) {
      const { lang } = props

      const getText = (langId: LanguageKeys, propVal: string): string => {
        const result = languages[langId][propVal]
        const txt = result ? 'error' : result
        return txt
      }

      return (
        <div className="LanguageSelect" data-test="languageSelect-box">
          <div className="languageArea">{getText(lang, 'title')}</div>
        </div>
      );
    }

    export default LanguageSelect;
</code>```

This way, you wouldn't be able to pass languages that don't exist to the LanguageSelect components and you will have auto-complete and all of that good stuff too.

Body:
Why do I get this error? How do I give languages an interface when its a object literal in another external module?

Element implicitly has an any type because expression of type string can't be used to index type { en: { title: string; }; es: { title: string; }; fi: { title: string; }; }.

No index signature with a parameter of type string was found on type { en: { title: string; }; es: { title: string; }; fi: { title: string; }; }.ts(7053)

export const languages = {
  en: {
    title: "English"
  },
  es: {
    title: "Español"
  },
  fi: {
    title: "Suomalainen"
  }
}

import React from 'react';
import { languages } from './utils/languageData'

interface IProps {
  lang: string
}

function LanguageSelect(props: IProps) {
  const { lang } = props

  const getText = (langId: string, propVal: string): string => {
    const result = languages[langId][propVal]
    const txt = result ? 'error' : result
    return txt
  }

  return (

{getText(lang, 'title')}

  );
}

export default LanguageSelect;

Body:
You can make your type check stricter all the way up to the component props.

export const languages = {
  en : {
    title: "English"
  },
  es: {
    title: "Español"
  },
  fi: {
    title: "Suomalainen"
  }
};
export type LanguageKeys = keyof typeof languages;

and then:

    import React from 'react';
    import { languages, LanguageKeys } from './utils/languageData'

    interface IProps {
      lang: LanguageKeys
    }

    function LanguageSelect(props: IProps) {
      const { lang } = props

      const getText = (langId: LanguageKeys, propVal: string): string => {
        const result = languages[langId][propVal]
        const txt = result ? 'error' : result
        return txt
      }

      return (
        <div className="LanguageSelect" data-test="languageSelect-box">
          <div className="languageArea">{getText(lang, 'title')}</div>
        </div>
      );
    }

    export default LanguageSelect;

This way, you wouldn't be able to pass languages that don't exist to the LanguageSelect components and you will have auto-complete and all of that good stuff too.


问:
Reflection api - find subclass type
Hi I am trying to find out the subclass, form an superclass object.

```<code>if Class Super is the super class.
and Class Sub1 and Class Sub2 extends Class Super.(all classes are public)

Lets say I have a object of Super type as
Super superObject = new Sub1();
</code>```

now for the superObject, is it possible to find which subclass the superObject extends in Java?

Since "SuperClass will not be aware of any SubClasses it has", can you please tell me is my above question valid in the first place, or am I missing any basic concept?

Thanks in advance.

答:
You want this method:

```<code>boolean isList = Subclass.isAssignableFrom(Superclass);
</code>```

From the JavaDoc:

Determines if the class or interface represented by this Class object is either the same as, or is a superclass or superinterface of, the class or interface represented by the specified Class parameter. It returns true if so; otherwise it returns false. If this Class object represents a primitive type, this method returns true if the specified Class parameter is exactly this Class object; otherwise it returns false.

Reference:

```<code> Class.isAssignableFrom(Class)
</code>```

ContentLicense: CC BY-SA 3.0

Title: Reflection api - find subclass type

Body:
Hi I am trying to find out the subclass, form an superclass object.

if Class Super is the super class.
and Class Sub1 and Class Sub2 extends Class Super.(all classes are public)

Lets say I have a object of Super type as
Super superObject = new Sub1();

now for the superObject, is it possible to find which subclass the superObject extends in Java?

Since "SuperClass will not be aware of any SubClasses it has", can you please tell me is my above question valid in the first place, or am I missing any basic concept?

Thanks in advance.

Body:
You want this method:

boolean isList = Subclass.isAssignableFrom(Superclass);

From the JavaDoc:

Determines if the class or interface represented by this Class object is either the same as, or is a superclass or superinterface of, the class or interface represented by the specified Class parameter. It returns true if so; otherwise it returns false. If this Class object represents a primitive type, this method returns true if the specified Class parameter is exactly this Class object; otherwise it returns false.

Reference:

 Class.isAssignableFrom(Class)


问:
webkitSpeechRecognition calling onend immediately after start()
As soon as I call rec.start() it calls onstart and then onend straight away, never goes into onresult.

Microphone is allowed for the web page, it asked once due to being https
Using Chrome 81.0.4044.122 on osx, which is listed as supporting speechRecognition.

I am aware this is a not a stable feature within browsers, but running the annyang demo works, detecting my voice, and I believe that is using the same speechRecognition kit.
https://www.talater.com/annyang/

Any ideas?

Here is my code

if (!window.webkitSpeechRecognition) {
  // not called, so assume browser supports webkitSpeechRecognition
  alert('Your browser doesn\'t support speech to text.\nTry Chrome 33+ :)');
} else {
  const promise = new Promise((resolve, reject) => {
    const recognition = new webkitSpeechRecognition();
    recognition.lang = lang;
    recognition.continuous = true; // tried true and false

    recognition.onstart = (e) => {
      // called immediately after .start() as expected
      console.log("onstart");
    }
    recognition.onend = () => {
      // called immediately after onstart, not as expected
      console.log("onend");
    }
    recognition.onresult = function(event) {
      // never called, because it ended as soon as it started
      console.log("onresult");
    };
    // also tried the following formats
    // recognition.onresult = (event) => {};
    // recognition.addEventListener('onresult', (event) => {};
    // original example written like the following
    // recognition.addEventListener('result', (event) => {};

    recognition.start();
  });
  return await promise;
}
```

答:
Sorry guys, it was a browser issue.

Chrome said it had updated, but it actually still needed restarting, only seen after going into Chrome Preferences.

I now have 83.0.4103.83 on both desktop and Android tablet, and it appears to be working correctly.


问:
in a windows form app when user changes a value after previously setting one, can i update an if statement result?
i have a windows form app (in c#)
with 2 comboboxes, 1 numericUpDown box, 1 textbox.
the user has to choose an input in the first combobox, the second combobox and then choose a value in the numericUpDown.
my program then has to show the result in the textbox.

i used a couple of if statements to display the result.

i know that c# reads the program from top to bottem
and it causes an issue for me.

when the user selects all the options my program will show the correct result, if however the user goes back and changes one of their options, the result is incorrect ( i think it doesn't correctly update the if statement due to c# already being past that part of code?)

i put each if statement in the corresponding "selectedIndexChanged" and "ValueChanged" ( is this the correct way to do it?)

should i use something other than an if statement?
or should i use a "calculate" button, which the user first has to press before showing ANY result?

could i use return or something? i don't really understand those

i tried to set the other bools to false if another one was set to true,  but that didn't do anything.

```<code>public bool staal = false; //steel
    public bool rvs = false; //stainless
    public string materiaal;

    public void materiaalDropBox_SelectedIndexChanged(object sender, EventArgs e)
    {
        materiaal = materiaalDropBox.Text; //text currently in combobox
        if (materiaal == "Staal")//material = steel
        {
            staal = true;
            rvs = false;

        }else if (materiaal == "RVS")
        {
            rvs = true; // material = stainless
            staal = false;
        }
    }

    public string soortboor; //kind of drill
    public bool hss = false; //high speed steel drill
    public bool hardmetaal = false; //cemented carbide drill
    public bool spiraal = false; //basic drill
    decimal VC = 0; // 318 * m/ms of drill on material

    public void soortBoorDropBox_SelectedIndexChanged(object sender, EventArgs e)
    {
        soortboor = soortBoorDropBox.Text;// text currently in combobox
        if (soortboor == "HSS")
        {
            hss = true; // drill is high speed steel
            hardmetaal = false;
            spiraal = false;
        }else if (soortboor == "Hardmetaal")
        {
            hardmetaal = true;// drill is cemented carbide
            hss = false;
            spiraal = false;
        }else if (soortboor == "Spiraal")
        {
            spiraal = true; // drill is normal
            hss = false;
            hardmetaal = false;

        }

        // if material && metal match a certain type, set VC value
        if (rvs && hardmetaal)
        {
            VC = Convert.ToDecimal(318 * 30);

        }else if (staal && hardmetaal)
        {
            VC = Convert.ToDecimal(318 * 60);
        }else if (staal && hss)
        {
            VC = Convert.ToDecimal(318 * 40);
        }else if (staal && spiraal)
        {
            VC = Convert.ToDecimal(318 * 15);
        }else
        {
            VC = 0;
        }

    }

    public decimal diameter; //drill diameter
    string RPM; //required RPM ( this is the output we want to calculate)

    public void diameterValue_ValueChanged(object sender, EventArgs e)
    {
        diameter = diameterValue.Value; //get diameter value from numericUpDown

        RPM = Convert.ToString(VC / diameter);//convert VC divided by diamter value to string

        toerentalValue.Text = RPM; // show RPM value as string in a textbox

    }
</code>```

答:
I don't think it's proper putting all your update code in each selectedIndex_Changed event. Change your code to something like this

```<code>public void materiaalDropBox_SelectedIndexChanged(object sender, EventArgs e)
{
   //Set your property values
   UpdateCalculation();
}

private void UpdateCalculation()
{
   //Holds all the other code for calculations
}
</code>```

So each time a SelectedIndex changes, you just set the value of the comboBox to a private field and then call UpdateCalculations to do the remaining job. UpdateCalculations then gets those values and work on them.

Body:
i have a windows form app (in c#)
with 2 comboboxes, 1 numericUpDown box, 1 textbox.
the user has to choose an input in the first combobox, the second combobox and then choose a value in the numericUpDown.
my program then has to show the result in the textbox.

i used a couple of if statements to display the result.

i know that c# reads the program from top to bottem
and it causes an issue for me.

when the user selects all the options my program will show the correct result, if however the user goes back and changes one of their options, the result is incorrect ( i think it doesn't correctly update the if statement due to c# already being past that part of code?)

i put each if statement in the corresponding "selectedIndexChanged" and "ValueChanged" ( is this the correct way to do it?)

should i use something other than an if statement?
or should i use a "calculate" button, which the user first has to press before showing ANY result?

could i use return or something? i don't really understand those

i tried to set the other bools to false if another one was set to true,  but that didn't do anything.

public bool staal = false; //steel
    public bool rvs = false; //stainless
    public string materiaal;

    public void materiaalDropBox_SelectedIndexChanged(object sender, EventArgs e)
    {
        materiaal = materiaalDropBox.Text; //text currently in combobox
        if (materiaal == "Staal")//material = steel
        {
            staal = true;
            rvs = false;

        }else if (materiaal == "RVS")
        {
            rvs = true; // material = stainless
            staal = false;
        }
    }

    public string soortboor; //kind of drill
    public bool hss = false; //high speed steel drill
    public bool hardmetaal = false; //cemented carbide drill
    public bool spiraal = false; //basic drill
    decimal VC = 0; // 318 * m/ms of drill on material

    public void soortBoorDropBox_SelectedIndexChanged(object sender, EventArgs e)
    {
        soortboor = soortBoorDropBox.Text;// text currently in combobox
        if (soortboor == "HSS")
        {
            hss = true; // drill is high speed steel
            hardmetaal = false;
            spiraal = false;
        }else if (soortboor == "Hardmetaal")
        {
            hardmetaal = true;// drill is cemented carbide
            hss = false;
            spiraal = false;
        }else if (soortboor == "Spiraal")
        {
            spiraal = true; // drill is normal
            hss = false;
            hardmetaal = false;

        }

        // if material && metal match a certain type, set VC value
        if (rvs && hardmetaal)
        {
            VC = Convert.ToDecimal(318 * 30);

        }else if (staal && hardmetaal)
        {
            VC = Convert.ToDecimal(318 * 60);
        }else if (staal && hss)
        {
            VC = Convert.ToDecimal(318 * 40);
        }else if (staal && spiraal)
        {
            VC = Convert.ToDecimal(318 * 15);
        }else
        {
            VC = 0;
        }

    }

    public decimal diameter; //drill diameter
    string RPM; //required RPM ( this is the output we want to calculate)

    public void diameterValue_ValueChanged(object sender, EventArgs e)
    {
        diameter = diameterValue.Value; //get diameter value from numericUpDown

        RPM = Convert.ToString(VC / diameter);//convert VC divided by diamter value to string

        toerentalValue.Text = RPM; // show RPM value as string in a textbox

    }

Body:
I don't think it's proper putting all your update code in each selectedIndex_Changed event. Change your code to something like this

public void materiaalDropBox_SelectedIndexChanged(object sender, EventArgs e)
{
   //Set your property values
   UpdateCalculation();
}

private void UpdateCalculation()
{
   //Holds all the other code for calculations
}

So each time a SelectedIndex changes, you just set the value of the comboBox to a private field and then call UpdateCalculations to do the remaining job. UpdateCalculations then gets those values and work on them.


问:
hide text from printing but keeping the space
We have in-house server which brings the records by php from mysql.

We have Dot matrix printer which we are using for printing on carbon less paper (2 copies:- one for official records,one for customer and one for gatekeeper).

We tried to print the content by display:none but it was removing that space from that Div.

Then we tried to print it with the white color font without display:none (we realized that print head reads everything), so it was printing the characters on the 2nd and 3rd copy.

So We want to know how can hide the text at the same time by keeping that much space blank.

Please tell how to do the same thing with border ?

thanks in advance

答:
visibility: hidden; makes it invisible, but leaves the space.

Check this


问:
java.lang.NullPointerException Error in my Database
Is there something wrong with my code? I've been for almost an hour in regards to where did I go wrong with my codes, everytime I add an information it always presents an error that it's nullpointerexception, is there a passionate programmers here to help this amateur programmer? I'm just starting out.</p>

```<code> if (tf_accnum.equals("") || tf_bankID.equals("") || uname.equals("") ||pword.equals("")) {
       JOptionPane.showMessageDialog(null,"ALL FIELDS ARE REQUIRED");
   } else  {

       try {

        String sql = "Insert into tbl_memaccount(memaccID,memberID,username,password)values(?,?,?,?)";
        PreparedStatement pst = con.prepareStatement(sql);
     ps.setString(1,tf_accnum.getText());
     ps.setString(2,tf_bankID.getText());
     ps.setString(3,uname.getText());
     ps.setString(4,pword.getText());
     ps.execute();
     JOptionPane.showMessageDialog(null,"Successful");

    } catch(Exception ex) {
        System.out.println(ex);
    }
}
</code>```

答:
I have a guess that exception is coming from the first line. If any of the your variables tf_accnum, tf_bankID, uname or pword is null you will get java.lang.NullPointerException.

You can make your empty string check safe as below:

```<code>if ("".equals(tf_accnum) || "".equals(tf_bankID) || "".equals(uname) || "".equals(pword))
</code>```

Using the above code, even if you get null values for your input variables, it will not get exception and will proceed to else code part. But you will be getting exception while setting insert parameters, as you used {your variable}.getText().

A full safe version of your code would be:

```<code>if (tf_accnum == null || "".equals(tf_accnum)
    || tf_bankID == null || "".equals(tf_bankID)
    || uname == null || "".equals(uname)
    || pword == null || "".equals(pword)) {
    JOptionPane.showMessageDialog(null,"ALL FIELDS ARE REQUIRED");
} else  {
    try {
        String sql = "Insert into tbl_memaccount(memaccID,memberID,username,password)values(?,?,?,?)";
        PreparedStatement pst = con.prepareStatement(sql);
        ps.setString(1,tf_accnum.getText());
        ps.setString(2,tf_bankID.getText());
        ps.setString(3,uname.getText());
        ps.setString(4,pword.getText());
        ps.execute();
        JOptionPane.showMessageDialog(null,"Successful");
    } catch(Exception ex) {
        System.out.println(ex);
    }
}
</code>```

Body:
Is there something wrong with my code? I've been for almost an hour in regards to where did I go wrong with my codes, everytime I add an information it always presents an error that it's nullpointerexception, is there a passionate programmers here to help this amateur programmer? I'm just starting out.

 if (tf_accnum.equals("") || tf_bankID.equals("") || uname.equals("") ||pword.equals("")) {
       JOptionPane.showMessageDialog(null,"ALL FIELDS ARE REQUIRED");
   } else  {

       try {

        String sql = "Insert into tbl_memaccount(memaccID,memberID,username,password)values(?,?,?,?)";
        PreparedStatement pst = con.prepareStatement(sql);
     ps.setString(1,tf_accnum.getText());
     ps.setString(2,tf_bankID.getText());
     ps.setString(3,uname.getText());
     ps.setString(4,pword.getText());
     ps.execute();
     JOptionPane.showMessageDialog(null,"Successful");

    } catch(Exception ex) {
        System.out.println(ex);
    }
}

Body:
I have a guess that exception is coming from the first line. If any of the your variables tf_accnum, tf_bankID, uname or pword is null you will get java.lang.NullPointerException.

You can make your empty string check safe as below:

if ("".equals(tf_accnum) || "".equals(tf_bankID) || "".equals(uname) || "".equals(pword))

Using the above code, even if you get null values for your input variables, it will not get exception and will proceed to else code part. But you will be getting exception while setting insert parameters, as you used {your variable}.getText().

A full safe version of your code would be:

if (tf_accnum == null || "".equals(tf_accnum)
    || tf_bankID == null || "".equals(tf_bankID)
    || uname == null || "".equals(uname)
    || pword == null || "".equals(pword)) {
    JOptionPane.showMessageDialog(null,"ALL FIELDS ARE REQUIRED");
} else  {
    try {
        String sql = "Insert into tbl_memaccount(memaccID,memberID,username,password)values(?,?,?,?)";
        PreparedStatement pst = con.prepareStatement(sql);
        ps.setString(1,tf_accnum.getText());
        ps.setString(2,tf_bankID.getText());
        ps.setString(3,uname.getText());
        ps.setString(4,pword.getText());
        ps.execute();
        JOptionPane.showMessageDialog(null,"Successful");
    } catch(Exception ex) {
        System.out.println(ex);
    }
}


问:
Logcat not showing anything android api level 22
I have problem with Logcat.
 Logcat not showing anything only if I use some device with Android API level 22.
I use Android Studio.I did: change ADB location on device,kill adb server, restart Logcat, Invalidies caches/restart, reinstal Device, reset Android Studio /Computer. nothing solved problem. </p>

答:
1) Ensure you have selected your device you are working on

2) Ensure your app package name is selected

3) Ensure 'vebose' is selected to show all logcat messages

4) No filter is applied


问:
Will modifications to a function's return value in the finally block take effect?
Consider the following code:

```<code> int dummy() {
     int x = 0;
     try {
        x = x + 1;
        throw new Exception();
     } catch (Exception e) {
       x = x + 2;
       return x;
     } finally {
      x = x + 4;
 }
</code>```

I need to "predict" the behaviour of this method without programming it. My question is, what will the return value be?

My guess would be that when an exception occurs, the finally block will be realized, so the value of x will be 4. But I think the value will not be returned. And if no exception occurs, the value will be 2 and it will be returned.

I'm a complete beginner (less than 3 months) in programming so I might be missing something.

答:
The following things will happen when you will call this method:

The expression, x = x + 1; will increase the value of x by 1 i.e. its value will become 1. Then, throw new Exception(); will be executed and as a result, the control will enter the catch block.

Inside the catch block, x = x + 2; will increase the value of x by 2 i.e. its value will become 3 which is the value that will be returned.

Since finally block is supposed to be executed irrespective of whether an exception is thrown or not, this block will be executed but it won't change the return value. Thus, finally block is useless here. Typically, finally block is used to release resources. Check this to learn more about it.

Body:
Consider the following code:

 int dummy() {
     int x = 0;
     try {
        x = x + 1;
        throw new Exception();
     } catch (Exception e) {
       x = x + 2;
       return x;
     } finally {
      x = x + 4;
 }

I need to "predict" the behaviour of this method without programming it. My question is, what will the return value be?

My guess would be that when an exception occurs, the finally block will be realized, so the value of x will be 4. But I think the value will not be returned. And if no exception occurs, the value will be 2 and it will be returned.

I'm a complete beginner (less than 3 months) in programming so I might be missing something.


问:
.htaccess RewriteRule issue here
Ok, so I am using this code in a .htaccess file.  This is the only code in there, but it doesn't seem to work at all and I know I have mod_rewrite installed and enabled.

```<code>RewriteEngine On
RewriteRule ^news\.js news.php [NC]
</code>```

have also tried this:

```<code>RewriteEngine On
RewriteRule news.js news.php [NC]
</code>```

Ok, so, I am using news.php to output a JS Script that I am linking to elsewhere.  So I want all links to news.js (and all links with text after this), to point to news.php instead.  And so news.php outputs the Javascript for this, but is a PHP file...

Am I setting up the PHP file correctly?

```<code><?php

// If there is a php error for any reason...hide it!
ini_set('display_errors', 'Off');

// Set the header-type.
header('Content-type: application/x-javascript');

// And it calls some functions in here

?>
</code>```

The problem is that it isn't working.  Can someone please help me?  Is my .htaccess file not set up properly?

Thanks for any help you can offer me.

答: do you have AllowOverride enabled for your .htaccess to work? http://www.blackbeagle.com/web-hosting/apache-mod_rewrite-and-allowoverride/</p>

Title: .htaccess RewriteRule issue here

Body:
Ok, so I am using this code in a .htaccess file.  This is the only code in there, but it doesn't seem to work at all and I know I have mod_rewrite installed and enabled.

RewriteEngine On
RewriteRule ^news\.js news.php [NC]

have also tried this:

RewriteEngine On
RewriteRule news.js news.php [NC]

Ok, so, I am using news.php to output a JS Script that I am linking to elsewhere.  So I want all links to news.js (and all links with text after this), to point to news.php instead.  And so news.php outputs the Javascript for this, but is a PHP file...

Am I setting up the PHP file correctly?

<?php

// If there is a php error for any reason...hide it!
ini_set('display_errors', 'Off');

// Set the header-type.
header('Content-type: application/x-javascript');

// And it calls some functions in here

?>

The problem is that it isn't working.  Can someone please help me?  Is my .htaccess file not set up properly?

Thanks for any help you can offer me.


问:
Cannot load font files, 404 error
I am using two font icons in a project. Font Awesome and a customize SVG font. All font files are in same folder. Here is the file structure:

```<code>-assets
    -css
        -font-awesome.min.css
        -themefy.css
    -fonts
        -font-awesome.eot
        -font-awesome.svg
        -font-awesome.ttf
        -font-awesome.woff
        -font-awesome.woff2
        -font-awesomed41d.eot
        -themify.eot
        -themify.svg
        -themify.ttf
        -themify.woff
        -themifyd41d.eot
</code>```

Both fonts are working fine in localhost but themify font doesn't works after deployment. It returns a 404 not found in chrome console. I had a lot of study on it for 2/3 days still can't figure out what is the problem. Here is my themify @font-face:

themify.css

```<code>@font-face {
    font-family: 'themify';
    src:url('../fonts/themify.eot?-fvbane');
    src:url('../fonts/themifyd41d.eot?#iefix-fvbane') format('embedded-opentype'),
        url('../fonts/themify.woff?-fvbane') format('woff'),
        url('../fonts/themify.ttf?-fvbane') format('truetype'),
        url('../fonts/themify.svg?-fvbane#themify') format('svg');
    font-weight: normal;
    font-style: normal;
}
</code>```

If you want to see it live: http://smartrahat.com/

答:
Add codes at the below to your Web.config file.</p>

```<code>  <system.webServer>
    <staticContent>
      <remove fileExtension=".woff" />
      <mimeMap fileExtension=".woff" mimeType="font/woff" />
    </staticContent>
  </system.webServer>
</code>```

Title: Cannot load font files, 404 error

Body:
I am using two font icons in a project. Font Awesome and a customize SVG font. All font files are in same folder. Here is the file structure:

-assets
    -css
        -font-awesome.min.css
        -themefy.css
    -fonts
        -font-awesome.eot
        -font-awesome.svg
        -font-awesome.ttf
        -font-awesome.woff
        -font-awesome.woff2
        -font-awesomed41d.eot
        -themify.eot
        -themify.svg
        -themify.ttf
        -themify.woff
        -themifyd41d.eot

Both fonts are working fine in localhost but themify font doesn't works after deployment. It returns a 404 not found in chrome console. I had a lot of study on it for 2/3 days still can't figure out what is the problem. Here is my themify @font-face:

themify.css

@font-face {
    font-family: 'themify';
    src:url('../fonts/themify.eot?-fvbane');
    src:url('../fonts/themifyd41d.eot?#iefix-fvbane') format('embedded-opentype'),
        url('../fonts/themify.woff?-fvbane') format('woff'),
        url('../fonts/themify.ttf?-fvbane') format('truetype'),
        url('../fonts/themify.svg?-fvbane#themify') format('svg');
    font-weight: normal;
    font-style: normal;
}

If you want to see it live: http://smartrahat.com/

Body:
Add codes at the below to your Web.config file.

  <system.webServer>
    <staticContent>
      <remove fileExtension=".woff" />
      <mimeMap fileExtension=".woff" mimeType="font/woff" />
    </staticContent>
  </system.webServer>


问:
SMTP sink socket server in PHP
Recently found this simple SMTP python script and trying to do the same in PHP.

```<code>from __future__ import print_function
from datetime import datetime
import asyncore
from smtpd import SMTPServer

class EmlServer(SMTPServer):
    no = 0
    def process_message(self, peer, mailfrom, rcpttos, data):
        filename = '%s-%d.eml' % (datetime.now().strftime('%Y%m%d%H%M%S'),
                self.no)
        f = open(filename, 'w')
        f.write(data)
        f.close
        print('%s saved.' % filename)
        self.no += 1

def run():
    # start the smtp server on localhost:1025
    foo = EmlServer(('localhost', 1025), None)
    try:
        asyncore.loop()
    except KeyboardInterrupt:
        pass

if __name__ == '__main__':
    run()
</code>```

I have tried Navarr's socket class (a simple php socket server) to receive the data and save it to a file. A set up EchoServer shows when I telnet to it and type. When I set my mail-client to connect to the EchoServer connects but breaks after a timeout. Obviously because it is not getting a reasonable reply ... any idea how I get similar function like the python?

答:
Found a solution by using FakeSMTP and made it to work with xinetd instead of inetd by adding this conf:</p>

```<code>service fakesmtp
{
    socket_type = stream
    protocol    = tcp
    user        = root
    wait        = no
    server      = /pathto/fake-smtp.php
}
</code>```

Title: SMTP sink socket server in PHP

Body:
Recently found this simple SMTP python script and trying to do the same in PHP.

from __future__ import print_function
from datetime import datetime
import asyncore
from smtpd import SMTPServer

class EmlServer(SMTPServer):
    no = 0
    def process_message(self, peer, mailfrom, rcpttos, data):
        filename = '%s-%d.eml' % (datetime.now().strftime('%Y%m%d%H%M%S'),
                self.no)
        f = open(filename, 'w')
        f.write(data)
        f.close
        print('%s saved.' % filename)
        self.no += 1

def run():
    # start the smtp server on localhost:1025
    foo = EmlServer(('localhost', 1025), None)
    try:
        asyncore.loop()
    except KeyboardInterrupt:
        pass

if __name__ == '__main__':
    run()

I have tried Navarr's socket class (a simple php socket server) to receive the data and save it to a file. A set up EchoServer shows when I telnet to it and type. When I set my mail-client to connect to the EchoServer connects but breaks after a timeout. Obviously because it is not getting a reasonable reply ... any idea how I get similar function like the python?

Body:
Found a solution by using FakeSMTP and made it to work with xinetd instead of inetd by adding this conf:

service fakesmtp
{
    socket_type = stream
    protocol    = tcp
    user        = root
    wait        = no
    server      = /pathto/fake-smtp.php
}


问:
ios how to read a crash log
I've never had to read a crash log before so I'm admittedly a n00b in these waters.

I can tell there was an EXC_BAD_ACCESS. How can I tell which object was released before it was supposed to be?

*note this happens after waking the device while the app is active. It doesn't always happen, but often enough.

** EDIT **

A symbolicated crash log:

```<code>Incident Identifier: 14FFD847-61CB-435B-9E98-C06B3B661429
CrashReporter Key:   7c5fd78cf04b38cfd2aa153f61eb1655ed671274
Hardware Model:      iPhone4,1
Process:         My iPhone App [2599]
Path:            /var/mobile/Applications/ABAB96ED-A203-48A5-8B50-B34BA3A8E4A4/My iPhone App.app/My iPhone App
Identifier:      My iPhone App
Version:         ??? (???)
Code Type:       ARM (Native)
Parent Process:  launchd [1]

Date/Time:       2012-07-01 22:17:43.458 -0600
OS Version:      iPhone OS 5.1 (9B179)
Report Version:  104

Exception Type:  EXC_BAD_ACCESS (SIGSEGV)
Exception Codes: KERN_INVALID_ADDRESS at 0xb4f05bbe
Crashed Thread:  0

Thread 0 name:  Dispatch queue: com.apple.main-thread
Thread 0 Crashed:
0   libobjc.A.dylib                 0x35a65f7e objc_msgSend + 22
1   UIKit                           0x33c31042 -[UIImageView isAnimating] + 130
2   UIKit                           0x33c3b100 -[UIImageView stopAnimating] + 96
3   UIKit                           0x33d5d1de -[UIActivityIndicatorView _tearDownAnimation] + 30
4   UIKit                           0x33cdb972 -[UIActivityIndicatorView _applicationDidEnterBackground:] + 34
5   Foundation                      0x37d8f4f8 __57-[NSNotificationCenter addObserver:selector:name:object:]_block_invoke_0 + 12
6   CoreFoundation                  0x37531540 ___CFXNotificationPost_block_invoke_0 + 64
7   CoreFoundation                  0x374bd090 _CFXNotificationPost + 1400
8   Foundation                      0x37d033e4 -[NSNotificationCenter postNotificationName:object:userInfo:] + 60
9   UIKit                           0x33c813f6 -[UIApplication _handleApplicationSuspend:eventInfo:] + 786
10  UIKit                           0x33c120a0 -[UIApplication handleEvent:withNewEvent:] + 2088
11  UIKit                           0x33c11708 -[UIApplication sendEvent:] + 48
12  UIKit                           0x33c110dc _UIApplicationHandleEvent + 5820
13  GraphicsServices                0x323c9224 PurpleEventCallback + 876
14  CoreFoundation                  0x3753951c __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 32
15  CoreFoundation                  0x375394be __CFRunLoopDoSource1 + 134
16  CoreFoundation                  0x3753830c __CFRunLoopRun + 1364
17  CoreFoundation                  0x374bb49e CFRunLoopRunSpecific + 294
18  CoreFoundation                  0x374bb366 CFRunLoopRunInMode + 98
19  GraphicsServices                0x323c8432 GSEventRunModal + 130
20  UIKit                           0x33c3fe76 UIApplicationMain + 1074
21  My iPhone App                   0x000f7ec2 0xdc000 + 114370
22  My iPhone App                   0x000ddc50 0xdc000 + 7248
</code>```

答:
In this case, the process may have attempted to message a deallocated object, You had better profile the application with the Zombies instrument to better understand the conditions of this crash

https://developer.apple.com/library/archive/technotes/tn2151/_index.html
This document is very good, which contains essential information about how to symbolicate, understand, and interpret crash reports.

Title: ios how to read a crash log

Body:
I've never had to read a crash log before so I'm admittedly a n00b in these waters.

I can tell there was an EXC_BAD_ACCESS. How can I tell which object was released before it was supposed to be?

*note this happens after waking the device while the app is active. It doesn't always happen, but often enough.

** EDIT **

A symbolicated crash log:

Incident Identifier: 14FFD847-61CB-435B-9E98-C06B3B661429
CrashReporter Key:   7c5fd78cf04b38cfd2aa153f61eb1655ed671274
Hardware Model:      iPhone4,1
Process:         My iPhone App [2599]
Path:            /var/mobile/Applications/ABAB96ED-A203-48A5-8B50-B34BA3A8E4A4/My iPhone App.app/My iPhone App
Identifier:      My iPhone App
Version:         ??? (???)
Code Type:       ARM (Native)
Parent Process:  launchd [1]

Date/Time:       2012-07-01 22:17:43.458 -0600
OS Version:      iPhone OS 5.1 (9B179)
Report Version:  104

Exception Type:  EXC_BAD_ACCESS (SIGSEGV)
Exception Codes: KERN_INVALID_ADDRESS at 0xb4f05bbe
Crashed Thread:  0

Thread 0 name:  Dispatch queue: com.apple.main-thread
Thread 0 Crashed:
0   libobjc.A.dylib                 0x35a65f7e objc_msgSend + 22
1   UIKit                           0x33c31042 -[UIImageView isAnimating] + 130
2   UIKit                           0x33c3b100 -[UIImageView stopAnimating] + 96
3   UIKit                           0x33d5d1de -[UIActivityIndicatorView _tearDownAnimation] + 30
4   UIKit                           0x33cdb972 -[UIActivityIndicatorView _applicationDidEnterBackground:] + 34
5   Foundation                      0x37d8f4f8 __57-[NSNotificationCenter addObserver:selector:name:object:]_block_invoke_0 + 12
6   CoreFoundation                  0x37531540 ___CFXNotificationPost_block_invoke_0 + 64
7   CoreFoundation                  0x374bd090 _CFXNotificationPost + 1400
8   Foundation                      0x37d033e4 -[NSNotificationCenter postNotificationName:object:userInfo:] + 60
9   UIKit                           0x33c813f6 -[UIApplication _handleApplicationSuspend:eventInfo:] + 786
10  UIKit                           0x33c120a0 -[UIApplication handleEvent:withNewEvent:] + 2088
11  UIKit                           0x33c11708 -[UIApplication sendEvent:] + 48
12  UIKit                           0x33c110dc _UIApplicationHandleEvent + 5820
13  GraphicsServices                0x323c9224 PurpleEventCallback + 876
14  CoreFoundation                  0x3753951c __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 32
15  CoreFoundation                  0x375394be __CFRunLoopDoSource1 + 134
16  CoreFoundation                  0x3753830c __CFRunLoopRun + 1364
17  CoreFoundation                  0x374bb49e CFRunLoopRunSpecific + 294
18  CoreFoundation                  0x374bb366 CFRunLoopRunInMode + 98
19  GraphicsServices                0x323c8432 GSEventRunModal + 130
20  UIKit                           0x33c3fe76 UIApplicationMain + 1074
21  My iPhone App                   0x000f7ec2 0xdc000 + 114370
22  My iPhone App                   0x000ddc50 0xdc000 + 7248


问:
Custom view default style not wokring without style tag
I have researched a lot and find many sources to this problem but no solutions working for me I don't know  what's going wrong.

Some resources i have look into

Custom view style, android's attributes are ignored

https://androidpedia.net/en/tutorial/1446/creating-custom-views

https://infinum.com/the-capsized-eight/how-to-support-themes-in-custom-views-for-android-apps

This is repo for this problem

https://github.com/burhankhanzada199888/CustomView-Style-StackOverflow-Question/tree/master/app

I have 2 custom view in my activity first without style tag and second with style tag but cardView style only apply when using in xml

custom_view.xml

```<code><merge xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:parentTag="com.google.android.material.card.MaterialCardView"
    tools:style="@style/CustomCardView">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginBottom="4dp"
        android:background="?colorSurface"
        android:gravity="center"
        android:orientation="horizontal">

        <ImageView
            android:id="@+id/imageView"
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:padding="8dp"
            android:src="@mipmap/ic_launcher"
            app:srcCompat="@mipmap/ic_launcher" />

        <TextView
            android:id="@+id/textView"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="?colorAccent"
            android:gravity="center"
            android:text="Lorem ipsum"
            android:textColor="@android:color/white"
            android:textSize="25sp" />

    </LinearLayout>

</merge>
</code>```

activity_main.xml

```<code> <com.myapp.CustomCardView
     android:layout_width="match_parent"
     android:layout_height="0dp"
     android:layout_weight="1" />

 <com.myapp.CustomCardView
     style="@style/CustomCardView"
     android:layout_width="match_parent"
     android:layout_height="0dp"
     android:layout_weight="1" />
</code>```

CustomCardView.java

```<code>public class CustomCardView extends MaterialCardView {

public CustomCardView(Context context) {
    this(context, null);
}

public CustomCardView(Context context, AttributeSet attrs) {
    this(context, attrs, 0);
}

public CustomCardView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);

    TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomCardView, defStyleAttr, R.style.CustomCardView);

    float imageSize = a.getDimension(R.styleable.CustomCardView_imageSize, 0);
    float textSize = a.getDimension(R.styleable.CustomCardView_textSize, 0);

    a.recycle();

    inflate(context, R.layout.custom_view, this);

    ImageView imageView = findViewById(R.id.imageView);
    imageView.getLayoutParams().height = (int) imageSize;
    imageView.getLayoutParams().width = (int) imageSize;

    TextView textView = findViewById(R.id.textView);
    textView.setTextSize(textSize);

}
</code>```

}

styles.xml

```<code><style name="CustomCardView" parent="Widget.MaterialComponents.CardView">
    <item name="cardElevation">8dp</item>
    <item name="cardCornerRadius">16dp</item>
    <item name="android:layout_margin">8dp</item>
    <item name="cardBackgroundColor">?colorPrimary</item>
    <item name="imageSize">150dp</item>
    <item name="textSize">50sp</item>
</style>
</code>```

attrs.xml

```<code><declare-styleable name="CustomCardView">
    <attr name="imageSize" format="dimension|reference" />
    <attr name="textSize" format="dimension|reference" />
</declare-styleable>
</code>```

答:
You can add in the attrs.xml:

```<code><attr format="reference" name="customCardViewStyle"/>
</code>```

Change the constructor:

```<code>public CustomCardView(Context context, AttributeSet attrs) {
    this(context, attrs, 0);
}
</code>```

to

```<code>public CustomCardView(Context context, AttributeSet attrs) {
    this(context, attrs, R.attr.customCardViewStyle);
}
</code>```

Then in your app theme add:

```<code><item name="customCardViewStyle">@style/CustomCardView</item>
</code>```

Just pay attention to <item name="android:layout_margin">...</item>. The LayoutParams are specific to the parent view type and you can't apply it with a theme.You can set the layout attributes in a style on in the layout.

Body:
I have researched a lot and find many sources to this problem but no solutions working for me I don't know  what's going wrong.

Some resources i have look into

Custom view style, android's attributes are ignored

https://androidpedia.net/en/tutorial/1446/creating-custom-views

https://infinum.com/the-capsized-eight/how-to-support-themes-in-custom-views-for-android-apps

This is repo for this problem

https://github.com/burhankhanzada199888/CustomView-Style-StackOverflow-Question/tree/master/app

I have 2 custom view in my activity first without style tag and second with style tag but cardView style only apply when using in xml

custom_view.xml

<merge xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:parentTag="com.google.android.material.card.MaterialCardView"
    tools:style="@style/CustomCardView">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginBottom="4dp"
        android:background="?colorSurface"
        android:gravity="center"
        android:orientation="horizontal">

        <ImageView
            android:id="@+id/imageView"
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:padding="8dp"
            android:src="@mipmap/ic_launcher"
            app:srcCompat="@mipmap/ic_launcher" />

        <TextView
            android:id="@+id/textView"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="?colorAccent"
            android:gravity="center"
            android:text="Lorem ipsum"
            android:textColor="@android:color/white"
            android:textSize="25sp" />

    </LinearLayout>

</merge>

activity_main.xml

 <com.myapp.CustomCardView
     android:layout_width="match_parent"
     android:layout_height="0dp"
     android:layout_weight="1" />

 <com.myapp.CustomCardView
     style="@style/CustomCardView"
     android:layout_width="match_parent"
     android:layout_height="0dp"
     android:layout_weight="1" />

CustomCardView.java

public class CustomCardView extends MaterialCardView {

public CustomCardView(Context context) {
    this(context, null);
}

public CustomCardView(Context context, AttributeSet attrs) {
    this(context, attrs, 0);
}

public CustomCardView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);

    TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomCardView, defStyleAttr, R.style.CustomCardView);

    float imageSize = a.getDimension(R.styleable.CustomCardView_imageSize, 0);
    float textSize = a.getDimension(R.styleable.CustomCardView_textSize, 0);

    a.recycle();

    inflate(context, R.layout.custom_view, this);

    ImageView imageView = findViewById(R.id.imageView);
    imageView.getLayoutParams().height = (int) imageSize;
    imageView.getLayoutParams().width = (int) imageSize;

    TextView textView = findViewById(R.id.textView);
    textView.setTextSize(textSize);

}

}

styles.xml

attrs.xml

<declare-styleable name="CustomCardView">
    <attr name="imageSize" format="dimension|reference" />
    <attr name="textSize" format="dimension|reference" />
</declare-styleable>

Body:
You can add in the attrs.xml:

<attr format="reference" name="customCardViewStyle"/>

Change the constructor:

public CustomCardView(Context context, AttributeSet attrs) {
    this(context, attrs, 0);
}

to

public CustomCardView(Context context, AttributeSet attrs) {
    this(context, attrs, R.attr.customCardViewStyle);
}

Then in your app theme add:

<item name="customCardViewStyle">@style/CustomCardView</item>

Just pay attention to <item name="android:layout_margin">...</item>. The LayoutParams are specific to the parent view type and you can't apply it with a theme.You can set the layout attributes in a style on in the layout.


问:
Correlation failed in net.core / asp.net identity / openid connect
I getting this error when a Azure AD user login (I able to get the user´s claims after), im using a combination of OpenIdConnect, with asp.net Identity core over net.core 2.0

An unhandled exception occurred while processing the request.
Exception: Correlation failed.
Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler+d__12.MoveNext()

The trace:

Exception: Correlation failed.
Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler+d__12.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.TaskAwaiter.GetResult()
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware+d__6.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware+d__7.MoveNext()

Here is my Startup.cs:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using BPT.PC.IdentityServer.Data;
using BPT.PC.IdentityServer.IdentityStore;
using BPT.PC.IdentityServer.Models;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace BPT.PC.IdentityServer.Web
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddIdentity<User, Role>()
                .AddUserStore<UserStore>()
                .AddRoleStore<RoleStore>()
                .AddDefaultTokenProviders();

            services.AddMemoryCache();
            services.AddDistributedMemoryCache();
            services.AddDbContext<IdentityServerDb>(options => options.UseSqlServer(Configuration.GetConnectionString("IdentityServerDb")));

            services.AddMvc();
            services.AddAuthentication(auth =>
            {
                auth.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                auth.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                auth.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            })
            .AddCookie()
            .AddOpenIdConnect("AzureAD", opts =>
            {
                Configuration.GetSection("OpenIdConnect").Bind(opts);
                opts.RemoteAuthenticationTimeout = TimeSpan.FromSeconds(120);
                opts.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;

                opts.CorrelationCookie = new Microsoft.AspNetCore.Http.CookieBuilder
                {
                    HttpOnly = false,
                    SameSite = Microsoft.AspNetCore.Http.SameSiteMode.None,
                    SecurePolicy = Microsoft.AspNetCore.Http.CookieSecurePolicy.None,
                    Expiration = TimeSpan.FromMinutes(10)
                };

                opts.Events = new OpenIdConnectEvents()
                {
                    OnRedirectToIdentityProvider = OnRedirectToIdentityProvider,
                    OnRemoteFailure = OnRemoteFailure,
                    OnAuthorizationCodeReceived = OnAuthorizationCodeReceived
                };
                //opts.Events = new OpenIdConnectEvents
                //{
                //    OnAuthorizationCodeReceived = ctx =>
                //    {
                //        return Task.CompletedTask;
                //    }
                //};
            });

            //services.ConfigureApplicationCookie(options =>
            //{
            //    // Cookie settings
            //    options.Cookie.HttpOnly = true;
            //    options.ExpireTimeSpan = TimeSpan.FromMinutes(30);
            //    options.SlidingExpiration = true;
            //});
        }

        private Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedContext arg)
        {
            return Task.FromResult(0);
        }

        private Task OnRemoteFailure(RemoteFailureContext arg)
        {
            return Task.FromResult(0);
        }

        private Task OnRedirectToIdentityProvider(RedirectContext arg)
        {
            return Task.FromResult(0);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseBrowserLink();
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();
            app.UseAuthentication();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Account}/{action=Login}/{id?}");
            });
        }
    }
}
</code>```

My appsettings.json:

```<code>{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  },

  "ConnectionStrings": {
    "IdentityServerDb": "Server=localhost;Database=IdentityServer;Trusted_Connection=True;MultipleActiveResultSets=true"
  },

  "OpenIdConnect": {
    "ClientId": "xxxxx",
    "Authority": "https://login.microsoftonline.com/xxxxx/",
    "PostLogoutRedirectUri": "/Account/SignoutOidc",
    "CallbackPath": "/Account/SigninOidc",
    "UseTokenLifetime": true,
    "RequireHttpsMetadata": false,
    //"ResponseType": "code id_token",
    "ClientSecret": "xxx",
    "Resource": "https://graph.microsoft.com/"
  }
}
</code>```

And the implementation:

```<code>[HttpGet]
public IActionResult CorpLogin()
{
  var authProperties = _signInManager
                .ConfigureExternalAuthenticationProperties("AzureAD",
     Url.Action("SigninOidc", "Account", null, Request.Scheme));

   return Challenge(authProperties, "AzureAD");
}

[HttpPost]
public IActionResult SigninOidc([FromForm]object data)
{
//this never runs
   return Ok();
}
</code>```

答: This issue is mostly happening when you  are running identity server on http and browser is chrome , try running the application on IE Edge or use https always should fix the issue</p>

Body:
I getting this error when a Azure AD user login (I able to get the user´s claims after), im using a combination of OpenIdConnect, with asp.net Identity core over net.core 2.0

An unhandled exception occurred while processing the request.
Exception: Correlation failed.
Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler+d__12.MoveNext()

The trace:

Exception: Correlation failed.
Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler+d__12.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.TaskAwaiter.GetResult()
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware+d__6.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware+d__7.MoveNext()

Here is my Startup.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using BPT.PC.IdentityServer.Data;
using BPT.PC.IdentityServer.IdentityStore;
using BPT.PC.IdentityServer.Models;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace BPT.PC.IdentityServer.Web
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddIdentity<User, Role>()
                .AddUserStore<UserStore>()
                .AddRoleStore<RoleStore>()
                .AddDefaultTokenProviders();

            services.AddMemoryCache();
            services.AddDistributedMemoryCache();
            services.AddDbContext<IdentityServerDb>(options => options.UseSqlServer(Configuration.GetConnectionString("IdentityServerDb")));

            services.AddMvc();
            services.AddAuthentication(auth =>
            {
                auth.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                auth.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                auth.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            })
            .AddCookie()
            .AddOpenIdConnect("AzureAD", opts =>
            {
                Configuration.GetSection("OpenIdConnect").Bind(opts);
                opts.RemoteAuthenticationTimeout = TimeSpan.FromSeconds(120);
                opts.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;

                opts.CorrelationCookie = new Microsoft.AspNetCore.Http.CookieBuilder
                {
                    HttpOnly = false,
                    SameSite = Microsoft.AspNetCore.Http.SameSiteMode.None,
                    SecurePolicy = Microsoft.AspNetCore.Http.CookieSecurePolicy.None,
                    Expiration = TimeSpan.FromMinutes(10)
                };

                opts.Events = new OpenIdConnectEvents()
                {
                    OnRedirectToIdentityProvider = OnRedirectToIdentityProvider,
                    OnRemoteFailure = OnRemoteFailure,
                    OnAuthorizationCodeReceived = OnAuthorizationCodeReceived
                };
                //opts.Events = new OpenIdConnectEvents
                //{
                //    OnAuthorizationCodeReceived = ctx =>
                //    {
                //        return Task.CompletedTask;
                //    }
                //};
            });

            //services.ConfigureApplicationCookie(options =>
            //{
            //    // Cookie settings
            //    options.Cookie.HttpOnly = true;
            //    options.ExpireTimeSpan = TimeSpan.FromMinutes(30);
            //    options.SlidingExpiration = true;
            //});
        }

        private Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedContext arg)
        {
            return Task.FromResult(0);
        }

        private Task OnRemoteFailure(RemoteFailureContext arg)
        {
            return Task.FromResult(0);
        }

        private Task OnRedirectToIdentityProvider(RedirectContext arg)
        {
            return Task.FromResult(0);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseBrowserLink();
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();
            app.UseAuthentication();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Account}/{action=Login}/{id?}");
            });
        }
    }
}

My appsettings.json:

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  },

  "ConnectionStrings": {
    "IdentityServerDb": "Server=localhost;Database=IdentityServer;Trusted_Connection=True;MultipleActiveResultSets=true"
  },

  "OpenIdConnect": {
    "ClientId": "xxxxx",
    "Authority": "https://login.microsoftonline.com/xxxxx/",
    "PostLogoutRedirectUri": "/Account/SignoutOidc",
    "CallbackPath": "/Account/SigninOidc",
    "UseTokenLifetime": true,
    "RequireHttpsMetadata": false,
    //"ResponseType": "code id_token",
    "ClientSecret": "xxx",
    "Resource": "https://graph.microsoft.com/"
  }
}

And the implementation:

[HttpGet]
public IActionResult CorpLogin()
{
  var authProperties = _signInManager
                .ConfigureExternalAuthenticationProperties("AzureAD",
     Url.Action("SigninOidc", "Account", null, Request.Scheme));

   return Challenge(authProperties, "AzureAD");
}

[HttpPost]
public IActionResult SigninOidc([FromForm]object data)
{
//this never runs
   return Ok();
}


问:
How to reload the current page once without changing the URL in javascript?
I am using the following javascript code to set a language cookie for users when they visit my site:

```<code>function setCookie(name, value, expires) {
    var expires = "";
    if(expires) {
        var date = new Date();
        date.setTime(date.getTime() + (expires * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toUTCString();
    }
    document.cookie = name + "=" + (value || "")  + expires + "; path=/";
}
function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while(c.charAt(0) == ' ') {
            c = c.substring(1, c.length);
        }
        if(c.indexOf(nameEQ) == 0) {
            return c.substring(nameEQ.length, c.length);
        }
    }
    return null;
}
function delCookie(name) {
    document.cookie = name+'=; expires=Wed, 31 Dec 1969 23:59:59 GMT; path=/'; // expires=-1
}

// After the page has finished loading, check that the user already has a language cookie?
document.addEventListener('DOMContentLoaded', function() {
    var lang = navigator.language || navigator.browserLanguage || navigator.userLanguage || navigator.systemLanguage;
    lang = lang.slice(0, 2).toLowerCase();
    if(!getCookie('language')) { // If not, set language cookie
        if(lang == 'vi') {
            setCookie('language', 'vi');
        }
        else {
            setCookie('language', 'en');
        }
    }
    if(getCookie('language')) { // If the user already has a language cookie
        if(getCookie('language') != 'vi' || getCookie('language') != 'en') { // If the user's language cookie is not supported
            setCookie('language', 'en'); // Then use English as the default
        }
    }
}, false);
</code>```

Now, I want after setting the language cookie for the user, the current page will be reloaded once without changing the URL (without adding the hash #, parameter,...).

I tried setting the cookie, then using location.reload(), once reloading will delete that cookie as follows:

```<code>// ... Skip Cookie Code ...
document.addEventListener('DOMContentLoaded', function() {
    var lang = navigator.language || navigator.browserLanguage || navigator.userLanguage || navigator.systemLanguage;
    lang = lang.slice(0, 2).toLowerCase();
    if(!getCookie('language')) {
        if(lang == 'vi') {
            setCookie('language', 'vi');
            setCookie('needreload', 'yes');
        }
        else {
            setCookie('language', 'en');
            setCookie('needreload', 'yes');
        }
    }
    if(getCookie('language')) {
        if(getCookie('language') != 'vi' || getCookie('language') != 'en') {
            setCookie('language', 'en');
            setCookie('needreload', 'yes');
        }
    }
    if(getCookie('needreload') == 'yes') {
        location.reload();
        delCookie('needreload');
    }
}, false);
</code>```

However, that makes my website reload constantly, infinite times instead of just once.

Please show me the method to solve this problem. I would appreciate the solution you give!

答:
I found the problem, is the code check the user's language cookie is supported have problem. I have to use && instead of || over there. If I use || then it is always true even if the user's language cookie is supported, resulting in an infinite page reload loop. Here is the code that worked fine:

```<code>document.addEventListener('DOMContentLoaded', function() {
    var lang = navigator.language || navigator.browserLanguage || navigator.userLanguage || navigator.systemLanguage;
    lang = lang.slice(0, 2).toLowerCase();
    if(!getCookie('language')) {
        if(lang == 'vi') {
            setCookie('language', 'vi');
        }
        else {
            setCookie('language', 'en');
        }
        setCookie('needreload', '1');
    }
    if(getCookie('language')) { // If it already exists
        if(getCookie('language') != 'vi' && getCookie('language') != 'en') { // Use && instead of || will make it work
            setCookie('language', 'en');
            setCookie('needreload', '1');
        }
    }
    if(getCookie('language') == '1') {
        location.reload();
        delCookie('needreload');
    }
}, false);
</code>```

Body:
I am using the following javascript code to set a language cookie for users when they visit my site:

function setCookie(name, value, expires) {
    var expires = "";
    if(expires) {
        var date = new Date();
        date.setTime(date.getTime() + (expires * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toUTCString();
    }
    document.cookie = name + "=" + (value || "")  + expires + "; path=/";
}
function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while(c.charAt(0) == ' ') {
            c = c.substring(1, c.length);
        }
        if(c.indexOf(nameEQ) == 0) {
            return c.substring(nameEQ.length, c.length);
        }
    }
    return null;
}
function delCookie(name) {
    document.cookie = name+'=; expires=Wed, 31 Dec 1969 23:59:59 GMT; path=/'; // expires=-1
}

// After the page has finished loading, check that the user already has a language cookie?
document.addEventListener('DOMContentLoaded', function() {
    var lang = navigator.language || navigator.browserLanguage || navigator.userLanguage || navigator.systemLanguage;
    lang = lang.slice(0, 2).toLowerCase();
    if(!getCookie('language')) { // If not, set language cookie
        if(lang == 'vi') {
            setCookie('language', 'vi');
        }
        else {
            setCookie('language', 'en');
        }
    }
    if(getCookie('language')) { // If the user already has a language cookie
        if(getCookie('language') != 'vi' || getCookie('language') != 'en') { // If the user's language cookie is not supported
            setCookie('language', 'en'); // Then use English as the default
        }
    }
}, false);

Now, I want after setting the language cookie for the user, the current page will be reloaded once without changing the URL (without adding the hash #, parameter,...).

I tried setting the cookie, then using location.reload(), once reloading will delete that cookie as follows:

// ... Skip Cookie Code ...
document.addEventListener('DOMContentLoaded', function() {
    var lang = navigator.language || navigator.browserLanguage || navigator.userLanguage || navigator.systemLanguage;
    lang = lang.slice(0, 2).toLowerCase();
    if(!getCookie('language')) {
        if(lang == 'vi') {
            setCookie('language', 'vi');
            setCookie('needreload', 'yes');
        }
        else {
            setCookie('language', 'en');
            setCookie('needreload', 'yes');
        }
    }
    if(getCookie('language')) {
        if(getCookie('language') != 'vi' || getCookie('language') != 'en') {
            setCookie('language', 'en');
            setCookie('needreload', 'yes');
        }
    }
    if(getCookie('needreload') == 'yes') {
        location.reload();
        delCookie('needreload');
    }
}, false);

However, that makes my website reload constantly, infinite times instead of just once.

Please show me the method to solve this problem. I would appreciate the solution you give!

Body:
I found the problem, is the code check the user's language cookie is supported have problem. I have to use && instead of || over there. If I use || then it is always true even if the user's language cookie is supported, resulting in an infinite page reload loop. Here is the code that worked fine:

document.addEventListener('DOMContentLoaded', function() {
    var lang = navigator.language || navigator.browserLanguage || navigator.userLanguage || navigator.systemLanguage;
    lang = lang.slice(0, 2).toLowerCase();
    if(!getCookie('language')) {
        if(lang == 'vi') {
            setCookie('language', 'vi');
        }
        else {
            setCookie('language', 'en');
        }
        setCookie('needreload', '1');
    }
    if(getCookie('language')) { // If it already exists
        if(getCookie('language') != 'vi' && getCookie('language') != 'en') { // Use && instead of || will make it work
            setCookie('language', 'en');
            setCookie('needreload', '1');
        }
    }
    if(getCookie('language') == '1') {
        location.reload();
        delCookie('needreload');
    }
}, false);


问:
Can someone show me how to make a unit test for this method?
I want to make a unit test for a game I have made, this code below is a simple move command for a grid-based game whereby when the user clicks a button the method is attached to, the player is moved up 1 row.</p>

```<code>public String moveUp() {     //Allows player to move when corresponding command is entered
        int targetRow;
        int targetCol;

        targetRow = goldMiner.getRow() - 1;
        targetCol = goldMiner.getCol();

        String response = "";
        //If player does not have enough stamina they will not be allowed to move
        if (goldMiner.getStamina() <= 0) {
            response = "You are out of Stamina";
        //Stops player from moving outside of map
        } else if (targetRow < 0) {
            response = "You can't move that way";
        //If all parameters are met allows player to move in corresponding direction
        } else {
            PlayerMove(targetRow, targetCol);
            response = "You moved Up";
        }
        return response;
    }

</code>```

答:
For this method, you need three unit tests to cover all the code and you also need to mock goldMiner. The unit test would be like the below code:

public UnitTest {
  Mock GoldMiner goldMiner;
  @Autowired
  Service service; // assume moveUp method in this service
  @BeforeEach
  void setUp() {
        goldMiner = mock(GoldMiner.class);
  }

  @Test
  public void shouldGetStamia_thenReturnOutof() {
   // You are out of Stamina
   when(goldMiner.getStamina()).thenReturn(-1);
   String response = service.moveUp();
   assertEquals(response, "You are out of Stamina");
  }

  //then another two cases are similar
  @Test
  public void shouldRowLessThanZero_thenCannotMove() {

  }

  @Test
  public void shouldNormal_thenMoveUp() {

  }
}

```

Body:
I want to make a unit test for a game I have made, this code below is a simple move command for a grid-based game whereby when the user clicks a button the method is attached to, the player is moved up 1 row.

public String moveUp() {     //Allows player to move when corresponding command is entered
        int targetRow;
        int targetCol;

        targetRow = goldMiner.getRow() - 1;
        targetCol = goldMiner.getCol();

        String response = "";
        //If player does not have enough stamina they will not be allowed to move
        if (goldMiner.getStamina() <= 0) {
            response = "You are out of Stamina";
        //Stops player from moving outside of map
        } else if (targetRow < 0) {
            response = "You can't move that way";
        //If all parameters are met allows player to move in corresponding direction
        } else {
            PlayerMove(targetRow, targetCol);
            response = "You moved Up";
        }
        return response;
    }


问:
How can I smoothly detect the welding joint using OpenCV-Python?
I have tried to detect the welding joint (bead) using the codes attached below in the last part of this question. I aim to draw a contour on the joint as shown in the third image but my results are poor and don't look similar to the expected results. here is the summary of what I did but the codes are well clear:
1. Reading the image .jpg format
2. Image blurring
3. Thresholding
4. Morphological operations
5. Creating mask
6. Finding contour

But the results are not promising, how can I get out from here

```<code>img_new = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
blur_image = cv2.bilateralFilter(img_new,5,21,21)
thresh = cv2.adaptiveThreshold(blur_image,255,
                               cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
                               cv2.THRESH_BINARY_INV,15,3)
kernel = np.ones((5,5),dtype='uint8')
thresh_dilated = cv2.dilate(thresh, kernel, iterations = 1)
num_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(thresh_dilated, connectivity=4)
sizes = stats[1:,-1]
min_size = 5000
num_labels = num_labels -1
img2 = np.zeros((labels.shape))
for i in range(0,num_labels):
    if sizes[i]>=min_size:
        img2[labels==i+1]=255
closing = cv2.morphologyEx(img2,cv2.MORPH_CLOSE,kernel)
opening = cv2.morphologyEx(closing,cv2.MORPH_OPEN,kernel)
result = opening.copy()
new_result = result.astype(dtype=np.uint8)

black = np.full((new_result.shape[0],new_result.shape[1],3),(0,0,0),np.uint8)
black1 = cv2.ellipse(black,(700,750),(300,140),0,0,360,(255,255,255),-1)
grayscale = cv2.cvtColor(black1,cv2.COLOR_BGR2GRAY)
ret,b_mask = cv2.threshold(grayscale,127,255,0)
img_result = cv2.bitwise_and(new_result,b_mask)

contours, hierarchy = cv2.findContours(img_result, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(img, contours, -1, (0,255,0), 2)
cv2.imshow('result',img)
cv2.waitKey(0)```
```

答:
Read any papers?

Is this for automatic processing of many welding joints on an assembly line? Does this have to work for many other similiar images? It does not make sense to fine tune an algorithm for a single picture in that case.

If yes, than you need to use more images to create the algorithm, maybe use a different light setup, maybe images taken with an IR camera right after the welding to get a "hot" mask. Or use light from left and right sight separately to combine two images for a single mark.

Another thing that would be very helpful is to get a "before" image from the parts. without the welding joint. In that case it could get easy. You would just create the difference between the images, do some filtering to remove the welding beads and the reddish layer.

Edit 1:

Another thing I forgot to mention is please look at the RGB layers separately. This is something that you should always try early on. Often there is something useful to see, e.g. in your case it could be that the blue layer might be interesting. Please add the layers to your question.

Body:
I have tried to detect the welding joint (bead) using the codes attached below in the last part of this question. I aim to draw a contour on the joint as shown in the third image but my results are poor and don't look similar to the expected results. here is the summary of what I did but the codes are well clear:
1. Reading the image .jpg format
2. Image blurring
3. Thresholding
4. Morphological operations
5. Creating mask
6. Finding contour

But the results are not promising, how can I get out from here

img_new = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
blur_image = cv2.bilateralFilter(img_new,5,21,21)
thresh = cv2.adaptiveThreshold(blur_image,255,
                               cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
                               cv2.THRESH_BINARY_INV,15,3)
kernel = np.ones((5,5),dtype='uint8')
thresh_dilated = cv2.dilate(thresh, kernel, iterations = 1)
num_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(thresh_dilated, connectivity=4)
sizes = stats[1:,-1]
min_size = 5000
num_labels = num_labels -1
img2 = np.zeros((labels.shape))
for i in range(0,num_labels):
    if sizes[i]>=min_size:
        img2[labels==i+1]=255
closing = cv2.morphologyEx(img2,cv2.MORPH_CLOSE,kernel)
opening = cv2.morphologyEx(closing,cv2.MORPH_OPEN,kernel)
result = opening.copy()
new_result = result.astype(dtype=np.uint8)

black = np.full((new_result.shape[0],new_result.shape[1],3),(0,0,0),np.uint8)
black1 = cv2.ellipse(black,(700,750),(300,140),0,0,360,(255,255,255),-1)
grayscale = cv2.cvtColor(black1,cv2.COLOR_BGR2GRAY)
ret,b_mask = cv2.threshold(grayscale,127,255,0)
img_result = cv2.bitwise_and(new_result,b_mask)

contours, hierarchy = cv2.findContours(img_result, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(img, contours, -1, (0,255,0), 2)
cv2.imshow('result',img)
cv2.waitKey(0)```


答:
I suggest using JUnit5.

One simple example:

```<code>import org.junit.Test;
import org.junit.Assert;

public class Tests {

  @Test     //This is needed
  public void testOne() {
    String response = moveUp(); //Call method
    Assert.assertEquals("expectedValue", response); //Comparing expectedValue with response
  }
}
</code>```

This method will test, whether response equals to the expected value (you will have to replace "expectedValue" with the real value).

I highly suggest to use an IDE like Eclipse to do Unit-tests. In Eclipse, you will have to import JUnit like explained here.

Please note: You can also have more than one test-method in Tests.java.

Title: Can someone show me how to make a unit test for this method?

Body:
I suggest using JUnit5.

One simple example:

import org.junit.Test;
import org.junit.Assert;

public class Tests {

  @Test     //This is needed
  public void testOne() {
    String response = moveUp(); //Call method
    Assert.assertEquals("expectedValue", response); //Comparing expectedValue with response
  }
}

This method will test, whether response equals to the expected value (you will have to replace "expectedValue" with the real value).

I highly suggest to use an IDE like Eclipse to do Unit-tests. In Eclipse, you will have to import JUnit like explained here.

Please note: You can also have more than one test-method in Tests.java.


问:
Use same database for Django and Laravel

I'm using Django for backend, but for some reason, I want to use Laravel beside Django and share the database between them. so the same database for Django and Laravel. but the problem is that Django migrations are not equal to Laravel migrations so the database is different from ( for example constraints and indexes and some other options).

Is this going to break backend if I use Django as the primary database and use Laravel as a secondary backend?

If true, how I can use Django and Laravel in the same database?

答:
Your database does not depend on Django or Laravel. It just stores data.

Constraints, triggers, indexes, etc are stored on the database itself, and they are completely independent of your framework. Frameworks just abstract the methods and provide easy methods to manage your database. At the core, they use the same commands which are provided by the database. The names of constraints are irrelevant, you can give whatever names you want, frameworks just provide their own uniform naming pattern, which can be customized by the user. So they can be used on both Django and Laravel or any other framework/programming language. That's the main purpose of having a database, to store data in a structured manner so it can be used by any language/framework

Since you already have migrations in Django, there's no need to create the migrations again in laravel. Just reuse the Django database and make your laravel application to properly handle the data (that part is completely in your control)


问:
Looping through a data array and giving a from control name to an input field does not work correctly?
Problem:

I am rendering input sets through a loop in angular. So in there I am setting form control name to the input field like this.

```<code><input  formControlName="{{data.attributeName}}  min="1" id="{{data.id}}" type="{{data.type}}" />
</code>```

But when I see the source in the inspect window it is not showing the form control name with the input field. Can someone help me to find out a way to solve this issue? Thank you very much.

答:
```<code><input [formControlName]="data.attributeName"  [id]="data.id"   [type]="data.type">
</code>```

You have to use property binding.

Body:
Problem:

I am rendering input sets through a loop in angular. So in there I am setting form control name to the input field like this.

<input  formControlName="{{data.attributeName}}  min="1" id="{{data.id}}" type="{{data.type}}" />

But when I see the source in the inspect window it is not showing the form control name with the input field. Can someone help me to find out a way to solve this issue? Thank you very much.

Body:
<input [formControlName]="data.attributeName"  [id]="data.id"   [type]="data.type">

You have to use property binding.


问:
PHP- Get file type by URL
I want to get the file type (eg. image/gif) by URL using PHP.I had tried

```<code><?php
$image_path="http://fc04.deviantart.net/fs71/f/2010/227/4/6/PNG_Test_by_Destron23.png";
exif_imagetype($image_path);
?>
</code>```

The above code gave me a blank page and the following code returned "3":

```<code><?php
$image_path="http://fc04.deviantart.net/fs71/f/2010/227/4/6/PNG_Test_by_Destron23.png";
echo exif_imagetype($image_path);
?>
</code>```

Where am I going wrong?
Solved: using Fileinfo to fetch content type

答:
the best way for my understanding </p>

```<code>if (!function_exists('getUrlMimeType')) {
    function getUrlMimeType($url)
    {
        $buffer = file_get_contents($url);
        $finfo = new finfo(FILEINFO_MIME_TYPE);
        return $finfo->buffer($buffer);
    }
}
</code>```

<p>is to create function depend on finfo class </p>

Title: PHP- Get file type by URL

Body:
I want to get the file type (eg. image/gif) by URL using PHP.I had tried

<?php
$image_path="http://fc04.deviantart.net/fs71/f/2010/227/4/6/PNG_Test_by_Destron23.png";
exif_imagetype($image_path);
?>

The above code gave me a blank page and the following code returned "3":

<?php
$image_path="http://fc04.deviantart.net/fs71/f/2010/227/4/6/PNG_Test_by_Destron23.png";
echo exif_imagetype($image_path);
?>

Where am I going wrong?
Solved: using Fileinfo to fetch content type

Body:
the best way for my understanding

if (!function_exists('getUrlMimeType')) {
    function getUrlMimeType($url)
    {
        $buffer = file_get_contents($url);
        $finfo = new finfo(FILEINFO_MIME_TYPE);
        return $finfo->buffer($buffer);
    }
}

is to create function depend on finfo class


问:
How can I detect the IP addresses of other devices on the local network?
I already detect local IP address of my computer using this code (use sockets):

```<code>Function Ip_Local : String;
  Var Acces_Sock : TCustomIpClient;
Begin
  Acces_Sock := TCustomIpClient.Create(Nil);
  Try
    Result := Acces_Sock.LocalHostAddr
  Finally
    Acces_Sock.Free;
  End;
End;
</code>```

What about detecting the internal LAN IP address of the router and, if possible, of any LAN-connected appliance such as a DVR?

答:
Using Indy:</p>

```<code>function CsiGetRemoteIpAddress(const pHostName: string): string;
begin
  TIdStack.IncUsage;
  try
    Result := GStack.ResolveHost(pHostName);
  finally
    TIdStack.DecUsage;
  end;
end;
</code>```

Body:
I already detect local IP address of my computer using this code (use sockets):

Function Ip_Local : String;
  Var Acces_Sock : TCustomIpClient;
Begin
  Acces_Sock := TCustomIpClient.Create(Nil);
  Try
    Result := Acces_Sock.LocalHostAddr
  Finally
    Acces_Sock.Free;
  End;
End;

What about detecting the internal LAN IP address of the router and, if possible, of any LAN-connected appliance such as a DVR?

Body:
Using Indy:

function CsiGetRemoteIpAddress(const pHostName: string): string;
begin
  TIdStack.IncUsage;
  try
    Result := GStack.ResolveHost(pHostName);
  finally
    TIdStack.DecUsage;
  end;
end;