问:
HTML table: same cell size
I know this should be easy and I've found many threads covering this but I must be missing something. After having tried out a couple of things this is my current code fiddle which should do the trick according to sources. But the cells do not have the same size.

#calendar {
  table-layout: fixed;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table border=1 id='calendar'>
  <tr>
    <td class='calendar_head'>hi</td>
    <td colspan=5 class='calendar_head_month' id='calendar_month'>
      ---</td>
    <td class='calendar_head'>hello</td>
  </tr>
  <tr>
    <td class='calendar_day'>Mo</td>
    <td class='calendar_day'>Di</td>
    <td class='calendar_day'>Mi</td>
    <td class='calendar_day'>Do</td>
    <td class='calendar_day'>Fr</td>
    <td class='calendar_day'>Sa</td>
    <td class='calendar_day'>So</td>
  </tr>
  <tr>
    <td class='calendar_entry' id='calendar_entry_1'></td>
    <td class='calendar_entry' id='calendar_entry_2'></td>
    <td class='calendar_entry' id='calendar_entry_3'></td>
    <td class='calendar_entry' id='calendar_entry_4'></td>
    <td class='calendar_entry' id='calendar_entry_5'></td>
    <td class='calendar_entry' id='calendar_entry_6'></td>
    <td class='calendar_entry' id='calendar_entry_7'></td>
  </tr>
</table></code>```

答:
You havent declared a couple of things, such as the parents width

body {width: 100%; min-height: 100%; height: 100%;} /* this is this parent element of table*/
#calendar{table-layout: fixed;}
table {width: 50%; height: 150px;} /* this is this parent element the table row*/
tr {
  width: 100%;
  min-height: calc(100% / 3);
  line-height: calc(100% / 3);
 }  /* this is this parent element the table data */
td.calendar_day {
  width: calc(100% / 7);
}
td.calendar_entry {
   width: calc(100% / 7);
}
td.calendar_entry:empty:before {
 content: "\00a0"; /* unicode zero width space character */
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
    <table border=1 id='calendar'>
        <tr>
            <td class='calendar_head'>hi</td>
            <td colspan=5 class='calendar_head_month' id='calendar_month'>
                ---</td>
            <td class='calendar_head'>hello</td>
        </tr>
        <tr>
            <td class='calendar_day'>Mo</td>
            <td class='calendar_day'>Di</td>
            <td class='calendar_day'>Mi</td>
            <td class='calendar_day'>Do</td>
            <td class='calendar_day'>Fr</td>
            <td class='calendar_day'>Sa</td>
            <td class='calendar_day'>So</td>
        </tr>
        <tr>
            <td class='calendar_entry' id='calendar_entry_1'></td>
            <td class='calendar_entry' id='calendar_entry_2'></td>
            <td class='calendar_entry' id='calendar_entry_3'></td>
            <td class='calendar_entry' id='calendar_entry_4'></td>
            <td class='calendar_entry' id='calendar_entry_5'></td>
            <td class='calendar_entry' id='calendar_entry_6'></td>
            <td class='calendar_entry' id='calendar_entry_7'></td>
        </tr>
    </table>
</body></code>```

see here: https://jsfiddle.net/e97ysbhz/6/

long story short, if you work in percentages, make sure that parents are declared

As i explained in comment, the size is determined by it's contents, so what i did to make it "appear" as there is something, hence I applied a little trick in the css.

Title: HTML table: same cell size

Body:
I know this should be easy and I've found many threads covering this but I must be missing something. After having tried out a couple of things this is my current code fiddle which should do the trick according to sources. But the cells do not have the same size.

#calendar {
  table-layout: fixed;
}

    hi

      ---
    hello

    Mo
    Di
    Mi
    Do
    Fr
    Sa
    So

Body:
You havent declared a couple of things, such as the parents width

body {width: 100%; min-height: 100%; height: 100%;} /* this is this parent element of table*/
#calendar{table-layout: fixed;}
table {width: 50%; height: 150px;} /* this is this parent element the table row*/
tr {
  width: 100%;
  min-height: calc(100% / 3);
  line-height: calc(100% / 3);
 }  /* this is this parent element the table data */
td.calendar_day {
  width: calc(100% / 7);
}
td.calendar_entry {
   width: calc(100% / 7);
}
td.calendar_entry:empty:before {
 content: "\00a0"; /* unicode zero width space character */
 }

<body>
    <table border=1 id='calendar'>
        <tr>
            <td class='calendar_head'>hi</td>
            <td colspan=5 class='calendar_head_month' id='calendar_month'>
                ---</td>
            <td class='calendar_head'>hello</td>
        </tr>
        <tr>
            <td class='calendar_day'>Mo</td>
            <td class='calendar_day'>Di</td>
            <td class='calendar_day'>Mi</td>
            <td class='calendar_day'>Do</td>
            <td class='calendar_day'>Fr</td>
            <td class='calendar_day'>Sa</td>
            <td class='calendar_day'>So</td>
        </tr>
        <tr>
            <td class='calendar_entry' id='calendar_entry_1'></td>
            <td class='calendar_entry' id='calendar_entry_2'></td>
            <td class='calendar_entry' id='calendar_entry_3'></td>
            <td class='calendar_entry' id='calendar_entry_4'></td>
            <td class='calendar_entry' id='calendar_entry_5'></td>
            <td class='calendar_entry' id='calendar_entry_6'></td>
            <td class='calendar_entry' id='calendar_entry_7'></td>
        </tr>
    </table>
</body>

see here: https://jsfiddle.net/e97ysbhz/6/

long story short, if you work in percentages, make sure that parents are declared

As i explained in comment, the size is determined by it's contents, so what i did to make it "appear" as there is something, hence I applied a little trick in the css.


来源: stackexchange

问:
How do I remove tinyMCE and then re-add it?
I am trying to add the tinyMCE editor to my page, remove it, then add it again but am getting errors.

When I run Part A, then Part B, Than Part A again I get the error:

```<code>Error: g.win.document is null
Source File: tiny_mce/tiny_mce.js Line: 1
</code>```

Part A

```<code>tinyMCE.init({
    'mode' : 'exact',
    'elements' : '" + ctrl.ID + "Editor',
    'plugins' : 'insertdatetime,TVCMSLink,TVCMSImage',
    'theme' : 'advanced',
    'theme_advanced_layout_manager' : 'SimpleLayout',
    'theme_advanced_buttons1' : 'backcolor, forecolor, |, bold, underline, strikethrough, |, numlist, bullist, charmap, |, undo, redo, |, anchor, link, tvlink, unlink',
    'theme_advanced_buttons2' : '',
    'theme_advanced_buttons3' : ''
});
</code>```

Part B

```<code>tinyMCE.getInstanceById('" + ctrl.ID + "Editor').remove();
</code>```

Edit:

Below is the full JavaScript function. The first time through it opens the dialog and works, the contents is in the editor and there is no error.  When I click the close button, the dialog is closed. When I run the function again, the dialog displays but the editor is empty and there is the above error.

```<code>function show_HP1B0() {
$('.EditLink').hide();
$.ajax({
    type: 'post',
    url: 'genericHandler.ashx',
    data: 'cmd=select&tableName=ExtraBlocks&id=4',
    dataType: 'json',
    success: function(data) {
        $('#HP1B0Editor').html(data['rows'][0]['Content']);
        alert($('#HP1B0Editor').html());
        tinyMCE.init({                 'mode' : 'exact',
            'elements' : 'HP1B0Editor',
            'plugins' : 'insertdatetime,Link,Image',
            'theme' : 'advanced',
            'theme_advanced_layout_manager' : 'SimpleLayout',
            'theme_advanced_buttons1' : 'backcolor, forecolor, |, bold, underline, strikethrough, |, numlist, bullist, charmap, |, undo, redo, |, anchor, link, tvlink, unlink',
            'theme_advanced_buttons2' : '',
            'theme_advanced_buttons3' : ''
        });
        var dlg = $('#ctl00_EXTRA_HTML_0_HP1B0Editor').dialog({
            modal: false,
            draggable: false,
            position: 'center',
            zIndex: 99999,  // Above the overlay
            width: 370,
            title: 'Content Block Editor',
            closeText: '',
            open: function () {
                $('body').css('overflow', 'hidden');
                if ($.browser.msie) { $('html').css('overflow', 'hidden'); } $('<div>').attr('id', 'loader').appendTo('body').show();
            },
            close: function () { $('body').css('overflow', 'auto'); if ($.browser.msie) { $('html').css('overflow', 'auto'); } $('#loader').remove(); },
            buttons: {
                'Save': function () {
                    tinyMCE.getInstanceById('HP1B0Editor').remove();
                    $('.EditLink').show();
                    $(this).dialog('close');
                },
                'Cancel': function () {
        alert('HP1B0Editor');
                    tinyMCE.getInstanceById('HP1B0Editor').remove();
                    $('.EditLink').show();
                    $(this).dialog('close');
                }
            }
        }).parent();
        dlg.appendTo(jQuery('form:first'));
    },
    error: function(data) {
        $('.EditLink').show();
        $('#HP1B0Editor').html('Error');
    }
});
}
</code>```

答:
Try this:  </p>

