问:
Storybook is loading stories from a yarn/lerna monorepo's packages' node_modules folder
I'm using storybook in a lerna/yarn workspaces monorepo. I noticed today that storybook is trying to load stories from packages/**/node_modules/@scope/foo/stories/foo.stories.js I've tried logging out the require.context keys in config.js but its not logged to console. Is there a ready way to tell storybook not to load symlinked local node_modules? Is it likely I've misconfigured storybook? Here's my config:

import '@storybook/addon-console';
import { withA11y } from '@storybook/addon-a11y';
import { addDecorator, addParameters, configure } from '@storybook/polymer';

import theme from './my-theme'

const req = require.context('../packages', true, /\.stories\.js$/);
const load = filename =>  req(filename);

addParameters({ options: {
  panelPosition: 'right',
  theme,
} })

addDecorator(withA11y)

configure(function loadStories() {
  req.keys()
    .filter(filename => !filename.match(/packages\/.*\/node_modules/))
    .forEach(load);
}, module);
```

<p>example error:</p>

```ERROR in ./packages/input/node_modules/@scope/collapse/stories/collapse.stories.js
Module not found: Error: Can't resolve '../../button/src/my-button' in '/Users/bennyp/Documents/web-components/packages/input/node_modules/@scope/collapse/stories'
```

This causes the storybook build to break.

How do I tell storybook not to load stories from internal node_modules?

答:
The following regex solved the problem

const req = require.context('../packages', true,
  /^((?![\\/]node_modules[\\/]).)*\.stories\.js$/
);
```

Body:
I'm using storybook in a lerna/yarn workspaces monorepo. I noticed today that storybook is trying to load stories from packages/**/node_modules/@scope/foo/stories/foo.stories.js I've tried logging out the require.context keys in config.js but its not logged to console. Is there a ready way to tell storybook not to load symlinked local node_modules? Is it likely I've misconfigured storybook? Here's my config:

import '@storybook/addon-console';
import { withA11y } from '@storybook/addon-a11y';
import { addDecorator, addParameters, configure } from '@storybook/polymer';

import theme from './my-theme'

const req = require.context('../packages', true, /\.stories\.js$/);
const load = filename =>  req(filename);

addParameters({ options: {
  panelPosition: 'right',
  theme,
} })

addDecorator(withA11y)

configure(function loadStories() {
  req.keys()
    .filter(filename => !filename.match(/packages\/.*\/node_modules/))
    .forEach(load);
}, module);

example error:

ERROR in ./packages/input/node_modules/@scope/collapse/stories/collapse.stories.js
Module not found: Error: Can't resolve '../../button/src/my-button' in '/Users/bennyp/Documents/web-components/packages/input/node_modules/@scope/collapse/stories'

This causes the storybook build to break.

How do I tell storybook not to load stories from internal node_modules?


来源: stackexchange

问:
How to remove top status bar black background
I'd like to create a TRUE fullscreen activity, but there is always a black status bar on screen top. Android 9.0.

I've tried almost all I can find with Google and existing Apps with similar jobs. Manifest, code, style, AS sample fullscreen activity, all were tried.

styles.xml:

```

<p>Manifest:</p>

<pre class="lang-xml prettyprint-override"><code><activity android:name=".ScreenActivity" android:theme="@style/AppThemeA" />
</code>```

Layout:

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <FrameLayout
        android:id="@+id/rootLayout"
        android:fitsSystemWindows="true"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</androidx.coordinatorlayout.widget.CoordinatorLayout>
```

<p>Kotlin (commented lines are tried and failed):</p>

```class ScreenActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        //setTheme(R.style.AppThemeDetector)
        super.onCreate(savedInstanceState)

        //window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN)
        //window.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS)
        //window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY or View.SYSTEM_UI_FLAG_FULLSCREEN

        /*
        window.decorView.systemUiVisibility = (
                View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        or View.SYSTEM_UI_FLAG_FULLSCREEN
                )*/

        setContentView(R.layout.activity_screen_detector)
        ...
    }
}
```

The expected result:

What I actually got:

[[[[ Solution ]]]]

Found what caused this. You should set the App to FullScreen App in Settings -> Display.

https://www.gottabemobile.com/how-to-enable-full-screen-apps-on-galaxy-s10

So fixed. Thanks for all your help.

答:
Here's a way to implement the edge-to-edge display starting from Android Q. The code is inspired by this blog.

First, in your styles.xml, modify the AppTheme like:

```<code><style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar">
        ...
    <item name="android:navigationBarColor">@android:color/transparent</item>
    <item name="android:statusBarColor">@android:color/transparent</item>
</style>
</code>```

Suppose, we need to make the MainActivity fullscreen, then in MainActivity.kt:

```<code>window.decorView.systemUiVisibility = (
                View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        or View.SYSTEM_UI_FLAG_FULLSCREEN
                )
</code>```

Also, check the docs here for enabling fullscreen mode.

ContentLicense: CC BY-SA 4.0

Body:
I'd like to create a TRUE fullscreen activity, but there is always a black status bar on screen top. Android 9.0.

I've tried almost all I can find with Google and existing Apps with similar jobs. Manifest, code, style, AS sample fullscreen activity, all were tried.

styles.xml:

Manifest:

<activity android:name=".ScreenActivity" android:theme="@style/AppThemeA" />

Layout:

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <FrameLayout
        android:id="@+id/rootLayout"
        android:fitsSystemWindows="true"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</androidx.coordinatorlayout.widget.CoordinatorLayout>

Kotlin (commented lines are tried and failed):

class ScreenActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        //setTheme(R.style.AppThemeDetector)
        super.onCreate(savedInstanceState)

        //window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN)
        //window.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS)
        //window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY or View.SYSTEM_UI_FLAG_FULLSCREEN

        /*
        window.decorView.systemUiVisibility = (
                View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        or View.SYSTEM_UI_FLAG_FULLSCREEN
                )*/

        setContentView(R.layout.activity_screen_detector)
        ...
    }
}

The expected result:

What I actually got:

[[[[ Solution ]]]]

Found what caused this. You should set the App to FullScreen App in Settings -> Display.

https://www.gottabemobile.com/how-to-enable-full-screen-apps-on-galaxy-s10

So fixed. Thanks for all your help.

Body:
Here's a way to implement the edge-to-edge display starting from Android Q. The code is inspired by this blog.

First, in your styles.xml, modify the AppTheme like:

<style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar">
        ...
    <item name="android:navigationBarColor">@android:color/transparent</item>
    <item name="android:statusBarColor">@android:color/transparent</item>
</style>

Suppose, we need to make the MainActivity fullscreen, then in MainActivity.kt:

window.decorView.systemUiVisibility = (
                View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        or View.SYSTEM_UI_FLAG_FULLSCREEN
                )

Also, check the docs here for enabling fullscreen mode.


问:
Why is this query adding null to the table instead of the selected string?
I am running the below query in Oracle SQL. Table has 2 columns, first is rowid type and second is a varchar.

```<code>INSERT INTO MYTABLE SELECT 'AAAAAAAAAAAAAAAAAA' RID, NULL FROM DUAL;
</code>```

The result is adding null in both columns.

Why is this happening?

Shouldn't 'AAAAAAAAAAAAAAAAAA' be added to the first column of the table?

答:
When you are adding 'AAAAAAAAAAAAAAAAAA' into rowid datatype column then oracle converts string to rowid and store it there.

```<code>select chartorowid('AAAAAAAAAAAAAAAAAA') from dual; -- Result: NULL
</code>```

'AAAAAAAAAAAAAAAAAA' rowid do not represent any physical location. In fact, Oracle uses 'AAAAAAAAAAAAAAAAAA' rowid to represent rows which are currently processed but do not exist physically. e.g. In trigger (new row).

Consider mentioned rowid as a special rowid used by Oracle which is allocated to all the rows which exist logically, not physically.

Hope, This is the answer you are looking for.

Body:
I am running the below query in Oracle SQL. Table has 2 columns, first is rowid type and second is a varchar.

INSERT INTO MYTABLE SELECT 'AAAAAAAAAAAAAAAAAA' RID, NULL FROM DUAL;

The result is adding null in both columns.

Why is this happening?

Shouldn't 'AAAAAAAAAAAAAAAAAA' be added to the first column of the table?

Body:
When you are adding 'AAAAAAAAAAAAAAAAAA' into rowid datatype column then oracle converts string to rowid and store it there.

select chartorowid('AAAAAAAAAAAAAAAAAA') from dual; -- Result: NULL

'AAAAAAAAAAAAAAAAAA' rowid do not represent any physical location. In fact, Oracle uses 'AAAAAAAAAAAAAAAAAA' rowid to represent rows which are currently processed but do not exist physically. e.g. In trigger (new row).

Consider mentioned rowid as a special rowid used by Oracle which is allocated to all the rows which exist logically, not physically.

Hope, This is the answer you are looking for.


问:
How to insert a CSS tranform rotate animation in JS fadein and fadeout slideshow?
I'm having an idea but I cannot apply it because I am not very familiar with Javascript. My problem is I have a JS script for fadein and fadeout slideshow, however, it seems to be nice to have a page rotation during transition. I have a CSS hover style to do this [.card:hover .card__side--front {transform: rotateY(-180deg); }] but I don't know how to integrate it in the JS script. Here is the JS script of the slideshow:</p>

```<code><script>
  $("#slideshow > div:gt(0)").hide();

setInterval(function() {
  $('#slideshow > div:first')
    .fadeOut(3000)
    .next()
    .fadeIn(3000)
    .end()
    .appendTo('#slideshow')
;
    ;
},  30000);
</script>
</code>```

答:
You may try out like,

var imgDuration = 3000;

function slideShow() {
    document.getElementById('slider').className += "fadeOut";
    setTimeout(function() {
        document.getElementById('slider').className = "";
    },1000);
    setTimeout(slideShow, imgDuration);
}
slideShow();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#slider {
    width:100px;
    height:70px;
    opacity:1;
    transition: all 1s;
}

#slider.fadeOut {
    opacity:0;
    transform: rotate(1800deg);
}</code>```

```

I have changed the code from the following reference,

REFERENCE: http://jsfiddle.net/pdb4kb1a/2/

Body:
You may try out like,

var imgDuration = 3000;

function slideShow() {
    document.getElementById('slider').className += "fadeOut";
    setTimeout(function() {
        document.getElementById('slider').className = "";
    },1000);
    setTimeout(slideShow, imgDuration);
}
slideShow();

#slider {
    width:100px;
    height:70px;
    opacity:1;
    transition: all 1s;
}

#slider.fadeOut {
    opacity:0;
    transform: rotate(1800deg);
}

<img id="slider" src="http://pngriver.com/wp-content/uploads/2018/03/Download-Batman-Fidget-Spinner-PNG-Transparent-058.png">

I have changed the code from the following reference,

REFERENCE: http://jsfiddle.net/pdb4kb1a/2/


问:
How to display html class HTML in PHP through echo?
I have a html code:

```<code>  <div class="col-lg-4 col-sm-6" id="filterDiv">
                            <a href="<?php echo $result['company_link']; ?>" class="feature feature-4 feature-center animated" data-animate="fadeInUp" data-delay=".3">
                                <div class="feature-img">
                                    <img src="images/products/a.jpg" alt="product">
                                </div>
                                <h5 class="title title-sm title-dark"><?php echo $result['company_name']; ?></h5>
                                <span id="myCategory">Category: </span> <?php echo $result['company_category']; ?> ||
                                <span id="myLocation">Location: </span> <?php echo $result['company_location']; ?>
                            </a>
                        </div>
