问:
angular component, check if attribute exists
Say I have an angular component ie <this-thing></this-thing> which does it's thing.

Now I want to add something extra to it, ie <this-thing glows></this-thing>
I would like the component to change a little if the glow attribute is there.

I have managed to do it via <this-thing [glows]="true"></this-thing> and in the component I have

```<code>@Input() public set glows(value: boolean) {
    console.log(value);
}
</code>```

But that becomes too verbose.

If glows attribute is not on the component, then it's false and if it is, then true.

Is there a better way to acheive this?

Thanks for looking.

答:
I think it depends on what you are trying to achieve. If it is just a boolean value to use in the component/template I don't think you need the setter, so that

```<code>@Input() glows : boolean;
</code>```

in the this-thing.component.ts would be sufficient.

In the this-thing.component.html you could then bind a specific class to the dom element with ngClass

```<code><div [ngClass]="{'glows': glows}">This glows if true</div>
</code>```

this-thing.component.css

```<code>.glows {
box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
}
</code>```

Body:
Say I have an angular component ie <this-thing></this-thing> which does it's thing.

Now I want to add something extra to it, ie <this-thing glows></this-thing>
I would like the component to change a little if the glow attribute is there.

I have managed to do it via <this-thing [glows]="true"></this-thing> and in the component I have

@Input() public set glows(value: boolean) {
    console.log(value);
}

But that becomes too verbose.

If glows attribute is not on the component, then it's false and if it is, then true.

Is there a better way to acheive this?

Thanks for looking.

Body:
I think it depends on what you are trying to achieve. If it is just a boolean value to use in the component/template I don't think you need the setter, so that

@Input() glows : boolean;

in the this-thing.component.ts would be sufficient.

In the this-thing.component.html you could then bind a specific class to the dom element with ngClass

<div [ngClass]="{'glows': glows}">This glows if true</div>

this-thing.component.css

.glows {
box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
}


来源: stackexchange

问:
simplest way to do a recurring text file upload to sql server
i have a TAB DELIMITTED log file where new data in this log file needs to be dumped into a sql server 2008 database. i am wondering what is the best way to automate this? is there a service i can use inside the management studio that will help me? </p>

答:
The best way and the simplest way might not be the same answer.  Probably the best way, since this is recurring, would be to build a SSIS job that converts the file and puts it into the database.  This will allow you to put any business logic into the import (cleaning up data, insert/update if needed, kicking out errors, automation, etc.)

Here is a simple tutorial that walks you through how to utilize SSIS to do this task:

http://decipherinfosys.wordpress.com/2008/07/28/ssis-importing-data-from-a-text-file-using-a-package/

If you want simple, create a little script to import the data in and then run it every time you have a file.  Here is a blog entry that talks about doing an import using just SQL commands.  It is for comma delimited, but you can modify it for tab delimited:

http://blog.sqlauthority.com/2008/02/06/sql-server-import-csv-file-into-sql-server-using-bulk-insert-load-comma-delimited-file-into-sql-server/

ContentLicense: CC BY-SA 3.0


问:
NotFound() returns 200 instead of 404
I've been stuck on this recently and can't figure out why this is happening.

I'm using an MVC Controller in .Net Core to return a NotFound() "404" response.
However, client side (using angular) if I console.log the response, it shows this...

status:200

  statusText:"OK"

Is there any reason why returning NotFound() would return an error code of 200 instead of the intended 404?

This is my Controller GET.

```<code> // GET: api/cause/cause-name
    [HttpGet("{name}")]
    [AllowAnonymous]
    public IActionResult GetCauseByName(string name)
    {
        var input =  _service.GetCauseByName(name);

        if (input == null)
        {
            return NotFound();
        }
        else
        {
            return Ok(input);
        }
    }
</code>```

Any help would be appreciated! Thanks!

To be clear, for this instance assume input is null.  What I'm testing is it hitting NotFound() not the return OK(input).  Breakpoints have been set and it does hit the NotFound() but still returns the response code of 200.

Headers--

```<code>GET /cause/dsdasdas
HTTP/1.1
Host: localhost:48373
Connection: keep-alive
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,/;q=0.8 Accept-Encoding: gzip, deflate, sdch, br Accept-Language: en-US,en;q=0.8

HTTP/1.1
200 OK
Transfer-Encoding: chunked
Content-Type: text/html; charset=utf-8
Content-Encoding: gzip Vary:
Accept-Encoding Server: Kestrel X-SourceFiles: =?UTF-8?B?QzpcVXNlcnNcaXR0ZW1wNVxEZXNrdG9wXFByb2plY3RGdW5kQXBwXHNyY1xQcm9qZWN0RnVuZFxjYXVzZVxkc2Rhc2Rhcw==?= X-Powered-By: ASP.NET Date: Thu, 25 May 2017 14:51:29 GMT –
</code>```

POSTMAN HEADERS

```<code>Content-Encoding →gzip
Content-Type →text/html; charset=utf-8
Date →Thu, 25 May 2017 15:18:31 GMT
Server →Kestrel
Transfer-Encoding →chunked
Vary →Accept-Encoding
X-Powered-By →ASP.NET
X-SourceFiles →=?UTF-8?B?QzpcVXNlcnNcaXR0ZW1wNVxEZXNrdG9wXFByb2plY3RGdW5kQXBwXHNyY1xQcm9qZWN0RnVuZFxjYXVzZVxkc2Rhc2Rhcw==?=
</code>```

答:
I have asked a similar question and received some kind of answer... NotFound() doesn't seem to work as expected

The solution Redirect("~/404.html"); returns 200.

However, there's another way.

```<code>// Wherever you want to return your standard 404 page
return Redirect("Home/StatusCode?code=404");

public class HomeController : Controller
{
    // This method allows for other status codes as well
    public IActionResult StatusCode(int? code)
    {
        // This method is invoked by Startup.cs >>> app.UseStatusCodePagesWithReExecute("/Home/StatusCode", "?code={0}");
        if (code.HasValue)
        {
            // here is the trick
            this.HttpContext.Response.StatusCode = code.Value;
        }

        //return a static file.
        try
        {
            return File("~/" + code + ".html", "text/html");
        }
        catch (FileNotFoundException)
        {
            return Redirect("Home/StatusCode?code=404");
        }
    }
}
</code>```

This does return 404.

Title: NotFound() returns 200 instead of 404

Body:
I've been stuck on this recently and can't figure out why this is happening.

I'm using an MVC Controller in .Net Core to return a NotFound() "404" response.
However, client side (using angular) if I console.log the response, it shows this...

status:200

  statusText:"OK"

Is there any reason why returning NotFound() would return an error code of 200 instead of the intended 404?

This is my Controller GET.

 // GET: api/cause/cause-name
    [HttpGet("{name}")]
    [AllowAnonymous]
    public IActionResult GetCauseByName(string name)
    {
        var input =  _service.GetCauseByName(name);

        if (input == null)
        {
            return NotFound();
        }
        else
        {
            return Ok(input);
        }
    }

Any help would be appreciated! Thanks!

To be clear, for this instance assume input is null.  What I'm testing is it hitting NotFound() not the return OK(input).  Breakpoints have been set and it does hit the NotFound() but still returns the response code of 200.

Headers--

GET /cause/dsdasdas
HTTP/1.1
Host: localhost:48373
Connection: keep-alive
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,/;q=0.8 Accept-Encoding: gzip, deflate, sdch, br Accept-Language: en-US,en;q=0.8

HTTP/1.1
200 OK
Transfer-Encoding: chunked
Content-Type: text/html; charset=utf-8
Content-Encoding: gzip Vary:
Accept-Encoding Server: Kestrel X-SourceFiles: =?UTF-8?B?QzpcVXNlcnNcaXR0ZW1wNVxEZXNrdG9wXFByb2plY3RGdW5kQXBwXHNyY1xQcm9qZWN0RnVuZFxjYXVzZVxkc2Rhc2Rhcw==?= X-Powered-By: ASP.NET Date: Thu, 25 May 2017 14:51:29 GMT –

POSTMAN HEADERS

Content-Encoding →gzip
Content-Type →text/html; charset=utf-8
Date →Thu, 25 May 2017 15:18:31 GMT
Server →Kestrel
Transfer-Encoding →chunked
Vary →Accept-Encoding
X-Powered-By →ASP.NET
X-SourceFiles →=?UTF-8?B?QzpcVXNlcnNcaXR0ZW1wNVxEZXNrdG9wXFByb2plY3RGdW5kQXBwXHNyY1xQcm9qZWN0RnVuZFxjYXVzZVxkc2Rhc2Rhcw==?=

Body:
I have asked a similar question and received some kind of answer... NotFound() doesn't seem to work as expected

The solution Redirect("~/404.html"); returns 200.

However, there's another way.

// Wherever you want to return your standard 404 page
return Redirect("Home/StatusCode?code=404");

public class HomeController : Controller
{
    // This method allows for other status codes as well
    public IActionResult StatusCode(int? code)
    {
        // This method is invoked by Startup.cs >>> app.UseStatusCodePagesWithReExecute("/Home/StatusCode", "?code={0}");
        if (code.HasValue)
        {
            // here is the trick
            this.HttpContext.Response.StatusCode = code.Value;
        }

        //return a static file.
        try
        {
            return File("~/" + code + ".html", "text/html");
        }
        catch (FileNotFoundException)
        {
            return Redirect("Home/StatusCode?code=404");
        }
    }
}

This does return 404.

ContentLicense: CC BY-SA 4.0


问:
How to display Video in Framelayout to portrait mode in Android?
When I launch the application, I need to open the rear camera and display the video. I am using FrameLayout for this. I am able to open the camera and display the video. But the video is getting displayed in landscape mode even though I set the screen orientation as Portrait. Below is the code.

MainActivity.java :