```<code> tinymce.remove();

    setTimeout(function () {
    tinymce.init(
        {
        selector: 'textarea',
        menubar: false,
        height: "300",
        plugins: [
            'advlist autolink lists link image charmap print preview anchor textcolor ksfm',
            'searchreplace visualblocks code fullscreen',
            'insertdatetime media table contextmenu paste code help'
        ],
        toolbar: 'undo redo | fontselect fontsizeselect styleselect | alignleft aligncenter alignright alignjustify | bold italic underline strikethrough | link table | ksfm'
        }
        );

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

ContentLicense: CC BY-SA 4.0

Body:
I am trying to add the tinyMCE editor to my page, remove it, then add it again but am getting errors.

When I run Part A, then Part B, Than Part A again I get the error:

Error: g.win.document is null
Source File: tiny_mce/tiny_mce.js Line: 1

Part A

tinyMCE.init({
    'mode' : 'exact',
    'elements' : '" + ctrl.ID + "Editor',
    'plugins' : 'insertdatetime,TVCMSLink,TVCMSImage',
    'theme' : 'advanced',
    'theme_advanced_layout_manager' : 'SimpleLayout',
    'theme_advanced_buttons1' : 'backcolor, forecolor, |, bold, underline, strikethrough, |, numlist, bullist, charmap, |, undo, redo, |, anchor, link, tvlink, unlink',
    'theme_advanced_buttons2' : '',
    'theme_advanced_buttons3' : ''
});

Part B

tinyMCE.getInstanceById('" + ctrl.ID + "Editor').remove();

Edit:

Below is the full JavaScript function. The first time through it opens the dialog and works, the contents is in the editor and there is no error.  When I click the close button, the dialog is closed. When I run the function again, the dialog displays but the editor is empty and there is the above error.

function show_HP1B0() {
$('.EditLink').hide();
$.ajax({
    type: 'post',
    url: 'genericHandler.ashx',
    data: 'cmd=select&tableName=ExtraBlocks&id=4',
    dataType: 'json',
    success: function(data) {
        $('#HP1B0Editor').html(data['rows'][0]['Content']);
        alert($('#HP1B0Editor').html());
        tinyMCE.init({                 'mode' : 'exact',
            'elements' : 'HP1B0Editor',
            'plugins' : 'insertdatetime,Link,Image',
            'theme' : 'advanced',
            'theme_advanced_layout_manager' : 'SimpleLayout',
            'theme_advanced_buttons1' : 'backcolor, forecolor, |, bold, underline, strikethrough, |, numlist, bullist, charmap, |, undo, redo, |, anchor, link, tvlink, unlink',
            'theme_advanced_buttons2' : '',
            'theme_advanced_buttons3' : ''
        });
        var dlg = $('#ctl00_EXTRA_HTML_0_HP1B0Editor').dialog({
            modal: false,
            draggable: false,
            position: 'center',
            zIndex: 99999,  // Above the overlay
            width: 370,
            title: 'Content Block Editor',
            closeText: '',
            open: function () {
                $('body').css('overflow', 'hidden');
                if ($.browser.msie) { $('html').css('overflow', 'hidden'); } $('
').attr('id', 'loader').appendTo('body').show();
            },
            close: function () { $('body').css('overflow', 'auto'); if ($.browser.msie) { $('html').css('overflow', 'auto'); } $('#loader').remove(); },
            buttons: {
                'Save': function () {
                    tinyMCE.getInstanceById('HP1B0Editor').remove();
                    $('.EditLink').show();
                    $(this).dialog('close');
                },
                'Cancel': function () {
        alert('HP1B0Editor');
                    tinyMCE.getInstanceById('HP1B0Editor').remove();
                    $('.EditLink').show();
                    $(this).dialog('close');
                }
            }
        }).parent();
        dlg.appendTo(jQuery('form:first'));
    },
    error: function(data) {
        $('.EditLink').show();
        $('#HP1B0Editor').html('Error');
    }
});
}

Body:
Try this:

 tinymce.remove();

    setTimeout(function () {
    tinymce.init(
        {
        selector: 'textarea',
        menubar: false,
        height: "300",
        plugins: [
            'advlist autolink lists link image charmap print preview anchor textcolor ksfm',
            'searchreplace visualblocks code fullscreen',
            'insertdatetime media table contextmenu paste code help'
        ],
        toolbar: 'undo redo | fontselect fontsizeselect styleselect | alignleft aligncenter alignright alignjustify | bold italic underline strikethrough | link table | ksfm'
        }
        );

    }, 1);

ContentLicense: CC BY-SA 3.0


问:
multiple blob file insertion php
i have a form where the user inputs his info and has the ability to insert more than 1 longblob file (either an image or another file such as pdf), the insertion isn't working yet, but i'm able to manually insert file in MySQL and retrieve it ( View / download ), the attachment is to be uploaded to an "Attachment" Table and into a column "attachment" in Customer table, here's a code snippet of what is achieved:

```<code><?php function insertFile_db($myFile,$conn,$tablename,$id){
                $fileCount = count($myFile["name"]);
                $sql="INSERT INTO Attachments (tableName,CustomerId,Name,File,Size,Type) ";
                for ($i = 0; $i < $fileCount; $i++) {

                       $fileName=$myFile["name"][$i];                                        // Note : $myFile=$_FILES['Attachment']
                        $fileTmp_name=$myFile["tmp_name"][$i];
                        $fileType=$myFile["type"][$i];
                        $fileSize=$myFile["size"][$i];

       //$fileContent = addslashes(file_get_contents($myFile['images']['tmp_name']));
        $file=fopen($fileTmp_name,'r');           //'r' open for reading only, pts at the beginning of the file
        $fileContent=fread($file,$fileSize);
        fclose($file);
         $fileContent = addslashes($fileContent);

             if(!get_magic_quotes_gpc())
             $fileName = addslashes($fileName);

         if( $i==($fileCount-1) && $i==0 )
            $sql.="VALUES ('".$tablename."', ".$id.", '".$fileName."','$fileContent','".$fileSize."','".$fileType."')" ;
         else if($i!=($fileCount-1) && $i==0)
            $sql.="VALUES ('".$tablename."', ".$id.", '".$fileName."','$fileContent','".$fileSize."','".$fileType."')," ;
         else if($i==($fileCount-1) && $i!=0 )
            $sql.="  ('".$tablename."', ".$id.", '".$fileName."','$fileContent','".$fileSize."','".$fileType."')" ;
         else
            $sql.="  ('".$tablename."', ".$id.", '".$fileName."','$fileContent','".$fileSize."','".$fileType."')," ;

            }

    if(!$conn->query($sql))
        return True;

    return Flase;

} ?>
</code>```

and i'm calling the function :

```<code>if(isset($_FILES['Attachment']) &&  !empty($_FILES['Attachment']['name'][0])){
     $last_id = $conn->insert_id;
         $error=insertFile_db($_FILES['Attachment'],$conn,CONTNAME,$last_id);
       if($error===True)
            {$conn->close();header("location:/skylite/".CONTNAME."/Create?error=Internal error");exit();}

}
</code>```

Now i'm focusing on insertion in Attachment table, i'd appreciate some tips and help!

答: After checking for errors with mysqli_error(), the main problem was a "Date" field in my database that didn't have a default value, therefore the query wasn't working, posting this in case someone else had such a problem, this was one solution!</p>

Title: multiple blob file insertion php

Body:
i have a form where the user inputs his info and has the ability to insert more than 1 longblob file (either an image or another file such as pdf), the insertion isn't working yet, but i'm able to manually insert file in MySQL and retrieve it ( View / download ), the attachment is to be uploaded to an "Attachment" Table and into a column "attachment" in Customer table, here's a code snippet of what is achieved:

<?php function insertFile_db($myFile,$conn,$tablename,$id){
                $fileCount = count($myFile["name"]);
                $sql="INSERT INTO Attachments (tableName,CustomerId,Name,File,Size,Type) ";
                for ($i = 0; $i < $fileCount; $i++) {

                       $fileName=$myFile["name"][$i];                                        // Note : $myFile=$_FILES['Attachment']
                        $fileTmp_name=$myFile["tmp_name"][$i];
                        $fileType=$myFile["type"][$i];
                        $fileSize=$myFile["size"][$i];

       //$fileContent = addslashes(file_get_contents($myFile['images']['tmp_name']));
        $file=fopen($fileTmp_name,'r');           //'r' open for reading only, pts at the beginning of the file
        $fileContent=fread($file,$fileSize);
        fclose($file);
         $fileContent = addslashes($fileContent);

             if(!get_magic_quotes_gpc())
             $fileName = addslashes($fileName);

         if( $i==($fileCount-1) && $i==0 )
            $sql.="VALUES ('".$tablename."', ".$id.", '".$fileName."','$fileContent','".$fileSize."','".$fileType."')" ;
         else if($i!=($fileCount-1) && $i==0)
            $sql.="VALUES ('".$tablename."', ".$id.", '".$fileName."','$fileContent','".$fileSize."','".$fileType."')," ;
         else if($i==($fileCount-1) && $i!=0 )
            $sql.="  ('".$tablename."', ".$id.", '".$fileName."','$fileContent','".$fileSize."','".$fileType."')" ;
         else
            $sql.="  ('".$tablename."', ".$id.", '".$fileName."','$fileContent','".$fileSize."','".$fileType."')," ;

            }

    if(!$conn->query($sql))
        return True;

    return Flase;

} ?>

and i'm calling the function :

if(isset($_FILES['Attachment']) &&  !empty($_FILES['Attachment']['name'][0])){
     $last_id = $conn->insert_id;
         $error=insertFile_db($_FILES['Attachment'],$conn,CONTNAME,$last_id);
       if($error===True)
            {$conn->close();header("location:/skylite/".CONTNAME."/Create?error=Internal error");exit();}

}

Now i'm focusing on insertion in Attachment table, i'd appreciate some tips and help!


问:
materialize css image slider position current image number
I‘ve done an image slider in materialize. works great. now I want to change other content depending on the actually shown image. how can I detect the slide position.

regards

答:
The following loop gives you the current tab/slide/image's position(position indexing starts with 0) which is active.I hope it helps.</p>

```<code>for(var i = 0; i < $('.slides').children().length; i++){
        if($('.slides').children()[i].className == "active")
          {
             console.log(i);
          }
     }
</code>```

Body:
The following loop gives you the current tab/slide/image's position(position indexing starts with 0) which is active.I hope it helps.

for(var i = 0; i < $('.slides').children().length; i++){
        if($('.slides').children()[i].className == "active")
          {
             console.log(i);
          }
     }


问:
How to utilise Sense UI widgets?
I was looking at my application (designed for 1.6) that uses the DatePicker controls on a HTC Desire the other day, and the owner of the phone showed me the native calendar program which uses much much nicer controls, i.e. the datepicker you can touch and scroll rather than having to repeatedly press the buttons to adjust days/months/year.

So my question is does anyone know if these sense controls can be automatically used in place of the stock datepicker controls?  I would ideally like my app to run on older devices i.e. 1.6 but show the nicer UI elements if running on a device that has the sense UI.

Thanks

答: Well unfortunately it appears you can't.   Maybe if you know the widget classes you can use them but as for packaging them up in your app so you can rely on them being present in every phone you install on..  not a good idea... as you can't guarantee they'll even work on all devices...</p>

ContentLicense: CC BY-SA 2.5

Title: How to utilise Sense UI widgets?


问:
How to fix the right aspect ratio of the camera preview (surfaceview) in Android?
I am creating the Android app with the camera functionality.
The camera screen contains the toolbar on the top, the surfaceview (camera preview) below the toolbar, and the camera control buttons on the bottom of the screen. The screen is always in portrait.

[Some lines of the code do not related to the issue are deleted]

This is my fragment FragmentCamera

```<code>import android.hardware.Camera;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.dmc.R;
import com.dmc.entities.Preview;