</code>```

I want to display this code in PHP. Can anybody Help me out in this?
Thanks in advance.

I have tried this code but it didn't work:

```<code>echo "<div class='nk-block nk-block-features-4 mgb-m30'>";
 echo  " <div class='row'>";
 echo "<div class=\"col-lg-4 col-sm-6\" id=\"filterDiv\">";
</code>```

Parse error:

```<code>syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting '-' or identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) in C:\xampp\htdocs\asaworkholding\ajax\category-search.php on line 31
</code>```

答:
Syntax Error, Please use this code

```<code>  echo "<div class='nk-block nk-block-features-4 mgb-m30'>";
     echo  " <div class='row'>";
     echo "<div class='col-lg-4 col-sm-6' id='filterDiv'>";
</code>```

Hope this helps you

Body:
I have a html code:

                            <a href="<?php echo $result['company_link']; ?>" class="feature feature-4 feature-center animated" data-animate="fadeInUp" data-delay=".3">

<?php echo $result['company_name']; ?>

                                Category:  <?php echo $result['company_category']; ?> ||
                                Location:  <?php echo $result['company_location']; ?>

I want to display this code in PHP. Can anybody Help me out in this?
Thanks in advance.

I have tried this code but it didn't work:

echo "
";
 echo  "
";
 echo "
";

Parse error:

syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting '-' or identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) in C:\xampp\htdocs\asaworkholding\ajax\category-search.php on line 31

Body:
Syntax Error, Please use this code

  echo "<div class='nk-block nk-block-features-4 mgb-m30'>";
     echo  " <div class='row'>";
     echo "<div class='col-lg-4 col-sm-6' id='filterDiv'>";

Hope this helps you


问:
How to pass custom parameters in header request
I have to call an API, I need to pass username and password along with header request. How to call API from angular service?

I tried with this code:

```<code>    checkUserApi(url: string): Observable<any> {
       const headers = new HttpHeaders()
           .set('Content-Type', 'application/json')
           .set('Accept', 'text/plain')
          .set('userName', 'username')
         .set('password', 'password');
    return this.http.post(url, { headers })
      .map((response: Response) => {
        console.log("response : " +response);
        return response;
      })
   }
</code>```

答:
To have the $resource .login method compute the header string at method invocation time, the header configuration needs to have a header property with a value which is a function declaration, not a function invocation.</p>

```<code> //resources
var Authentication = $resource('/users/authentication',{},{
    login:{
        method: 'GET',
        isArray: false,
        //USE function declaration
        headers: {
           'Authentication':
                function () {
                    return btoa(getUserCredentials())
                }
        }
        //NOT function invocation
        //headers: {'Authentication':btoa(getUserCredentials())}
    }
});
</code>```

Body:
I have to call an API, I need to pass username and password along with header request. How to call API from angular service?

I tried with this code:

    checkUserApi(url: string): Observable<any> {
       const headers = new HttpHeaders()
           .set('Content-Type', 'application/json')
           .set('Accept', 'text/plain')
          .set('userName', 'username')
         .set('password', 'password');
    return this.http.post(url, { headers })
      .map((response: Response) => {
        console.log("response : " +response);
        return response;
      })
   }

Body:
To have the $resource .login method compute the header string at method invocation time, the header configuration needs to have a header property with a value which is a function declaration, not a function invocation.

 //resources
var Authentication = $resource('/users/authentication',{},{
    login:{
        method: 'GET',
        isArray: false,
        //USE function declaration
        headers: {
           'Authentication':
                function () {
                    return btoa(getUserCredentials())
                }
        }
        //NOT function invocation
        //headers: {'Authentication':btoa(getUserCredentials())}
    }
});


问:
How to convert month name to number in unix?
Input :

```<code>01-DEC-18|"0308"|"RUB"
01-DEC-18|"0308"|"RUB"
01-DEC-18|"0308"|"RUB"
01-DEC-18|"0308"|"RUB"
</code>```

Expected output :

```<code>01-12-18|"0308"|"RUB"
01-12-18|"0308"|"RUB"
01-12-18|"0308"|"RUB"
01-12-18|"0308"|"RUB"
</code>```

How do I convert the abbreviated month name to month number and achieve the expected output?

答:
you mean something like this?</p>

```<code>#!/bin/bash
while  read -r line; do
   # use date to convert first column of line
   newdate=$(date -d "${line%%|*}" +"%d-%m-%y")

   # print new date and the last two columns
   printf "%s|%s\n" "$newdate" "${line#*|}"
done < input
</code>```

Body:
Input :

01-DEC-18|"0308"|"RUB"
01-DEC-18|"0308"|"RUB"
01-DEC-18|"0308"|"RUB"
01-DEC-18|"0308"|"RUB"

Expected output :

01-12-18|"0308"|"RUB"
01-12-18|"0308"|"RUB"
01-12-18|"0308"|"RUB"
01-12-18|"0308"|"RUB"

How do I convert the abbreviated month name to month number and achieve the expected output?

Body:
you mean something like this?

#!/bin/bash
while  read -r line; do
   # use date to convert first column of line
   newdate=$(date -d "${line%%|*}" +"%d-%m-%y")

   # print new date and the last two columns
   printf "%s|%s\n" "$newdate" "${line#*|}"
done < input


问:
Remove Screen from navigation stack

App structure -

Home Screen - Have button navigate to shopping cart

ShoppingCart Screen - have button navigate to shop screen

Shop Screen - Have button navigate to shopping cart

Using - react-native: 0.59.5, react-navigation: ^3.8.1

step 1 - go to shopping cart from home

step 2 - go to shop from shopping cart

step 3 - add some items to cart in shop

step 4 - go to shopping cart from shop - problem goes here.

in step 4 action show the previous screen of shoppingCart( that appeared screen at step 1 ).There are no new added items in the cart only have previous states.

I haven't any idea how to slolve this ? can anyone help ?

答:
The current screen can be replaced using replace method

navigation.replace(routeName, params, action)

https://reactnavigation.org/docs/en/navigation-prop.html#replace

Title: Remove Screen from navigation stack


问:
Reading multiple screen clicks and displaying the same on edittext
Am new to Android, and am building a simple calculator app. I want to read the multiple clicks made on the screen (i.e numbers) and display the same in edittext.

Kindly find the code below, in the button's onclicklistener event, am displaying  the numbers directly in edittext. With this piece of code, the displayed numbers in edittext are getting overwritten (i.e it is not getting appended). For example when I click '1', it appears correctly, and next when I click '2', it appears as '2', instead of "12". I know my logic is wrong here, but how can I make the characters to append in edittext?

Code:

```<code>    button00.setOnClickListener(new Button.OnClickListener(){
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            EditText01.setText("0");
        }
    });

    button01.setOnClickListener(new Button.OnClickListener(){
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            EditText01.setText("1");
        }
    });

    button02.setOnClickListener(new Button.OnClickListener(){
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            EditText01.setText("2");
        }
    });
</code>```

Thanks in advance

答:
setText() doesn't depend on what was in the box previously, so you'll have to just do some simple string concatenating:

```<code>String prevText = EditText01.getText().toString();
EditText01.setText(prevText + "2");
</code>```

Since getText() returns an Editable, you have to convert it to a String, but after that point, yeah, just do the above for each number. You could probably further optimize it by having a class StringBuilder, and just using StringBuilder.append() to add and set the value, but the above should work just fine.

ContentLicense: CC BY-SA 3.0

Body:
Am new to Android, and am building a simple calculator app. I want to read the multiple clicks made on the screen (i.e numbers) and display the same in edittext.

Kindly find the code below, in the button's onclicklistener event, am displaying  the numbers directly in edittext. With this piece of code, the displayed numbers in edittext are getting overwritten (i.e it is not getting appended). For example when I click '1', it appears correctly, and next when I click '2', it appears as '2', instead of "12". I know my logic is wrong here, but how can I make the characters to append in edittext?

Code:

    button00.setOnClickListener(new Button.OnClickListener(){
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            EditText01.setText("0");
        }
    });

    button01.setOnClickListener(new Button.OnClickListener(){
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            EditText01.setText("1");
        }
    });

    button02.setOnClickListener(new Button.OnClickListener(){
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            EditText01.setText("2");
        }
    });

Thanks in advance

Body:
setText() doesn't depend on what was in the box previously, so you'll have to just do some simple string concatenating:

String prevText = EditText01.getText().toString();
EditText01.setText(prevText + "2");

Since getText() returns an Editable, you have to convert it to a String, but after that point, yeah, just do the above for each number. You could probably further optimize it by having a class StringBuilder, and just using StringBuilder.append() to add and set the value, but the above should work just fine.


问:
Why late init var cannot be used with Nullable?
Why can't we use lateinit with nullable variables?

```<code>lateinit var v: String?
</code>```

lateinit modifier is not allowed on properties of nullable types

答:
lateinit is only for avoid null checks in future, that's why lateinit modifier is not allowed on properties of nullable types.

If you want it to be nullable then simply you can use like var b: String? = null

Body:
Why can't we use lateinit with nullable variables?

lateinit var v: String?

lateinit modifier is not allowed on properties of nullable types


问:
How to select the maximum quarter from the result set?
I have a list of period for each quarter for many years, I need to select the maximum period from the result.

Say for example, the actual data would be like this;

```<code>**period description**
2014 Q2
2014 Q1
2018 Q3
2016 Q1
2017 Q4
2018 Q4
</code>```

Here I need to fetch only the latest quarter in the given data..i.e. we need to get 2018 Q4.

I tried :

```<code>select substring  (perioddescription, 1, 4)
</code>```

but I've a string in between them so any help would be much appreciated.thanks in advacne

答:
Another possible approach using custom ORDER BY clause:

Input:

```<code>CREATE TABLE #Data (
   [Period] varchar(7)
)
INSERT INTO #Data
   ([Period])
VALUES
   ('2014 Q2'),
   ('2014 Q1'),
   ('2018 Q3'),
   ('2016 Q1'),
   ('2017 Q4'),
   ('2018 Q4')
</code>```

T-SQL:

```<code>SELECT TOP(1) [Period]
FROM #Data
ORDER BY
   CONVERT(int, SUBSTRING([Period], 1, 4)) * 10 +
   CONVERT(int, SUBSTRING([Period], 7, 1)) DESC