```<code>public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    private static final int VIDEO_CAPTURE = 1;
    private static final int MY_CAMERA_REQUEST_CODE = 100;
    private Camera mCamera;
    private CameraPreview mPreview;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MainActivity.this.setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); // NOT WORKING ------------------------------
        setContentView(R.layout.activity_main);

        TextView wifiTextView = (TextView) findViewById(R.id.wifi_text);

        WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        int rssi = wifiManager.getConnectionInfo().getRssi();
        wifiTextView.setTextColor(Color.WHITE);
        wifiTextView.setText(Integer.toString(rssi));

        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                Log.d(TAG, "No camera permission");
                requestPermissions(new String[]{Manifest.permission.CAMERA}, MY_CAMERA_REQUEST_CODE);
            }
            else {
                Log.d(TAG, "camera permission");
                mCamera = getCameraInstance();
                mPreview = new CameraPreview(this, mCamera);
                FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
                preview.addView(mPreview);
            }
        }
        else {
            Log.d(TAG, "Use camera in OnCreate");
            mCamera = getCameraInstance();
            mPreview = new CameraPreview(this, mCamera);
            FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
            preview.addView(mPreview);
        }
    }

    public static Camera getCameraInstance(){
        Camera c = null;
        try {
            c = Camera.open(); // attempt to get a Camera instance
        }
        catch (Exception e){
            // Camera is not available (in use or does not exist)
        }
        return c; // returns null if camera is unavailable
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == MY_CAMERA_REQUEST_CODE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this, "camera permission granted", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(this, "camera permission denied", Toast.LENGTH_LONG).show();
            }
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        // NOT COMING HERE -------------------------------------------------------
        if(newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            Log.d(TAG, "COnfiguration LANDSCAPE");
        }
        else if(newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
            Log.d(TAG, "COnfiguration PORTRAIT");
        }
        else {
            Log.d(TAG, "Default code");
        }
    }
}
</code>```

CameraPreview.java :

```<code>/** A basic Camera preview class */
public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
    private static final String TAG = "CameraPreview";
    private SurfaceHolder mHolder;
    private Camera mCamera;

    public CameraPreview(Context context, Camera camera) {
        super(context);
        mCamera = camera;

        // Install a SurfaceHolder.Callback so we get notified when the
        // underlying surface is created and destroyed.
        mHolder = getHolder();
        mHolder.addCallback(this);

        // deprecated setting, but required on Android versions prior to 3.0
        mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }

    public void surfaceCreated(SurfaceHolder holder) {
        // The Surface has been created, now tell the camera where to draw the preview.
        try {
            mCamera.setPreviewDisplay(holder);
            mCamera.startPreview();
        } catch (IOException e) {
            Log.d(TAG, "Error setting camera preview: " + e.getMessage());
        }
    }

    public void surfaceDestroyed(SurfaceHolder holder) {
        // empty. Take care of releasing the Camera preview in your activity.
    }

    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
        // If your preview can change or rotate, take care of those events here.
        // Make sure to stop the preview before resizing or reformatting it.

        if (mHolder.getSurface() == null){
            // preview surface does not exist
            return;
        }

        // stop preview before making changes
        try {
            mCamera.stopPreview();
        } catch (Exception e){
            // ignore: tried to stop a non-existent preview
        }

        // set preview size and make any resize, rotate or
        // reformatting changes here

        // start preview with new settings
        try {
            mCamera.setPreviewDisplay(mHolder);
            mCamera.startPreview();

        } catch (Exception e){
            Log.d(TAG, "Error starting camera preview: " + e.getMessage());
        }
    }
}
</code>```

Manifest :

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myapplication">
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-feature android:name="android.hardware.camera" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity"
            android:screenOrientation="portrait"
            android:configChanges="keyboardHidden">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
</code>```

Layout :

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

    <FrameLayout
        android:id="@+id/camera_preview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:screenOrientation="portrait"
        android:layout_weight="1" />

    <TextView
        android:id="@+id/wifi_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

I set the screen Orientation of MainAcitivity as PORTRAIT in Manifest and screen Orientation of FrameLayout as PORTRAIT in Layout. Still Video is getting displayed in Landscape mode. Can any one please let me know how to display Video in Portrait mode programatically.

答:
Please add mCamera.setDisplayOrientation(90); inside CameraPreview(Context context, Camera camera) constructor method and try.

setDisplayOrientation(int) method sets value clockwise and the
  valid values are 0, 90, 180, and 270.

Inorder to set orientation to output video, please add mediaRecorder.setOrientationHint(90); after creating instance of MediaRecorder, as like below

```<code> mediaRecorder = new MediaRecorder();
 mediaRecorder.setOrientationHint(90);
</code>```

setOrientationHint() will set the rotation angle to the output(recorded) video.

For more information, please refer the below links

1.setDisplayOrientation(int)

https://developer.android.com/reference/android/hardware/Camera#setDisplayOrientation(int)enter link description here

2.setOrientationHint(int)

https://developer.android.com/reference/android/media/MediaRecorder#setOrientationHint(int)

Body:
When I launch the application, I need to open the rear camera and display the video. I am using FrameLayout for this. I am able to open the camera and display the video. But the video is getting displayed in landscape mode even though I set the screen orientation as Portrait. Below is the code.

MainActivity.java :

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    private static final int VIDEO_CAPTURE = 1;
    private static final int MY_CAMERA_REQUEST_CODE = 100;
    private Camera mCamera;
    private CameraPreview mPreview;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MainActivity.this.setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); // NOT WORKING ------------------------------
        setContentView(R.layout.activity_main);

        TextView wifiTextView = (TextView) findViewById(R.id.wifi_text);

        WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        int rssi = wifiManager.getConnectionInfo().getRssi();
        wifiTextView.setTextColor(Color.WHITE);
        wifiTextView.setText(Integer.toString(rssi));

        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                Log.d(TAG, "No camera permission");
                requestPermissions(new String[]{Manifest.permission.CAMERA}, MY_CAMERA_REQUEST_CODE);
            }
            else {
                Log.d(TAG, "camera permission");
                mCamera = getCameraInstance();
                mPreview = new CameraPreview(this, mCamera);
                FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
                preview.addView(mPreview);
            }
        }
        else {
            Log.d(TAG, "Use camera in OnCreate");
            mCamera = getCameraInstance();
            mPreview = new CameraPreview(this, mCamera);
            FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
            preview.addView(mPreview);
        }
    }

    public static Camera getCameraInstance(){
        Camera c = null;
        try {
            c = Camera.open(); // attempt to get a Camera instance
        }
        catch (Exception e){
            // Camera is not available (in use or does not exist)
        }
        return c; // returns null if camera is unavailable
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == MY_CAMERA_REQUEST_CODE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this, "camera permission granted", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(this, "camera permission denied", Toast.LENGTH_LONG).show();
            }
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        // NOT COMING HERE -------------------------------------------------------
        if(newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            Log.d(TAG, "COnfiguration LANDSCAPE");
        }
        else if(newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
            Log.d(TAG, "COnfiguration PORTRAIT");
        }
        else {
            Log.d(TAG, "Default code");
        }
    }
}

CameraPreview.java :

/** A basic Camera preview class */
public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
    private static final String TAG = "CameraPreview";
    private SurfaceHolder mHolder;
    private Camera mCamera;

    public CameraPreview(Context context, Camera camera) {
        super(context);
        mCamera = camera;

        // Install a SurfaceHolder.Callback so we get notified when the
        // underlying surface is created and destroyed.
        mHolder = getHolder();
        mHolder.addCallback(this);

        // deprecated setting, but required on Android versions prior to 3.0
        mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }

    public void surfaceCreated(SurfaceHolder holder) {
        // The Surface has been created, now tell the camera where to draw the preview.
        try {
            mCamera.setPreviewDisplay(holder);
            mCamera.startPreview();
        } catch (IOException e) {
            Log.d(TAG, "Error setting camera preview: " + e.getMessage());
        }
    }

    public void surfaceDestroyed(SurfaceHolder holder) {
        // empty. Take care of releasing the Camera preview in your activity.
    }

    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
        // If your preview can change or rotate, take care of those events here.
        // Make sure to stop the preview before resizing or reformatting it.

        if (mHolder.getSurface() == null){
            // preview surface does not exist
            return;
        }

        // stop preview before making changes
        try {
            mCamera.stopPreview();
        } catch (Exception e){
            // ignore: tried to stop a non-existent preview
        }

        // set preview size and make any resize, rotate or
        // reformatting changes here

        // start preview with new settings
        try {
            mCamera.setPreviewDisplay(mHolder);
            mCamera.startPreview();

        } catch (Exception e){
            Log.d(TAG, "Error starting camera preview: " + e.getMessage());
        }
    }
}

Manifest :

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myapplication">
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-feature android:name="android.hardware.camera" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity"
            android:screenOrientation="portrait"
            android:configChanges="keyboardHidden">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Layout :

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

    <FrameLayout
        android:id="@+id/camera_preview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:screenOrientation="portrait"
        android:layout_weight="1" />

    <TextView
        android:id="@+id/wifi_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

I set the screen Orientation of MainAcitivity as PORTRAIT in Manifest and screen Orientation of FrameLayout as PORTRAIT in Layout. Still Video is getting displayed in Landscape mode. Can any one please let me know how to display Video in Portrait mode programatically.

Body:
Please add mCamera.setDisplayOrientation(90); inside CameraPreview(Context context, Camera camera) constructor method and try.

setDisplayOrientation(int) method sets value clockwise and the
  valid values are 0, 90, 180, and 270.

Inorder to set orientation to output video, please add mediaRecorder.setOrientationHint(90); after creating instance of MediaRecorder, as like below

 mediaRecorder = new MediaRecorder();
 mediaRecorder.setOrientationHint(90);

setOrientationHint() will set the rotation angle to the output(recorded) video.

For more information, please refer the below links

1.setDisplayOrientation(int)

https://developer.android.com/reference/android/hardware/Camera#setDisplayOrientation(int)enter link description here

2.setOrientationHint(int)

https://developer.android.com/reference/android/media/MediaRecorder#setOrientationHint(int)


问:
How to create multiple falling down objects by using threads in java?
**   Here i created only one moving object ,i want to create more objects which falls down and has random X coordinate .i know i should implement runnable and i should create squres then store them in a collection but its really hard for me to merge everything.i also might have done some mistakes btw . Could you help me some ?  **</p>

```<code>import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.Random;