public class CameraFragment implements View.OnClickListener, View.OnTouchListener {

    public static final String ARG_CAMERA_MODE = "camera.mode";
    public static final String TYPE_CAMERA_MODE_IMAGE = "image";
    public static final String TYPE_CAMERA_MODE_VIDEO = "video";
    public MediaRecorder mrec = new MediaRecorder();

    private Camera camera;
    private String mCameraMode = TYPE_CAMERA_MODE_IMAGE; //or video
    private com.dmc.entities.Preview preview;
    private ImageView btnStopRecording;
    private SurfaceView surfaceView;
    private View view;

    public static FrCamera getInstance(String cameraMode) {
        CameraFragment fragment = new CameraFragment();
        Bundle bundle = new Bundle(1);
        bundle.putString(ARG_CAMERA_MODE, cameraMode);
        return fragment.setArguments(bundle);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mCameraMode = getArguments().getString(ARG_CAMERA_MODE);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_camera, container, false);
        view.setOnTouchListener(this);
        btnStopRecording = (ImageView) view.findViewById(R.id.btnStopRecording);
        if (!mCameraMode.equals(TYPE_CAMERA_MODE_IMAGE)) {
            btnStopRecording.setOnClickListener(this);
        }
        surfaceView = (SurfaceView) view.findViewById(R.id.surfaceView);
        view.findViewById(R.id.imgCameraTakePicture).setOnClickListener(this);

        preview = new Preview(getActivity(), (SurfaceView) view.findViewById(R.id.surfaceView));
        preview.setKeepScreenOn(true);
        return view;
    }

    @Override
    public void onStart() {
        super.onStart();

        int numCams = Camera.getNumberOfCameras();
        if (numCams > 0) {
            try {
                camera = Camera.open(0);
                preview.setCamera(camera);
                camera.startPreview();
            } catch (RuntimeException ex) {
            }
        }
    }

    @Override
    public void onPause() {
        if (camera != null) {
            camera.stopPreview();
            preview.setCamera(null);
            camera.release();
            camera = null;
        }
        super.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();
        camera.startPreview();
    }

    private void startVideoRecording() {
        try {
            mrec = new MediaRecorder();
            mrec.setCamera(camera);
            mrec.setVideoSource(MediaRecorder.VideoSource.CAMERA);
            mrec.setAudioSource(MediaRecorder.AudioSource.MIC);
            CamcorderProfile profile = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH);
            mrec.setProfile(profile);
            camera.lock();
            camera.unlock();
            mrec.setPreviewDisplay(preview.mHolder.getSurface());
            mrec.setOutputFile(outVideoFile.getPath());
            mrec.setOrientationHint(Preview.rotate);
            mrec.prepare();
            mrec.start();
        } catch (Exception ex) {
            Log.e(getClass().getName(), ex.getMessage());
        }
    }

    protected void stopRecording() {
        if (mrec != null) {
            mrec.stop();
            mrec.release();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.imgCameraTakenPicture:
                // Save image
                break;
            case R.id.btnStopRecording:
                stopRecording();
                break;
            case R.id.imgCameraTakePicture:
                if (mCameraMode.equals(TYPE_CAMERA_MODE_IMAGE)) {
                    camera.takePicture(shutterCallback, rawCallback, jpegCallback);
                } else
                    startVideoRecording();
                break;
        }
    }
}
</code>```

This is the Preview

```<code>import android.app.Activity;
import android.content.Context;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.hardware.Camera.Size;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;

import java.io.IOException;
import java.util.List;

public class Preview extends ViewGroup implements SurfaceHolder.Callback {
    public static final float RATIO = 0.75f;
    public static int rotate;

    public SurfaceView mSurfaceView;
    public SurfaceHolder mHolder;
    Size mPreviewSize;
    List<Size> mSupportedPreviewSizes;
    Camera mCamera;

    public Preview(Context context, SurfaceView sv) {
        super(context);
        mSurfaceView = sv;
        mHolder = mSurfaceView.getHolder();
        mHolder.addCallback(this);
        mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }

    public void setCamera(Camera camera) {
        mCamera = camera;
        if (mCamera != null) {
            mSupportedPreviewSizes = mCamera.getParameters().getSupportedPreviewSizes();
            requestLayout();
            // get Camera parameters
            Camera.Parameters params = mCamera.getParameters();

            List<String> focusModes = params.getSupportedFocusModes();
            if (focusModes.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)) {
                params.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
            } else {
                params.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
            }

            params.setJpegThumbnailQuality(100);
            params.setJpegQuality(100);

            // Configure image format. RGB_565 is the most common format.
            List<Integer> formats = params.getSupportedPictureFormats();
            if (formats.contains(PixelFormat.RGB_565))
                params.setPictureFormat(PixelFormat.RGB_565);
            else if (formats.contains(PixelFormat.JPEG))
                params.setPictureFormat(PixelFormat.JPEG);
            else params.setPictureFormat(formats.get(0));

            Camera.CameraInfo camInfo = new Camera.CameraInfo();
            Camera.getCameraInfo(Camera.CameraInfo.CAMERA_FACING_BACK, camInfo);
            int cameraRotationOffset = camInfo.orientation;

            Camera.Parameters parameters = mCamera.getParameters();

            int rotation = ((Activity) getContext()).getWindowManager().getDefaultDisplay().getRotation();
            int degrees = 0;
            switch (rotation) {
                case Surface.ROTATION_0:
                    degrees = 0;
                    break; // Natural orientation
                case Surface.ROTATION_90:
                    degrees = 90;
                    break; // Landscape left
                case Surface.ROTATION_180:
                    degrees = 180;
                    break;// Upside down
                case Surface.ROTATION_270:
                    degrees = 270;
                    break;// Landscape right
            }
            int displayRotation;
            if (camInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
                displayRotation = (cameraRotationOffset + degrees) % 360;
                //displayRotation = (360 - displayRotation) % 360; // compensate the mirror
            } else { // back-facing
                displayRotation = (cameraRotationOffset - degrees + 360) % 360;
            }
            mCamera.setDisplayOrientation(displayRotation);

            if (camInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
                rotate = (360 + cameraRotationOffset + degrees) % 360;
            } else {
                rotate = (360 + cameraRotationOffset - degrees) % 360;
            }

            parameters.set("orientation", "portrait");
            parameters.setRotation(rotate);

            mCamera.setParameters(params);
        }
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        if (changed && getChildCount() > 0) {
            final View child = getChildAt(0);

            final int width = r - l;
            final int height = b - t;

            int previewWidth = width;
            int previewHeight = height;
            if (mPreviewSize != null) {
                previewWidth = mPreviewSize.width;
                previewHeight = mPreviewSize.height;
            }

            // Center the child SurfaceView within the parent.
            if (width * previewHeight > height * previewWidth) {
                final int scaledChildWidth = previewWidth * height / previewHeight;
                child.layout((width - scaledChildWidth) / 2, 0,
                        (width + scaledChildWidth) / 2, height);
            } else {
                final int scaledChildHeight = previewHeight * width / previewWidth;
                child.layout(0, (height - scaledChildHeight) / 2,
                        width, (height + scaledChildHeight) / 2);
            }
        }
    }

    public void surfaceCreated(SurfaceHolder holder) {
        try {
            if (mCamera != null) {
                mCamera.setPreviewDisplay(holder);
                mCamera.startPreview();
            }
        } catch (IOException exception) {}
    }

    public void surfaceDestroyed(SurfaceHolder holder) {
        if (mCamera != null) {
            mCamera.stopPreview();
            mCamera.release();
        }
    }

    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        if (mHolder.getSurface() == null) {
            return;
        }
        stopPreview();
        setCamera(mCamera);
        startPreview();
        mCamera.startPreview();
    }

    public void startPreview() {
        try {
            if (mCamera != null) {
                mCamera.setPreviewDisplay(mHolder);
                mCamera.startPreview();
            }
        } catch (Exception e) {}
    }

    public void stopPreview() {
        try {
            if (mCamera != null)
                mCamera.stopPreview();
        } catch (Exception e) {}
    }
}
</code>```

The expected result is on the image on left side. The obtained result is on the image on the right side. The camera preview is stretched. How to fix the right aspect ratio of the camera preview?

答:
Source code for Camera1 and Android 4-5:

```<code>@Override
protected void onResume() {
    super.onResume();
    camera = Camera.open(CAMERA_ID);
    setPreviewSize();
}