</code>```

Output:

```<code>-------
Period
-------
2018 Q4
</code>```

Notes: If you are not sure, that all your data is in yyyy Qq format, use TRY_CONVERT():

```<code>SELECT TOP(1) [Period]
FROM #Data
ORDER BY
   COALESCE(TRY_CONVERT(int, SUBSTRING([Period], 1, 4)), 0) * 10 +
   COALESCE(TRY_CONVERT(int, SUBSTRING([Period], 7, 1)), 0) DESC
</code>```

Body:
I have a list of period for each quarter for many years, I need to select the maximum period from the result.

Say for example, the actual data would be like this;

**period description**
2014 Q2
2014 Q1
2018 Q3
2016 Q1
2017 Q4
2018 Q4

Here I need to fetch only the latest quarter in the given data..i.e. we need to get 2018 Q4.

I tried :

select substring  (perioddescription, 1, 4)

but I've a string in between them so any help would be much appreciated.thanks in advacne

Body:
Another possible approach using custom ORDER BY clause:

Input:

CREATE TABLE #Data (
   [Period] varchar(7)
)
INSERT INTO #Data
   ([Period])
VALUES
   ('2014 Q2'),
   ('2014 Q1'),
   ('2018 Q3'),
   ('2016 Q1'),
   ('2017 Q4'),
   ('2018 Q4')

T-SQL:

SELECT TOP(1) [Period]
FROM #Data
ORDER BY
   CONVERT(int, SUBSTRING([Period], 1, 4)) * 10 +
   CONVERT(int, SUBSTRING([Period], 7, 1)) DESC

Output:

-------
Period
-------
2018 Q4

Notes: If you are not sure, that all your data is in yyyy Qq format, use TRY_CONVERT():

SELECT TOP(1) [Period]
FROM #Data
ORDER BY
   COALESCE(TRY_CONVERT(int, SUBSTRING([Period], 1, 4)), 0) * 10 +
   COALESCE(TRY_CONVERT(int, SUBSTRING([Period], 7, 1)), 0) DESC


问:
Is there a way to inherit parameters from a parent class's constructor?
The problem I'm having is that I have some base (generic) classes whose properties are initialized via the class's constructor. When I then go to extend this class to create a more specific class, I must re-type the same parameters that the base class's constructor has, just so I can pass them to super. If you imagine a very generic class that has many properties that are initialized via a constructor , and that is extended quite often, having to constantly re-type all these properties just to pass them to super each time seems inefficient. I am likely missing some common way of preventing this. Any ideas how to make this more efficient? Perhaps by somehow "inheriting" the parent class's constructor parameters?

Here's a code example, and, as you can see, in Programmer's constructor, I have to re-type name, age, and height again just to pass it to super:

class Person {
    name: string;
    age: number;
    height: number;

    constructor(name: string, age: number, height: number) {
        this.name = name;
        this.age = age;
        this.height = height;
    }
}

class Programmer extends Person {
    languages: string[];

    constructor(name: string, age: number, height: number, languages: string[]) {
        super(name, age, height);

        this.languages = languages;
    }
}
```

答:
As Person is base class which can not be initialize without name, age and height, the extended class Programmer will compulsory needs the same constructor args.

As you have mentioned in case there are many arguments, you can use creation pattern (like builder pattern) to create object of extended class.

If you want no arg constructor you can make super constructor parameter as optional.

```<code>class Person {
  name: string;
  age: number;
  height: number;

  constructor(name?: string, age?: number, height?: number) {
      this.name = name;
      this.age = age;
      this.height = height;
  }
}

class Programmer extends Person {
  languages: string[];

  constructor(languages: string[]) {
      super();

      this.languages = languages;
  }
}
</code>```

Body:
As Person is base class which can not be initialize without name, age and height, the extended class Programmer will compulsory needs the same constructor args.

As you have mentioned in case there are many arguments, you can use creation pattern (like builder pattern) to create object of extended class.

If you want no arg constructor you can make super constructor parameter as optional.

class Person {
  name: string;
  age: number;
  height: number;

  constructor(name?: string, age?: number, height?: number) {
      this.name = name;
      this.age = age;
      this.height = height;
  }
}

class Programmer extends Person {
  languages: string[];

  constructor(languages: string[]) {
      super();

      this.languages = languages;
  }
}


问:
How to validate date time with many format in laravel
I want to check my request datetime with many format look like below format:

```<code>Y-m-d
Y-m-
Y-m
</code>```

In Laravel, I use Validator to validate datetime, but Validator can not make checking with many format. This is my code:

```<code>Validator::make(['date' => $departureDate], [
   'date' => 'required|date_format:Y-m-d, Y-m, Y-m-'
]);
</code>```

How can I do it in laravel
Please help me! Many thanks!

答:
You can register custom validator in file app/Providers/AppServiceProvider.php in boot method.

```<code>Validator::extend('several_date_format', function ($attribute, $value, $parameters,$validator) {
    foreach ($parameters as $parameter){
        if (!$validator->validateDateFormat($attribute,$value,[$parameter]))
           return false;
    }
    return true;
});
</code>```

Now you can use it

```<code>'your_date' => 'required|several_date_format:Y-m-d,...'
</code>```

Optional after it you can add custom message in resources/lang/en/validation.php

```<code>return [
   ...
   'several_date_format' => 'Error text'
   ...
]
</code>```

Body:
I want to check my request datetime with many format look like below format:

Y-m-d
Y-m-
Y-m

In Laravel, I use Validator to validate datetime, but Validator can not make checking with many format. This is my code:

Validator::make(['date' => $departureDate], [
   'date' => 'required|date_format:Y-m-d, Y-m, Y-m-'
]);

How can I do it in laravel
Please help me! Many thanks!

Body:
You can register custom validator in file app/Providers/AppServiceProvider.php in boot method.

Validator::extend('several_date_format', function ($attribute, $value, $parameters,$validator) {
    foreach ($parameters as $parameter){
        if (!$validator->validateDateFormat($attribute,$value,[$parameter]))
           return false;
    }
    return true;
});

Now you can use it

'your_date' => 'required|several_date_format:Y-m-d,...'

Optional after it you can add custom message in resources/lang/en/validation.php

return [
   ...
   'several_date_format' => 'Error text'
   ...
]


问:
Message in Leaderboard: "Hmm, something went wrong in Play Games"
I added Google Play Games Services support to my board game app and implemented Achievements and a Leaderboard through the corresponding clients in a similar way as the GPGS sample app "Type A Number" did. When debugging with adb and my tester account, these features worked fine. When I released the app into production, the Leaderboard started showing the message "Hmm, something went wrong in Play Games". Additionally, achievements can be unlocked and are being shown properly. But after closing the app, this progress is being lost.

Under Google APIs -> Google Play Games Services I get this feedback of the GPGS API calls (in the production phase):

GPGS method calls

Since the release, I apparently mainly get 401 as a response code according to the metrics.

SOLUTION: Google Play Games doesn't work with app published in PlayStore

答:
I had the same problem. Leaderboards stopped appearing after first post. I tried removing OAuth keys and putting them back on, but that didn't seem to do the job. Went for a hail mary and linked the same app AGAIN to Games Services and voila! Image below shows what to do. Worked for me, hope it works for you. Cheers!

 Game Services > Link App > Link Another App">


答:
Normally, properties declared as having a non-null type must be
  initialized in the constructor. However, fairly often this is not
  convenient.

For example, properties can be initialized through dependency
  injection, or in the setup method of a unit test. In this case, you
  cannot supply a non-null initializer in the constructor, but you
  still want to avoid null checks when referencing the property
  inside the body of a class.

To handle this case, you can mark the property with the lateinit
  modifier.

That's why it doesn't support null.

So, if you indicate any var as lateinit meaning compiler simply ignores it for initialization and mark it as non-null type that would be initialized in nearer future and is why it doesn't support nullable type to avoid runtime ambiguities.

Title: Why late init var cannot be used with Nullable?


答:
you can try like this,</p>

```<code>checkUserApi(url: string): Observable<any> {
    const config = { headers:  {
        'Content-Type': 'application/json',
        'Accept': 'text/plain',
        "X-userName": "testUser",
        "X-password": "testPwd"
    }
  };
 return this.http.post(url, config)
      .map((response: Response) => {
        console.log("response : " +response);
        return response;
      });
}
</code>```

Title: How to pass custom parameters in header request

Body:
you can try like this,

checkUserApi(url: string): Observable<any> {
    const config = { headers:  {
        'Content-Type': 'application/json',
        'Accept': 'text/plain',
        "X-userName": "testUser",
        "X-password": "testPwd"
    }
  };
 return this.http.post(url, config)
      .map((response: Response) => {
        console.log("response : " +response);
        return response;
      });
}


问:
Objective-C retain question
In Xcode I have a UINavigationController on wichh I push a UIViewController.

In that UIViewController I init an UIScrollView.

All good.

However, after switching to another view I log the retain count of the controller and to my surprise it's one instead of zero.

Here's the code:

```<code>scroller = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];

[self.view addSubview:scroller];
</code>```

and:

```<code>- (void)dealloc {
    [super dealloc];

    NSLog(@"retaincount, %d", [scroller retainCount]);  //displays 2

    [scroller release];

    NSLog(@"retaincount, %d", [scroller retainCount]); // displays 1
}
</code>```

I only init it ones and add it to the UIViewControllers view.

Kind regards,

Tom

答:
Do not use retainCount! From the apple documentation:

Important: This method is typically of no value in debugging memory management issues. Because any number of framework objects may have retained an object in order to hold references to it, while at the same time autorelease pools may be holding any number of deferred releases on an object, it is very unlikely that you can get useful information from this method.

To understand the fundamental rules of memory management that you must abide by, read “Memory Management Rules”. To diagnose memory management problems, use a suitable tool:

The LLVM/Clang Static analyzer can typically find memory management problems even before you run your program.

The Object Alloc instrument in the Instruments application (see Instruments User Guide) can track object allocation and destruction.

Shark (see Shark User Guide) also profiles memory allocations (amongst numerous other aspects of your program).

Having said that: You have to call [super dealloc] in the very last line of your dealloc method. Besides that everything in your code should be ok. Don't try to manually lower the retainCount. Use proper memory management. Again, do not look at the retainCount.

And you are not allowed to use an object after you have released it. If the scroller would be deallocated because of your release the second NSLog would result in a BAD_ACCESS exception.

Title: Objective-C retain question

Body:
In Xcode I have a UINavigationController on wichh I push a UIViewController.

In that UIViewController I init an UIScrollView.

All good.

However, after switching to another view I log the retain count of the controller and to my surprise it's one instead of zero.

Here's the code:

scroller = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];

[self.view addSubview:scroller];

and:

- (void)dealloc {
    [super dealloc];

    NSLog(@"retaincount, %d", [scroller retainCount]);  //displays 2

    [scroller release];

    NSLog(@"retaincount, %d", [scroller retainCount]); // displays 1
}

I only init it ones and add it to the UIViewControllers view.

Kind regards,

Tom


问:
Keep getting "identifier expected" and "; expected" error messages
I am trying to make a high score system for my game in unity and am not really sure on how to do that, but I tried this code nonetheless and I keep receiving error messages.

I have tried to search up these errors but since I am quite new to unity and coding in general none of the solutions there make sense to me.