public class Project3 extends JFrame {
    public Project3(){
        super("Game");
        setSize(600,600);
        add(new Game(600,600));
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setVisible(true);

    }
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new Project3());
    }

    class Squares{
        public int x;
        public int y;

        public Squares(int x, int y) {
            this.x = x;
            this.y = y;
        }

        public int getX() {
            return x;
        }

        public void setX(int x) {
            this.x = x;
        }

        public int getY() {
            return y;
        }

        public void setY(int y) {
            this.y = y;
        }
    }

    class Game extends JPanel implements ActionListener {
        private int score;
        private java.util.List<Squares> shapeList=new ArrayList<>();
        private boolean play ;
        private int X=50;
        private int Y=0;
        Timer timer=new Timer(10,this);

        public Game(int w , int h){
            Dimension d = new Dimension(w, h);
            setBackground(Color.BLUE);

        }

        @Override
        public void paint(Graphics g) {
            super.paint(g);
            Graphics2D g2d = (Graphics2D) g;
            g2d.fillRect(X,Y,60,60);
            timer.start();

        }

        @Override
        public void actionPerformed(ActionEvent e) {
            Y=Y+5;
            repaint();
            if(Y==600){
                Random random=new Random();
                Y=0;
                X=random.nextInt(600-60);
            }
        }
    }
}
</code>```

```<code>import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;

public class Project3 extends JFrame {
    public Project3() {
        super("Game");
        setSize(600, 600);
        add(new Game(600,600));
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new Project3());
    }

    class Square {
        public int squareX;
        public int squareY;
        int squareW = 25;
        int squareH = 25;

        public Square(int X, int Y) {
            this.squareX = X;
            this.squareY = Y;
        }

        public int getSquareX() {
            return squareX;
        }

        public void setSquareX(int X) {
            this.squareX = X;
        }

        public int getSquareY() {
            return squareY;
        }

        public void setSquareY(int Y) {
            this.squareY = Y;
        }

    }

    class Game extends JPanel implements ActionListener ,Runnable,MouseListener {
        public int score;
        private java.util.List<Square> shapeList = new ArrayList<>();
        Timer timer = new Timer(10, this);
        private boolean play= true;

        public Game(int w, int h) {
            Dimension d = new Dimension(600, 600);
            setBackground(Color.BLUE);
            add(new Label("SCORE...."),BorderLayout.PAGE_END);
        }

        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.setColor(Color.YELLOW);
            for (Square s:shapeList) {
                g.fillRect(s.squareX,s.squareY,25,25);
            }
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            for (Square k : shapeList) {
                k.setSquareY(k.getSquareY() + 5);
                repaint();
            }
        }
        public void stop() {
            play = false;
        }
        @Override
        public void run() {
            while(play){

                int randomNumber=(int)(Math.random()*600)+1;
                shapeList.add(new Square(randomNumber,0));

                for (Square k : shapeList) {
                    if (k.getSquareY()== 600) {
                    stop();
                }try {
                    Thread.sleep(500);
                } catch (InterruptedException ignored) {
                    }
            }
        }
    }

        @Override
        public void mouseClicked(MouseEvent e) {

        }

        @Override
        public void mousePressed(MouseEvent e) {
            int mouseX=e.getX();
            int mouseY=e.getY();
            for (Square s:shapeList){
                if ((mouseX > s.squareX) && (mouseX < s.squareX + s.squareW) && (mouseY > s.squareY) && (mouseY < s.squareY + s.squareH)) {
                    shapeList.remove(s);
                    score++;
                }
            }

        }

        @Override
        public void mouseReleased(MouseEvent e) {

        }

        @Override
        public void mouseEntered(MouseEvent e) {

        }

        @Override
        public void mouseExited(MouseEvent e) {

        }
    }
}
</code>```

答:
This code produces three layers of 'snow flakes' which drift towards the bottom of the screen. </p>

<p>Have a look over it, for tips: </p>

```<code>import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.util.Random;

public class AnimatedSnowFall {

    private JComponent ui = null;

    AnimatedSnowFall() {
        initUI();
    }

    public final void initUI() {
        if (ui != null) {
            return;
        }

        ui = new JPanel(new BorderLayout(4, 4));
        ui.setBorder(new EmptyBorder(4, 4, 4, 4));

        ui.add(new SnowFall());
    }

    public JComponent getUI() {
        return ui;
    }

    public static void main(String[] args) {
        Runnable r = () -> {
            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            } catch (Exception useDefault) {
            }
            AnimatedSnowFall o = new AnimatedSnowFall();

            JFrame f = new JFrame(o.getClass().getSimpleName());
            f.setResizable(false);
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setLocationByPlatform(true);

            f.setContentPane(o.getUI());
            f.pack();
            f.setMinimumSize(f.getSize());

            f.setVisible(true);
        };
        SwingUtilities.invokeLater(r);
    }
}

class SnowFall extends JPanel implements ActionListener {

    Dimension prefSize = new Dimension(1600, 900);
    SnowFlake[] farFlakes = new SnowFlake[200];
    SnowFlake[] midFlakes = new SnowFlake[150];
    SnowFlake[] closeFlakes = new SnowFlake[75];
    Color farColor = new Color(100,100,255);
    Color midColor = new Color(150,150,255);
    Color closeColor = new Color(255,255,255);

    SnowFall() {
        setBackground(Color.BLACK);
        for (int ii = 0; ii < farFlakes.length; ii++) {
            farFlakes[ii] = new SnowFlake(prefSize.width, prefSize.height, 2, 4);
        }
        for (int ii = 0; ii < midFlakes.length; ii++) {
            midFlakes[ii] = new SnowFlake(prefSize.width, prefSize.height, 3, 6);
        }
        for (int ii = 0; ii < closeFlakes.length; ii++) {
            closeFlakes[ii] = new SnowFlake(prefSize.width, prefSize.height, 4, 8);
        }
        Timer timer = new Timer(50, this);
        timer.start();
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);

        g.setColor(farColor);
        for (SnowFlake snowFlake : farFlakes) {
            snowFlake.draw(g);
        }

        g.setColor(midColor);
        for (SnowFlake snowFlake : midFlakes) {
            snowFlake.draw(g);
        }

        g.setColor(closeColor);
        for (SnowFlake snowFlake : closeFlakes) {
            snowFlake.draw(g);
        }
    }

    @Override
    public Dimension getPreferredSize() {
        return prefSize;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        repaint();
    }
}

class SnowFlake {

    int w;
    int h;
    int x;
    int y;
    int size;
    int speed;
    static Random r = new Random();

    SnowFlake(int w, int h, int size, int speed) {
        this.w = w;
        this.h = h;
        x = r.nextInt(w);
        y = r.nextInt(h);
        this.size = size;
        this.speed = speed;
    }