@Override
protected void onPause() {
    super.onPause();
    if (camera != null)
        camera.release();
    camera = null;
}
...
void setPreviewSize() {
    // получаем размеры экрана
    Display display = getWindowManager().getDefaultDisplay();
    int w1 = display.getWidth();
    int h1 = display.getHeight();
    boolean widthIsMax = display.getWidth() > display.getHeight();

    // определяем размеры превью камеры
    Camera.Size size = camera.getParameters().getPreviewSize();

    RectF rectDisplay = new RectF();
    RectF rectPreview = new RectF();

    // RectF экрана, соотвествует размерам экрана
    rectDisplay.set(0, 0, w1, h1);

    // подготовка матрицы преобразования
    Matrix matrix = new Matrix();
    // RectF первью
    if (widthIsMax) {
        // превью в горизонтальной ориентации
        rectPreview.set(0, 0, size.width, size.height);

        // если экран будет "втиснут" в превью (третий вариант из урока)
        matrix.setRectToRect(rectPreview, rectDisplay,
                Matrix.ScaleToFit.START);
    } else {
        // превью в вертикальной ориентации
        rectPreview.set(0, 0, size.height, size.width);

        // если превью будет "втиснут" в экран (второй вариант из урока)
        matrix.setRectToRect(rectPreview, rectDisplay,
                Matrix.ScaleToFit.START);
    }

    // преобразование
    matrix.mapRect(rectPreview);

    // установка размеров surface из получившегося преобразования
    h0 = (int) (rectPreview.bottom);
    w0 = (int) (rectPreview.right);

    surfaceView.getLayoutParams().height = h0;
    surfaceView.getLayoutParams().width = w0;
}
</code>```

See http://startandroid.ru/ru/uroki/vse-uroki-spiskom/264-urok-132-kamera-vyvod-izobrazhenija-na-ekran-obrabotka-povorota.html

Body:
I am creating the Android app with the camera functionality.
The camera screen contains the toolbar on the top, the surfaceview (camera preview) below the toolbar, and the camera control buttons on the bottom of the screen. The screen is always in portrait.

[Some lines of the code do not related to the issue are deleted]

This is my fragment FragmentCamera

import android.hardware.Camera;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.dmc.R;
import com.dmc.entities.Preview;

public class CameraFragment implements View.OnClickListener, View.OnTouchListener {

    public static final String ARG_CAMERA_MODE = "camera.mode";
    public static final String TYPE_CAMERA_MODE_IMAGE = "image";
    public static final String TYPE_CAMERA_MODE_VIDEO = "video";
    public MediaRecorder mrec = new MediaRecorder();

    private Camera camera;
    private String mCameraMode = TYPE_CAMERA_MODE_IMAGE; //or video
    private com.dmc.entities.Preview preview;
    private ImageView btnStopRecording;
    private SurfaceView surfaceView;
    private View view;

    public static FrCamera getInstance(String cameraMode) {
        CameraFragment fragment = new CameraFragment();
        Bundle bundle = new Bundle(1);
        bundle.putString(ARG_CAMERA_MODE, cameraMode);
        return fragment.setArguments(bundle);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mCameraMode = getArguments().getString(ARG_CAMERA_MODE);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_camera, container, false);
        view.setOnTouchListener(this);
        btnStopRecording = (ImageView) view.findViewById(R.id.btnStopRecording);
        if (!mCameraMode.equals(TYPE_CAMERA_MODE_IMAGE)) {
            btnStopRecording.setOnClickListener(this);
        }
        surfaceView = (SurfaceView) view.findViewById(R.id.surfaceView);
        view.findViewById(R.id.imgCameraTakePicture).setOnClickListener(this);

        preview = new Preview(getActivity(), (SurfaceView) view.findViewById(R.id.surfaceView));
        preview.setKeepScreenOn(true);
        return view;
    }

    @Override
    public void onStart() {
        super.onStart();

        int numCams = Camera.getNumberOfCameras();
        if (numCams > 0) {
            try {
                camera = Camera.open(0);
                preview.setCamera(camera);
                camera.startPreview();
            } catch (RuntimeException ex) {
            }
        }
    }

    @Override
    public void onPause() {
        if (camera != null) {
            camera.stopPreview();
            preview.setCamera(null);
            camera.release();
            camera = null;
        }
        super.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();
        camera.startPreview();
    }

    private void startVideoRecording() {
        try {
            mrec = new MediaRecorder();
            mrec.setCamera(camera);
            mrec.setVideoSource(MediaRecorder.VideoSource.CAMERA);
            mrec.setAudioSource(MediaRecorder.AudioSource.MIC);
            CamcorderProfile profile = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH);
            mrec.setProfile(profile);
            camera.lock();
            camera.unlock();
            mrec.setPreviewDisplay(preview.mHolder.getSurface());
            mrec.setOutputFile(outVideoFile.getPath());
            mrec.setOrientationHint(Preview.rotate);
            mrec.prepare();
            mrec.start();
        } catch (Exception ex) {
            Log.e(getClass().getName(), ex.getMessage());
        }
    }

    protected void stopRecording() {
        if (mrec != null) {
            mrec.stop();
            mrec.release();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.imgCameraTakenPicture:
                // Save image
                break;
            case R.id.btnStopRecording:
                stopRecording();
                break;
            case R.id.imgCameraTakePicture:
                if (mCameraMode.equals(TYPE_CAMERA_MODE_IMAGE)) {
                    camera.takePicture(shutterCallback, rawCallback, jpegCallback);
                } else
                    startVideoRecording();
                break;
        }
    }
}

This is the Preview

import android.app.Activity;
import android.content.Context;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.hardware.Camera.Size;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;

import java.io.IOException;
import java.util.List;

public class Preview extends ViewGroup implements SurfaceHolder.Callback {
    public static final float RATIO = 0.75f;
    public static int rotate;

    public SurfaceView mSurfaceView;
    public SurfaceHolder mHolder;
    Size mPreviewSize;
    List<Size> mSupportedPreviewSizes;
    Camera mCamera;

    public Preview(Context context, SurfaceView sv) {
        super(context);
        mSurfaceView = sv;
        mHolder = mSurfaceView.getHolder();
        mHolder.addCallback(this);
        mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }

    public void setCamera(Camera camera) {
        mCamera = camera;
        if (mCamera != null) {
            mSupportedPreviewSizes = mCamera.getParameters().getSupportedPreviewSizes();
            requestLayout();
            // get Camera parameters
            Camera.Parameters params = mCamera.getParameters();

            List<String> focusModes = params.getSupportedFocusModes();
            if (focusModes.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)) {
                params.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
            } else {
                params.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
            }

            params.setJpegThumbnailQuality(100);
            params.setJpegQuality(100);

            // Configure image format. RGB_565 is the most common format.
            List<Integer> formats = params.getSupportedPictureFormats();
            if (formats.contains(PixelFormat.RGB_565))
                params.setPictureFormat(PixelFormat.RGB_565);
            else if (formats.contains(PixelFormat.JPEG))
                params.setPictureFormat(PixelFormat.JPEG);
            else params.setPictureFormat(formats.get(0));

            Camera.CameraInfo camInfo = new Camera.CameraInfo();
            Camera.getCameraInfo(Camera.CameraInfo.CAMERA_FACING_BACK, camInfo);
            int cameraRotationOffset = camInfo.orientation;

            Camera.Parameters parameters = mCamera.getParameters();

            int rotation = ((Activity) getContext()).getWindowManager().getDefaultDisplay().getRotation();
            int degrees = 0;
            switch (rotation) {
                case Surface.ROTATION_0:
                    degrees = 0;
                    break; // Natural orientation
                case Surface.ROTATION_90:
                    degrees = 90;
                    break; // Landscape left
                case Surface.ROTATION_180:
                    degrees = 180;
                    break;// Upside down
                case Surface.ROTATION_270:
                    degrees = 270;
                    break;// Landscape right
            }
            int displayRotation;
            if (camInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
                displayRotation = (cameraRotationOffset + degrees) % 360;
                //displayRotation = (360 - displayRotation) % 360; // compensate the mirror
            } else { // back-facing
                displayRotation = (cameraRotationOffset - degrees + 360) % 360;
            }
            mCamera.setDisplayOrientation(displayRotation);

            if (camInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
                rotate = (360 + cameraRotationOffset + degrees) % 360;
            } else {
                rotate = (360 + cameraRotationOffset - degrees) % 360;
            }

            parameters.set("orientation", "portrait");
            parameters.setRotation(rotate);

            mCamera.setParameters(params);
        }
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        if (changed && getChildCount() > 0) {
            final View child = getChildAt(0);

            final int width = r - l;
            final int height = b - t;

            int previewWidth = width;
            int previewHeight = height;
            if (mPreviewSize != null) {
                previewWidth = mPreviewSize.width;
                previewHeight = mPreviewSize.height;
            }

            // Center the child SurfaceView within the parent.
            if (width * previewHeight > height * previewWidth) {
                final int scaledChildWidth = previewWidth * height / previewHeight;
                child.layout((width - scaledChildWidth) / 2, 0,
                        (width + scaledChildWidth) / 2, height);
            } else {
                final int scaledChildHeight = previewHeight * width / previewWidth;
                child.layout(0, (height - scaledChildHeight) / 2,
                        width, (height + scaledChildHeight) / 2);
            }
        }
    }

    public void surfaceCreated(SurfaceHolder holder) {
        try {
            if (mCamera != null) {
                mCamera.setPreviewDisplay(holder);
                mCamera.startPreview();
            }
        } catch (IOException exception) {}
    }

    public void surfaceDestroyed(SurfaceHolder holder) {
        if (mCamera != null) {
            mCamera.stopPreview();
            mCamera.release();
        }
    }

    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        if (mHolder.getSurface() == null) {
            return;
        }
        stopPreview();
        setCamera(mCamera);
        startPreview();
        mCamera.startPreview();
    }

    public void startPreview() {
        try {
            if (mCamera != null) {
                mCamera.setPreviewDisplay(mHolder);
                mCamera.startPreview();
            }
        } catch (Exception e) {}
    }

    public void stopPreview() {
        try {
            if (mCamera != null)
                mCamera.stopPreview();
        } catch (Exception e) {}
    }
}

The expected result is on the image on left side. The obtained result is on the image on the right side. The camera preview is stretched. How to fix the right aspect ratio of the camera preview?

Body:
Source code for Camera1 and Android 4-5:

@Override
protected void onResume() {
    super.onResume();
    camera = Camera.open(CAMERA_ID);
    setPreviewSize();
}

@Override
protected void onPause() {
    super.onPause();
    if (camera != null)
        camera.release();
    camera = null;
}
...
void setPreviewSize() {
    // получаем размеры экрана
    Display display = getWindowManager().getDefaultDisplay();
    int w1 = display.getWidth();
    int h1 = display.getHeight();
    boolean widthIsMax = display.getWidth() > display.getHeight();

    // определяем размеры превью камеры
    Camera.Size size = camera.getParameters().getPreviewSize();

    RectF rectDisplay = new RectF();
    RectF rectPreview = new RectF();

    // RectF экрана, соотвествует размерам экрана
    rectDisplay.set(0, 0, w1, h1);

    // подготовка матрицы преобразования
    Matrix matrix = new Matrix();
    // RectF первью
    if (widthIsMax) {
        // превью в горизонтальной ориентации
        rectPreview.set(0, 0, size.width, size.height);

        // если экран будет "втиснут" в превью (третий вариант из урока)
        matrix.setRectToRect(rectPreview, rectDisplay,
                Matrix.ScaleToFit.START);
    } else {
        // превью в вертикальной ориентации
        rectPreview.set(0, 0, size.height, size.width);

        // если превью будет "втиснут" в экран (второй вариант из урока)
        matrix.setRectToRect(rectPreview, rectDisplay,
                Matrix.ScaleToFit.START);
    }

    // преобразование
    matrix.mapRect(rectPreview);

    // установка размеров surface из получившегося преобразования
    h0 = (int) (rectPreview.bottom);
    w0 = (int) (rectPreview.right);

    surfaceView.getLayoutParams().height = h0;
    surfaceView.getLayoutParams().width = w0;
}

See http://startandroid.ru/ru/uroki/vse-uroki-spiskom/264-urok-132-kamera-vyvod-izobrazhenija-na-ekran-obrabotka-povorota.html


问:
Dynamic variable in Jenkins pipeline with groovy method variable
I have a Jenkinsfile in Groovy for a declarative pipeline and two created Jenkins variables with names OCP_TOKEN_VALUE_ONE and OCP_TOKEN_VALUE_TWO and the corresponding values. The problem comes when I try to pass a method variable and use it in an sh command.

I have the next code:

```<code>private def deployToOpenShift(projectProps, environment, openshiftNamespaceGroupToken) {
  sh """/opt/ose/oc login ${OCP_URL} --token=${openshiftNamespaceGroupToken} --namespace=${projectProps.namespace}-${environment}"""
}
</code>```

The problem is, the method deployToOpenShift has in the openshiftNamespaceGroupToken variable, a value that is the name of variable that has been set in Jenkins. It needs to be dynamic and the problem is that Jenkins don't resolve the Jenkins variable value, just the one passed as String, I mean, the result is:

--token=OCP_TOKEN_VALUE_ONE

If I put in the code

```<code>private def deployToOpenShift(projectProps, environment, openshiftNamespaceGroupToken) {
  sh """/opt/ose/oc login ${OCP_URL} --token=${OCP_TOKEN_VALUE_ONE} --namespace=${projectProps.namespace}-${environment}"""
}
</code>```

works perfect but is not dynamic that is the point of the method variable. I have tried with the """ stuff as you can see, but not working.

Any extra idea?

Edited with the code that calls the method:

```<code>...
projectProps = readProperties file: './gradle.properties'
openShiftTokenByGroup = 'OCP_TOKEN_' + projectProps.namespace.toUpperCase()