```<code>public Transform player;
public Text scoreText;
public Text highScore;

// Update is called once per frame
void Update()
{
    scoreText.text = player.position.z.ToString("0");
    scoreText = scoreText.int.Parse;

    if (scoreText > PlayerPrefs.GetInt("High Score", 0)) ;
    {
        PlayerPrefs.SetInt("High Score", scoreText);
        highScore.text = scoreText.ToString;
    }
</code>```

These are the error messages that show up

Assets\Score.cs(15,31): error CS1001: Identifier expected

Assets\Score.cs(15,31): error CS1002: ; expected

答:
Try this code:</p>

```<code>public Transform player;
public Text scoreText;
public Text highScore;

// Update is called once per frame
void Update()
{
    scoreText.text = player.position.z.ToString("0");
    int scoreTextNumber = int.Parse(scoreText.text);

    if (scoreText > PlayerPrefs.GetInt("High Score", 0))
    {
        PlayerPrefs.SetInt("High Score", scoreTextNumber);
        highScore.text = scoreTextNumber.ToString("0");
    }
</code>```

Body:
I am trying to make a high score system for my game in unity and am not really sure on how to do that, but I tried this code nonetheless and I keep receiving error messages.

I have tried to search up these errors but since I am quite new to unity and coding in general none of the solutions there make sense to me.

public Transform player;
public Text scoreText;
public Text highScore;