    public void draw(Graphics g) {
        y += speed;
        if (y > h) {
            x = r.nextInt(w);
            y = 0;
        }
        g.fillOval(x, y, size, size);
    }
}
</code>```

Body:
**   Here i created only one moving object ,i want to create more objects which falls down and has random X coordinate .i know i should implement runnable and i should create squres then store them in a collection but its really hard for me to merge everything.i also might have done some mistakes btw . Could you help me some ?  **

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.Random;

public class Project3 extends JFrame {
    public Project3(){
        super("Game");
        setSize(600,600);
        add(new Game(600,600));
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setVisible(true);

    }
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new Project3());
    }

    class Squares{
        public int x;
        public int y;

        public Squares(int x, int y) {
            this.x = x;
            this.y = y;
        }

        public int getX() {
            return x;
        }

        public void setX(int x) {
            this.x = x;
        }

        public int getY() {
            return y;
        }

        public void setY(int y) {
            this.y = y;
        }
    }

    class Game extends JPanel implements ActionListener {
        private int score;
        private java.util.List<Squares> shapeList=new ArrayList<>();
        private boolean play ;
        private int X=50;
        private int Y=0;
        Timer timer=new Timer(10,this);

        public Game(int w , int h){
            Dimension d = new Dimension(w, h);
            setBackground(Color.BLUE);

        }

        @Override
        public void paint(Graphics g) {
            super.paint(g);
            Graphics2D g2d = (Graphics2D) g;
            g2d.fillRect(X,Y,60,60);
            timer.start();

        }

        @Override
        public void actionPerformed(ActionEvent e) {
            Y=Y+5;
            repaint();
            if(Y==600){
                Random random=new Random();
                Y=0;
                X=random.nextInt(600-60);
            }
        }
    }
}

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;

public class Project3 extends JFrame {
    public Project3() {
        super("Game");
        setSize(600, 600);
        add(new Game(600,600));
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new Project3());
    }

    class Square {
        public int squareX;
        public int squareY;
        int squareW = 25;
        int squareH = 25;

        public Square(int X, int Y) {
            this.squareX = X;
            this.squareY = Y;
        }

        public int getSquareX() {
            return squareX;
        }

        public void setSquareX(int X) {
            this.squareX = X;
        }

        public int getSquareY() {
            return squareY;
        }

        public void setSquareY(int Y) {
            this.squareY = Y;
        }

    }

    class Game extends JPanel implements ActionListener ,Runnable,MouseListener {
        public int score;
        private java.util.List<Square> shapeList = new ArrayList<>();
        Timer timer = new Timer(10, this);
        private boolean play= true;

        public Game(int w, int h) {
            Dimension d = new Dimension(600, 600);
            setBackground(Color.BLUE);
            add(new Label("SCORE...."),BorderLayout.PAGE_END);
        }

        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.setColor(Color.YELLOW);
            for (Square s:shapeList) {
                g.fillRect(s.squareX,s.squareY,25,25);
            }
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            for (Square k : shapeList) {
                k.setSquareY(k.getSquareY() + 5);
                repaint();
            }
        }
        public void stop() {
            play = false;
        }
        @Override
        public void run() {
            while(play){

                int randomNumber=(int)(Math.random()*600)+1;
                shapeList.add(new Square(randomNumber,0));

                for (Square k : shapeList) {
                    if (k.getSquareY()== 600) {
                    stop();
                }try {
                    Thread.sleep(500);
                } catch (InterruptedException ignored) {
                    }
            }
        }
    }

        @Override
        public void mouseClicked(MouseEvent e) {

        }

        @Override
        public void mousePressed(MouseEvent e) {
            int mouseX=e.getX();
            int mouseY=e.getY();
            for (Square s:shapeList){
                if ((mouseX > s.squareX) && (mouseX < s.squareX + s.squareW) && (mouseY > s.squareY) && (mouseY < s.squareY + s.squareH)) {
                    shapeList.remove(s);
                    score++;
                }
            }

        }

        @Override
        public void mouseReleased(MouseEvent e) {

        }

        @Override
        public void mouseEntered(MouseEvent e) {

        }

        @Override
        public void mouseExited(MouseEvent e) {

        }
    }
}

Body:
This code produces three layers of 'snow flakes' which drift towards the bottom of the screen.

Have a look over it, for tips:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.util.Random;

public class AnimatedSnowFall {

    private JComponent ui = null;

    AnimatedSnowFall() {
        initUI();
    }

    public final void initUI() {
        if (ui != null) {
            return;
        }

        ui = new JPanel(new BorderLayout(4, 4));
        ui.setBorder(new EmptyBorder(4, 4, 4, 4));

        ui.add(new SnowFall());
    }

    public JComponent getUI() {
        return ui;
    }

    public static void main(String[] args) {
        Runnable r = () -> {
            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            } catch (Exception useDefault) {
            }
            AnimatedSnowFall o = new AnimatedSnowFall();

            JFrame f = new JFrame(o.getClass().getSimpleName());
            f.setResizable(false);
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setLocationByPlatform(true);

            f.setContentPane(o.getUI());
            f.pack();
            f.setMinimumSize(f.getSize());

            f.setVisible(true);
        };
        SwingUtilities.invokeLater(r);
    }
}

class SnowFall extends JPanel implements ActionListener {

    Dimension prefSize = new Dimension(1600, 900);
    SnowFlake[] farFlakes = new SnowFlake[200];
    SnowFlake[] midFlakes = new SnowFlake[150];
    SnowFlake[] closeFlakes = new SnowFlake[75];
    Color farColor = new Color(100,100,255);
    Color midColor = new Color(150,150,255);
    Color closeColor = new Color(255,255,255);

    SnowFall() {
        setBackground(Color.BLACK);
        for (int ii = 0; ii < farFlakes.length; ii++) {
            farFlakes[ii] = new SnowFlake(prefSize.width, prefSize.height, 2, 4);
        }
        for (int ii = 0; ii < midFlakes.length; ii++) {
            midFlakes[ii] = new SnowFlake(prefSize.width, prefSize.height, 3, 6);
        }
        for (int ii = 0; ii < closeFlakes.length; ii++) {
            closeFlakes[ii] = new SnowFlake(prefSize.width, prefSize.height, 4, 8);
        }
        Timer timer = new Timer(50, this);
        timer.start();
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);

        g.setColor(farColor);
        for (SnowFlake snowFlake : farFlakes) {
            snowFlake.draw(g);
        }

        g.setColor(midColor);
        for (SnowFlake snowFlake : midFlakes) {
            snowFlake.draw(g);
        }

        g.setColor(closeColor);
        for (SnowFlake snowFlake : closeFlakes) {
            snowFlake.draw(g);
        }
    }

    @Override
    public Dimension getPreferredSize() {
        return prefSize;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        repaint();
    }
}

class SnowFlake {

    int w;
    int h;
    int x;
    int y;
    int size;
    int speed;
    static Random r = new Random();

    SnowFlake(int w, int h, int size, int speed) {
        this.w = w;
        this.h = h;
        x = r.nextInt(w);
        y = r.nextInt(h);
        this.size = size;
        this.speed = speed;
    }

    public void draw(Graphics g) {
        y += speed;
        if (y > h) {
            x = r.nextInt(w);
            y = 0;
        }
        g.fillOval(x, y, size, size);
    }
}


问:
How to refer to an object properties if I have the object name as string
I'm using Python (the latest one with PyQt5)
In my screen I have 30 labels and their names are label_01 to label_30.
I want to change the text of several labels based on some logic.

The labels that I want to change are kept in a list of strings (names of the labels)
For instance lets assume the my logic selected these labels: label_13, label_16, label_28

The question
Since the list of the labels is dynamic, how can I change the labels in loop that based on the list?

I can do this:  self.label_1.setText('Command sent..')
But how can I pass the label name as parameter instead of "label_1"

Thank you
Eyal

答:
Try setattr which receives 3 params: the object whose attribute has to be set (can be self if used inside of class definition), the name of the attribute as a string and the new value.

Try:

```<code># let `labels_to_change` be your dynamic list of labels you want to change and set them to be equal to new_value
labels_to_change = ['label_1','label_3']
new_value = "new_value"

for label in labels_to_change:
    setattr(getattr(self, label), "text", new_value)
</code>```

Body:
Try setattr which receives 3 params: the object whose attribute has to be set (can be self if used inside of class definition), the name of the attribute as a string and the new value.

Try:

# let `labels_to_change` be your dynamic list of labels you want to change and set them to be equal to new_value
labels_to_change = ['label_1','label_3']
new_value = "new_value"

for label in labels_to_change:
    setattr(getattr(self, label), "text", new_value)


问:
React - Ag-grid cellRendering only on one column header
I am trying to add a button to only one AG-Grid header. I am able to add buttons to all headers using frameworkComponents but I need to apply it to a specific column. I tried headerComponentFramework but couldn't succeed. Any Idea of how to achieve it in ReactJS based project. This question is similar to Angular - Ag-grid cellRendering only on one column header </p>

答: Hope this will help you.You can use any custom button. I used material button for demo Button in custom header of Ag-gird</p>


问:
This is undefined in Vue, using debounce method
I know that using the arrow syntax for a method will cause 'this' to not be mapped to the Vue instance, however in my example I'm using lodash.debounce, and as far as I know I'm not using the arrow syntax here?

Returns Cannot read property '$emit' of undefined

```<code>methods: {
  onChange: debounce(function(el) {
    this.$emit('change', el.target.value)
  }, 1000)
}
</code>```

is there a syntax error in the way I'm writing this debounce function without arrow notation?

答:
Your code should be working. Can you provide some additional context?

A slight improvement: it's usually best to create the debounced function per instance rather than sharing one across all instances of that component.

methods: {
  onChange(e) {
    this.$emit('change', e.target.value)
  }
},

created() {
  this.onChange = _.debounce(this.onChange, 1000)
}
```

<p>Here's a working example:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>new Vue({
  el: '#app',

  data: {
    text: '',
  },

  created() {
    this.onClick = _.debounce(this.onClick, 1000)
  },

  methods: {
    onClick() {
      // this is not undefined here
      this.text += 'Debounced! ';
    }
  }
})</code>```

  <button @click="onClick">Click Me</button>

{{ text }}

```

Body:
I know that using the arrow syntax for a method will cause 'this' to not be mapped to the Vue instance, however in my example I'm using lodash.debounce, and as far as I know I'm not using the arrow syntax here?

Returns Cannot read property '$emit' of undefined

methods: {
  onChange: debounce(function(el) {
    this.$emit('change', el.target.value)
  }, 1000)
}

is there a syntax error in the way I'm writing this debounce function without arrow notation?

Body:
Your code should be working. Can you provide some additional context?

A slight improvement: it's usually best to create the debounced function per instance rather than sharing one across all instances of that component.

methods: {
  onChange(e) {
    this.$emit('change', e.target.value)
  }
},

created() {
  this.onChange = _.debounce(this.onChange, 1000)
}

Here's a working example:

new Vue({
  el: '#app',

  data: {
    text: '',
  },

  created() {
    this.onClick = _.debounce(this.onClick, 1000)
  },

  methods: {
    onClick() {
      // this is not undefined here
      this.text += 'Debounced! ';
    }
  }
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <button @click="onClick">Click Me</button>
  <p>{{ text }}</p>
</div>


问:
Customised programs for Dvorak
I have not configured much keybindings due to my change from QWERTY to Dvorak, 4 months ago. I am using a programmer version of the layout. I find many terminal-based programs, such as Elinks and Vim, easier to use. The experience raises a question:

Which programs are customised for Dvorak?

[Some Elaborating] The term "customised program" means that you can easily use a Dvorak with the program. At least for me, Dvorak has opened my eyes to the shortcuts that I found odd earlier. How about you? Please, do not hesitate mention the programs.

[My Findings]

Opera browser
Opera's keys, such "CTRL+A", "CTRL+E", "CTRL+D" and "CTRL+H", are on the home row in Dvorak. Then, have a look at Qwerty: not on the home row. Is Opera customised for Dvorak or vice versa? Or is it just because of Unix? Earlier, I used Firefox 95% of my time. Now, the ratio is 40% for Firefox.

Terminal apps
The answers have mentioned terminal apps, such as GNU Screen. I am interested to know more about them.

答:
I've been using Dvorak for 10+ years now, and actually have found that most of the QWERTY keybindings are actually just fine on a Dvorak layout.

But, since you're looking for things to customize, I have made extensive bindings changes in gnu emacs for my favorite bindings.  It's fully customizable, and a great editor.  My .emacs file has over 15 years of changes in it -- I'm sure others here have been using it for much longer than that!

Another great program to customize for keybindings is gnu screen, which I'm beginning to use extensively on the machines that I administer remotely.

OwnerDisplayName: UnixBasics

ContentLicense: CC BY-SA 2.5

Title: Customised programs for Dvorak

LastEditorDisplayName: UnixBasics

OwnerDisplayName: slacy


问:
Get live data of nse stocks of all symbols in python/Django
I m working on a stock prediction project. This is how I want:

To show all the stocks available in Nifty50, Nifty100 or so and then the user will select the stock to predict the high and low price of a stock on next day only.

I m using Django.

What I have done till now:
I m able to display a list of stock.

```<code>def index(request):
    api_key = 'myAPI_Key'

    url50 = 'https://archives.nseindia.com/content/indices/ind_nifty50list.csv'
    url100 = 'https://archives.nseindia.com/content/indices/ind_nifty100list.csv'
    url200 = 'https://archives.nseindia.com/content/indices/ind_nifty200list.csv'

    sfifty = requests.get(url50).content
    shundred = requests.get(url100).content
    stwohundred = requests.get(url200).content

    nifty50 = pd.read_csv(io.StringIO(sfifty.decode('utf-8')))
    nifty100 = pd.read_csv(io.StringIO(shundred.decode('utf-8')))
    nifty200 = pd.read_csv(io.StringIO(stwohundred.decode('utf-8')))

    nifty50 = nifty50['Symbol']
    nifty100 = nifty100['Symbol']
    nifty200 = nifty200['Symbol']

    context = {
        'fifty': nifty50,
        'hundred': nifty100,
        'twohundred': nifty200
               }

    return render(request, 'StockPrediction/index.html', context)
</code>```

What I want:
I want to get the live data of all stocks open, high,LTP,Change, Volume.by mean of live data is that it will change as per stock values will change.

Please Help!

答:
You must combine Ajax/Jquery like code below to periodically get data and update values in DOM  :

```<code>(function getStocks() {
    $.ajax({
            type: "GET",
            url: "url to your view",
            success: function (data) {
                // here you can get data from backend and do changes like
                // changing color by the data coming from your view.
            }
        }).then(function() {           // on completion, restart
       setTimeout(getStocks, 30000);  // function refers to itself
    });
})();
</code>```

But be careful about making too requests, you must choose proper interval right in this line setTimeout(getStocks, "proper interval");

And in your view you should put queries into a JSON format something like this :

```<code>return JsonResponse({'stocks': stocks})
</code>```

here stocks must be in json format.

Body:
I m working on a stock prediction project. This is how I want:

To show all the stocks available in Nifty50, Nifty100 or so and then the user will select the stock to predict the high and low price of a stock on next day only.

I m using Django.

What I have done till now:
I m able to display a list of stock.

def index(request):
    api_key = 'myAPI_Key'

    url50 = 'https://archives.nseindia.com/content/indices/ind_nifty50list.csv'
    url100 = 'https://archives.nseindia.com/content/indices/ind_nifty100list.csv'
    url200 = 'https://archives.nseindia.com/content/indices/ind_nifty200list.csv'

    sfifty = requests.get(url50).content
    shundred = requests.get(url100).content
    stwohundred = requests.get(url200).content

    nifty50 = pd.read_csv(io.StringIO(sfifty.decode('utf-8')))
    nifty100 = pd.read_csv(io.StringIO(shundred.decode('utf-8')))
    nifty200 = pd.read_csv(io.StringIO(stwohundred.decode('utf-8')))

    nifty50 = nifty50['Symbol']
    nifty100 = nifty100['Symbol']
    nifty200 = nifty200['Symbol']

    context = {
        'fifty': nifty50,
        'hundred': nifty100,
        'twohundred': nifty200
               }

    return render(request, 'StockPrediction/index.html', context)

What I want:
I want to get the live data of all stocks open, high,LTP,Change, Volume.by mean of live data is that it will change as per stock values will change.

Please Help!

Body:
You must combine Ajax/Jquery like code below to periodically get data and update values in DOM  :

(function getStocks() {
    $.ajax({
            type: "GET",
            url: "url to your view",
            success: function (data) {
                // here you can get data from backend and do changes like
                // changing color by the data coming from your view.
            }
        }).then(function() {           // on completion, restart
       setTimeout(getStocks, 30000);  // function refers to itself
    });
})();

But be careful about making too requests, you must choose proper interval right in this line setTimeout(getStocks, "proper interval");

And in your view you should put queries into a JSON format something like this :

return JsonResponse({'stocks': stocks})

here stocks must be in json format.


问:
Array in URL parameter (Angular)
I have a filter with checkboxes where after checking added parameter to the url like this

```<code>https://localhost:8080/api/records?page=0&locationIds=1,2
</code>```

But want to be like this

```<code>https://localhost:8080/api/records?page=0&locationIds=1&locationIds=2
</code>```

As I understood thats 'cause I pass an Array to URL parameter and my main thought is to rewrite this forEach not for 'key', but for 'httpParams[key]' in file candidate.service.ts(not sure) but don't know how to make it right.
Here is my code:

filter.service.ts. (In this service filter returns as array)

```<code>filterByValues(filterType: string, value): FilterParams {
  if (!this.filterParams[filterType]) {
    this.filterParams[filterType] = [value];
  } else if (this.isValueInParams(this.filterParams[filterType], value)) {
    this.filterParams[filterType] = this.removeValueFromParams(this.filterParams[filterType], value);
  } else {
    this.filterParams[filterType].push(value); //return  [1, 2]
  }
  return this.filterParams;
}

isValueInParams(params, value) {
  return params.some(item => value === item);
}
</code>```

I use this service in other file, when I check some of checkboxes, this id added to Array

candidate-filter.ts

```<code>filterByLocation(location: Location) {
  const filtersToEmit = this.filterService.filterByValues(CandidateFilter.LOCATION, location.id);
  this.candidatesHttpParams.emit(filtersToEmit);
}
</code>```

Here where I add the url:

candidate.service.ts

```<code>get(page: number, httpParams: FilterParams): Observable<Candidate[]> {
  let params = new HttpParams().set('page', page.toString());

  //My main thought is to rewrite this forEach not for 'key', but for 'httpParams[key]'. Not sure

  Object.keys(httpParams).forEach(key =>
  params = params.append(key, httpParams[key])); //key = locationIds, httpParams[key] = [1,2]
  return this.http.get<Candidate[]>(this.url, { params });
}
</code>```

And where actually get Candidates

import-page.ts

```<code> private getCandidates(page: number) {
this.candidateViewService.get(page, this.params)

//this.params = {key: Array(2)} // [1, 2]

  .subscribe(
    (candidates: CandidateView[]) => this.candidates = candidates,
    error => this.logger.error(error.message));
    console.log('this Params',this.params)
}
</code>```

Hope my question is clear. Would be really grateful for any help!

答:
Here is how you can do it.

If you want to pass multiple values from an array for a given key (say locationId), you need to repeat params.append(key, v), for each value v of your array ([1,2])

```<code>get(page: number, filterParams: any): Observable<Candidates[]> {
    let params = new HttpParams().set('page', page.toString());

    Object.keys(filterParams).forEach(key=>
    {
      let val: any = filterParams[key];

      if(Array.isArray(val)) //For arrays, repeatedly add values
      {
          for(let v of val)
          {
            params = params.append(key, v);
          }
      }
      else
      {
        params = params.append(key, val); //add value as is
      }

   });
 return this.http.get<any[]>(this.url, { params  });
}
</code>```

Stackblitz demo (check network tab to see request)

Title: Array in URL parameter (Angular)

Body:
I have a filter with checkboxes where after checking added parameter to the url like this

https://localhost:8080/api/records?page=0&locationIds=1,2

But want to be like this

https://localhost:8080/api/records?page=0&locationIds=1&locationIds=2

As I understood thats 'cause I pass an Array to URL parameter and my main thought is to rewrite this forEach not for 'key', but for 'httpParams[key]' in file candidate.service.ts(not sure) but don't know how to make it right.
Here is my code:

filter.service.ts. (In this service filter returns as array)

filterByValues(filterType: string, value): FilterParams {
  if (!this.filterParams[filterType]) {
    this.filterParams[filterType] = [value];
  } else if (this.isValueInParams(this.filterParams[filterType], value)) {
    this.filterParams[filterType] = this.removeValueFromParams(this.filterParams[filterType], value);
  } else {
    this.filterParams[filterType].push(value); //return  [1, 2]
  }
  return this.filterParams;
}

isValueInParams(params, value) {
  return params.some(item => value === item);
}

I use this service in other file, when I check some of checkboxes, this id added to Array

candidate-filter.ts

filterByLocation(location: Location) {
  const filtersToEmit = this.filterService.filterByValues(CandidateFilter.LOCATION, location.id);
  this.candidatesHttpParams.emit(filtersToEmit);
}

Here where I add the url:

candidate.service.ts

get(page: number, httpParams: FilterParams): Observable<Candidate[]> {
  let params = new HttpParams().set('page', page.toString());

  //My main thought is to rewrite this forEach not for 'key', but for 'httpParams[key]'. Not sure

  Object.keys(httpParams).forEach(key =>
  params = params.append(key, httpParams[key])); //key = locationIds, httpParams[key] = [1,2]
  return this.http.get<Candidate[]>(this.url, { params });
}

And where actually get Candidates

import-page.ts

 private getCandidates(page: number) {
this.candidateViewService.get(page, this.params)

//this.params = {key: Array(2)} // [1, 2]

  .subscribe(
    (candidates: CandidateView[]) => this.candidates = candidates,
    error => this.logger.error(error.message));
    console.log('this Params',this.params)
}

Hope my question is clear. Would be really grateful for any help!

Body:
Here is how you can do it.

If you want to pass multiple values from an array for a given key (say locationId), you need to repeat params.append(key, v), for each value v of your array ([1,2])

get(page: number, filterParams: any): Observable<Candidates[]> {
    let params = new HttpParams().set('page', page.toString());

    Object.keys(filterParams).forEach(key=>
    {
      let val: any = filterParams[key];

      if(Array.isArray(val)) //For arrays, repeatedly add values
      {
          for(let v of val)
          {
            params = params.append(key, v);
          }
      }
      else
      {
        params = params.append(key, val); //add value as is
      }

   });
 return this.http.get<any[]>(this.url, { params  });
}

Stackblitz demo (check network tab to see request)


问:
How to return multiple values from function in Dart?
Say I have:

```<code>Function(int x, int y) func = (int x, int y) {
  return (1, 2); // error
};
</code>```

How to actually return (1, 2) from above function?

答:
Methods in Dart can only return one value. So if you need to return multiple values you need to pack them inside another object which could e.g. be your own defined class, a list, a map or something else.

In your case with x and y you could consider using the Point class from dart:math:

```<code>import 'dart:math';

Point<int> func(int x, int y) => Point(x, y);
</code>```

Support for returning multiple values in Dart are a ongoing discussion here:
https://github.com/dart-lang/language/issues/68

Body:
Say I have:

Function(int x, int y) func = (int x, int y) {
  return (1, 2); // error
};

How to actually return (1, 2) from above function?

Body:
Methods in Dart can only return one value. So if you need to return multiple values you need to pack them inside another object which could e.g. be your own defined class, a list, a map or something else.

In your case with x and y you could consider using the Point class from dart:math:

import 'dart:math';

Point<int> func(int x, int y) => Point(x, y);

Support for returning multiple values in Dart are a ongoing discussion here:
https://github.com/dart-lang/language/issues/68


问:
How to remove an element from MySQL's JSON array inside an object?
I have a mysql table "tbl1" with a JSON field "numbers" containing values like this:

{ "start" : ["101","102","104"], "final" : ["102","105","106"] }

How can i update "numbers" to remove a specific element (i.e. "102") from "start" and "final" ?

I know i have to use a combination of JSON_REMOVE and JSON_SEARCH but i don't find the solution.

答:
```<code>WITH RECURSIVE
cte AS ( SELECT JSON_REMOVE(json_field, JSON_UNQUOTE(JSON_SEARCH(json_field, 'one', '102'))) json_field
         FROM source_table
         UNION ALL
         SELECT JSON_REMOVE(json_field, JSON_UNQUOTE(JSON_SEARCH(json_field, 'one', '102'))) json_field
         FROM cte
         WHERE JSON_SEARCH(json_field, 'one', '102') )
SELECT json_field
FROM cte
WHERE JSON_SEARCH(json_field, 'one', '102') IS NULL;
</code>```

and respectively

```<code>UPDATE source_table
JOIN (  WITH RECURSIVE
        cte AS ( SELECT id, JSON_REMOVE(json_field, JSON_UNQUOTE(JSON_SEARCH(json_field, 'one', '102'))) json_field
                 FROM source_table
                 UNION ALL
                 SELECT id, JSON_REMOVE(json_field, JSON_UNQUOTE(JSON_SEARCH(json_field, 'one', '102'))) json_field
                 FROM cte
                 WHERE JSON_SEARCH(json_field, 'one', '102') )
        SELECT id, json_field
        FROM cte
        WHERE JSON_SEARCH(json_field, 'one', '102') IS NULL
     ) processed USING (id)
SET source_table.json_field = processed.json_field;
</code>```

Body:
WITH RECURSIVE
cte AS ( SELECT JSON_REMOVE(json_field, JSON_UNQUOTE(JSON_SEARCH(json_field, 'one', '102'))) json_field
         FROM source_table
         UNION ALL
         SELECT JSON_REMOVE(json_field, JSON_UNQUOTE(JSON_SEARCH(json_field, 'one', '102'))) json_field
         FROM cte
         WHERE JSON_SEARCH(json_field, 'one', '102') )
SELECT json_field
FROM cte
WHERE JSON_SEARCH(json_field, 'one', '102') IS NULL;

and respectively

UPDATE source_table
JOIN (  WITH RECURSIVE
        cte AS ( SELECT id, JSON_REMOVE(json_field, JSON_UNQUOTE(JSON_SEARCH(json_field, 'one', '102'))) json_field
                 FROM source_table
                 UNION ALL
                 SELECT id, JSON_REMOVE(json_field, JSON_UNQUOTE(JSON_SEARCH(json_field, 'one', '102'))) json_field
                 FROM cte
                 WHERE JSON_SEARCH(json_field, 'one', '102') )
        SELECT id, json_field
        FROM cte
        WHERE JSON_SEARCH(json_field, 'one', '102') IS NULL
     ) processed USING (id)
SET source_table.json_field = processed.json_field;


问:
what is the use of ! sign in some ruby methods

Possible Duplicate:

  Why are exclamation marks used in Ruby methods?

Hi All,

In ruby/rails I have seen some methods ended up with ! sign like

```<code>before_filter :authenticated!
</code>```

just wonder what does mean by authenticated!, '!' sign

thanks in advance

cheers

sameera

答:
As a convention, identifier? are used as predicate names, and identifier! are used for the more destructive (or more dangerous) methods than the method which have same name without !.

Source

Example:

lstrip will return a new string with leading spaces removed thus original string is un-modified.
lstrip! will modify the string-in place

Body:
Possible Duplicate:

  Why are exclamation marks used in Ruby methods?

Hi All,

In ruby/rails I have seen some methods ended up with ! sign like

before_filter :authenticated!

just wonder what does mean by authenticated!, '!' sign

thanks in advance

cheers

sameera


问:
Building Mapbox in Unity
I don't know if this has already been asked but I am trying to build an app in unity using the Mapbox SDK. The problem is that when I try building it in a WebGL format, then it says this:

"Build completed with a result of 'Failed'
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr) (at C:/buildslave/unity/build/Modules/IMGUI/GUIUtility.cs:179)"

Does anyone if Mapbox supports building in WebGL and if not, what another way can I use to share my app as an online game?
I hope this is enough info. Please try and make it simple, I don't know much about this kind of stuff.

Thank you!

答:
From below 2 posts, it appears that in order to build it on WebGL, you would have to get rid of the AR folders and files.

https://github.com/mapbox/mapbox-gl-js/issues/7531

https://medium.com/@jonathanwitcoski/day-20-making-a-webgl-game-in-unity-with-mapbox-sdk-31aeb147df15

Title: Building Mapbox in Unity


问:
result from a template function unexpected
this code doesn't give me the expected result! how is that?

```<code>template<typename T, std::enable_if_t < std::is_arithmetic_v<T>,bool> =true>
auto avr(T t)
{
    return t;
}
template<typename T,class ... C, std::enable_if_t<(std::is_arithmetic_v<T> &&...&& std::is_arithmetic_v<C>), bool> =true>
auto avr(T t,C...c)
{
    return (t + avr(c...)) / (sizeof...(c)+1);
}

int main()
{
    std::cout<<avr(1,5,3,7);

    return 0;
}
</code>```

can someone explain how to resolve that?

答:
Because each time you divide by the sizeof, not just the first one, instead you should do something like this:

```<code>template<class ... C, std::enable_if_t<(...&& std::is_arithmetic_v<C>), bool> =true>
auto sum(C...c)
{
    return (c + ...);
}
template<typename T,class ... C, std::enable_if_t<(std::is_arithmetic_v<T> &&...&& std::is_arithmetic_v<C>), bool> =true>
auto avr(T t,C...c)
{
    return (t + sum(c...)) / (sizeof...(c)+1);
}
</code>```

and so first sum the numbers, and then divide (only one time)

Body:
this code doesn't give me the expected result! how is that?

template<typename T, std::enable_if_t < std::is_arithmetic_v<T>,bool> =true>
auto avr(T t)
{
    return t;
}
template<typename T,class ... C, std::enable_if_t<(std::is_arithmetic_v<T> &&...&& std::is_arithmetic_v<C>), bool> =true>
auto avr(T t,C...c)
{
    return (t + avr(c...)) / (sizeof...(c)+1);
}

int main()
{
    std::cout<<avr(1,5,3,7);

    return 0;
}

can someone explain how to resolve that?

Body:
Because each time you divide by the sizeof, not just the first one, instead you should do something like this:

template<class ... C, std::enable_if_t<(...&& std::is_arithmetic_v<C>), bool> =true>
auto sum(C...c)
{
    return (c + ...);
}
template<typename T,class ... C, std::enable_if_t<(std::is_arithmetic_v<T> &&...&& std::is_arithmetic_v<C>), bool> =true>
auto avr(T t,C...c)
{
    return (t + sum(c...)) / (sizeof...(c)+1);
}

and so first sum the numbers, and then divide (only one time)


问:
Why Apps Script execution failed only when it is triggered by onEdit event on Google Spreadsheet?
I am working on Google Apps Script. I have apps script that I have wrote that is supposed to be executed by onEdit event on specific sheet.

onEdit.gs

```<code>function onEdit(e) {
    var syokuninIchiran = new SyokuninIchiran();
    syokuninIchiran.syncTable();
}
</code>```

When the above is executed by edit on the sheet, this error occurs:

You do not have permission to call openById. Required privilege: https://www.googleapis.com/auth/spreadsheets

But, it works with no problem when the script is triggered from Google Apps Script development window. I call the same code by making a test function as follows:

```<code>function test(){
  var syokuninIchiran = new SyokuninIchiran();
  syokuninIchiran.syncTable();
}
</code>```

It might be problem for this issue? The spreadsheet's owner is not mine. My account has right to edit as the image below.

Try1:
I tried to add the scope manually into the manifest file(appsscript.json). And I approved the authorization. But, nothing changed. It still have the same error message.

```<code>{
  "oauthScopes": [
    "https://www.googleapis.com/auth/sqlservice",
    "https://www.googleapis.com/auth/spreadsheets",
    "https://www.googleapis.com/auth/script.external_request"
    ]
}
</code>```

答:
Answer:

Simple Triggers can not open files aside from the file it is bound to. For this, you need to use an installable trigger.

More Information:

As per the documentation on Simple Trigger restrictions:

Because simple triggers fire automatically, without asking the user for authorization, they are subject to several restrictions:

They can modify the file they are bound to, but cannot access other files because that would require authorization.

So an installable trigger must be used.

Setting up the Installable Trigger:

Follow the Edit > Current project's triggers menu item, which will open a new page in the G Suite Developer Hub. Click the + Add Trigger button in the bottom right and set up the trigger settings as follows:

Choose which function to run: onEdit

Choose which deployment should run: Head

Select event source: From Spreadsheet

Select type of time based trigger: On Edit

And press save. This will increase the range of functionality of your edit triggers.

References:

Simple Triggers | Apps Script | Google Developers

Installable Triggers | Apps Script | Google Developers

Body:
I am working on Google Apps Script. I have apps script that I have wrote that is supposed to be executed by onEdit event on specific sheet.

onEdit.gs

function onEdit(e) {
    var syokuninIchiran = new SyokuninIchiran();
    syokuninIchiran.syncTable();
}

When the above is executed by edit on the sheet, this error occurs:

You do not have permission to call openById. Required privilege: https://www.googleapis.com/auth/spreadsheets

But, it works with no problem when the script is triggered from Google Apps Script development window. I call the same code by making a test function as follows:

function test(){
  var syokuninIchiran = new SyokuninIchiran();
  syokuninIchiran.syncTable();
}

It might be problem for this issue? The spreadsheet's owner is not mine. My account has right to edit as the image below.

Try1:
I tried to add the scope manually into the manifest file(appsscript.json). And I approved the authorization. But, nothing changed. It still have the same error message.

{
  "oauthScopes": [
    "https://www.googleapis.com/auth/sqlservice",
    "https://www.googleapis.com/auth/spreadsheets",
    "https://www.googleapis.com/auth/script.external_request"
    ]
}


答:
I assumed that you wanted to use an incremental mean computation.

In that case there are two problems:

First: you need to multiply by sizeof...(c) for each update

```<code>auto
avr(T t, C... c)
{
  return (t + sizeof...(c)*avr(c...)) / (sizeof...(c) + 1);
}
</code>```

Second: you must use avr(1., 5., 3., 7.) otherwise, with avr(1, 5, 3, 7), you use integer arithmetic (T,C...=int) and get a wrong result

```<code>int
main()
{
  std::cout << avr(1., 5., 3., 7.);

  return 0;
}
</code>```

With these two modifications you get your expected result: 4

Update: if you wanted to use the classical formula: mean = sum / n, see other answers. However you still have to use real arithmetic for the last division.

Title: result from a template function unexpected

Body:
I assumed that you wanted to use an incremental mean computation.

In that case there are two problems:

First: you need to multiply by sizeof...(c) for each update

auto
avr(T t, C... c)
{
  return (t + sizeof...(c)*avr(c...)) / (sizeof...(c) + 1);
}

Second: you must use avr(1., 5., 3., 7.) otherwise, with avr(1, 5, 3, 7), you use integer arithmetic (T,C...=int) and get a wrong result

int
main()
{
  std::cout << avr(1., 5., 3., 7.);

  return 0;
}

With these two modifications you get your expected result: 4

Update: if you wanted to use the classical formula: mean = sum / n, see other answers. However you still have to use real arithmetic for the last division.


问:
Adsense code with heavily negative impact on google pagespeed score
After integrating the adsense javascript (adsbygoogle.js) on my website, i loose mobile around 14 points. Check the before after screenshot (88 vs 74 points on mobile). </p>

<p>Google punishes their own scripts?! Does someone of you has a solution for that? </p>

答:
There is no quick solution for that. In my experience Adsense does slow pages down a little, but that's because they have to go through a whole process of auctioning and showing ads.

The real question you should be asking yourself is: does monetization make up for the loss of speed?

Body:
After integrating the adsense javascript (adsbygoogle.js) on my website, i loose mobile around 14 points. Check the before after screenshot (88 vs 74 points on mobile).

Google punishes their own scripts?! Does someone of you has a solution for that?


问:
_corrupt_record error when reading a JSON file into Spark
I've got this JSON file

```<code>{
    "a": 1,
    "b": 2
}
</code>```

which has been obtained with Python json.dump method.
Now, I want to read this file into a DataFrame in Spark, using pyspark. Following documentation, I'm doing this

sc = SparkContext()

sqlc = SQLContext(sc)

df = sqlc.read.json('my_file.json')

print df.show()

The print statement spits out this though:

```<code>+---------------+
|_corrupt_record|
+---------------+
|              {|
|       "a": 1, |
|         "b": 2|
|              }|
+---------------+
</code>```

Anyone knows what's going on and why it is not interpreting the file correctly?

答:
I want to share my experience in which I have a JSON column String  but with Python notation, which means I have None instead of null, False instead of false and True instead of true.

When parsing this column, spark returns me a column named _corrupt_record. So what I had to do before parsing the JSON String is replacing the Python notation with the standard JSON notation:

```<code>df.withColumn("json_notation",
    F.regexp_replace(F.regexp_replace(F.regexp_replace("_corrupt_record", "None", "null"), "False", "false") ,"True", "true")
</code>```

After this transformation I was then able to use for example the function F.from_json() on the json_notation column and here Pyspark was able to correctly parse the JSON object.

Body:
I've got this JSON file

{
    "a": 1,
    "b": 2
}

which has been obtained with Python json.dump method.
Now, I want to read this file into a DataFrame in Spark, using pyspark. Following documentation, I'm doing this

sc = SparkContext()

sqlc = SQLContext(sc)

df = sqlc.read.json('my_file.json')

print df.show()

The print statement spits out this though:

+---------------+
|_corrupt_record|
+---------------+
|              {|
|       "a": 1, |
|         "b": 2|
|              }|
+---------------+

Anyone knows what's going on and why it is not interpreting the file correctly?

Body:
I want to share my experience in which I have a JSON column String  but with Python notation, which means I have None instead of null, False instead of false and True instead of true.

When parsing this column, spark returns me a column named _corrupt_record. So what I had to do before parsing the JSON String is replacing the Python notation with the standard JSON notation:

df.withColumn("json_notation",
    F.regexp_replace(F.regexp_replace(F.regexp_replace("_corrupt_record", "None", "null"), "False", "false") ,"True", "true")

After this transformation I was then able to use for example the function F.from_json() on the json_notation column and here Pyspark was able to correctly parse the JSON object.


问:
React.js: Set time limit for axios to wait for a response
I want to set a time limit for an axios request to wait for a response

For example, I fired a request from the client then I would like to set the system to wait for only 8 seconds then show a request time out

Kindly see my axios request below

```<code>executeJwtAuthenticationService(username, password) {
    return axios.post(`${API_URL_LOCAL}`, {
      username,
      password,
    });
  }
</code>```

How would I pattern it similar to this?

```<code>axios({
  method: 'post',
  url: '/user',
  timeout: 8000, // Let's say you want to wait at least 8 seconds
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
})
</code>```

答:
Try Promise.race:

```<code>executeJwtAuthenticationService(username, password) {
  const timeoutPromise = new Promise(resolve => {
    const timeout = setTimeout(() => {
      clearTimeout(timeout);
      resolve('It took too long...');
    }, 8000);
  });

  const request = axios.post(`${API_URL_LOCAL}`, {
    username,
    password,
  });

  return Promise.race([timeoutPromise, request]);
}
</code>```

You'll probably want to add a similar promise timeout to 'catch' in case response takes long time and fails in the end.
Read about race on MDN

Body:
I want to set a time limit for an axios request to wait for a response

For example, I fired a request from the client then I would like to set the system to wait for only 8 seconds then show a request time out

Kindly see my axios request below

executeJwtAuthenticationService(username, password) {
    return axios.post(`${API_URL_LOCAL}`, {
      username,
      password,
    });
  }

How would I pattern it similar to this?

axios({
  method: 'post',
  url: '/user',
  timeout: 8000, // Let's say you want to wait at least 8 seconds
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
})

Body:
Try Promise.race:

executeJwtAuthenticationService(username, password) {
  const timeoutPromise = new Promise(resolve => {
    const timeout = setTimeout(() => {
      clearTimeout(timeout);
      resolve('It took too long...');
    }, 8000);
  });

  const request = axios.post(`${API_URL_LOCAL}`, {
    username,
    password,
  });

  return Promise.race([timeoutPromise, request]);
}

You'll probably want to add a similar promise timeout to 'catch' in case response takes long time and fails in the end.
Read about race on MDN


问:
PayTm Transaction Status API
I need a help in implementing of paytm payment gateway. i am implementing the gateway in laravel and i have coded it correctly and i have no errors and the sandbox keys are working fine and i am getting the responses also. My Issue is, I need to get the details of a transaction with the transaction ID/TXNID,

I've gone through the doc and found this [https://developer.paytm.com/docs/transaction-status-api/][1]
found almost what i can achieve, But It's getting the parameter of ORDER_ID Not TXN_ID, Is there any way get the details of transaction via Transaction ID.

Thank you.

答: There is no such api to get the status of payment via transaction id. Kindly use ORDERID which you sent in the request parameter at the time of transaction..</p>

Title: PayTm Transaction Status API


问:
Fill new pandas df based off values in another df
I am new here, so please don't be to hard on me! :)

See picture below!

I am trying to create a new dataframe (df['New_df']) based on the values in df['Datan'] so that df['New_df'] is equal to df['Datan'] on the rows where the string #SRU appears. If the string is not in df['Datan'], I want df['New_df'] to "keep" the value of the row above (where the #SRU string was included).

See below df of what I am trying to do.

```<code>                                          Datan          New_df
                                 #SRU 1512 7251  #SRU 1512 7251
   #KONTO 1513 "Kundfordringar - delad faktura"  #SRU 1512 7251
                                 #SRU 1513 7251  #SRU 1513 7251
   #KONTO 1519 "Nedskrivning av kundfordringar"  #SRU 1513 7251
                                 #SRU 1519 7251  #SRU 1519 7251
</code>```

I have been trying around with for loops combined with if statements with the apply method in particular but haven't reached a solution as of yet. Not able to find this specific problem in any other threads here.

答:
Use, the combination of Series.str.contains, Series.mask & Series.ffill:

```<code>m = df['Datan'].str.contains(r'#SRU')
df['New_df'] = df['Datan'].mask(~m).ffill()
</code>```

Result:

```<code># print(df)
                                          Datan          New_df
0                                #SRU 1512 7251  #SRU 1512 7251
1  #KONTO 1513 "Kundfordringar - delad faktura"  #SRU 1512 7251
2                                #SRU 1513 7251  #SRU 1513 7251
3  #KONTO 1519 "Nedskrivning av kundfordringar"  #SRU 1513 7251
4                                #SRU 1519 7251  #SRU 1519 7251
</code>```

Body:
I am new here, so please don't be to hard on me! :)

See picture below!

I am trying to create a new dataframe (df['New_df']) based on the values in df['Datan'] so that df['New_df'] is equal to df['Datan'] on the rows where the string #SRU appears. If the string is not in df['Datan'], I want df['New_df'] to "keep" the value of the row above (where the #SRU string was included).

See below df of what I am trying to do.

                                          Datan          New_df
                                 #SRU 1512 7251  #SRU 1512 7251
   #KONTO 1513 "Kundfordringar - delad faktura"  #SRU 1512 7251
                                 #SRU 1513 7251  #SRU 1513 7251
   #KONTO 1519 "Nedskrivning av kundfordringar"  #SRU 1513 7251
                                 #SRU 1519 7251  #SRU 1519 7251

I have been trying around with for loops combined with if statements with the apply method in particular but haven't reached a solution as of yet. Not able to find this specific problem in any other threads here.

Body:
Use, the combination of Series.str.contains, Series.mask & Series.ffill:

m = df['Datan'].str.contains(r'#SRU')
df['New_df'] = df['Datan'].mask(~m).ffill()

Result:

# print(df)
                                          Datan          New_df
0                                #SRU 1512 7251  #SRU 1512 7251
1  #KONTO 1513 "Kundfordringar - delad faktura"  #SRU 1512 7251
2                                #SRU 1513 7251  #SRU 1513 7251
3  #KONTO 1519 "Nedskrivning av kundfordringar"  #SRU 1513 7251
4                                #SRU 1519 7251  #SRU 1519 7251


问:
How to make a navbar that could change size individually on mouse hover?

<!DOCTYPE html>

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

Responsive Navbar with Links of Same Width

Try to resize the browser window to see the responsive effect.

    Home
    Search
    Contact
    Login

```

enter image description here

In the image, when I hover to the home in navbar, all the height of the nav bar changed same with the one that is hovered. My question is, Is there a way to make the size change individually on hover, so when I hover the home link, it only change the height of the home link?

答:
You can give the parent .navbar a fixed height, and remove overflow: auto (which will set it to the default value overflow:visible.

```<code> .navbar {
      height: 45px;
      width: 100%;
      background-color: #555;
    }
</code>```

JSFiddle: Demo

Body:
<!DOCTYPE html>

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

Responsive Navbar with Links of Same Width

Try to resize the browser window to see the responsive effect.

    Home
    Search
    Contact
    Login

enter image description here

In the image, when I hover to the home in navbar, all the height of the nav bar changed same with the one that is hovered. My question is, Is there a way to make the size change individually on hover, so when I hover the home link, it only change the height of the home link?

Body:
You can give the parent .navbar a fixed height, and remove overflow: auto (which will set it to the default value overflow:visible.

 .navbar {
      height: 45px;
      width: 100%;
      background-color: #555;
    }

JSFiddle: Demo


问:
Django urls handle slug with slash inside e.g. /main/subpage
I have this in my urls.py

```<code>path('<str:slug>', views.page, name='page'),
</code>```

which I want to handle any links that didn't get caught above, think of the slug like a url link that can be deep like main\subpage\sub-sub-link which I can match to a page.

Thing is it seems the slug will only handle one layer like \main is there a way to pipe all of that sublink info e.g. domain.com/this/that/that-that so my slug will be this/that/that-that

答:
You should probably use get_absolute_url()

In your models.py

```<code>from django.urls import reverse

# some model...

class Post(models.Model):
    slug = models.SlugField()

    # ...other model parameters

    def get_absolute_url(self):
        return reverse('<your_app_name>:page', {'slug':self.slug})
</code>```

In your urls.py

```<code>path('<slug>/', views.page, name='page'),
</code>```

In your views.py

```<code>from .models import Post

def page(request):
  posts = Post.objects.all()

  context = {
       'posts':posts
   }
   return render('path_to_your_template.html', request, context)
</code>```

In your template.html
You can do

```<code>{%for post in posts %}
    <a href={{post.get_absolute_url}}>{{post.title}}</a>
{%endfor%}
</code>```

Body:
I have this in my urls.py

path('<str:slug>', views.page, name='page'),

which I want to handle any links that didn't get caught above, think of the slug like a url link that can be deep like main\subpage\sub-sub-link which I can match to a page.

Thing is it seems the slug will only handle one layer like \main is there a way to pipe all of that sublink info e.g. domain.com/this/that/that-that so my slug will be this/that/that-that

Body:
You should probably use get_absolute_url()

In your models.py

from django.urls import reverse

# some model...

class Post(models.Model):
    slug = models.SlugField()

    # ...other model parameters

    def get_absolute_url(self):
        return reverse('<your_app_name>:page', {'slug':self.slug})

In your urls.py

path('<slug>/', views.page, name='page'),

In your views.py

from .models import Post

def page(request):
  posts = Post.objects.all()

  context = {
       'posts':posts
   }
   return render('path_to_your_template.html', request, context)

In your template.html
You can do

{%for post in posts %}
    <a href={{post.get_absolute_url}}>{{post.title}}</a>
{%endfor%}


答:
Use str.contains to check string match and then use ffill to fill na

```<code>df['New_df'] = df.Datan.where(df.Datan.str.contains('#SRU')).ffill()
</code>```

```<code>df
   Index                                           Datan            New_df
0     95                                 #SRU 1512 7251    #SRU 1512 7251
1     96   #KONTO 1513 "Kundfordringar - delad faktura"    #SRU 1512 7251
2     97                                 #SRU 1513 7251    #SRU 1513 7251
3     98   #KONTO 1519 "Nedskrivning av kundfordringar"    #SRU 1513 7251
4     99                                 #SRU 1519 7251    #SRU 1519 7251
</code>```

Title: Fill new pandas df based off values in another df

Body:
Use str.contains to check string match and then use ffill to fill na

df['New_df'] = df.Datan.where(df.Datan.str.contains('#SRU')).ffill()

df
   Index                                           Datan            New_df
0     95                                 #SRU 1512 7251    #SRU 1512 7251
1     96   #KONTO 1513 "Kundfordringar - delad faktura"    #SRU 1512 7251
2     97                                 #SRU 1513 7251    #SRU 1513 7251
3     98   #KONTO 1519 "Nedskrivning av kundfordringar"    #SRU 1513 7251
4     99                                 #SRU 1519 7251    #SRU 1519 7251


问:
recover lost unversioned files after git clean -d -f
I have the feeling the answer to this question is no but I figured I would ask anyways.

Long story short I accidentally did a git clean -d -f on a branch and lost about 20 files that I needed. These files have not been committed so as far as I know git shouldn't know about them. Is there any way I can get these files back?

答:
I also just lost files. Why the hell git doesn't recycle them, or stick them in its own internal cache, I do not know.

I was able to recover some files with both r-studio and Pendora Recover.

But not the biggest, most complicated one!


问:
How does control go to a main goroutine when no line calls it?
```<code>// _Closing_ a channel indicates that no more values
// will be sent on it. This can be useful to communicate
// completion to the channel's receivers.

package main

import "fmt"

// In this example we'll use a `jobs` channel to
// communicate work to be done from the `main()` goroutine
// to a worker goroutine. When we have no more jobs for
// the worker we'll `close` the `jobs` channel.
func main() {
    jobs := make(chan int, 5)
    done := make(chan bool)

    fmt.Println("1")
    go func() {
        for {
                fmt.Println("4")
            j, more := <-jobs
            if more {
                fmt.Println("received job", j)
            } else {
                fmt.Println("received all jobs")
                done <- true
                return
            }
        }
    }()

    fmt.Println("2")
    // This sends 3 jobs to the worker over the `jobs`
    // channel, then closes it.
    for j := 1; j <= 3; j++ {
            fmt.Println("3", j)
        jobs <- j
        fmt.Println("sent job", j)
    }

    fmt.Println("5")
    close(jobs)

    fmt.Println("6")
    fmt.Println("sent all jobs")
    //How does control go from here to the main's go routine - line 18. Who call's it? and How?

    // We await the worker using the
    // [synchronization](channel-synchronization) approach
    // we saw earlier.
    <-done

    fmt.Println("7")
}
</code>```

https://play.golang.org/p/Xe_wh3YTmwk

How does control go from line 46 to 18 ?

答:
When you compile your Go app into an executable binary, the compiler includes a runtime in the binary. When running your app, this runtime is responsible for scheduling and running goroutines.

In line 17 you launch a goroutine, so the runtime will schedule to run it concurrently with the main goroutine, and possibly in parallel (if there are enough cores and GOMAXPROCS allows it, for details see Concurrency is not parallelism).

Spec: Go statements:

The function value and parameters are evaluated as usual in the calling goroutine, but unlike with a regular call, program execution does not wait for the invoked function to complete. Instead, the function begins executing independently in a new goroutine. When the function terminates, its goroutine also terminates. If the function has any return values, they are discarded when the function completes.

Body:
// _Closing_ a channel indicates that no more values
// will be sent on it. This can be useful to communicate
// completion to the channel's receivers.

package main

import "fmt"

// In this example we'll use a `jobs` channel to
// communicate work to be done from the `main()` goroutine
// to a worker goroutine. When we have no more jobs for
// the worker we'll `close` the `jobs` channel.
func main() {
    jobs := make(chan int, 5)
    done := make(chan bool)

    fmt.Println("1")
    go func() {
        for {
                fmt.Println("4")
            j, more := <-jobs
            if more {
                fmt.Println("received job", j)
            } else {
                fmt.Println("received all jobs")
                done <- true
                return
            }
        }
    }()

    fmt.Println("2")
    // This sends 3 jobs to the worker over the `jobs`
    // channel, then closes it.
    for j := 1; j <= 3; j++ {
            fmt.Println("3", j)
        jobs <- j
        fmt.Println("sent job", j)
    }

    fmt.Println("5")
    close(jobs)

    fmt.Println("6")
    fmt.Println("sent all jobs")
    //How does control go from here to the main's go routine - line 18. Who call's it? and How?

    // We await the worker using the
    // [synchronization](channel-synchronization) approach
    // we saw earlier.
    <-done

    fmt.Println("7")
}

https://play.golang.org/p/Xe_wh3YTmwk

How does control go from line 46 to 18 ?


问:
angular component, check if attribute exists
Say I have an angular component ie <this-thing></this-thing> which does it's thing.

Now I want to add something extra to it, ie <this-thing glows></this-thing>
I would like the component to change a little if the glow attribute is there.

I have managed to do it via <this-thing [glows]="true"></this-thing> and in the component I have

```<code>@Input() public set glows(value: boolean) {
    console.log(value);
}
</code>```

But that becomes too verbose.

If glows attribute is not on the component, then it's false and if it is, then true.

Is there a better way to acheive this?

Thanks for looking.

答:
You can achieve this with the @HostBinding decorator which allows you to change the attribute later inside your code.

Example code for glows attribute in the component code

```<code>@HostBinding('attr.glows')
public glows: boolean;

this.glows = true; // Sets the glows attribute
this.glows = false; // Removes the glows attribute
</code>```

Example code for glows attribute in the component styles

```<code>:host([glows]) {
  /* Custom styles for component when the attribute is present */
}
</code>```

Body:
Say I have an angular component ie <this-thing></this-thing> which does it's thing.

Now I want to add something extra to it, ie <this-thing glows></this-thing>
I would like the component to change a little if the glow attribute is there.

I have managed to do it via <this-thing [glows]="true"></this-thing> and in the component I have

@Input() public set glows(value: boolean) {
    console.log(value);
}

But that becomes too verbose.

If glows attribute is not on the component, then it's false and if it is, then true.

Is there a better way to acheive this?

Thanks for looking.

Body:
You can achieve this with the @HostBinding decorator which allows you to change the attribute later inside your code.

Example code for glows attribute in the component code

@HostBinding('attr.glows')
public glows: boolean;

this.glows = true; // Sets the glows attribute
this.glows = false; // Removes the glows attribute

Example code for glows attribute in the component styles

:host([glows]) {
  /* Custom styles for component when the attribute is present */
}