...

stage ('Deploy-Dev') {
  agent any
  steps {
    milestone ordinal : 10, label: "Deploy-Dev Milestone"
    deployToOpenShift(projectProps, 'dev', openShiftTokenByGroup)
  }
}
</code>```

答:
I have got two different ways to do that. One is using evaluate from groovy like this:

```<code>def openShiftTokenByGroup = 'OCP_TOKEN_' + projectProps.namespace.toUpperCase()

evaluate("${openShiftTokenByGroup}") //This will resolve the configured value in Jenkins
</code>```

The second one is the same approach but in the sh command with eval escaping the $ character:

```<code>sh """
eval \$$openShiftTokenByGroup
echo "Token: $openShiftTokenByGroup
 """
</code>```

This will do the magic too and you'll get the Jenkins configured value.

Body:
I have a Jenkinsfile in Groovy for a declarative pipeline and two created Jenkins variables with names OCP_TOKEN_VALUE_ONE and OCP_TOKEN_VALUE_TWO and the corresponding values. The problem comes when I try to pass a method variable and use it in an sh command.

I have the next code:

private def deployToOpenShift(projectProps, environment, openshiftNamespaceGroupToken) {
  sh """/opt/ose/oc login ${OCP_URL} --token=${openshiftNamespaceGroupToken} --namespace=${projectProps.namespace}-${environment}"""
}

The problem is, the method deployToOpenShift has in the openshiftNamespaceGroupToken variable, a value that is the name of variable that has been set in Jenkins. It needs to be dynamic and the problem is that Jenkins don't resolve the Jenkins variable value, just the one passed as String, I mean, the result is:

--token=OCP_TOKEN_VALUE_ONE

If I put in the code

private def deployToOpenShift(projectProps, environment, openshiftNamespaceGroupToken) {
  sh """/opt/ose/oc login ${OCP_URL} --token=${OCP_TOKEN_VALUE_ONE} --namespace=${projectProps.namespace}-${environment}"""
}

works perfect but is not dynamic that is the point of the method variable. I have tried with the """ stuff as you can see, but not working.

Any extra idea?

Edited with the code that calls the method:

...
projectProps = readProperties file: './gradle.properties'
openShiftTokenByGroup = 'OCP_TOKEN_' + projectProps.namespace.toUpperCase()

...

stage ('Deploy-Dev') {
  agent any
  steps {
    milestone ordinal : 10, label: "Deploy-Dev Milestone"
    deployToOpenShift(projectProps, 'dev', openShiftTokenByGroup)
  }
}

Body:
I have got two different ways to do that. One is using evaluate from groovy like this:

def openShiftTokenByGroup = 'OCP_TOKEN_' + projectProps.namespace.toUpperCase()

evaluate("${openShiftTokenByGroup}") //This will resolve the configured value in Jenkins

The second one is the same approach but in the sh command with eval escaping the $ character:

sh """
eval \$$openShiftTokenByGroup
echo "Token: $openShiftTokenByGroup
 """

This will do the magic too and you'll get the Jenkins configured value.


问:
How to make TFS deploy ASP.net Web App after successful build?
I am trying to set up one of my ASP.net projects for continuous integration with TFS.  Amongst my requirements, I need to set up TFS so that each time there is a successful build with passing tests, the ASP.net code should be deployed to my development web server.

What I have done so far is I have set up a private agent behind my firewall (so that the agent has a "line of sight" to the development web server.  I've set up a build that runs all unit tests, and I have the gated check-in setup up so that the build is rejected if the tests don't pass.

I can see that the build artifact is created by the agent, but I am stuck with trying to figure out how to actually deploy the artifact to the development web server.

I have my publish profiles in Visual Studio, but I'm guessing that those are useless in TFS.

答:
You can refer to below link and follow the steps mentioned in the article to  deploy the artifact to the web server:

End to End Walkthrough: Deploying Web Applications Using Team Build
and Release Management

Deploy to a Windows Virtual Machine

Visual Studio Team Services Release Management IIS Web Deployment
vnext

For the publish profiles, you can pass parameters into MSBuild during the building in TFS, eg : /p:DeployOnBuild=true;PublishProfile=MyProfile

Reference below threads to use the Publish Profiles:

TFS 2017 publish with PublishProfile

Build and Deploy a Web Application with TFS 2017 using Web Deploy Package


问:
Casting List of object and Get the Result
I'm Trying to cast a list to an object like:

```<code>public static List<Object> lstproductname = new List<Object>();

var partialResult = db.Company.OrderBy(x => x.id).Take(1);
            var finalResult = (from j in db.productListDbSet
                               join comp in partialResult
                               on j.mstr_company_id equals comp.id
                               select new { j.id, j.name }).OrderBy(x => x.name).ToList();

            lstproductname = finalResult.Cast<object>().ToList();
</code>```

Trying to use foreach as a result but no luck..

```<code>            foreach (var d in lstproductname.ToList())
            {
                string s =   d.ToString();
            }
</code>```

lstproductname has a content like { id = 1, name = "Product1" }

I need to get the id value and the name value but unfortunately can't get it..

I tried something from foreach like

```<code>foreach (var d in lstproductname.ToList())
            {
                string id =   d.id.ToString();
                string name = d.name.ToString();
            }
</code>```

This one is not working..

```<code> string id =   d.id.ToString();
 string name = d.name.ToString();
</code>```

Any idea how to get this is Highly Appreciated.

答:
Don't use object.  cast to a concrete class or something. Declare this:

```<code>class ResultItem
{
    public int Id { get; set; }
    public string Name { get; set; }
}
</code>```

Then do this:

```<code>var finalResults = (from j in db.productListDbSet
                           join comp in partialResult
                           on j.mstr_company_id equals comp.id
                           select new ResultItem{ Id=j.id, Name=j.name })
    .OrderBy(x => x.name).ToList();

foreach (var result in finalResults)
{
    string id = result.Id.ToString();
    string name = result.Name.ToString();
    //do stuff...
}
</code>```

Body:
I'm Trying to cast a list to an object like:

public static List<Object> lstproductname = new List<Object>();

var partialResult = db.Company.OrderBy(x => x.id).Take(1);
            var finalResult = (from j in db.productListDbSet
                               join comp in partialResult
                               on j.mstr_company_id equals comp.id
                               select new { j.id, j.name }).OrderBy(x => x.name).ToList();

            lstproductname = finalResult.Cast<object>().ToList();

Trying to use foreach as a result but no luck..

            foreach (var d in lstproductname.ToList())
            {
                string s =   d.ToString();
            }

lstproductname has a content like { id = 1, name = "Product1" }

I need to get the id value and the name value but unfortunately can't get it..

I tried something from foreach like

foreach (var d in lstproductname.ToList())
            {
                string id =   d.id.ToString();
                string name = d.name.ToString();
            }

This one is not working..

 string id =   d.id.ToString();
 string name = d.name.ToString();

Any idea how to get this is Highly Appreciated.

Body:
Don't use object.  cast to a concrete class or something. Declare this:

class ResultItem
{
    public int Id { get; set; }
    public string Name { get; set; }
}

Then do this:

var finalResults = (from j in db.productListDbSet
                           join comp in partialResult
                           on j.mstr_company_id equals comp.id
                           select new ResultItem{ Id=j.id, Name=j.name })
    .OrderBy(x => x.name).ToList();

foreach (var result in finalResults)
{
    string id = result.Id.ToString();
    string name = result.Name.ToString();
    //do stuff...
}


问:
if statements for c++
My program so far, my question is do i have to include the if statements after each cout/cin code or is there a way to generalize it? : </p>

```<code>#include <iostream>
using namespace std;

int main ()
{
   double watts, hours_per_day, watt_hours, dollars_per_wh, result;

   dollars_per_wh= .00008;

   cout << " How many Watts for the Air conditioner? ";
   cin >> watts;
   cout << " How many hours/day do you run the Air Conditioner? ";
   cin >> hours_per_day;

   if (watts< 0)
   {
      cout << "Error- negative watts detected " << endl;
      return 1;
   }

   if (hours_per_day< 0)
   {
      cout << "Error - negative hours/day detected " << endl;
      return 1;
   }

   cout << "How many Watts for the Television? " ;
   cin >> watts;
   cout << "How many hours/day do you run the Television? " ;
   cin >> hours_per_day;

   if (watts< 0)
   {
      cout << "Error- negative watts detected " << endl;
      return 1;
   }

   if (hours_per_day< 0)
   {
      cout << "Error - negative hours/day detected " << endl;
      return 1;
   }

   cout << "How many Watts for the Washer? " ;
   cin >> watts;
   cout << "How many hours/day do you run the Washer? " ;
   cin >> hours_per_day;

   if (watts< 0)
   {
      cout << "Error- negative watts detected " << endl;
      return 1;
   }

   if (hours_per_day< 0)
   {
      cout << "Error - negative hours/day detected " << endl;
      return 1;
   }

  return 0 ;
}
</code>```

答:
The following solution gives you a function that:

Returns a boolean that says if the function succeeded/failed

Allows you to name the value that should be received

Allows you to set minimal and maximal values

If needed, you can build other custom functions for getting integers, or other functions for getting any other kind of input. This way you can concentrate all the input tests into a single place.

```<code>#include <iostream>
using namespace std;