// Update is called once per frame
void Update()
{
    scoreText.text = player.position.z.ToString("0");
    scoreText = scoreText.int.Parse;

    if (scoreText > PlayerPrefs.GetInt("High Score", 0)) ;
    {
        PlayerPrefs.SetInt("High Score", scoreText);
        highScore.text = scoreText.ToString;
    }

These are the error messages that show up

Assets\Score.cs(15,31): error CS1001: Identifier expected

Assets\Score.cs(15,31): error CS1002: ; expected

Body:
Try this code:

public Transform player;
public Text scoreText;
public Text highScore;

// Update is called once per frame
void Update()
{
    scoreText.text = player.position.z.ToString("0");
    int scoreTextNumber = int.Parse(scoreText.text);

    if (scoreText > PlayerPrefs.GetInt("High Score", 0))
    {
        PlayerPrefs.SetInt("High Score", scoreTextNumber);
        highScore.text = scoreTextNumber.ToString("0");
    }


问:
Able to select "I'm Feeling Lucky" but cannot click it
I am trying to write a simple program to open up chrome, go to Google, and click on "I'm Feeling Lucky." I see that it acts as if the cursor is placed over the icon, but it will not perform a click.

```<code>driver.get("https://www.google.com")
element = WebDriverWait(driver, 20) \
    .until(EC.visibility_of_element_located((By.ID, "gbqfbb")))
element.click()
</code>```

No errors occur in the code, but it will not click the element.

答:
I cannot find that ID either.

here's what worked for me using css_selector

```<code>from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from appium.webdriver.common.mobileby import, By
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome()

driver.get("https://www.google.com")
element = WebDriverWait(driver, 20) \
    .until(EC.visibility_of_any_elements_located((By. CSS_SELECTOR, '[name="btnI"][type="submit"]')))[0]
element.click()
</code>```

I suggest to use visibility_of_any_elements_located over visibility_of_element_located. The reason is that the selector finds two elements. One visible and one that is not.

When using visibility_of_element_located it will use find_element and it will get the element that is not visible.

When using visibility_of_any_elements_located it will use find_elements and it will get both elements. it will loop through all elements and if one or more are visible it will return it right away.

Body:
I am trying to write a simple program to open up chrome, go to Google, and click on "I'm Feeling Lucky." I see that it acts as if the cursor is placed over the icon, but it will not perform a click.

driver.get("https://www.google.com")
element = WebDriverWait(driver, 20) \
    .until(EC.visibility_of_element_located((By.ID, "gbqfbb")))
element.click()

No errors occur in the code, but it will not click the element.

Body:
I cannot find that ID either.

here's what worked for me using css_selector

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from appium.webdriver.common.mobileby import, By
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome()

driver.get("https://www.google.com")
element = WebDriverWait(driver, 20) \
    .until(EC.visibility_of_any_elements_located((By. CSS_SELECTOR, '[name="btnI"][type="submit"]')))[0]
element.click()

I suggest to use visibility_of_any_elements_located over visibility_of_element_located. The reason is that the selector finds two elements. One visible and one that is not.

When using visibility_of_element_located it will use find_element and it will get the element that is not visible.

When using visibility_of_any_elements_located it will use find_elements and it will get both elements. it will loop through all elements and if one or more are visible it will return it right away.


问:
how to set proxy with authentication in selenium chromedriver python?
I am creating a script that crawls one website to gather some data but the problem is that they blocked me after too many requests but using a proxy I can send more request then currently I do. I have integrated proxy with chrome option --proxy-server

options.add_argument('--proxy-server={}'.format('http://ip:port'))

but I am using a paid proxy so it requires authentication and as below screenshot it gives the alert box for username and password

Then I tried to use it with username and password

options.add_argument('--proxy-server={}'.format('http://username:password@ip:port'))

But it also does not seems to work. I was looking for a solution and found below solution and I used it with the chrome extension proxy auto auth and without the chrome extension

```<code>proxy = {'address': settings.PROXY,
             'username': settings.PROXY_USER,
             'password': settings.PROXY_PASSWORD}

capabilities = dict(DesiredCapabilities.CHROME)
capabilities['proxy'] = {'proxyType': 'MANUAL',
                             'httpProxy': proxy['address'],
                             'ftpProxy': proxy['address'],
                             'sslProxy': proxy['address'],
                             'noProxy': '',
                             'class': "org.openqa.selenium.Proxy",
                             'autodetect': False,
                             'socksUsername': proxy['username'],
                             'socksPassword': proxy['password']}
options.add_extension(os.path.join(settings.DIR, "extension_2_0.crx")) # proxy auth extension
</code>```

but neither of above worked properly it seems working because after above code the proxy authentication alert disappeared and when I checked my IP by googling what is my IP and confirmed that is not working.

please anyone who can help me to authenticate the proxy server on chromedriver.

答:
Here is a quick, creative solution that doesn't require modification of selenium's Options or uploading a file to chromedriver. It makes use of pyautogui (can use any python package that simulates key presses) to enter proxy auth details. It also uses threading to account for chrome authentication popup window that would otherwise pause the script.

```<code>import time
from threading import Thread
import pyautogui
from selenium.webdriver.chrome.options import Options
from selenium import webdriver

hostname = "HOST_NAME"
port = "PORT"
proxy_username = "USERNAME"
proxy_password = "PASSWORD"

chrome_options = Options()
chrome_options.add_argument('--proxy-server={}'.format(hostname + ":" + port))
driver = webdriver.Chrome(options=chrome_options)

def enter_proxy_auth(proxy_username, proxy_password):
    time.sleep(1)
    pyautogui.typewrite(proxy_username)
    pyautogui.press('tab')
    pyautogui.typewrite(proxy_password)
    pyautogui.press('enter')

def open_a_page(driver, url):
    driver.get(url)

Thread(target=open_a_page, args=(driver, "http://www.example.com/")).start()
Thread(target=enter_proxy_auth, args=(proxy_username, proxy_password)).start()
</code>```

NOTE: For any serious project or test suite I would recommend opting for a more robust solution. However, if you are just experimenting and require a quick and effective solution, this is an option.

Body:
I am creating a script that crawls one website to gather some data but the problem is that they blocked me after too many requests but using a proxy I can send more request then currently I do. I have integrated proxy with chrome option --proxy-server

options.add_argument('--proxy-server={}'.format('http://ip:port'))

but I am using a paid proxy so it requires authentication and as below screenshot it gives the alert box for username and password

Then I tried to use it with username and password

options.add_argument('--proxy-server={}'.format('http://username:password@ip:port'))

But it also does not seems to work. I was looking for a solution and found below solution and I used it with the chrome extension proxy auto auth and without the chrome extension

proxy = {'address': settings.PROXY,
             'username': settings.PROXY_USER,
             'password': settings.PROXY_PASSWORD}

capabilities = dict(DesiredCapabilities.CHROME)
capabilities['proxy'] = {'proxyType': 'MANUAL',
                             'httpProxy': proxy['address'],
                             'ftpProxy': proxy['address'],
                             'sslProxy': proxy['address'],
                             'noProxy': '',
                             'class': "org.openqa.selenium.Proxy",
                             'autodetect': False,
                             'socksUsername': proxy['username'],
                             'socksPassword': proxy['password']}
options.add_extension(os.path.join(settings.DIR, "extension_2_0.crx")) # proxy auth extension

but neither of above worked properly it seems working because after above code the proxy authentication alert disappeared and when I checked my IP by googling what is my IP and confirmed that is not working.

please anyone who can help me to authenticate the proxy server on chromedriver.

Body:
Here is a quick, creative solution that doesn't require modification of selenium's Options or uploading a file to chromedriver. It makes use of pyautogui (can use any python package that simulates key presses) to enter proxy auth details. It also uses threading to account for chrome authentication popup window that would otherwise pause the script.

import time
from threading import Thread
import pyautogui
from selenium.webdriver.chrome.options import Options
from selenium import webdriver

hostname = "HOST_NAME"
port = "PORT"
proxy_username = "USERNAME"
proxy_password = "PASSWORD"

chrome_options = Options()
chrome_options.add_argument('--proxy-server={}'.format(hostname + ":" + port))
driver = webdriver.Chrome(options=chrome_options)

def enter_proxy_auth(proxy_username, proxy_password):
    time.sleep(1)
    pyautogui.typewrite(proxy_username)
    pyautogui.press('tab')
    pyautogui.typewrite(proxy_password)
    pyautogui.press('enter')

def open_a_page(driver, url):
    driver.get(url)

Thread(target=open_a_page, args=(driver, "http://www.example.com/")).start()
Thread(target=enter_proxy_auth, args=(proxy_username, proxy_password)).start()

NOTE: For any serious project or test suite I would recommend opting for a more robust solution. However, if you are just experimenting and require a quick and effective solution, this is an option.


问:
Using SFINAE to check function std::to_string exists for a type
I want to create a function template that is specialized for types that may have std::to_string applied to them, another for classes for which I have defined a mylib::to_string, and let any types for which it may not fall through to other implementations or specializations.

Example:

```<code>// I only want this to be found if std::to_string exists for ItemType
template<typename ItemType>
void func(ItemType &i)
{
     std::cout << std::to_string(i);
}

// I only want this to be found if mylib::to_string exists for ItemType
template<typename ItemType>
void func(ItemType &i)
{
     std::cout << mylib::to_string(i);
}

// And finally, I'd like to be able to fall through to anything that has a << defined for streams
template<>
void func<MyClass>(MyClass &i)
{
     std::cout << MySpecialConverterFunc(i);
}
</code>```

I always have problems with std::enable_if syntax. How would you add it to the first template?

答:
For SFINAE you need not to specialize, but to overload. Which is saner than dealing with specializations anyway (those have quirks). SFINAE is a mechanism to guide overload resolution, not for choosing explicit specializations of function templates.

As for the check itself, you don't need enable_if really. Just a little bit of expression SFINAE will do:

```<code>template<typename ItemType>
auto func(ItemType &i) -> decltype(std::to_string(i), void())
{
     std::cout << std::to_string(i);
}

void func(MyClass &i)
{
     std::cout << MySpecialConverterFunc(i);
}
</code>```

In the above code, decltype is applied to a comma expression. The left hand side is std::to_string(i), if it isn't well-formed, the whole expression isn't well formed, and we get a substitution error, making the compiler discard that overload (the "not an error" part). If it's well-formed, the right hand side is a void() literal, so decltype resolves to void as you intended.

When substitution fails, all we are left with is the second overload, so it's picked. It would have been picked for this case anyway, because non-template overloads are always favored in overload resolution if the signature is the same. But adding a check to better guide the compiler in other cases is not a bad idea in and of itself.

Body:
I want to create a function template that is specialized for types that may have std::to_string applied to them, another for classes for which I have defined a mylib::to_string, and let any types for which it may not fall through to other implementations or specializations.

Example:

// I only want this to be found if std::to_string exists for ItemType
template<typename ItemType>
void func(ItemType &i)
{
     std::cout << std::to_string(i);
}

// I only want this to be found if mylib::to_string exists for ItemType
template<typename ItemType>
void func(ItemType &i)
{
     std::cout << mylib::to_string(i);
}

// And finally, I'd like to be able to fall through to anything that has a << defined for streams
template<>
void func<MyClass>(MyClass &i)
{
     std::cout << MySpecialConverterFunc(i);
}

I always have problems with std::enable_if syntax. How would you add it to the first template?

Body:
For SFINAE you need not to specialize, but to overload. Which is saner than dealing with specializations anyway (those have quirks). SFINAE is a mechanism to guide overload resolution, not for choosing explicit specializations of function templates.

As for the check itself, you don't need enable_if really. Just a little bit of expression SFINAE will do:

template<typename ItemType>
auto func(ItemType &i) -> decltype(std::to_string(i), void())
{
     std::cout << std::to_string(i);
}

void func(MyClass &i)
{
     std::cout << MySpecialConverterFunc(i);
}

In the above code, decltype is applied to a comma expression. The left hand side is std::to_string(i), if it isn't well-formed, the whole expression isn't well formed, and we get a substitution error, making the compiler discard that overload (the "not an error" part). If it's well-formed, the right hand side is a void() literal, so decltype resolves to void as you intended.

When substitution fails, all we are left with is the second overload, so it's picked. It would have been picked for this case anyway, because non-template overloads are always favored in overload resolution if the signature is the same. But adding a check to better guide the compiler in other cases is not a bad idea in and of itself.


问:
How to start with a PHP website?
For a school project I have to produce a website using PHP that allows user to generate there own article or comment on news or others articles. I was wondering how it is best to use the GET function to show the content in an include file and also use the get function for other include files such as the login page and other content the developer (me) has added to website not as articles but as links etc. Anyone got any suggestions or good tutorials they could post up. </p>

答:
You'll definitely want to sanitize anything that comes in through the GET parameter before
 including a file. You normally do this by checking for valid characters, and since it is directly calling a file from the file system I usually manually enter the valid navigation actions. This isn't the most elegant solution but often the easiest and safest for a small application.

I usually use case switches for this, but I've seen people use fancy regular expressions as well.

Something along the lines of:

```<code>if (isset($_GET['nav'])) {
    switch ($_GET['nav']) {
        case 'login':
        case 'logout':
        case 'article':
             include($_GET['nav'] . '.php');
             break;
        default:
             die('Invalid nav parameter');
             break;
    }
}
</code>```

OwnerDisplayName: Cool Hand Luke UK

Title: How to start with a PHP website?

LastEditorDisplayName: Rex M

Body:
You'll definitely want to sanitize anything that comes in through the GET parameter before
 including a file. You normally do this by checking for valid characters, and since it is directly calling a file from the file system I usually manually enter the valid navigation actions. This isn't the most elegant solution but often the easiest and safest for a small application.

I usually use case switches for this, but I've seen people use fancy regular expressions as well.

Something along the lines of:

if (isset($_GET['nav'])) {
    switch ($_GET['nav']) {
        case 'login':
        case 'logout':
        case 'article':
             include($_GET['nav'] . '.php');
             break;
        default:
             die('Invalid nav parameter');
             break;
    }
}

ContentLicense: CC BY-SA 2.5


问:
Want to add more drops to my mining function
So I have a working button that adds exp to my total exp then has a chance to give you 1 bronze on click. I want when my mininglv >=10 for silver to be added to that.

I've tried making another if  statement (probably formatted it wrong) that is if (mininglv >=10 && mininglv < 20) then repeating the lines for bronze and mining exp then adding a silver random thing. I cant figure out how to add silver to the chance to get from the click of the button and give it a chance of 0.25.

This is my javaScript code:

```<code>var Bronzechance = 0.5
var Silverchance = 0.25

function Miningaction() {
    if (MiningCexp < NextMaxMiningExp && Mininglv >= 1) {
        MiningCexp = MiningCexp + 1;
        if (Math.random() < Bronzechance)
        Bronze = Bronze + 1
    document.getElementById("Bronze").innerHTML = Bronze;
    document.getElementById("MiningCexp").innerHTML = MiningCexp;
}
if(Mininglv >=10 && Mininglv <20){
    MiningCexp = MiningCexp + 1;
    if (Math.random() < Silverchance){
        Silver = Silver + 1;
    }
    document.getElementById("Bronze").innerHTML = Bronze;
    document.getElementById("Silver").innerHTML = Silver;
    document.getElementById("MiningCexp").innerHTML = MiningCexp;

} else {
    Mininglv = Mininglv + 1
    MiningCexp = 0
    Mining = Mining + 1
    NextMaxMiningExp = NextMaxMiningExp * 1.5;
    document.getElementById('MiningMexp').innerHTML = NextMaxMiningExp;
    document.getElementById('Mininglv').innerHTML = Mininglv;
    document.getElementById('MiningCexp').innerHTML = MiningCexp;
    document.getElementById('Mining').innerHTML = Mining;
}
</code>```

}

Html code :

```<code> Bronze: <span id="Bronze">0</span>
 <br />
 Silver: <span id="Bronze">0</span>

<button onclick="Miningaction()"><img src="cave.png" alt="cave"
height="45" width="45"> </button>
</code>```

I expect when button clicked when mining level is 10 or higher but not higher then 20 to have a chance to give you silver. But the actual output I can't get silver to drop.

答:
Is this what you're looking for?</p>

```<code>
var Bronzechance = 0.5;
var Silverchance = 0.25;
var Bronze = 0;
var Silver = 0;

function Miningaction() {
    MiningCexp = MiningCexp + 1;
    if (Mininglv >= 1) {
        if (Math.random() < Bronzechance)
            Bronze = Bronze + 1;
        document.getElementById("Bronze").innerHTML = Bronze;
        document.getElementById("MiningCexp").innerHTML = MiningCexp;

    }

    if(Mininglv >=10 && Mininglv < 20){
        if (Math.random() < Silverchance){
            Silver = Silver + 1;
        }
        document.getElementById("Silver").innerHTML = Silver;
        document.getElementById("MiningCexp").innerHTML = MiningCexp;

    if(MiningCexp >= NextMaxMiningExp)
        Mininglv = Mininglv + 1;
        MiningCexp = 0;
        Mining = Mining + 1;
        NextMaxMiningExp = NextMaxMiningExp * 1.5;
        document.getElementById('MiningMexp').innerHTML = NextMaxMiningExp;
        document.getElementById('Mininglv').innerHTML = Mininglv;
        document.getElementById('MiningCexp').innerHTML = MiningCexp;
        document.getElementById('Mining').innerHTML = Mining;
    }
}
</code>```

Body:
So I have a working button that adds exp to my total exp then has a chance to give you 1 bronze on click. I want when my mininglv >=10 for silver to be added to that.

I've tried making another if  statement (probably formatted it wrong) that is if (mininglv >=10 && mininglv < 20) then repeating the lines for bronze and mining exp then adding a silver random thing. I cant figure out how to add silver to the chance to get from the click of the button and give it a chance of 0.25.

This is my javaScript code:

var Bronzechance = 0.5
var Silverchance = 0.25

function Miningaction() {
    if (MiningCexp < NextMaxMiningExp && Mininglv >= 1) {
        MiningCexp = MiningCexp + 1;
        if (Math.random() < Bronzechance)
        Bronze = Bronze + 1
    document.getElementById("Bronze").innerHTML = Bronze;
    document.getElementById("MiningCexp").innerHTML = MiningCexp;
}
if(Mininglv >=10 && Mininglv <20){
    MiningCexp = MiningCexp + 1;
    if (Math.random() < Silverchance){
        Silver = Silver + 1;
    }
    document.getElementById("Bronze").innerHTML = Bronze;
    document.getElementById("Silver").innerHTML = Silver;
    document.getElementById("MiningCexp").innerHTML = MiningCexp;

} else {
    Mininglv = Mininglv + 1
    MiningCexp = 0
    Mining = Mining + 1
    NextMaxMiningExp = NextMaxMiningExp * 1.5;
    document.getElementById('MiningMexp').innerHTML = NextMaxMiningExp;
    document.getElementById('Mininglv').innerHTML = Mininglv;
    document.getElementById('MiningCexp').innerHTML = MiningCexp;
    document.getElementById('Mining').innerHTML = Mining;
}

}

Html code :

 Bronze: 0

 Silver: 0

<button onclick="Miningaction()"> </button>

I expect when button clicked when mining level is 10 or higher but not higher then 20 to have a chance to give you silver. But the actual output I can't get silver to drop.

Body:
Is this what you're looking for?

var Bronzechance = 0.5;
var Silverchance = 0.25;
var Bronze = 0;
var Silver = 0;

function Miningaction() {
    MiningCexp = MiningCexp + 1;
    if (Mininglv >= 1) {
        if (Math.random() < Bronzechance)
            Bronze = Bronze + 1;
        document.getElementById("Bronze").innerHTML = Bronze;
        document.getElementById("MiningCexp").innerHTML = MiningCexp;

    }

    if(Mininglv >=10 && Mininglv < 20){
        if (Math.random() < Silverchance){
            Silver = Silver + 1;
        }
        document.getElementById("Silver").innerHTML = Silver;
        document.getElementById("MiningCexp").innerHTML = MiningCexp;

    if(MiningCexp >= NextMaxMiningExp)
        Mininglv = Mininglv + 1;
        MiningCexp = 0;
        Mining = Mining + 1;
        NextMaxMiningExp = NextMaxMiningExp * 1.5;
        document.getElementById('MiningMexp').innerHTML = NextMaxMiningExp;
        document.getElementById('Mininglv').innerHTML = Mininglv;
        document.getElementById('MiningCexp').innerHTML = MiningCexp;
        document.getElementById('Mining').innerHTML = Mining;
    }
}


问:
How to set status bar background as gradient color or a drawable in Android?
I want to set status bar background as gradient theme also  status bar and action bar color should same gradient drawable, as per documentation  we can set color to status bar in API level 21 and above by using

<item name="android:statusBarColor">@color/colorPrimary</item>
```
<p>But I am searching something like</p>
<pre class="lang-xml prettyprint-override"><code><item name="android:statusBarDrawable">@drawable/myDrawable</item>
</code>```

I have seen example that use

<item name="android:windowTranslucentStatus">false</item>
<item name="android:windowTranslucentNavigation">false</item>
```

But in that case status bar and action bar overlap (use fitSystemWindow=true but still not solved) also try with https://github.com/jgilfelt/SystemBarTint this library but still no luck.

答: the answer provided by sushant goswami is actually working fine, after wasting one day finally realized that the status bar color and the gradient start color both were same in my case,after changing gradient color to some color other than default status bar color it was working well</p>

Body:
I want to set status bar background as gradient theme also  status bar and action bar color should same gradient drawable, as per documentation  we can set color to status bar in API level 21 and above by using

<item name="android:statusBarColor">@color/colorPrimary</item>

But I am searching something like

<item name="android:statusBarDrawable">@drawable/myDrawable</item>

I have seen example that use

<item name="android:windowTranslucentStatus">false</item>
<item name="android:windowTranslucentNavigation">false</item>

But in that case status bar and action bar overlap (use fitSystemWindow=true but still not solved) also try with https://github.com/jgilfelt/SystemBarTint this library but still no luck.


答:
Kotlin's type system is aimed at eliminating the danger of null references from code

so both represent compromises. With lateinit you ensure that the variable will eventually be initialized to non-null. If you cannot even guarantee that, you can use nullable.

Body:
Why can't we use lateinit with nullable variables?

lateinit var v: String?

lateinit modifier is not allowed on properties of nullable types


问:
Html Table Button Taking too much space
I want make two buttons sit next to each other within the same cell. How can I go about that without having alot space in the cell. Only Enough space to have the buttons sit in comfortable space between each other.

I have used display: inline-block; as well as display:block and style='white-space: nowrap'. Have looked at similar questions and their answers don't work with my project.

    Employee Name
    Email Address
    Action

    Johnny Depp
    hotdog69@gmail.com

      <button type="button">Add</button>
      <button type="button">Edit</button>

```

When one or two buttons are present within a cell, they create this super long horizontal cell. The buttons are also far apart from each other.

答:
You can use "table-layout:fixed" property to make your table use fixed width and assign width to "th" as per your choice. It will help you to adjust space of your table layout easily.

For email id, use "word-break: break-all" property to break text instead of using "white-space: nowrap" property.

    Employee Name
    Email Address
    Action

    Johnny Depp
    hotdog69@gmail.com

      <button type="button">Add</button>
      <button type="button">Edit</button>

```

Title: Html Table Button Taking too much space

Body:
I want make two buttons sit next to each other within the same cell. How can I go about that without having alot space in the cell. Only Enough space to have the buttons sit in comfortable space between each other.

I have used display: inline-block; as well as display:block and style='white-space: nowrap'. Have looked at similar questions and their answers don't work with my project.

    Employee Name
    Email Address
    Action

    Johnny Depp
    hotdog69@gmail.com

      <button type="button">Add</button>
      <button type="button">Edit</button>

When one or two buttons are present within a cell, they create this super long horizontal cell. The buttons are also far apart from each other.

Body:
You can use "table-layout:fixed" property to make your table use fixed width and assign width to "th" as per your choice. It will help you to adjust space of your table layout easily.

For email id, use "word-break: break-all" property to break text instead of using "white-space: nowrap" property.

<table style="table-layout:fixed;text-align:left">
  <tr>
    <th width="115px">Employee Name</th>
    <th width="105px">Email Address</th>
    <th width="90px">Action</th>
  </tr>
  <tr>
    <td>Johnny Depp</td>
    <td style="word-break:break-all;">hotdog69@gmail.com</td>
    <td>
      <button type="button">Add</button>
      <button type="button">Edit</button>
    </td>
  </tr>
</table>


问:
Update with DOM children and data propagation
I want to update the DOM containing children with data propagation.

The first time when DOM is populated, the data is properly propagated to their children.
However when I update the parent DOM with new data, the children DOM doesn't update along with it.

Also surprisingly, the old data were retrievable from the children elements, which I am strongly against because the data is too huge and I don't want to have old/extra data persist, which holds the reference and retains the old data. (Memory leak in my sense)

const DATA = [{
  name: "data1",
  left: 70,
  top: 70,
  radius: 20
}, {
  name: "data2",
  left: 200,
  top: 100,
  radius: 50
}];
const svg = d3.select("#svg");

// Not working as expected
function loadData(data) {
  console.log(data);
  const container = svg.selectAll(".container")
    .data(data);
  container.exit().remove();
  const enter = container.enter().append("g")
    .attr("class", "container");
  enter.append("circle");
  enter.append("text");

  container.merge(enter)
    .attr("transform", entry => `translate(0,${entry.top})`)
  svg.selectAll(".container circle")
    .attr("r", entry => entry.radius)
    .attr("cx", entry => entry.left);
  svg.selectAll(".container text")
    .text(entry => entry.name);
}

// Working, but not desired
function expected(data) {
  console.log(data);
  const container = svg.selectAll(".container")
    .data(data);
  container.exit().remove();
  const enter = container.enter().append("g")
    .attr("class", "container");
  enter.append("circle");
  enter.append("text");

  container.merge(enter)
    .attr("transform", entry => `translate(0,${entry.top})`)
  svg.selectAll(".container circle")
    .data(data)
    .attr("r", entry => entry.radius)
    .attr("cx", entry => entry.left);
  svg.selectAll(".container text")
    .data(data)
    .text(entry => entry.name);
}
let i = 0;
loadData(DATA);

function updateData() {
  i = (i+1) % 2;
  loadData(DATA.slice(i,i+1));
}
function expectedUpdate() {
  i = (i+1) % 2;
  expected(DATA.slice(i,i+1));
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>button {
  display: inline-block;
}
svg {
  width: 300px;
  height: 300px;
  display: block;
}</code>```

<button onclick="updateData();">Update</button>
<button onclick="expectedUpdate();">Expected</button>
<svg id="svg"></svg>```

This is just demonstration, where I have a parent <g> element, and 2 children <circle> & <text> are appending to it.

The first time when it renders, I used the loadData() method to populate the DOM, the corresponding children DOMs (circle & text) were able to retrieve the data inserted into their parent DOM (g), which showed a proper data propagation along the DOM tree.

However when I press "update" button multiple times, only the parent DOM is updating, and children DOMs are able access the non-existing data (old data).

The "expected" button shows what is the expected behaviour, but I can see the data is being binded multiple times, which I as a javascript engineer am so afraid of this kind of data binding.

答:
The main problem in your non-working function (loadData) is that you're using selectAll. Unlike select, selectAll doesn't propagate the data.

Have a look at this table I made summarising the differences between them:

Method
select()
selectAll()

Selection
selects the first element that matches the selector string
selects all elements that match the selector string

Grouping
Does not affect grouping
Affects grouping

Data propagation
Propagates data
Doesn't propagate data

As you can see, the main information for you is this:

select: propagates the data.

selectAll: doesn't propagate the data.

Given that your snippet has just one child (circle and text) per group, the simplest solution is just changing selectAll to select. However, if you have more than one child per parent, the best (and idiomatic) solution is creating a nested enter-update-exit selection, which is a bit more laborious.

Besides that, you're missing the key function:

```<code>const container = svg.selectAll(".container")
    .data(data, function(d) {
        return d.name;
    });
</code>```

Here is your code with those changes:

const DATA = [{
  name: "data1",
  left: 70,
  top: 70,
  radius: 20
}, {
  name: "data2",
  left: 200,
  top: 100,
  radius: 50
}];
const svg = d3.select("#svg");

// Not working as expected
function loadData(data) {
  console.log(data);
  const container = svg.selectAll(".container")
    .data(data, function(d) {
      return d.name;
    });
  container.exit().remove();
  const enter = container.enter().append("g")
    .attr("class", "container");
  enter.append("circle");
  enter.append("text");

  container.merge(enter)
    .attr("transform", entry => `translate(0,${entry.top})`)
  svg.select(".container circle")
    .attr("r", entry => entry.radius)
    .attr("cx", entry => entry.left);
  svg.select(".container text")
    .text(entry => entry.name);
}

// Working, but not desired
function expected(data) {
  console.log(data);
  const container = svg.selectAll(".container")
    .data(data);
  container.exit().remove();
  const enter = container.enter().append("g")
    .attr("class", "container");
  enter.append("circle");
  enter.append("text");

  container.merge(enter)
    .attr("transform", entry => `translate(0,${entry.top})`)
  svg.selectAll(".container circle")
    .data(data)
    .attr("r", entry => entry.radius)
    .attr("cx", entry => entry.left);
  svg.selectAll(".container text")
    .data(data)
    .text(entry => entry.name);
}
let i = 0;
loadData(DATA);

function updateData() {
  i = (i + 1) % 2;
  loadData(DATA.slice(i, i + 1));
}

function expectedUpdate() {
  i = (i + 1) % 2;
  expected(DATA.slice(i, i + 1));
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>button {
  display: inline-block;
}

svg {
  width: 300px;
  height: 300px;
  display: block;
}</code>```

<button onclick="updateData();">Update</button>
<button onclick="expectedUpdate();">Expected</button>
<svg id="svg"></svg>```

Body:
I want to update the DOM containing children with data propagation.

The first time when DOM is populated, the data is properly propagated to their children.
However when I update the parent DOM with new data, the children DOM doesn't update along with it.

Also surprisingly, the old data were retrievable from the children elements, which I am strongly against because the data is too huge and I don't want to have old/extra data persist, which holds the reference and retains the old data. (Memory leak in my sense)

const DATA = [{
  name: "data1",
  left: 70,
  top: 70,
  radius: 20
}, {
  name: "data2",
  left: 200,
  top: 100,
  radius: 50
}];
const svg = d3.select("#svg");

// Not working as expected
function loadData(data) {
  console.log(data);
  const container = svg.selectAll(".container")
    .data(data);
  container.exit().remove();
  const enter = container.enter().append("g")
    .attr("class", "container");
  enter.append("circle");
  enter.append("text");

  container.merge(enter)
    .attr("transform", entry => `translate(0,${entry.top})`)
  svg.selectAll(".container circle")
    .attr("r", entry => entry.radius)
    .attr("cx", entry => entry.left);
  svg.selectAll(".container text")
    .text(entry => entry.name);
}

// Working, but not desired
function expected(data) {
  console.log(data);
  const container = svg.selectAll(".container")
    .data(data);
  container.exit().remove();
  const enter = container.enter().append("g")
    .attr("class", "container");
  enter.append("circle");
  enter.append("text");

  container.merge(enter)
    .attr("transform", entry => `translate(0,${entry.top})`)
  svg.selectAll(".container circle")
    .data(data)
    .attr("r", entry => entry.radius)
    .attr("cx", entry => entry.left);
  svg.selectAll(".container text")
    .data(data)
    .text(entry => entry.name);
}
let i = 0;
loadData(DATA);

function updateData() {
  i = (i+1) % 2;
  loadData(DATA.slice(i,i+1));
}
function expectedUpdate() {
  i = (i+1) % 2;
  expected(DATA.slice(i,i+1));
}

button {
  display: inline-block;
}
svg {
  width: 300px;
  height: 300px;
  display: block;
}

<button onclick="updateData();">Update</button>
<button onclick="expectedUpdate();">Expected</button>
<svg id="svg"></svg>

This is just demonstration, where I have a parent <g> element, and 2 children <circle> & <text> are appending to it.

The first time when it renders, I used the loadData() method to populate the DOM, the corresponding children DOMs (circle & text) were able to retrieve the data inserted into their parent DOM (g), which showed a proper data propagation along the DOM tree.

However when I press "update" button multiple times, only the parent DOM is updating, and children DOMs are able access the non-existing data (old data).

The "expected" button shows what is the expected behaviour, but I can see the data is being binded multiple times, which I as a javascript engineer am so afraid of this kind of data binding.

Body:
The main problem in your non-working function (loadData) is that you're using selectAll. Unlike select, selectAll doesn't propagate the data.

Have a look at this table I made summarising the differences between them:

Method
select()
selectAll()

Selection
selects the first element that matches the selector string
selects all elements that match the selector string

Grouping
Does not affect grouping
Affects grouping

Data propagation
Propagates data
Doesn't propagate data

As you can see, the main information for you is this:

select: propagates the data.

selectAll: doesn't propagate the data.

Given that your snippet has just one child (circle and text) per group, the simplest solution is just changing selectAll to select. However, if you have more than one child per parent, the best (and idiomatic) solution is creating a nested enter-update-exit selection, which is a bit more laborious.

Besides that, you're missing the key function:

const container = svg.selectAll(".container")
    .data(data, function(d) {
        return d.name;
    });

Here is your code with those changes:

const DATA = [{
  name: "data1",
  left: 70,
  top: 70,
  radius: 20
}, {
  name: "data2",
  left: 200,
  top: 100,
  radius: 50
}];
const svg = d3.select("#svg");

// Not working as expected
function loadData(data) {
  console.log(data);
  const container = svg.selectAll(".container")
    .data(data, function(d) {
      return d.name;
    });
  container.exit().remove();
  const enter = container.enter().append("g")
    .attr("class", "container");
  enter.append("circle");
  enter.append("text");

  container.merge(enter)
    .attr("transform", entry => `translate(0,${entry.top})`)
  svg.select(".container circle")
    .attr("r", entry => entry.radius)
    .attr("cx", entry => entry.left);
  svg.select(".container text")
    .text(entry => entry.name);
}

// Working, but not desired
function expected(data) {
  console.log(data);
  const container = svg.selectAll(".container")
    .data(data);
  container.exit().remove();
  const enter = container.enter().append("g")
    .attr("class", "container");
  enter.append("circle");
  enter.append("text");

  container.merge(enter)
    .attr("transform", entry => `translate(0,${entry.top})`)
  svg.selectAll(".container circle")
    .data(data)
    .attr("r", entry => entry.radius)
    .attr("cx", entry => entry.left);
  svg.selectAll(".container text")
    .data(data)
    .text(entry => entry.name);
}
let i = 0;
loadData(DATA);

function updateData() {
  i = (i + 1) % 2;
  loadData(DATA.slice(i, i + 1));
}

function expectedUpdate() {
  i = (i + 1) % 2;
  expected(DATA.slice(i, i + 1));
}

button {
  display: inline-block;
}

svg {
  width: 300px;
  height: 300px;
  display: block;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<button onclick="updateData();">Update</button>
<button onclick="expectedUpdate();">Expected</button>
<svg id="svg"></svg>


问:
Rails update element based on AJAX request?
I've been reading a lot about Rails and AJAX and 5.1 Unobtrusive javascript. It explains a lot about responding to Rails version of AJAX calls with a .js file for example.

However what im wanting to do isn't serving up an entire .js file, it's simply updating an element after a <% link_to %> POST request. From my understanding setting remote: true submits it as a AJAX request.

Essentially I have a "Post" which a user can like via a linked Like button. This sends a POST request to the "Post" controller which updates a post to liked and adds a like to the post.

Unfortunately to see the effects of the post being liked (Which is simply that the link changes color as well as the font-awesome icon) you need to refresh the page. I basically want it to update without needing refresh.

I "think" based off what i've read I need to make a respond do and respond via .js to the request with a .js file in the view I want to update (for instance if the controller action is called "like", maybe a like.js.erb file in the view im updating?). But I don't want to serve an entire new page..or would this simply just run the .js?

Then I could do something like $('i.fa-icon#id').style.color = "blue" or something? (Im assuming I can send data from the controller to the .js.erb file?). Not sure the best way to do this, don't rails elements a lot of times have some sort of data-attribute or something (Im still a beginner at this).

答:
Not sure if I understand the question, but if you want to update like button:

What you want to do is to add an event listener to the button, and when clicked it makes a POST request to whatever route handles the likes(with the correct parameters) and your controller should respond with the like object (or whatever in the database gets stored). Have your post request on success method to grab the like button and change it to whatever you want it to look like

```<code>$(“#like-btn”).click(function(){
Rails.ajax({
  url: "/some/url/to/like/controller",
  type: "post",
 data: [your post data],
  success: function(data) { $(`#${ data[“btn-name”] }`).attr(“color”, “blue”; }
})
}
</code>```

You can stick this script right in the bottom of the html page

You don’t have to do it exactly like this, just giving you an idea of how to set up the pattern of having JavaScript and Ajax handle the post request and updating of the frontend instead of using html buttons

Body:
Not sure if I understand the question, but if you want to update like button:

What you want to do is to add an event listener to the button, and when clicked it makes a POST request to whatever route handles the likes(with the correct parameters) and your controller should respond with the like object (or whatever in the database gets stored). Have your post request on success method to grab the like button and change it to whatever you want it to look like

$(“#like-btn”).click(function(){
Rails.ajax({
  url: "/some/url/to/like/controller",
  type: "post",
 data: [your post data],
  success: function(data) { $(`#${ data[“btn-name”] }`).attr(“color”, “blue”; }
})
}

You can stick this script right in the bottom of the html page

You don’t have to do it exactly like this, just giving you an idea of how to set up the pattern of having JavaScript and Ajax handle the post request and updating of the frontend instead of using html buttons


问:
Why grep doesn't match "\<\-v\>"
I want to grep the manual page of gcc for the option '-v'.

man gcc | grep -w '\-v'  works. But I wanted to use regex.

However the following line doesn't match '-v' at the beginning of a word, as I expected:

```<code>grep '\<-v' <<<$'-v'
</code>```

Why?

答:
The word boundary escape sequences differ slightly from -w option, from man grep

-w, --word-regexp

Select  only  those  lines  containing  matches  that  form whole words.  The test is that the matching
  substring must either be at the beginning of the line, or preceded by a non-word constituent character.
  Similarly,  it  must  be either at the end of the line or followed by a non-word constituent character.
  Word-constituent characters are letters, digits, and the underscore.

whereas, word boundaries in regex will only come into play if there are word characters

```<code>$ # this fails because there is no word boundary between space and +
$ # assumes \b is supported, like GNU grep
$ echo '2 +3 = 5' | grep '\b+3\b'
$ # this works as -w only ensures that there are no surrounding word characters
$ echo '2 +3 = 5' | grep -w '+3'
2 +3 = 5

$ # doesn't work as , isn't at start of word boundary
$ echo 'hi, 2 one' | grep '\<, 2\>'
$ # won't match as there are word characters before ,
$ echo 'hi, 2 one' | grep -w ', 2'
$ # works as \b matches both edges and , is at end of word after i
$ echo 'hi, 2 one' | grep '\b, 2\b'
hi, 2 one
</code>```