bool getint(int &result, const char *name, int minValue, int maxValue)
{
    bool success = false;
    int value = 0;
    cout << "Please enter " << name << ": ";
    if (!(cin >> value))
    {
        cout << "Error: bad input detected" << endl;
    }
    else if (value < minValue)
    {
        cout << "Error: " << name << " is less than " << minValue << endl;
    }
    else if (value > maxValue)
    {
        cout << "Error: " << name << " is more than " << maxValue << endl;
    }
    else
    {
        success = true;
        result = value;
    }
    return success;
}

int main()
{
    int watts;
    getint(watts, "Watts for the AC", 0, 10000);

    return 0;
}
</code>```

Title: if statements for c++

Body:
My program so far, my question is do i have to include the if statements after each cout/cin code or is there a way to generalize it? :

#include <iostream>
using namespace std;

int main ()
{
   double watts, hours_per_day, watt_hours, dollars_per_wh, result;

   dollars_per_wh= .00008;

   cout << " How many Watts for the Air conditioner? ";
   cin >> watts;
   cout << " How many hours/day do you run the Air Conditioner? ";
   cin >> hours_per_day;

   if (watts< 0)
   {
      cout << "Error- negative watts detected " << endl;
      return 1;
   }

   if (hours_per_day< 0)
   {
      cout << "Error - negative hours/day detected " << endl;
      return 1;
   }

   cout << "How many Watts for the Television? " ;
   cin >> watts;
   cout << "How many hours/day do you run the Television? " ;
   cin >> hours_per_day;

   if (watts< 0)
   {
      cout << "Error- negative watts detected " << endl;
      return 1;
   }

   if (hours_per_day< 0)
   {
      cout << "Error - negative hours/day detected " << endl;
      return 1;
   }

   cout << "How many Watts for the Washer? " ;
   cin >> watts;
   cout << "How many hours/day do you run the Washer? " ;
   cin >> hours_per_day;

   if (watts< 0)
   {
      cout << "Error- negative watts detected " << endl;
      return 1;
   }

   if (hours_per_day< 0)
   {
      cout << "Error - negative hours/day detected " << endl;
      return 1;
   }

  return 0 ;
}

Body:
The following solution gives you a function that:

Returns a boolean that says if the function succeeded/failed

Allows you to name the value that should be received

Allows you to set minimal and maximal values

If needed, you can build other custom functions for getting integers, or other functions for getting any other kind of input. This way you can concentrate all the input tests into a single place.

#include <iostream>
using namespace std;

bool getint(int &result, const char *name, int minValue, int maxValue)
{
    bool success = false;
    int value = 0;
    cout << "Please enter " << name << ": ";
    if (!(cin >> value))
    {
        cout << "Error: bad input detected" << endl;
    }
    else if (value < minValue)
    {
        cout << "Error: " << name << " is less than " << minValue << endl;
    }
    else if (value > maxValue)
    {
        cout << "Error: " << name << " is more than " << maxValue << endl;
    }
    else
    {
        success = true;
        result = value;
    }
    return success;
}

int main()
{
    int watts;
    getint(watts, "Watts for the AC", 0, 10000);

    return 0;
}


问:
Disabled Select dropdown not showing option value in Reactive Forms Angular 4 Application
I have a very simple Dropdown in a Angular Form which is loading only one option where object name coming through rest service.

I also want to disable the dropdown based on some condition. I know I can't use [disabled] property on HTML elements in reactive forms. So I am stuck with two options.
Either using [attr.disabled] or custom directive.

But both options not showing option value in disabled dropdown. Here is the code.

```<code><select class="custom-select"
     name="objectName"
     id="objectName"
     formControlName="objectNameDropDown"
     [attr.disabled]="conditionTrue ? 'disabled': null"
     *ngIf="!someCondition; else loadDifferentDropdown;">
       <option>{{object.name}}</option>
</select>
</code>```

I tried to use ngModel too but I think it is not needed. I also used custom Directive in place of [attr.disabled] but it is producing same result. Dropdown is disabled and empty. Option value is there but it is not coming as selected.

Note:- Above code is working fine if I place this dropdown out of angular form and use [disabled]="someCondition"

Any idea what I am doing wrong here?

答:
I had the same problem and I finally used something like this : </p>

```<code>this.form.getRawValue().objectNameDropDown;
</code>```

Body:
I have a very simple Dropdown in a Angular Form which is loading only one option where object name coming through rest service.

I also want to disable the dropdown based on some condition. I know I can't use [disabled] property on HTML elements in reactive forms. So I am stuck with two options.
Either using [attr.disabled] or custom directive.

But both options not showing option value in disabled dropdown. Here is the code.

<select class="custom-select"
     name="objectName"
     id="objectName"
     formControlName="objectNameDropDown"
     [attr.disabled]="conditionTrue ? 'disabled': null"
     *ngIf="!someCondition; else loadDifferentDropdown;">
       <option>{{object.name}}</option>
</select>

I tried to use ngModel too but I think it is not needed. I also used custom Directive in place of [attr.disabled] but it is producing same result. Dropdown is disabled and empty. Option value is there but it is not coming as selected.

Note:- Above code is working fine if I place this dropdown out of angular form and use [disabled]="someCondition"

Any idea what I am doing wrong here?

Body:
I had the same problem and I finally used something like this :

this.form.getRawValue().objectNameDropDown;


问:
JavaScript - How to make sure array manipulations are persistent inside a function?
I am trying to write a JavaScript function (ES5) that will take in an array, filter it, and set the original array to the new one.

Here is my plunk: https://plnkr.co/edit/OWeOjJ3SLVGYRaweyy3Z

Here is the basic pseudocode of what I am trying to do:

```<code>var result = [{ 'date': '20171116' }, { 'date': '20171115' }];
var data = { 'date': '2017116' };
deleteEntry(data, result);
console.log(result); //should  have one entry

function deleteEntry(data, result) {
  result = result.filter(function(item) {
    return item.date !== data.date;
  });
}
</code>```

I believe the issue is to do with array references. I am not sure how to accomplish the task.

答:
Array.filter returns a new array instance so you loose the reference of your original array when you do result = result.filter(...). You can use array.splice instead:

var result = [{ 'date': '20171116' }, { 'date': '20171115' }];
var data = { 'date': '20171116' };
deleteEntry(data, result);
function deleteEntry(data, result) {
    var index = result.findIndex(item => item.date === data.date);
    result.splice(index, 1);
}
console.log(result);```

Body:
I am trying to write a JavaScript function (ES5) that will take in an array, filter it, and set the original array to the new one.

Here is my plunk: https://plnkr.co/edit/OWeOjJ3SLVGYRaweyy3Z

Here is the basic pseudocode of what I am trying to do:

var result = [{ 'date': '20171116' }, { 'date': '20171115' }];
var data = { 'date': '2017116' };
deleteEntry(data, result);
console.log(result); //should  have one entry

function deleteEntry(data, result) {
  result = result.filter(function(item) {
    return item.date !== data.date;
  });
}

I believe the issue is to do with array references. I am not sure how to accomplish the task.


问:
Position sticky broken in Firefox 57
I'm trying to use position sticky to make a sticky table header.

The following jsfiddle works in Chrome v64, but isn't working in Firefox v57.

https://jsfiddle.net/b5fv94m0/

Is there some additional CSS I'm missing to make it work in Firefox?

CSS

```<code>.container {
  height: 200px;
  overflow: scroll;
}

th {
  position: sticky;
  top: 0;
}
</code>```

HTML

```<code><div class="container">
<table>
<thead>
  <tr>
    <th>Header</th>
  </tr>
</thead>
<tbody>
  <tr>
    <td>Cell</td>
  </tr>
  <tr>
    <td>Cell</td>
  </tr>
  <tr>
    <td>Cell</td>
  </tr>
  <tr>
    <td>Cell</td>
  </tr>
  <tr>
    <td>Cell</td>
  </tr>
  <tr>
    <td>Cell</td>
  </tr>
  <tr>
    <td>Cell</td>
  </tr>
  <tr>
    <td>Cell</td>
  </tr>
  <tr>
    <td>Cell</td>
  </tr>
  <tr>
    <td>Cell</td>
  </tr>
</tbody>
</table>
</div>
</code>```

答:
position:sticky

This css is not compatible to all browser so better use position: fixed

Title: Position sticky broken in Firefox 57

Body:
I'm trying to use position sticky to make a sticky table header.

The following jsfiddle works in Chrome v64, but isn't working in Firefox v57.

https://jsfiddle.net/b5fv94m0/

Is there some additional CSS I'm missing to make it work in Firefox?

CSS

.container {
  height: 200px;
  overflow: scroll;
}

th {
  position: sticky;
  top: 0;
}

HTML

    Header

    Cell

    Cell

    Cell

    Cell

    Cell

    Cell

    Cell

    Cell

    Cell

    Cell


问:
bootstrap img-responsive is not working for firefox pseudo elements
I am loading my images through CSS using content and they are working fine for Chrome and Safari, but Firefox has an issue with it which forces me to use Pseudo Elements. However, the Pseudo Elements are not working with the img-responsive class.

HTML code:

```<code><div class="container">
    <div class="row">
        <div class="col-xs-12">
            <a href="https://www.facebook.com/">
                <img class="img-responsive center-block" id="imgEN" />
            </a>
        </div>
    </div>
</div>
</code>```

CSS code:

```<code>#imgEN::after  {
content:url("images/banner.png");
    text-align: -moz-center;
}

.img-responsive {
width:100%;
}
</code>```

How do I make the img element to be responsive? It looks fine on bigger resolution, but on smaller resolution/screen, the image will be out from the div.

答: you have to add max-width: 100% to your a tag. Maybe over a class selector or directly as inline style

Body:
I am loading my images through CSS using content and they are working fine for Chrome and Safari, but Firefox has an issue with it which forces me to use Pseudo Elements. However, the Pseudo Elements are not working with the img-responsive class.

HTML code:

CSS code:

#imgEN::after  {
content:url("images/banner.png");
    text-align: -moz-center;
}

.img-responsive {
width:100%;
}

How do I make the img element to be responsive? It looks fine on bigger resolution, but on smaller resolution/screen, the image will be out from the div.


问:
Including jQuery Ul widgets. How to include jQuery Ul on localhost?
I am trying to build jQuery code using local server with XAMPP. The problem is when I try to include jQueryUI. When I open the file in a browser in the standard way it's working fine, but when I open it in localhost it shows me this error:

GET http://localhost/jQuery_files/jquery-ui-1.12.1/jquery-ui.css net::ERR_ABORTED.

What am I missing here, is there any solution?

```<code><head>
    <link href="jquery-ui-1.12.1/jquery-ui.css" rel="stylesheet">
</head>
<body>
    <script src="jquery-ui-1.12.1/jquery-ui.js"></script>
</body>
</code>```

答:
You need to download jquery library file for using it in localhost, or you can include jquery by jquery library 's absolute path.

Reference in here
https://www.w3schools.com/jquery/jquery_get_started.asp

Body:
I am trying to build jQuery code using local server with XAMPP. The problem is when I try to include jQueryUI. When I open the file in a browser in the standard way it's working fine, but when I open it in localhost it shows me this error:

GET http://localhost/jQuery_files/jquery-ui-1.12.1/jquery-ui.css net::ERR_ABORTED.

What am I missing here, is there any solution?

    <link href="jquery-ui-1.12.1/jquery-ui.css" rel="stylesheet">


问:
Using a REST web service how do you make a method that returns text passed to it?
I am currently using Eclipse and Tomcat for my servers and I am trying to make a method that passes an input string as output onto the HTML website.

I got some help from the question below, but how would I go about implementing the code from that link into a servlet file?

How to create a Restful web service with input parameters?

If anyone has any other solutions to taking text, passing it to the method and outputting it I'd appreciate it.

The code I'm using is a demo for Hello World (scroll to the very bottom):

https://www.ibm.com/developerworks/library/os-eclipse-tomcat/index.html

答:
Just configure the servlet referred through the link you provided like:

```<code><servlet>
  <servlet-name>HelloServlet</servlet-name>
  <servlet-class>
     com.example.servlets.HelloServlet
  </servlet-class>
  <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
  <servlet-name>HelloServlet</servlet-name>
  <url-pattern>/</url-pattern>
</servlet-mapping>
</code>```

Once you hit the servlet through browser it will display Hello World on the HTML page. As said you can pass any parameters to this servlet and then can manipulate, display those in HTML output.

Body:
Just configure the servlet referred through the link you provided like:

<servlet>
  <servlet-name>HelloServlet</servlet-name>
  <servlet-class>
     com.example.servlets.HelloServlet
  </servlet-class>
  <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
  <servlet-name>HelloServlet</servlet-name>
  <url-pattern>/</url-pattern>
</servlet-mapping>

Once you hit the servlet through browser it will display Hello World on the HTML page. As said you can pass any parameters to this servlet and then can manipulate, display those in HTML output.


问:
How can I access the text of Html.ValidationMessage() to check it in Razor?
I have some code to booking tickets on movie. If somebody already booked ticket he may book more tickets, only if there is specific error message.

This var validationSummary receives only the tags (). But in the web page @validationSummary prints correct message.
How can I and can I access the text of the error message to check it at all?

```<code>@{
    @Html.ValidationSummary(true)
    var validationSummary = Html.ValidationMessage("Saving");
    bool buyAnotherVal = validationSummary.ToString().Contains("By continuing this form, you will booking another some tickets");
 }
 @using ( Html.BeginUmbracoForm<MovieBookingSurfaceController>( "SubmitBuyerDetails", new { buyAnother = buyAnotherVal }) )
 {
    @validationSummary
</code>```

答:
I solved this problem so:

```<code>@Html.ValidationSummary(true)
var validationSummary = Html.ValidationMessage("Saving");
bool bookAnotherVal = Html.ValidationSummary().ToString().Contains(BookingException.Msg_EmailDuplicatedBookAnother);
</code>```