Title: Why grep doesn't match "\<\-v\>"

Body:
I want to grep the manual page of gcc for the option '-v'.

man gcc | grep -w '\-v'  works. But I wanted to use regex.

However the following line doesn't match '-v' at the beginning of a word, as I expected:

grep '\<-v' <<<$'-v'

Why?

Body:
The word boundary escape sequences differ slightly from -w option, from man grep

-w, --word-regexp

Select  only  those  lines  containing  matches  that  form whole words.  The test is that the matching
  substring must either be at the beginning of the line, or preceded by a non-word constituent character.
  Similarly,  it  must  be either at the end of the line or followed by a non-word constituent character.
  Word-constituent characters are letters, digits, and the underscore.

whereas, word boundaries in regex will only come into play if there are word characters

$ # this fails because there is no word boundary between space and +
$ # assumes \b is supported, like GNU grep
$ echo '2 +3 = 5' | grep '\b+3\b'
$ # this works as -w only ensures that there are no surrounding word characters
$ echo '2 +3 = 5' | grep -w '+3'
2 +3 = 5

$ # doesn't work as , isn't at start of word boundary
$ echo 'hi, 2 one' | grep '\<, 2\>'
$ # won't match as there are word characters before ,
$ echo 'hi, 2 one' | grep -w ', 2'
$ # works as \b matches both edges and , is at end of word after i
$ echo 'hi, 2 one' | grep '\b, 2\b'
hi, 2 one


问:
Why late init var cannot be used with Nullable?
Why can't we use lateinit with nullable variables?

```<code>lateinit var v: String?
</code>```

lateinit modifier is not allowed on properties of nullable types

答:
If you want to make a variable of nullable type then you don't need late init . The doc says

Normally, properties declared as having a non-null type must be initialized in the constructor.
  However, fairly often this is not convenient. For example, properties can be initialized through
  dependency injection, or in the setup method of a unit test. In this case, you cannot supply a nonnull
  initializer in the constructor, but you still want to avoid null checks when referencing the
  property inside the body of a class.

So late init is intended to be used when you intend to initialize a variable somewhere not in the constructor and also want to avoid null checks.


问:
How to count the elements belonging to one label class in a custom keras loss function?
I'm looking for a way to count to number of occurrences of each class in the y_true array in a custom loss function and replace each element in the array with its respective number of occurrences.

I've already implemented a numpy solution, but I can't seem to translate it into keras (with tf backend).

Example Input:

y_true = np.array([0, 1, 1, 1, 0, 3])
```

<p>Imports:</p>

<pre class="lang-py prettyprint-override"><code>import numpy as np
from keras import backend as k
</code>```

Numpy implementation:

def custom_loss(y_true, y_pred):
    bins = np.bincount(y_true)
    y_true_counts = bins[y_true]

    >>> y_true_counts: [2 3 3 3 2 1]
```

<p>Keras implementation:</p>

<pre class="lang-py prettyprint-override"><code>def custom_loss(y_true, y_pred)
    bins = k.tf.bincount(y_true)
    y_true_counts = bins[y_true]
</code>```

While the numpy solution works fine, when I want to evaluate the keras implementation I get the following error:

```<code>a = custom_loss(y_true, y_pred)
>>> InvalidArgumentError: Shape must be rank 1 but is rank 2 for 'strided_slice_4' (op: 'StridedSlice') with input shapes: [?], [1,6], [1,6], [1].
[...]
----> 3     y_true_counts = bins[y_true]
[...]
</code>```

答:
Try tf.bincount and tf.gather.

```<code>import tensorflow as tf

y_true = tf.constant([0, 1, 1, 1, 0, 3],dtype=tf.int32)
bins = tf.bincount(y_true)
y_true_counts = tf.gather(bins,y_true)

with tf.Session()as sess:
    print(sess.run(bins))
    print(sess.run(y_true_counts))

[2 3 0 1]
[2 3 3 3 2 1]
</code>```

Body:
I'm looking for a way to count to number of occurrences of each class in the y_true array in a custom loss function and replace each element in the array with its respective number of occurrences.

I've already implemented a numpy solution, but I can't seem to translate it into keras (with tf backend).

Example Input:

y_true = np.array([0, 1, 1, 1, 0, 3])

Imports:

import numpy as np
from keras import backend as k

Numpy implementation:

def custom_loss(y_true, y_pred):
    bins = np.bincount(y_true)
    y_true_counts = bins[y_true]

    >>> y_true_counts: [2 3 3 3 2 1]

Keras implementation:

def custom_loss(y_true, y_pred)
    bins = k.tf.bincount(y_true)
    y_true_counts = bins[y_true]

While the numpy solution works fine, when I want to evaluate the keras implementation I get the following error:

a = custom_loss(y_true, y_pred)
>>> InvalidArgumentError: Shape must be rank 1 but is rank 2 for 'strided_slice_4' (op: 'StridedSlice') with input shapes: [?], [1,6], [1,6], [1].
[...]
----> 3     y_true_counts = bins[y_true]
[...]

Body:
Try tf.bincount and tf.gather.

import tensorflow as tf

y_true = tf.constant([0, 1, 1, 1, 0, 3],dtype=tf.int32)
bins = tf.bincount(y_true)
y_true_counts = tf.gather(bins,y_true)

with tf.Session()as sess:
    print(sess.run(bins))
    print(sess.run(y_true_counts))

[2 3 0 1]
[2 3 3 3 2 1]


问:
Mixing for each and lambdas in c++
I wanted to play a little bit with  lambdas and for each(Range-based for-loop, not STL for_each) in C++0x. So i went to wiki and tried to rewrite examples from wiki using lambdas:

```<code>    std::vector<int> some_list;
some_list.push_back(42);
some_list.push_back(37);
int total = 0;
int value = 5;
for(int& x:some_list)
{
    [](int x)
    {
        cout << "xL=" <<x <<endl;
    };
}

for(auto x:some_list)
    cout<< "x="<<x<<endl;

    return result;
}
</code>```

Problem is that I don't see any cout in the lambda version, for each version prints x nicely... I presume that it is impossible to mix for each and lambdas because lambdas can only be in the place of the "functions", and cannot act as loop body, but I'm not sure, so if somebody can confirm it would be cool

compiler: GCC 4.6

答:
In the first "for" you only create lambda-function, not call it.

Actually lambda-function doesn't seem to be useful here - you may just write the code. But if you want to use lambda anyway, add "()" after "}".

It's useful in another situation - when std::for_each is used.

Title: Mixing for each and lambdas in c++

Body:
I wanted to play a little bit with  lambdas and for each(Range-based for-loop, not STL for_each) in C++0x. So i went to wiki and tried to rewrite examples from wiki using lambdas:

    std::vector<int> some_list;
some_list.push_back(42);
some_list.push_back(37);
int total = 0;
int value = 5;
for(int& x:some_list)
{
    [](int x)
    {
        cout << "xL=" <<x <<endl;
    };
}

for(auto x:some_list)
    cout<< "x="<<x<<endl;

    return result;
}

Problem is that I don't see any cout in the lambda version, for each version prints x nicely... I presume that it is impossible to mix for each and lambdas because lambdas can only be in the place of the "functions", and cannot act as loop body, but I'm not sure, so if somebody can confirm it would be cool

compiler: GCC 4.6


问:
How can we convert the sql in laravel eloquent / querybuilder
Basically I need to show report where I need to provide few details based on cityId and postCode.

so if, cityId IS NULL  AND postCode IS NULL THEN count of those records should be under data1.

similarly,
 - WHEN    cityId IN (123, 456)   THEN count of those record should be in 'data2'
 - WHEN    cityId IN (789, 999) THEN 'data3'
 - WHEN    cityId IN (111, 222) THEN 'data4'
 - ELSE    'data5'

I have 2 queries here:

Convert this sql into laravel eloquent/querybuilder way.

The last condition which is mentioned

COUNT(CASE WHEN cityId IS NOT NULL AND cityId NOT IN (123, 456, 789, 999, 111, 222) then 1 ELSE NULL END ) as \"data5\"
  from customer
          ")

has to be the else part of all above condition.

I have tried this but not able to achieve the desired result

```<code>$result = Customer::select(Customer::raw("SELECT
    COUNT(CASE WHEN cityId IS NULL AND postCode IS NULL then 1 ELSE NULL END) as \"data1\",
    COUNT(CASE WHEN cityId IN (123, 456) then 1 ELSE NULL END) as \"data2\",
    COUNT(CASE WHEN cityId IN (789,999) then 1 ELSE NULL END) as \"data3\",
    COUNT(CASE WHEN cityId IN (111, 222) then 1 ELSE NULL END) as \"data4\",
    COUNT(CASE WHEN cityId IS NOT NULL AND cityId NOT IN (123, 456, 789, 999, 111, 222) then 1 ELSE NULL END ) as \"data5\"
from trial
        "))->get();
</code>```

Desired Result:
data1: 7
data2: 5
data3: 12
data4: 10
data5: 1

答:
For time being, I got an alternative solution for my question mentioned above which somehow fix my 1st point question.

Still looking for 2nd point of question.

```<code>DB::table('customers')
        ->select(
            DB::raw('COUNT(CASE WHEN cityId IS NULL AND postCode IS NULL then 1 ELSE NULL END) as "data1",
                    COUNT(CASE WHEN cityId IN (123, 456) then 1 ELSE NULL END) as "data2",
                    COUNT(CASE WHEN cityId IN (789,999) then 1 ELSE NULL END) as "data3",
                    COUNT(CASE WHEN cityId IN (4965,4959) then 1 ELSE NULL END) as "data4",
                    COUNT(CASE WHEN cityId IS NOT NULL AND cityId NOT IN (123, 456, 789, 999, 111, 222) then 1 ELSE NULl END ) as "data5"')
        )->get();
</code>```

Body:
Basically I need to show report where I need to provide few details based on cityId and postCode.

so if, cityId IS NULL  AND postCode IS NULL THEN count of those records should be under data1.

similarly,
 - WHEN    cityId IN (123, 456)   THEN count of those record should be in 'data2'
 - WHEN    cityId IN (789, 999) THEN 'data3'
 - WHEN    cityId IN (111, 222) THEN 'data4'
 - ELSE    'data5'

I have 2 queries here:

Convert this sql into laravel eloquent/querybuilder way.

The last condition which is mentioned

COUNT(CASE WHEN cityId IS NOT NULL AND cityId NOT IN (123, 456, 789, 999, 111, 222) then 1 ELSE NULL END ) as \"data5\"
  from customer
          ")

has to be the else part of all above condition.

I have tried this but not able to achieve the desired result

$result = Customer::select(Customer::raw("SELECT
    COUNT(CASE WHEN cityId IS NULL AND postCode IS NULL then 1 ELSE NULL END) as \"data1\",
    COUNT(CASE WHEN cityId IN (123, 456) then 1 ELSE NULL END) as \"data2\",
    COUNT(CASE WHEN cityId IN (789,999) then 1 ELSE NULL END) as \"data3\",
    COUNT(CASE WHEN cityId IN (111, 222) then 1 ELSE NULL END) as \"data4\",
    COUNT(CASE WHEN cityId IS NOT NULL AND cityId NOT IN (123, 456, 789, 999, 111, 222) then 1 ELSE NULL END ) as \"data5\"
from trial
        "))->get();

Desired Result:
data1: 7
data2: 5
data3: 12
data4: 10
data5: 1

Body:
For time being, I got an alternative solution for my question mentioned above which somehow fix my 1st point question.

Still looking for 2nd point of question.

DB::table('customers')
        ->select(
            DB::raw('COUNT(CASE WHEN cityId IS NULL AND postCode IS NULL then 1 ELSE NULL END) as "data1",
                    COUNT(CASE WHEN cityId IN (123, 456) then 1 ELSE NULL END) as "data2",
                    COUNT(CASE WHEN cityId IN (789,999) then 1 ELSE NULL END) as "data3",
                    COUNT(CASE WHEN cityId IN (4965,4959) then 1 ELSE NULL END) as "data4",
                    COUNT(CASE WHEN cityId IS NOT NULL AND cityId NOT IN (123, 456, 789, 999, 111, 222) then 1 ELSE NULl END ) as "data5"')
        )->get();


问:
How to switch to either c++_shared or c++_static with CMAKE?
On android Studio trying to build a project with CPP code but it gave gnustl_static is no longer supported. error. From other answer I added following on build.gradle:

```<code> ndk {
        moduleName = "app"
        stl = "stlport_static"
    }
</code>```

but it doesn't work and shows this error message again. Tried this link added ANDROID_STL=c++_static on cmake{...} but got following error:

```<code>CMake Error: The source directory "G:/Applications/.../app/ANDROID_STL=c++_static" does not exist.
</code>```

How to solve this error message on latest android studio?

答:
The stl property might have been available in the past. But nowadays you would specify the STL using the arguments property, e.g.:

```<code>android {
    defaultConfig {
        externalNativeBuild {
            cmake {
                arguments '-DANDROID_STL=c++_static'
            }
         }
    }
}
</code>```

Note that c++_static is the default when building for Android with cmake. So if that's the STL you want you don't need to specify it at all.

Body:
On android Studio trying to build a project with CPP code but it gave gnustl_static is no longer supported. error. From other answer I added following on build.gradle:

 ndk {
        moduleName = "app"
        stl = "stlport_static"
    }

but it doesn't work and shows this error message again. Tried this link added ANDROID_STL=c++_static on cmake{...} but got following error:

CMake Error: The source directory "G:/Applications/.../app/ANDROID_STL=c++_static" does not exist.

How to solve this error message on latest android studio?

Body:
The stl property might have been available in the past. But nowadays you would specify the STL using the arguments property, e.g.:

android {
    defaultConfig {
        externalNativeBuild {
            cmake {
                arguments '-DANDROID_STL=c++_static'
            }
         }
    }
}

Note that c++_static is the default when building for Android with cmake. So if that's the STL you want you don't need to specify it at all.