The ValidationSummary method displays a list of all validation messages on the page. (https://msdn.microsoft.com/en-us//library/system.web.mvc.html.validationextensions.validationsummary(v=vs.118).aspx)

Body:
I have some code to booking tickets on movie. If somebody already booked ticket he may book more tickets, only if there is specific error message.

This var validationSummary receives only the tags (). But in the web page @validationSummary prints correct message.
How can I and can I access the text of the error message to check it at all?

@{
    @Html.ValidationSummary(true)
    var validationSummary = Html.ValidationMessage("Saving");
    bool buyAnotherVal = validationSummary.ToString().Contains("By continuing this form, you will booking another some tickets");
 }
 @using ( Html.BeginUmbracoForm<MovieBookingSurfaceController>( "SubmitBuyerDetails", new { buyAnother = buyAnotherVal }) )
 {
    @validationSummary

Body:
I solved this problem so:

@Html.ValidationSummary(true)
var validationSummary = Html.ValidationMessage("Saving");
bool bookAnotherVal = Html.ValidationSummary().ToString().Contains(BookingException.Msg_EmailDuplicatedBookAnother);

The ValidationSummary method displays a list of all validation messages on the page. (https://msdn.microsoft.com/en-us//library/system.web.mvc.html.validationextensions.validationsummary(v=vs.118).aspx)


问:
Check for value definedness in C++
I'm working in C++ and I need to know if a scalar value (for instance a double) is "defined" or not. I also need to be able to "undef" it if needed:

```<code>class Foo {
public:
    double get_bar();

private:
    double bar;
    void calculate_bar() {
        bar = something();
    }
};

double Foo::get_bar() {
    if ( undefined(bar) )
        calculate_bar();
    return bar;
}
</code>```

Is it possible in C++?

Thanks

答:
Why not maintain a separate flag that gets initialized to false and then gets set to true when bar is calculated. It can then be 'undefed' by setting the flag to false again.</p>

```<code>if(!isBarValid)
{
    calculateBar();
    isBarValid = true;
}
return bar;
</code>```

OwnerDisplayName: Tunnuz

Title: Check for value definedness in C++

Body:
I'm working in C++ and I need to know if a scalar value (for instance a double) is "defined" or not. I also need to be able to "undef" it if needed:

class Foo {
public:
    double get_bar();

private:
    double bar;
    void calculate_bar() {
        bar = something();
    }
};

double Foo::get_bar() {
    if ( undefined(bar) )
        calculate_bar();
    return bar;
}

Is it possible in C++?

Thanks

Body:
Why not maintain a separate flag that gets initialized to false and then gets set to true when bar is calculated. It can then be 'undefed' by setting the flag to false again.

if(!isBarValid)
{
    calculateBar();
    isBarValid = true;
}
return bar;

OwnerDisplayName: Stephen Doyle


问:
square numbers given in an sequence
Given a positive integer sequence of numbers in an array with common difference 2
for e.g 2 4 6 8
Now replace each number by its square. Perform the computations efficiently.
I was asked this question in an interview and i gave him o(n) solution using bitwise operator since it is operation in the multiples of 2.If there is any better method please suggest.</p>

答:
I dunno if its better but it's recursive!!! :-)</p>

```<code>(n+2)(n+2) = n**2 + 4*n + 4 // and you got n**2
</code>```

Title: square numbers given in an sequence

LastEditorDisplayName: Aryabhatta

Body:
I dunno if its better but it's recursive!!! :-)

(n+2)(n+2) = n**2 + 4*n + 4 // and you got n**2


问:
MS Word Insert > Pictures (from Ribbon) Stopped Working
In MS Word (2016) I am trying to insert an image (usually a trivial thing) using the insert tab on the ribbon.  I click the Pictures button expecting a browse dialogue to appear but nothing happens.

On a side note, the VBA application.Dialogs(wdDialogInsertPicture).Show also fails to produce the insert picture dialogue.

Thoughts?

答: EITHER of these settings prevent users from adding images


问:
login() is not working at all - Django
I have a django app and I am trying to integrate the login system that they have within the framework. I have the following line of code:

```<code>user = authenticate(username=username, password=password)
login(request, user)
</code>```

I am running this method right after I create a new user after the user signs up and creates an account. I know the authentication is going to be successfull because I just created the account and I know it is there. I am gettting the following error

```<code>login() takes 1 positional argument but 2 were given
</code>```

In the documentation is says you pass in a request and user... so why is it not working. this is driving me crazy....

Here is the documentation on djangos websites:

```<code>login(request, user, backend=None)[source]¶
To log a user in, from a view, use login(). It takes an HttpRequest object and a User object. login() saves the user’s ID in the session, using Django’s session framework.

Note that any data set during the anonymous session is retained in the session after a user logs in.

This example shows how you might use both authenticate() and login():

from django.contrib.auth import authenticate, login

def my_view(request):
    username = request.POST['username']
    password = request.POST['password']
    user = authenticate(request, username=username, password=password)
    if user is not None:
        login(request, user)
</code>```

Here is my full signup method:

```<code>def signup(request):
    if request.method == 'POST':
        form = SignupForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            username = cd['username']
            password = cd['password']
            verify = cd['verify']
            email = cd['email']
            if password == verify:
                secure_password = make_password(password)
                user = User.objects.create(
                    username = username,
                    password = secure_password,
                    email = email,
                )
                user = authenticate(username=username, password=password)
                if user is not None:
                    login(request, user)
                else:
                    return redirect('home')
            else:
                form = SignupForm()
                parameters = {
                    'form':form,
                }
                return render(request, 'users/signup.html', parameters)
    else:
        form = SignupForm()
        parameters = {
            'form':form
        }
        return render(request, 'users/signup.html', parameters)
</code>```

答:
if you havent declared any function with the same name as login

then

```<code>user = authenticate(request, username=username, password=password)
    if user is not None:
        login(request, user)
</code>```

you missed the request in the authenticate.

and if you have declared a function with the name login then change it to something else

Title: login() is not working at all - Django

Body:
I have a django app and I am trying to integrate the login system that they have within the framework. I have the following line of code:

user = authenticate(username=username, password=password)
login(request, user)

I am running this method right after I create a new user after the user signs up and creates an account. I know the authentication is going to be successfull because I just created the account and I know it is there. I am gettting the following error

login() takes 1 positional argument but 2 were given

In the documentation is says you pass in a request and user... so why is it not working. this is driving me crazy....

Here is the documentation on djangos websites:

login(request, user, backend=None)[source]¶
To log a user in, from a view, use login(). It takes an HttpRequest object and a User object. login() saves the user’s ID in the session, using Django’s session framework.

Note that any data set during the anonymous session is retained in the session after a user logs in.

This example shows how you might use both authenticate() and login():

from django.contrib.auth import authenticate, login

def my_view(request):
    username = request.POST['username']
    password = request.POST['password']
    user = authenticate(request, username=username, password=password)
    if user is not None:
        login(request, user)

Here is my full signup method:

def signup(request):
    if request.method == 'POST':
        form = SignupForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            username = cd['username']
            password = cd['password']
            verify = cd['verify']
            email = cd['email']
            if password == verify:
                secure_password = make_password(password)
                user = User.objects.create(
                    username = username,
                    password = secure_password,
                    email = email,
                )
                user = authenticate(username=username, password=password)
                if user is not None:
                    login(request, user)
                else:
                    return redirect('home')
            else:
                form = SignupForm()
                parameters = {
                    'form':form,
                }
                return render(request, 'users/signup.html', parameters)
    else:
        form = SignupForm()
        parameters = {
            'form':form
        }
        return render(request, 'users/signup.html', parameters)

Body:
if you havent declared any function with the same name as login

then

user = authenticate(request, username=username, password=password)
    if user is not None:
        login(request, user)

you missed the request in the authenticate.

and if you have declared a function with the name login then change it to something else


问:
Getting the field of an object
I have objects like below

```<code>{
"user": "58a9bf92e0f78000055dd932",
"type": "template_created",
"count": 2
}
</code>```

I need to get 'user' field, ..->type returns "template_created" and ..->count gives its value but ..->user returns null. These objects come from mongodb aggregation framework by the way.

答:
Use this code</p>

```<code>$data = json_decode($data); //where $data contain the json
$data->user;
</code>```

Title: Getting the field of an object

Body:
I have objects like below

{
"user": "58a9bf92e0f78000055dd932",
"type": "template_created",
"count": 2
}

I need to get 'user' field, ..->type returns "template_created" and ..->count gives its value but ..->user returns null. These objects come from mongodb aggregation framework by the way.

Body:
Use this code

$data = json_decode($data); //where $data contain the json
$data->user;


问:
Modular Java Application on GIT repository
I'm working on a "modular Java application", it has around 60 independent modules, all obviously "buildable" on their own.

I'm trying to understand what can be the best approach to structure this type of application under GIT.

I'll explain better myself:

I've been working several years with SVN and it would be really easy for me to structure a project like this under a centralized version control tool such as SVN, while I'm not sure about the GIT best practices and pros/cons.

With SVN:

I would import all the project under the same repository

I would consider two different approaches, with similar consequences, for example:

```<code> mod_A
   |___trunk
   |___branches
   |   |___branch_A
   |
   |___tags
 mod_B
   |___trunk
   |___branches
   |   |___branch_A
   |   |___branch_B
   |
   |___tags
</code>```

OR

```<code> trunk
   |___mod_a
   |___mod_b
   |___mod_c
 branches
   |___branch_A
   |   |___mod_a
   |___branch_B
       |___mod_a
       |___mod_b
</code>```

With both the approaches it would be really easy for me to achieve information like, which are the modules branched for a particular feature, and see the application from the modules prospective but also from the branches prospective.

Moreover, with both the structures I would be able to easily branch just some of the modules without being forced to branch them all anytime.

With GIT:

At the moment the modular application i'm working with is structured with a single independent repo for any module, in my view this structure, even if brings some advantages, has also a real big issue.

In fact it looks hard for me to have a clear whole overview of the application, cause I've to connect to every single repository and check the branches to understand which modules are involved in a particular branch, so if I've to manage a branched version of my application, that for example involves just 7 modules to be branched in a particular BUG_FIXING or FEATURE branch and not the whole application, I would have no way to get this info through GIT, and I should manage this information in a custom way.

Then even if the application would have been set up within the same repo, i would have been unable to decide to branch just a subset of modules cause "Git operates on the entire repository, not on individual directories".

Can you please clarify how can be the best approach to follow with a modular application, can GIT sub modules be a solution? Is there any other approach i'm not considering, or i'm moving from wrong assumptions?

Thanks a lot!

答:
First you should manage the module Java application in one git repo as you managed in one SVN repo, since all the modules are works for the same project.

For the branching module structure for you application, I will suggest manage each module in separate branches(modX), and manage your entire project  in master branch.

The work flow can be:

Manage the project level files in master branch. the structure for master branch as:

```<code>Root (master branch)
   |___... (project level files)
</code>```

Checkout module branches  (such as modA branch, modB branch and modC branch) from master. Deleted the project level files and add files for module in mod_X folder.

Such as for branch modA, the structure is:

```<code>Root (modA branch)
   |___mod_A (folder)
           |___... (module A level files)
</code>```

When you finished work for module X, then merge modX branch into master branch.

After all the modules are finished work (and merged into master), the file structure for master branch should be:

```<code>Root (master branch)
   |___... (project level files)
   |___mod_A (folder)
           |___... (module A level files)
   |___mod_B (folder)
           |___... (module B level files)
   |___mod_C (folder)
           |___... (module C level files)
</code>```

If you update module X in modX branch, then merge modX branch again into master branch to make sure the application is updated.

To maintain project-level (application aggregator) files, you can also develop/test/fixbug on develop, feature and hotfix branches:

master branch as the production version for your java application.

develop branch (long living branch which should checkout from master branch) is used for all the developers work on it. When the changed application is build successful (verified), you can merge develop branch into master.

featurebranches are short living branches. If you need to develop new features for your application, you can checkout a feature branch from develop branch. And then the feature is finished, merge feature branch into develop branch to verify your code.

hotfix branches are also short living branches. You can fix bugs on the branches, when the bug(s) is fixed, merge the hotfix branch into develop branch.

And there has a successful branching model you can refer for managing the project-level (application aggregator) files.

Body:
I'm working on a "modular Java application", it has around 60 independent modules, all obviously "buildable" on their own.

I'm trying to understand what can be the best approach to structure this type of application under GIT.

I'll explain better myself:

I've been working several years with SVN and it would be really easy for me to structure a project like this under a centralized version control tool such as SVN, while I'm not sure about the GIT best practices and pros/cons.

With SVN:

I would import all the project under the same repository

I would consider two different approaches, with similar consequences, for example:

 mod_A
   |___trunk
   |___branches
   |   |___branch_A
   |
   |___tags
 mod_B
   |___trunk
   |___branches
   |   |___branch_A
   |   |___branch_B
   |
   |___tags

OR

 trunk
   |___mod_a
   |___mod_b
   |___mod_c
 branches
   |___branch_A
   |   |___mod_a
   |___branch_B
       |___mod_a
       |___mod_b

With both the approaches it would be really easy for me to achieve information like, which are the modules branched for a particular feature, and see the application from the modules prospective but also from the branches prospective.

Moreover, with both the structures I would be able to easily branch just some of the modules without being forced to branch them all anytime.

With GIT:

At the moment the modular application i'm working with is structured with a single independent repo for any module, in my view this structure, even if brings some advantages, has also a real big issue.

In fact it looks hard for me to have a clear whole overview of the application, cause I've to connect to every single repository and check the branches to understand which modules are involved in a particular branch, so if I've to manage a branched version of my application, that for example involves just 7 modules to be branched in a particular BUG_FIXING or FEATURE branch and not the whole application, I would have no way to get this info through GIT, and I should manage this information in a custom way.

Then even if the application would have been set up within the same repo, i would have been unable to decide to branch just a subset of modules cause "Git operates on the entire repository, not on individual directories".

Can you please clarify how can be the best approach to follow with a modular application, can GIT sub modules be a solution? Is there any other approach i'm not considering, or i'm moving from wrong assumptions?

Thanks a lot!

Body:
First you should manage the module Java application in one git repo as you managed in one SVN repo, since all the modules are works for the same project.

For the branching module structure for you application, I will suggest manage each module in separate branches(modX), and manage your entire project  in master branch.

The work flow can be:

Manage the project level files in master branch. the structure for master branch as:

Root (master branch)
   |___... (project level files)

Checkout module branches  (such as modA branch, modB branch and modC branch) from master. Deleted the project level files and add files for module in mod_X folder.

Such as for branch modA, the structure is:

Root (modA branch)
   |___mod_A (folder)
           |___... (module A level files)

When you finished work for module X, then merge modX branch into master branch.

After all the modules are finished work (and merged into master), the file structure for master branch should be:

Root (master branch)
   |___... (project level files)
   |___mod_A (folder)
           |___... (module A level files)
   |___mod_B (folder)
           |___... (module B level files)
   |___mod_C (folder)
           |___... (module C level files)

If you update module X in modX branch, then merge modX branch again into master branch to make sure the application is updated.

To maintain project-level (application aggregator) files, you can also develop/test/fixbug on develop, feature and hotfix branches:

master branch as the production version for your java application.

develop branch (long living branch which should checkout from master branch) is used for all the developers work on it. When the changed application is build successful (verified), you can merge develop branch into master.

featurebranches are short living branches. If you need to develop new features for your application, you can checkout a feature branch from develop branch. And then the feature is finished, merge feature branch into develop branch to verify your code.

hotfix branches are also short living branches. You can fix bugs on the branches, when the bug(s) is fixed, merge the hotfix branch into develop branch.

And there has a successful branching model you can refer for managing the project-level (application aggregator) files.


问:
Why info about removed queue is not logged in RabbitMQ
Why I cannot find information about deleted queue in logs of RabbitMQ?  When queue is removed from /vhost then no information about it is logged.

Is it possible to have this information in log because we have problem with disappearing queue which is shoveled with other RabbitMQ cluster.

Updated
I would like to add that queues are not temporary and auto-delete but just let say normal and durable.

答:
The RabbitMQ team monitors this mailing list and only sometimes answers questions on StackOverflow.

I recommend asking this question on the mailing list. You may be able to get information via debug logging. If queues "disappear" it may because they are being declared as temporary or auto-delete (docs).