问:
Find the maximum distance between two pairwise given elements
This code is  designed to find the minimum distance between two elements.As example below the minimum distance between 3 and 3 should return 5 but I need
the furthest one not the nearest one, what I should to find the maximum distance between no 3 and no 3?</p>

```<code>   internal class MinimumDistance
{
    internal virtual int minDist(int[] arr, int n, int x, int y)
    {
        int i, j;
        int min_dist = int.MaxValue;
        for (i = 0; i < n; i++)
        {
            for (j = i + 1; j < n; j++)
            {
                if ((x == arr[i] && y == arr[j] || y == arr[i] && x == arr[j]) && min_dist > Math.Abs(i - j))
                {
                    min_dist = Math.Abs(i - j);
                }
            }
        }
        return min_dist;
    }

    public static void Main(string[] args)
    {
        MinimumDistance min = new MinimumDistance();
        int[] arr = new int[] { 3, 2, 4, 2, 6, 5, 3, 6, 5, 4, 8, 3 };
        int n = arr.Length;
        int x = 3;
        int y = 3;

        Console.WriteLine("Minimum distance between " + x + " and " + y + " is " + min.minDist(arr, n, x, y)); //return the nearest 3 so it will be 5
    }
}
</code>```

答:
This code should do:</p>

```<code>internal class MaximumDistance
{
    internal virtual int maxDist(int[] arr, int n, int x, int y)
    {
        var max_dist = int.MinValue;
        for (var i = 0; i < n; i++)
            for (var j = i + 1; j < n; j++)
                if ((x == arr[i] && y == arr[j] || y == arr[i] && x == arr[j]) && max_dist < Math.Abs(i - j))
                    max_dist = Math.Abs(i - j);
        return max_dist;
    }

    public static void Main(string[] args)
    {
        var max = new MaximumDistance();
        var arr = new int[] { 3, 2, 4, 2, 6, 5, 3, 6, 5, 4, 8, 3 };
        var n = arr.Length;
        var x = 3;
        var y = 3;

        Console.WriteLine("Maximum distance between " + x + " and " + y + " is " + max.maxDist(arr, n, x, y));
    }
}
</code>```

Body:
This code is  designed to find the minimum distance between two elements.As example below the minimum distance between 3 and 3 should return 5 but I need
the furthest one not the nearest one, what I should to find the maximum distance between no 3 and no 3?

   internal class MinimumDistance
{
    internal virtual int minDist(int[] arr, int n, int x, int y)
    {
        int i, j;
        int min_dist = int.MaxValue;
        for (i = 0; i < n; i++)
        {
            for (j = i + 1; j < n; j++)
            {
                if ((x == arr[i] && y == arr[j] || y == arr[i] && x == arr[j]) && min_dist > Math.Abs(i - j))
                {
                    min_dist = Math.Abs(i - j);
                }
            }
        }
        return min_dist;
    }

    public static void Main(string[] args)
    {
        MinimumDistance min = new MinimumDistance();
        int[] arr = new int[] { 3, 2, 4, 2, 6, 5, 3, 6, 5, 4, 8, 3 };
        int n = arr.Length;
        int x = 3;
        int y = 3;

        Console.WriteLine("Minimum distance between " + x + " and " + y + " is " + min.minDist(arr, n, x, y)); //return the nearest 3 so it will be 5
    }
}

Body:
This code should do:

internal class MaximumDistance
{
    internal virtual int maxDist(int[] arr, int n, int x, int y)
    {
        var max_dist = int.MinValue;
        for (var i = 0; i < n; i++)
            for (var j = i + 1; j < n; j++)
                if ((x == arr[i] && y == arr[j] || y == arr[i] && x == arr[j]) && max_dist < Math.Abs(i - j))
                    max_dist = Math.Abs(i - j);
        return max_dist;
    }

    public static void Main(string[] args)
    {
        var max = new MaximumDistance();
        var arr = new int[] { 3, 2, 4, 2, 6, 5, 3, 6, 5, 4, 8, 3 };
        var n = arr.Length;
        var x = 3;
        var y = 3;

        Console.WriteLine("Maximum distance between " + x + " and " + y + " is " + max.maxDist(arr, n, x, y));
    }
}


来源: stackexchange

问:
How to export to Excel from Spring MVC
I want to export some data which I have retrieved from the database to the controller level. From the controller I need to export this data to an Excel file without using a view.

I wrote:

```<code>        ReportSearchVO searchL = formL.getObjReportSearchG();

        loggerG.info("Resource List:" + searchL.getResourceListG());

        projDetailReportL = reportServiceG.createProjectDetailReport(formL);

        formL.setProjDetailReport(projDetailReportL);
        formL.setReportTypeEnum(ReportTypeEnum.PROJECTDETAILREPORT);
        formL.setObjReportSearchG(searchL);

        requestR.setAttribute("resLevelForm", formL);
        returnModelAndView = new ModelAndView(
            ViewConstants.FINAL_VIEW_PROJECT_DETAILS_REPORT, "reportForm",
            formL);
</code>```

but this uses a view.

答:
Using AbstractExcelView and ModalAndView its possible in SpringMVC. Refer below for more details

http://learnfromexamples.com/generate-excel-in-spring-mvc-application-using-apache-poi/

ContentLicense: CC BY-SA 3.0

Title: How to export to Excel from Spring MVC

Body:
I want to export some data which I have retrieved from the database to the controller level. From the controller I need to export this data to an Excel file without using a view.

I wrote:

        ReportSearchVO searchL = formL.getObjReportSearchG();

        loggerG.info("Resource List:" + searchL.getResourceListG());

        projDetailReportL = reportServiceG.createProjectDetailReport(formL);

        formL.setProjDetailReport(projDetailReportL);
        formL.setReportTypeEnum(ReportTypeEnum.PROJECTDETAILREPORT);
        formL.setObjReportSearchG(searchL);

        requestR.setAttribute("resLevelForm", formL);
        returnModelAndView = new ModelAndView(
            ViewConstants.FINAL_VIEW_PROJECT_DETAILS_REPORT, "reportForm",
            formL);

but this uses a view.


问:
How to draw a rounded rectangle (rectangle with rounded corners) with OpenCV?
How can I draw a rectangle with rounded corners in OpenCV? I know that the functions ellipse() and line() can be simply put together to draw it. I just wonder if someone has done it before and has put it in a proper function so I can use it? Ideally the corner radius is to calibrate  in a parameter.

I searched a lot for that, but it seems no one had that problem before. If no one has such I function I will probably post my own solution here in a few days.

答:
Here's a Python implementation(in case anyone was looking for one): it draws a rounded corner (of random radius and line thickness --- change that if you want) border around an image:</p>

```<code>def addRoundedRectangleBorder(img):
    height, width, channels = img.shape

    border_radius = int(width * random.randint(1, 10)/100.0)
    line_thickness = int(max(width, height) * random.randint(1, 3)/100.0)
    edge_shift = int(line_thickness/2.0)

    red = random.randint(230,255)
    green = random.randint(230,255)
    blue = random.randint(230,255)
    color = (blue, green, red)

    #draw lines
    #top
    cv2.line(img, (border_radius, edge_shift),
    (width - border_radius, edge_shift), (blue, green, red), line_thickness)
    #bottom
    cv2.line(img, (border_radius, height-line_thickness),
    (width - border_radius, height-line_thickness), (blue, green, red), line_thickness)
    #left
    cv2.line(img, (edge_shift, border_radius),
    (edge_shift, height  - border_radius), (blue, green, red), line_thickness)
    #right
    cv2.line(img, (width - line_thickness, border_radius),
    (width - line_thickness, height  - border_radius), (blue, green, red), line_thickness)

    #corners
    cv2.ellipse(img, (border_radius+ edge_shift, border_radius+edge_shift),
    (border_radius, border_radius), 180, 0, 90, color, line_thickness)
    cv2.ellipse(img, (width-(border_radius+line_thickness), border_radius),
    (border_radius, border_radius), 270, 0, 90, color, line_thickness)
    cv2.ellipse(img, (width-(border_radius+line_thickness), height-(border_radius + line_thickness)),
    (border_radius, border_radius), 10, 0, 90, color, line_thickness)
    cv2.ellipse(img, (border_radius+edge_shift, height-(border_radius + line_thickness)),
    (border_radius, border_radius), 90, 0, 90, color, line_thickness)

    return img
</code>```

Body:
Here's a Python implementation(in case anyone was looking for one): it draws a rounded corner (of random radius and line thickness --- change that if you want) border around an image:

def addRoundedRectangleBorder(img):
    height, width, channels = img.shape

    border_radius = int(width * random.randint(1, 10)/100.0)
    line_thickness = int(max(width, height) * random.randint(1, 3)/100.0)
    edge_shift = int(line_thickness/2.0)

    red = random.randint(230,255)
    green = random.randint(230,255)
    blue = random.randint(230,255)
    color = (blue, green, red)

    #draw lines
    #top
    cv2.line(img, (border_radius, edge_shift),
    (width - border_radius, edge_shift), (blue, green, red), line_thickness)
    #bottom
    cv2.line(img, (border_radius, height-line_thickness),
    (width - border_radius, height-line_thickness), (blue, green, red), line_thickness)
    #left
    cv2.line(img, (edge_shift, border_radius),
    (edge_shift, height  - border_radius), (blue, green, red), line_thickness)
    #right
    cv2.line(img, (width - line_thickness, border_radius),
    (width - line_thickness, height  - border_radius), (blue, green, red), line_thickness)

    #corners
    cv2.ellipse(img, (border_radius+ edge_shift, border_radius+edge_shift),
    (border_radius, border_radius), 180, 0, 90, color, line_thickness)
    cv2.ellipse(img, (width-(border_radius+line_thickness), border_radius),
    (border_radius, border_radius), 270, 0, 90, color, line_thickness)
    cv2.ellipse(img, (width-(border_radius+line_thickness), height-(border_radius + line_thickness)),
    (border_radius, border_radius), 10, 0, 90, color, line_thickness)
    cv2.ellipse(img, (border_radius+edge_shift, height-(border_radius + line_thickness)),
    (border_radius, border_radius), 90, 0, 90, color, line_thickness)

    return img


问:
Why does my app crash when I press a button and how to fix it
I am trying to make a basic dice roller for a card game. It is on the second screen of two. The screen opens fine when I press the button to open it, but when I click the dice button the app simply crashes. I am using the newest version of Android Studio. Here's my code:</p>

```<code>import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;
import java.util.Random;
import static android.R.attr.value;

public class Extras extends AppCompatActivity implements OnClickListener{

    Button btn1;
    TextView numberGenerator;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_extras);

        btn1 = (Button) findViewById(R.id.diceButton);

        btn1.setOnClickListener(this);
        numberGenerator = (TextView)findViewById(R.id.numberGenerator);

    }

    @Override

    public void onClick(View v) {
        int min = 1;
        int max = 6;
        Random random = new Random();
        int value = random.nextInt(max - min) + min;
        numberGenerator.setText(value+"");

        if (v == btn1) {
            numberGenerator.setText(value);
        }

    }
    ...
}
</code>```

答:
Your app is crashes because you are trying to put int value to the setText() method.

Here:

```<code>if (v == btn1) {
    numberGenerator.setText(value);
}
</code>```

Try instead:

```<code>if (v == btn1) {
    numberGenerator.setText(String.valueOf(value));
}
</code>```

If this does not work post your stacktrace.

Body:
I am trying to make a basic dice roller for a card game. It is on the second screen of two. The screen opens fine when I press the button to open it, but when I click the dice button the app simply crashes. I am using the newest version of Android Studio. Here's my code:

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;
import java.util.Random;
import static android.R.attr.value;

public class Extras extends AppCompatActivity implements OnClickListener{

    Button btn1;
    TextView numberGenerator;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_extras);

        btn1 = (Button) findViewById(R.id.diceButton);

        btn1.setOnClickListener(this);
        numberGenerator = (TextView)findViewById(R.id.numberGenerator);

    }

    @Override

    public void onClick(View v) {
        int min = 1;
        int max = 6;
        Random random = new Random();
        int value = random.nextInt(max - min) + min;
        numberGenerator.setText(value+"");

        if (v == btn1) {
            numberGenerator.setText(value);
        }

    }
    ...
}

Body:
Your app is crashes because you are trying to put int value to the setText() method.

Here:

if (v == btn1) {
    numberGenerator.setText(value);
}

Try instead:

if (v == btn1) {
    numberGenerator.setText(String.valueOf(value));
}

If this does not work post your stacktrace.


问:
Running a class from within a jar using ant
im trying to invoke a specific class from within a jar file but I'm gettign below exception -

```<code>Buildfile: C:\Projects\GranHermano\build.xml
SignJadFilesInDir:
    [java] java.lang.NoClassDefFoundError: org/apache/poi/ss/usermodel/Cell
</code>```

My jar file contains all required jars (in this case poi-3.6-20091214.jar) so above exception should not be thrown.

This is how I am invoking the class -

```<code><target name="SignJadFilesInDir" description="Signs all jad files in a dir" >
 <java classname="com.src.SignDeviceJadInDir">
     <classpath>
        <pathelement location="BuildUtils.jar"/>
      </classpath>
  <arg line="${jadFileDir}"/>
  <arg line="${devicesExcelDir}"/>
  <arg line="${wtkDir}"/>
  <arg line="${keyStoreDir}"/>
  <arg line="${keyStoreId}"/>
  <arg line="${keyStorePwd}"/>
 </java>
</target>
</code>```

Thanks

答:
Can you please open jar BuildUtils.jar to ensure it well contains the classes of poi (and not poi jar, as I'm not aware of JRE support for jar-in-a-jar out of the box) ?
If your BuildUtils.jar contains poi-3.6-20091214.jar and not its classes, your exception is quite normal.

ContentLicense: CC BY-SA 2.5

Body:
im trying to invoke a specific class from within a jar file but I'm gettign below exception -

Buildfile: C:\Projects\GranHermano\build.xml
SignJadFilesInDir:
    [java] java.lang.NoClassDefFoundError: org/apache/poi/ss/usermodel/Cell

My jar file contains all required jars (in this case poi-3.6-20091214.jar) so above exception should not be thrown.

This is how I am invoking the class -

<target name="SignJadFilesInDir" description="Signs all jad files in a dir" >
 <java classname="com.src.SignDeviceJadInDir">
     <classpath>
        <pathelement location="BuildUtils.jar"/>
      </classpath>
  <arg line="${jadFileDir}"/>
  <arg line="${devicesExcelDir}"/>
  <arg line="${wtkDir}"/>
  <arg line="${keyStoreDir}"/>
  <arg line="${keyStoreId}"/>
  <arg line="${keyStorePwd}"/>
 </java>
</target>

Thanks


问:
Using jQuery to add content to multiple elements returned by find()
How can I add content to the second and third td?

I just found that the following will not work.  I can find a way by creating some variable to hold the found elements, but would like to learn cleaner "more jQueryish" way if available.

```<code><tr id="clone"><td></td><td></td><td></td></tr>

$.each(records, function( index, row ) {
    $('#clone').clone()
    .removeAttr('id')
    .find('td')
    .eq(1).text(row.name).parent()
    .eq(2).text(row.message).parent()
    .appendTo(content)
});
</code>```

答:
You need to use .end() instead of parent()

End the most recent filtering operation in the current chain and return the set of matched elements to its previous state.

$('#clone').clone()
  .removeAttr('id')
  .find('td')
  .eq(1).text('Added 1').end()
  .eq(2).text('Added 2').end()
  .appendTo('table')```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<table>
  <tr id="clone">
    <td>1</td>
    <td>2</td>
    <td>3</td>
  </tr>
</table></code>```

However I prefer having reference cloned element in a variable.

var clonedElement = $('#clone').clone()
  .removeAttr('id');

//Manipulate element
var tds = clonedElement.find('td');
tds.eq(1).text('Added 1');
tds.eq(2).text('Added 2');

//Append it
clonedElement.appendTo('table');```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<table>
  <tr id="clone">
    <td>1</td>
    <td>2</td>
    <td>3</td>
  </tr>
</table></code>```

Body:
How can I add content to the second and third td?

I just found that the following will not work.  I can find a way by creating some variable to hold the found elements, but would like to learn cleaner "more jQueryish" way if available.

$.each(records, function( index, row ) {
    $('#clone').clone()
    .removeAttr('id')
    .find('td')
    .eq(1).text(row.name).parent()
    .eq(2).text(row.message).parent()
    .appendTo(content)
});

Body:
You need to use .end() instead of parent()

End the most recent filtering operation in the current chain and return the set of matched elements to its previous state.

$('#clone').clone()
  .removeAttr('id')
  .find('td')
  .eq(1).text('Added 1').end()
  .eq(2).text('Added 2').end()
  .appendTo('table')

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<table>
  <tr id="clone">
    <td>1</td>
    <td>2</td>
    <td>3</td>
  </tr>
</table>

However I prefer having reference cloned element in a variable.

var clonedElement = $('#clone').clone()
  .removeAttr('id');

//Manipulate element
var tds = clonedElement.find('td');
tds.eq(1).text('Added 1');
tds.eq(2).text('Added 2');

//Append it
clonedElement.appendTo('table');

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<table>
  <tr id="clone">
    <td>1</td>
    <td>2</td>
    <td>3</td>
  </tr>
</table>


问:
Why does .sort() actually change the variable?
I am learning Python and I came across the sort method and I want to understand why running sort.() actually changes the list and I don't have to reassign it? </p>

```<code>>>> list = [88,1,4,56,9,7,8,9]
>>> list
[88, 1, 4, 56, 9, 7, 8, 9]
>>> list.sort()
>>> list
[1, 4, 7, 8, 9, 9, 56, 88]
</code>```

答:
Basically, because it can.

Lists are mutable objects, so the sort() method can modify it. There's  already a sorted() function, so it doesn't make much sense to have it leave the object unmodified.

Strings are immutable, so they cannot be modified in place. The upper() method cannot modify the original string.

Body:
I am learning Python and I came across the sort method and I want to understand why running sort.() actually changes the list and I don't have to reassign it?

>>> list = [88,1,4,56,9,7,8,9]
>>> list
[88, 1, 4, 56, 9, 7, 8, 9]
>>> list.sort()
>>> list
[1, 4, 7, 8, 9, 9, 56, 88]


问:
How to change the remote repository for a git submodule?
I've created a git repository with a submodule in it. I'm able to tell the submodule itself to change its remote repository path, but I'm not sure how to tell the parent repository how to change the remote repository path for the submodule.

I wouldn't be surprised if I'm somewhat out of luck and have to do things manually, as even deleting submodules isn't easy.

答: git config --file=.gitmodules -e opens the default editor in which you can update the path

ContentLicense: CC BY-SA 4.0


问:
How to use both binary and continuous features in the k-Nearest-Neighbor algorithm?
My feature vector has both continuous (or widely ranging) and binary components.  If I simply use Euclidean distance, the continuous components will have a much greater impact:

Representing symmetric vs. asymmetric as 0 and 1 and some less important ratio ranging from 0 to 100, changing from symmetric to asymmetric has a tiny distance impact compared to changing the ratio by 25.

I can add more weight to the symmetry (by making it 0 or 100 for example), but is there a better way to do this?

答:
You could try using the normalized Euclidean distance, described, for example, at the end of the first section here.

It simply scales every feature (continuous or discrete) by its standard deviation. This is more robust than, say, scaling by the range (max-min) as suggested by another poster.


问:
What are the differences between camera and camers2 API
I am working on an application where I am trying to scan barcode with the help of mobile vision API. I am creating TextureView in my activity, so I need camera to render on `TextureView.

I have been using old camera API, just came across new camera2 API. Can anyone help me what are the differences between them ?

答:
This article provides a lot of information about how to set up a project with the Camera2 API. From the first few paragraphs:

DSLR-like levels of customization, such as native control over exposure and raw sensor capture are finally possible. And while this new approach requires a little more thought and legwork, the level of control you get in return is well worth the effort.

So the main difference is that you have more control over what you can do with the phone's camera. It is also likely that there is an improvement in performance and photo quality, but I haven't found any mentions of it anywhere.

If you don't want to use the Camera2 API as it is somewhat more complicated, the deprecated version seems to work fine on most devices, however it is more than likely that it will eventually be removed, which will cause your app to... not work. So regardless of which API you prefer using, it is always going to be better to go with the one that isn't deprecated.

To help with implementing the API, there's a nice and simple library I like here, or if you don't like libraries or have a more specific use for it you could take a look at this sample project.


问:
How can I show this Toast message only if I click the second Tab?
I have a navigation bar with three tabs each tab is a Fragment.
I wrote in the onCreateView method of my second fragment this toast message:

```<code>public class SecondFragment extends Fragment{

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView=inflater.inflate(R.layout.second_layout,container,false);

        Toast.makeText(getContext(), "Test", Toast.LENGTH_LONG).show();

        return rootView;
    }
</code>```

What I want is that only if I click this tab the message displays.
But the problem is that if I start the application the message displays directly, but why?

Here is my MainActivity.java:

```<code>public class MainActivity extends AppCompatActivity{
    NavigationView mNavigationView;
    FragmentManager mFragmentManager;
    FragmentTransaction mFragmentTransaction;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        /**
         *Setup the DrawerLayout and NavigationView
         */

        mNavigationView = (NavigationView) findViewById(R.id.shitstuff) ;

        /**
         * Lets inflate the very first fragment
         * Here , we are inflating the TabFragment as the first Fragment
         */

        mFragmentManager = getSupportFragmentManager();
        mFragmentTransaction = mFragmentManager.beginTransaction();
        mFragmentTransaction.replace(R.id.containerView,new TabFragment()).commit();

    }

}
</code>```

And (I think this is Important for this question) my TabFragment:

```<code>public class TabFragment extends Fragment {
    public static TabLayout tabLayout;
    public static ViewPager viewPager;
    public static int int_items = 3 ;

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

        /**
         *Inflate tab_layout and setup Views.
         */
            View x =  inflater.inflate(R.layout.tab_layout,null);
            tabLayout = (TabLayout) x.findViewById(R.id.tabs);
            viewPager = (ViewPager) x.findViewById(R.id.viewpager);

        /**
         *Set an Apater for the View Pager
         */
        viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));

        /**
         * Now , this is a workaround ,
         * The setupWithViewPager dose't works without the runnable .
         * Maybe a Support Library Bug .
         */

        tabLayout.post(new Runnable() {
            @Override
            public void run() {
                    tabLayout.setupWithViewPager(viewPager);
                   }
        });

        return x;

    }

    class MyAdapter extends FragmentPagerAdapter {

        public MyAdapter(FragmentManager fm) {
            super(fm);
        }

        /**
         * Return fragment with respect to Position .
         */

        @Override
        public Fragment getItem(int position)
        {

            if(position == 0){
                return new FirstFragment();
            }
            if(position == 1){
                return new SecondFragment();
            }
            if(position == 2){
                return new ThirdFragment();
            }

        return null;
        }

        @Override
        public int getCount() {

            return int_items;

        }

        /**
         * This method returns the title of the tab according to the position.
         */

        @Override
        public CharSequence getPageTitle(int position) {

            switch (position){
                case 0 :
                    return "First";
                case 1 :
                    return "Second";
                case 2 :
                    return "Third";
            }
                return null;
        }
    }

}
</code>```

So where do I have to say Toast.makeText(getContext(), "Test", Toast.LENGTH_LONG).show(); to display it only by pressing on the second tab?

答:
You can use the code for terminating the toast once it is shown so that it will not be visible when you click on another fragment.

try this one

```<code>toast = new Toast(getContext());
toast.cancel(); //this will prevent toast from displaying multiple times
</code>```

Hope it will work

Body:
I have a navigation bar with three tabs each tab is a Fragment.
I wrote in the onCreateView method of my second fragment this toast message:

public class SecondFragment extends Fragment{

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView=inflater.inflate(R.layout.second_layout,container,false);

        Toast.makeText(getContext(), "Test", Toast.LENGTH_LONG).show();

        return rootView;
    }

What I want is that only if I click this tab the message displays.
But the problem is that if I start the application the message displays directly, but why?

Here is my MainActivity.java:

public class MainActivity extends AppCompatActivity{
    NavigationView mNavigationView;
    FragmentManager mFragmentManager;
    FragmentTransaction mFragmentTransaction;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        /**
         *Setup the DrawerLayout and NavigationView
         */

        mNavigationView = (NavigationView) findViewById(R.id.shitstuff) ;

        /**
         * Lets inflate the very first fragment
         * Here , we are inflating the TabFragment as the first Fragment
         */

        mFragmentManager = getSupportFragmentManager();
        mFragmentTransaction = mFragmentManager.beginTransaction();
        mFragmentTransaction.replace(R.id.containerView,new TabFragment()).commit();

    }

}

And (I think this is Important for this question) my TabFragment:

public class TabFragment extends Fragment {
    public static TabLayout tabLayout;
    public static ViewPager viewPager;
    public static int int_items = 3 ;

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

        /**
         *Inflate tab_layout and setup Views.
         */
            View x =  inflater.inflate(R.layout.tab_layout,null);
            tabLayout = (TabLayout) x.findViewById(R.id.tabs);
            viewPager = (ViewPager) x.findViewById(R.id.viewpager);

        /**
         *Set an Apater for the View Pager
         */
        viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));

        /**
         * Now , this is a workaround ,
         * The setupWithViewPager dose't works without the runnable .
         * Maybe a Support Library Bug .
         */

        tabLayout.post(new Runnable() {
            @Override
            public void run() {
                    tabLayout.setupWithViewPager(viewPager);
                   }
        });

        return x;

    }

    class MyAdapter extends FragmentPagerAdapter {

        public MyAdapter(FragmentManager fm) {
            super(fm);
        }

        /**
         * Return fragment with respect to Position .
         */

        @Override
        public Fragment getItem(int position)
        {

            if(position == 0){
                return new FirstFragment();
            }
            if(position == 1){
                return new SecondFragment();
            }
            if(position == 2){
                return new ThirdFragment();
            }

        return null;
        }

        @Override
        public int getCount() {

            return int_items;

        }

        /**
         * This method returns the title of the tab according to the position.
         */

        @Override
        public CharSequence getPageTitle(int position) {

            switch (position){
                case 0 :
                    return "First";
                case 1 :
                    return "Second";
                case 2 :
                    return "Third";
            }
                return null;
        }
    }

}

So where do I have to say Toast.makeText(getContext(), "Test", Toast.LENGTH_LONG).show(); to display it only by pressing on the second tab?

Body:
You can use the code for terminating the toast once it is shown so that it will not be visible when you click on another fragment.

try this one

toast = new Toast(getContext());
toast.cancel(); //this will prevent toast from displaying multiple times

Hope it will work


答:
I believe, what you are looking for could be something like the following:

```<code>$('#clone').clone()
.removeAttr('id')
.find('td')
 .eq(1).text(row.name).end()
 .eq(2).text(row.message).end()
 .appendTo(content)
</code>```

end() will get you back to the previous selection while parent() will refer you up one level in the DOM model.

Title: Using jQuery to add content to multiple elements returned by find()

Body:
I believe, what you are looking for could be something like the following:

$('#clone').clone()
.removeAttr('id')
.find('td')
 .eq(1).text(row.name).end()
 .eq(2).text(row.message).end()
 .appendTo(content)

end() will get you back to the previous selection while parent() will refer you up one level in the DOM model.


问:
Odoo 10 - Form view opened in edit mode
I'm developing on Odoo 10.

I created a dynamic form view which search and display a product from its barcode, but I've got a problem.

Since the view has no initial record to display it is opened in edit mode, and that's ok, because I want to type the 'barcode' field.

But, after the product is displayed, when I exit from that view the 'can_be_discarded' function is fired, opening the confirm dialog.

Have I to create a new view type inheriting from FormView or is there a way to workaround this problem?

The view is a classic form view, with nothing special.

Here's the server code instead.

class ProductFromBarcode(models.TransientModel):
    _name = 'levelprime_product_general_status.product_from_barcode'
    _inherits = { 'product.product': 'product_id' }

    product_id      = fields.Many2one(
                            comodel_name='product.product',
                            store=False)
    product_barcode = fields.Integer(help='Insert the barcode to search '
                                          'the correspondent product',
                                     store=False)

    @api.onchange('product_barcode')
    def on_barcode_changed(self):
        if self.product_barcode != 0:
            self.product_id = self.get_product_from_barcode(self.product_barcode)

    @api.model
    def get_product_from_barcode(self, barcode):
        r = self.env['product.product'].search([('barcode', '=', barcode)])
        if r:
            return r
```

答:
from what you are saying you are using inherits to show the information of the product selected by the barcode remove it and use related field:
add the fields that you are showing on the form view to you model

```<code>name = fields.Char(related='product_id.name', readonly=True)
</code>```

Now you can use name on your view it's like compute field or proxy.
you can make them readonly if you want to display them.

Title: Odoo 10 - Form view opened in edit mode

Body:
from what you are saying you are using inherits to show the information of the product selected by the barcode remove it and use related field:
add the fields that you are showing on the form view to you model

name = fields.Char(related='product_id.name', readonly=True)

Now you can use name on your view it's like compute field or proxy.
you can make them readonly if you want to display them.


问:
Convert a list of character vectors into dataframe
my output a looks like:

```<code>str(a)
List of 8883695
 $ : chr [1:3] "20MICRONS" "A" "ACCRUALS"
 $ : chr [1:3] "20MICRONS" "A" "ACCRUALS"
 $ : chr [1:3] "20MICRONS" "A" "ACCRUALS"
 $ : chr [1:3] "20MICRONS" "A" "ACCRUALS"
 $ : chr [1:3] "20MICRONS" "A" "ACCRUALS"
 $ : chr [1:3] "20MICRONS" "A" "ACCRUALS"
 $ : chr [1:3] "20MICRONS" "A" "ACCRUALS"
 $ : chr [1:3] "20MICRONS" "A" "ACCRUALS"
 $ : chr [1:3] "20MICRONS" "A" "ACCRUALS"
 $ : chr [1:3] "20MICRONS" "A" "ACCRUALS"
 $ : chr [1:3] "20MICRONS" "A" "ACCRUALS"
 $ : chr [1:3] "20MICRONS" "A" "ACCRUALS"
 $ : chr [1:3] "20MICRONS" "A" "AE"
 $ : chr [1:3] "20MICRONS" "A" "AE"
 $ : chr [1:3] "20MICRONS" "A" "AE"
</code>```

I want to convert this into a dataframe like:

ticker       frequency field

20MICRONS      A         ACCRUALS

20MICRONS      A         ACCRUALS

20MICRONS      A         AE

20MICRONS      A         AE

20MICRONS      A         AE

20MICRONS      A         AE

I have tried this:

```<code>b <- as.data.frame(a)
Error in sort.list(y) : 'x' must be atomic for 'sort.list'
Have you called 'sort' on a list?
</code>```

But not working. Please help. I am new to R and stack overflow.

答:
The list elements are not of equal length.  So, we need to convert it to equal length by padding with NA

```<code>mx <- max(lengths(a))
d1 <- data.frame(lapply(a, `length<-`, mx))
</code>```

Body:
my output a looks like:

str(a)
List of 8883695
 $ : chr [1:3] "20MICRONS" "A" "ACCRUALS"
 $ : chr [1:3] "20MICRONS" "A" "ACCRUALS"
 $ : chr [1:3] "20MICRONS" "A" "ACCRUALS"
 $ : chr [1:3] "20MICRONS" "A" "ACCRUALS"
 $ : chr [1:3] "20MICRONS" "A" "ACCRUALS"
 $ : chr [1:3] "20MICRONS" "A" "ACCRUALS"
 $ : chr [1:3] "20MICRONS" "A" "ACCRUALS"
 $ : chr [1:3] "20MICRONS" "A" "ACCRUALS"
 $ : chr [1:3] "20MICRONS" "A" "ACCRUALS"
 $ : chr [1:3] "20MICRONS" "A" "ACCRUALS"
 $ : chr [1:3] "20MICRONS" "A" "ACCRUALS"
 $ : chr [1:3] "20MICRONS" "A" "ACCRUALS"
 $ : chr [1:3] "20MICRONS" "A" "AE"
 $ : chr [1:3] "20MICRONS" "A" "AE"
 $ : chr [1:3] "20MICRONS" "A" "AE"

I want to convert this into a dataframe like:

ticker       frequency field

20MICRONS      A         ACCRUALS

20MICRONS      A         ACCRUALS

20MICRONS      A         AE

20MICRONS      A         AE

20MICRONS      A         AE

20MICRONS      A         AE

I have tried this:

b <- as.data.frame(a)
Error in sort.list(y) : 'x' must be atomic for 'sort.list'
Have you called 'sort' on a list?

But not working. Please help. I am new to R and stack overflow.

Body:
The list elements are not of equal length.  So, we need to convert it to equal length by padding with NA

mx <- max(lengths(a))
d1 <- data.frame(lapply(a, `length<-`, mx))


问:
How to check if segue completed Swift 3?
I have a segue which passes location data from a table view. I need to add a map annotation after this segue has completed, but the map is my initial VC, so it crashes on load due to the lack of data as the segue has not occurred.

I think I need to wrap the following code (in the viewDidLoad) in an if statement that checks if the segue has occurred, or check if there is any data available to use.

```<code>    let roomPin = MGLPointAnnotation()
    roomPin.coordinate = CLLocationCoordinate2D(latitude: room.latitude, longitude: room.longitude)

    mapView.addAnnotation(roomPin)
</code>```

Not entirely sure how I should be checking if there is any data to use.

edit:

room is a custom class loaded with alamofire

```<code>class Room {

var roomNumber : String!
var roomName : String!
var latitude : Double!
var longitude : Double!

init(json : JSON) {
    roomNumber = json["room_number"].stringValue
    roomName = json["room_name"].stringValue
    latitude = json["latitude"].double
    longitude = json ["longitude"].double
}
</code>```

}

then is called in a tableview to display the name and number. When pressed it performs a segue passing the Room object to my mapVC

```<code>    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    if segue.identifier == "mapSegue" {
        if let destination = segue.destination as? ViewController {
            destination.room = sender as! Room

        }
    }
}
</code>```

and in my map view controller I have that above annotation code in the viewDidLoad, with room being declared as:

```<code>var room : Room!
</code>```

Any help is appreciated!

答: I guess the problem is in the line destination.room = sender as! Room because sender will be of type UITableViewCell class and when you try to typecast sender to Room object type it crashes.

Body:
I have a segue which passes location data from a table view. I need to add a map annotation after this segue has completed, but the map is my initial VC, so it crashes on load due to the lack of data as the segue has not occurred.

I think I need to wrap the following code (in the viewDidLoad) in an if statement that checks if the segue has occurred, or check if there is any data available to use.

    let roomPin = MGLPointAnnotation()
    roomPin.coordinate = CLLocationCoordinate2D(latitude: room.latitude, longitude: room.longitude)

    mapView.addAnnotation(roomPin)

Not entirely sure how I should be checking if there is any data to use.

edit:

room is a custom class loaded with alamofire

class Room {

var roomNumber : String!
var roomName : String!
var latitude : Double!
var longitude : Double!

init(json : JSON) {
    roomNumber = json["room_number"].stringValue
    roomName = json["room_name"].stringValue
    latitude = json["latitude"].double
    longitude = json ["longitude"].double
}

}

then is called in a tableview to display the name and number. When pressed it performs a segue passing the Room object to my mapVC

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    if segue.identifier == "mapSegue" {
        if let destination = segue.destination as? ViewController {
            destination.room = sender as! Room

        }
    }
}

and in my map view controller I have that above annotation code in the viewDidLoad, with room being declared as:

var room : Room!

Any help is appreciated!


问:
selenium Test case for facebook login and logout
Scenario is to Login to facebook account and then logout. I tried using xpath className and id. But everytime it shows error as ElementNotfound or element not visible. Later I Checked it using SELENIUM IDE and got this xpath for the LOGOUT link. But still the error persists. Kindly help me.

public class FacebookLogin {

    public static void main(String[] args) throws InterruptedException {
        // TODO Auto-generated method stub
        WebDriver driver = new FirefoxDriver();
        driver.manage().window().maximize();
        driver.get("https://www.facebook.com/");
        Thread.sleep(2000);
        WebElement username = driver.findElement(By.id("email"));
        WebElement password = driver.findElement(By.id("pass"));
        WebElement Login = driver.findElement(By.id("u_0_v"));
        username.sendKeys("myusername@xyz.com");
        password.sendKeys("mypassword");
        Login.click();
        Thread.sleep(2000);
        //driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
        WebElement navigationclick = driver.findElement(By.id("logoutMenu"));
        WebElement logout = driver.findElement(By.xpath("//div[@id='u_d_1']/div/div/div/div/div/ul/li[12]/a/span/span"));
        navigationclick.click();
        if(logout.isEnabled() && logout.isDisplayed()) {
            logout.click();
        }
        else {
            System.out.println("Element not found");
        }

    }

}
```

HTML CODE FOR LOG OUT

    Log Out

答:
Adding below simple code:</p>

```<code>    package open_website;

    import java.util.concurrent.TimeUnit;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.By;
    import org.openqa.selenium.chrome.ChromeDriver;

        public class Open_website_1
       {

        public static void main(String[] args) {
        // TODO Auto-generated method stub

        String expath = "D:\\Eclipse\\chromedriver_win32\\chromedriver.exe";

        System.setProperty("webdriver.chrome.driver", "D:\\Eclipse\\chromedriver_win32\\chromedriver.exe");

        WebDriver driver = new ChromeDriver();

        driver.get("http:\\www.facebook.com");

        WebElement element1 = driver.findElement(By.id("email"));
        element1.sendKeys("patil_y7@yahoo.com");

        WebElement element2 = driver.findElement(By.id("pass"));
        element2.sendKeys("pa$$word123");

        WebElement element3 = driver.findElement(By.id("u_0_q"));
        element3.click();

        System.out.println("Login");

        WebElement lstitem=driver.findElement(By.id("userNavigationLabel"));
        lstitem.click();

        driver.manage().timeouts().implicitlyWait(60,TimeUnit.SECONDS);

        driver.findElement(By.partialLinkText("Log Out")).click();

        System.out.println("Log out");

    }

}
</code>```

Body:
Scenario is to Login to facebook account and then logout. I tried using xpath className and id. But everytime it shows error as ElementNotfound or element not visible. Later I Checked it using SELENIUM IDE and got this xpath for the LOGOUT link. But still the error persists. Kindly help me.

public class FacebookLogin {

    public static void main(String[] args) throws InterruptedException {
        // TODO Auto-generated method stub
        WebDriver driver = new FirefoxDriver();
        driver.manage().window().maximize();
        driver.get("https://www.facebook.com/");
        Thread.sleep(2000);
        WebElement username = driver.findElement(By.id("email"));
        WebElement password = driver.findElement(By.id("pass"));
        WebElement Login = driver.findElement(By.id("u_0_v"));
        username.sendKeys("myusername@xyz.com");
        password.sendKeys("mypassword");
        Login.click();
        Thread.sleep(2000);
        //driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
        WebElement navigationclick = driver.findElement(By.id("logoutMenu"));
        WebElement logout = driver.findElement(By.xpath("//div[@id='u_d_1']/div/div/div/div/div/ul/li[12]/a/span/span"));
        navigationclick.click();
        if(logout.isEnabled() && logout.isDisplayed()) {
            logout.click();
        }
        else {
            System.out.println("Element not found");
        }

    }

}

HTML CODE FOR LOG OUT

    Log Out

Body:
Adding below simple code:

    package open_website;

    import java.util.concurrent.TimeUnit;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.By;
    import org.openqa.selenium.chrome.ChromeDriver;

        public class Open_website_1
       {

        public static void main(String[] args) {
        // TODO Auto-generated method stub

        String expath = "D:\\Eclipse\\chromedriver_win32\\chromedriver.exe";

        System.setProperty("webdriver.chrome.driver", "D:\\Eclipse\\chromedriver_win32\\chromedriver.exe");

        WebDriver driver = new ChromeDriver();

        driver.get("http:\\www.facebook.com");

        WebElement element1 = driver.findElement(By.id("email"));
        element1.sendKeys("patil_y7@yahoo.com");

        WebElement element2 = driver.findElement(By.id("pass"));
        element2.sendKeys("pa$$word123");

        WebElement element3 = driver.findElement(By.id("u_0_q"));
        element3.click();

        System.out.println("Login");

        WebElement lstitem=driver.findElement(By.id("userNavigationLabel"));
        lstitem.click();

        driver.manage().timeouts().implicitlyWait(60,TimeUnit.SECONDS);

        driver.findElement(By.partialLinkText("Log Out")).click();

        System.out.println("Log out");

    }

}


问:
Which Xcode project files can I 'exclude' from my git repo?
I'm working on an iOS project and am using git to do version control. I'm working on this with another developer.

Which Xcode project files should I keep in the repo and which ones can I exclude so that it doesn't affect the other developer negatively?

Here are some of the non-code files that git is telling me has been modified or added...
(BTW, these are only viewable in the OSX file manager if you "Show Package Contents" for YourProject.xcodeproj file)

exclude ?

contents.xcwordspacedata (I think this is just workspace settings)

UserInterfaceState.xcuserstate (based on the name it seems only specific to me)

Breakpoints.xcbkptlist (...my breakpoints settings)

INCLUDE ?

project.pbxproj (INCLUDE...project settings)

*.xscheme (INCLUDE...scheme definitions)

xschememanagement.plist (INCLUDE...scheme manager settings?)

Does this seem right?

(Just an FYI for those that want to use the exclude feature of git. Edit your .git/info/exclude file in your local repository. Put in the files or the patterns for files that you want git to ignore. For example, if you want git to ignore foo.temp, bar.temp you can put a line in the file that says *.temp)

答: This site (www.gitignore.io) lets you specify your IDE and or language and shows you a tailored .gitignore - Awesome site!</p>


问:
MVVM Handle all un handled keystrokes on ViewModel
I don't know if this is a good way to work but i need to handle all unhandled keystrokes on my ViewModel so my idea was to use a Behavior on my ShellView that would relay all unhandled keystrokes to the ViewModel..

But the problem is how do i get all unhandled key presses?

Here is my first try to just catch them

```<code>Public Class ForwardKeyBehavior
    Inherits Behavior(Of DependencyObject)

    Protected Overrides Sub OnAttached()
        Keyboard.AddKeyDownHandler(Me.AssociatedObject, AddressOf OnKeyPressed)
        Keyboard.AddPreviewKeyDownHandler(Me.AssociatedObject, AddressOf OnPreviewKeyPressed)
        MyBase.OnAttached()
    End Sub

    Protected Overrides Sub OnDetaching()
        Keyboard.RemoveKeyDownHandler(Me.AssociatedObject, AddressOf OnKeyPressed)
        MyBase.OnDetaching()
    End Sub

    Private Sub OnPreviewKeyPressed(ByVal sender As Object, ByVal e As KeyEventArgs)

    End Sub

    Private Sub OnKeyPressed(ByVal sender As Object, ByVal e As KeyEventArgs)
        If (Not e.Handled) Then
            Trace.Write(e.Key.ToString())
        End If
    End Sub

End Class
</code>```

But it seems that e.Handled always is false so what am i missing even if i press a key in a textbox?

答:
Check out MSDN

Pay attention to "The Concept of Handled" section, especially the handledEventsToo part.

Body:
I don't know if this is a good way to work but i need to handle all unhandled keystrokes on my ViewModel so my idea was to use a Behavior on my ShellView that would relay all unhandled keystrokes to the ViewModel..

But the problem is how do i get all unhandled key presses?

Here is my first try to just catch them

Public Class ForwardKeyBehavior
    Inherits Behavior(Of DependencyObject)

    Protected Overrides Sub OnAttached()
        Keyboard.AddKeyDownHandler(Me.AssociatedObject, AddressOf OnKeyPressed)
        Keyboard.AddPreviewKeyDownHandler(Me.AssociatedObject, AddressOf OnPreviewKeyPressed)
        MyBase.OnAttached()
    End Sub

    Protected Overrides Sub OnDetaching()
        Keyboard.RemoveKeyDownHandler(Me.AssociatedObject, AddressOf OnKeyPressed)
        MyBase.OnDetaching()
    End Sub

    Private Sub OnPreviewKeyPressed(ByVal sender As Object, ByVal e As KeyEventArgs)

    End Sub

    Private Sub OnKeyPressed(ByVal sender As Object, ByVal e As KeyEventArgs)
        If (Not e.Handled) Then
            Trace.Write(e.Key.ToString())
        End If
    End Sub

End Class

But it seems that e.Handled always is false so what am i missing even if i press a key in a textbox?


问:
How to Pass params in g:link
I need to pass two params via g:link like below

<g:link controller="ClaimDetails" action="downloadFile1" params="[basePath:${session.basePath}, projCode:${session.projCode}]"><g:message code="claimDetails.ling.notice" /></g:link>

but it gives me an error like

Attribute value quote wasn't closed (controller="ClaimDetails" action="downloadFile1" params="[basePath:${session.basePath}, projCode:${session.projCode}]")

When i give params like basePath:'${session.basePath}'

It gives me the text only.

What i need to do?

答:
You don't need to use the ${} inside a g:link tag so:

```<code><g:link controller="ClaimDetails" action="downloadFile1" params="[basePath: session.basePath, projCode: session.projCode]">
    <g:message code="claimDetails.ling.notice" />
</g:link>
</code>```

Note: why do you use those parameters? cause you have the session object available on your action.

```<code>def action(){
    String basePath = session.basePath
    String projCode = session.projCode
}
</code>```

Title: How to Pass params in g:link

Body:
You don't need to use the ${} inside a g:link tag so:

<g:link controller="ClaimDetails" action="downloadFile1" params="[basePath: session.basePath, projCode: session.projCode]">
    <g:message code="claimDetails.ling.notice" />
</g:link>

Note: why do you use those parameters? cause you have the session object available on your action.

def action(){
    String basePath = session.basePath
    String projCode = session.projCode
}


问:
Octave - Create a matrix of all binary values
In Octave, given a number, (say 5), I need to make a matrix of (2^5 X 5) with each row having the binary representation of numbers from 0 to 2^5 - 1 i.e the matrix would be like

[[ 0,  0,  0,  0,  0],

[ 0,  0,  0,  0,  1]]

[ 0,  0,  0,  1,  0]]

and so on. Is there any built-in function to do this? Unable to figure out how to do it efficiently? One way I can think of is running a loop and generating the binary value for each value from 0:(2^5-1) and storing it in matrix, but this seems very inefficient.

答:
Here's another way:</p>

```<code>N = 5;
result = mod(floor(bsxfun(@rdivide, (0:2^N-1).', 2.^(N-1:-1:0))), 2);
</code>```

Body:
Here's another way:

N = 5;
result = mod(floor(bsxfun(@rdivide, (0:2^N-1).', 2.^(N-1:-1:0))), 2);


问:
SQL Server: Importing database from .mdf?
I have an .mdf file on my local box.

I have SQL Server 2008 Express and SQL Management Studio 2008 Express installed on my local box.

How in the world do I import this .mdf file as a new database into my SQL Server?

This seems like a ridiculously common task that must be performed thousands of times a day across the globe, and I cannot figure out how to do it in Management Studio Express.

What am I missing?

答:
If you do not have an LDF file then:

1) put the MDF in the C:\Program Files\Microsoft SQL Server\MSSQL13.SQLEXPRESS\MSSQL\DATA\

2) In ssms, go to Databases -> Attach and add the MDF file. It will not let you add it this way but it will tell you the database name contained within.

3) Make sure the user you are running ssms.exe as has acccess to this MDF file.

4) Now that you know the DbName, run

```<code>EXEC sp_attach_single_file_db @dbname = 'DbName',
@physname = N'C:\Program Files\Microsoft SQL Server\MSSQL13.SQLEXPRESS\MSSQL\DATA\yourfile.mdf';
</code>```

Reference: https://dba.stackexchange.com/questions/12089/attaching-mdf-without-ldf

Body:
If you do not have an LDF file then:

1) put the MDF in the C:\Program Files\Microsoft SQL Server\MSSQL13.SQLEXPRESS\MSSQL\DATA\

2) In ssms, go to Databases -> Attach and add the MDF file. It will not let you add it this way but it will tell you the database name contained within.

3) Make sure the user you are running ssms.exe as has acccess to this MDF file.

4) Now that you know the DbName, run

EXEC sp_attach_single_file_db @dbname = 'DbName',
@physname = N'C:\Program Files\Microsoft SQL Server\MSSQL13.SQLEXPRESS\MSSQL\DATA\yourfile.mdf';

Reference: https://dba.stackexchange.com/questions/12089/attaching-mdf-without-ldf


问:
Does Heroku support `rails dbconsole`?
I'm trying to fire up rails dbconsole on Heroku but get the following error:

```<code>heroku run rails dbconsole
# => Couldn't find database client: psql. Check your $PATH and try again
</code>```

Is it possible to use the dbconsole on Heroku? If not is there another client that can be used?

答:
Is it possible to use the dbconsole on Heroku? If not is there another client that can be used?

You can use online database client if you use activeadmin.

Just add the gem activeadmin-sqlpage:

```<code>gem 'activeadmin-sqlpage'
</code>```

And create activeadmin page:

```<code># file app/admin/sql.rb
ActiveAdmin::SqlPage::register
</code>```

Restart your server. Then go to admin panel and navigate the menu SQL. Enter any sql command and press Ctrl+Enter or Submit button.

Title: Does Heroku support `rails dbconsole`?

Body:
I'm trying to fire up rails dbconsole on Heroku but get the following error:

heroku run rails dbconsole
# => Couldn't find database client: psql. Check your $PATH and try again

Is it possible to use the dbconsole on Heroku? If not is there another client that can be used?

Body:
Is it possible to use the dbconsole on Heroku? If not is there another client that can be used?

You can use online database client if you use activeadmin.

Just add the gem activeadmin-sqlpage:

gem 'activeadmin-sqlpage'

And create activeadmin page:

# file app/admin/sql.rb
ActiveAdmin::SqlPage::register

Restart your server. Then go to admin panel and navigate the menu SQL. Enter any sql command and press Ctrl+Enter or Submit button.


问:
Display orders placed before April 1, 2009. Write the query in two different ways
I did it the usual way. I don't get how to write the query in another way.

```<code>SELECT Order#, Shipdate
FROM Orders
WHERE Shipdate < '01-APR-2009';
</code>```

What can be the another way to write the same query?

答:
Perhaps what Utsav wrote (which is your query, with the needed correction so that the right-hand side of the inequality is a DATE), and this modification:

```<code>SELECT Order#, Shipdate FROM Orders
 WHERE Shipdate < date '2009-04-01';
</code>```

using the date literal syntax (DATE <string> where the string is enclosed in single-quotes and must be in the exact format yyyy-mm-dd, no deviation permitted; even the dashes must be dashes, not / or . or anything else).

Body:
I did it the usual way. I don't get how to write the query in another way.

SELECT Order#, Shipdate
FROM Orders
WHERE Shipdate < '01-APR-2009';

What can be the another way to write the same query?

Body:
Perhaps what Utsav wrote (which is your query, with the needed correction so that the right-hand side of the inequality is a DATE), and this modification:

SELECT Order#, Shipdate FROM Orders
 WHERE Shipdate < date '2009-04-01';

using the date literal syntax (DATE <string> where the string is enclosed in single-quotes and must be in the exact format yyyy-mm-dd, no deviation permitted; even the dashes must be dashes, not / or . or anything else).


问:
Xamarin Forms Padding in StaticResource
I want to build few pages with specific Padding in sytacklayout. I do not want to wrote it in every pages. And its not good design considering if I want to change it in future. Is there a way to define padding in static resource? So that I can define it in one place App.xml and use it in other pages.

I have tried

```<code><ContentPage.Resources>
    <ResourceDictionary>
        <x:String x:Key="padding">45, 0, 45, 0</x:String>
    </ResourceDictionary>
</ContentPage.Resources>
<StackLayout Padding="{StaticResource padding}">
    <Label Text="{StaticResource padding}"/>
</StackLayout>
</code>```

答:
Just use Thickness instead of a string:

```<code><ContentPage.Resources>
<ResourceDictionary>
    <Thickness x:Key="padding">45,0</Thickness>
</ResourceDictionary>
</ContentPage.Resources>
<StackLayout Padding="{StaticResource padding}">
    <Label Text="{StaticResource padding}"/>
</StackLayout>
</code>```

Title: Xamarin Forms Padding in StaticResource

Body:
I want to build few pages with specific Padding in sytacklayout. I do not want to wrote it in every pages. And its not good design considering if I want to change it in future. Is there a way to define padding in static resource? So that I can define it in one place App.xml and use it in other pages.

I have tried

<ContentPage.Resources>
    <ResourceDictionary>
        <x:String x:Key="padding">45, 0, 45, 0</x:String>
    </ResourceDictionary>
</ContentPage.Resources>
<StackLayout Padding="{StaticResource padding}">

</StackLayout>

Body:
Just use Thickness instead of a string:

<ContentPage.Resources>
<ResourceDictionary>
    <Thickness x:Key="padding">45,0</Thickness>
</ResourceDictionary>
</ContentPage.Resources>
<StackLayout Padding="{StaticResource padding}">
    <Label Text="{StaticResource padding}"/>
</StackLayout>


问:
ListView height not adjusting to content
I am struggling with Xamarin and the layout for an Android application. I have a ListView as shown in the code below, but whenever I populate it with more than one city, the ListView doesn't expand. Instead I need to scroll it, while the hight only allows for showing one item at a time.

What I really want is the ListView to expand as it contains more and more items. But at the same time, I don't want the keyboard to cover the EditText-fields. It feels that I have tried Everything, including putting everything inside a scrollview and setting layout_height for the ListView to wrap_content. But it just won't work.

```<code><?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/scrollView1">
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:minWidth="25px"
        android:minHeight="25px"
        android:paddingLeft="15px"
        android:paddingRight="15px"
        android:paddingBottom="15px"
        android:paddingTop="15px"
        android:id="@+id/linearLayout1">
        <TextView
            android:text="Select algorithm:"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/textView1" />
        <RadioGroup
            android:minWidth="25px"
            android:minHeight="25px"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/radioGroup1"
            android:animateLayoutChanges="true"
            android:orientation="horizontal">
            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:checked="true"
                android:text="Greedy Best first Search"
                android:id="@+id/radioButton1" />
            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="A* Best First Search"
                android:id="@+id/radioButton2" />
        </RadioGroup>
        <TextView
            android:text="Add location coordinates:"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/linearLayout2"
            android:paddingTop="30px" />
        <ListView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/listViewCoords" />
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">
            <EditText
                android:inputType="numberDecimal"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_gravity="left"
                android:layout_weight="1"
                android:id="@+id/editTextX" />
            <EditText
                android:inputType="numberDecimal"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_gravity="right"
                android:layout_weight="1"
                android:id="@+id/editTextY" />
        </LinearLayout>
        <Button
            android:text="Add"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/buttonAdd" />
        <Button
            android:text="Clear all"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/buttonClear" />
        <Button
            android:text="Find shortest path"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/buttonSearch" />
    </LinearLayout>
</ScrollView>
</code>```

答:
Do not use ListView into ScrollView. It's too wrong in many ways.

If you want to use Lists into Scrollable content, use RecyclerView and Wrap them with NestedScrollView.

Body:
I am struggling with Xamarin and the layout for an Android application. I have a ListView as shown in the code below, but whenever I populate it with more than one city, the ListView doesn't expand. Instead I need to scroll it, while the hight only allows for showing one item at a time.

What I really want is the ListView to expand as it contains more and more items. But at the same time, I don't want the keyboard to cover the EditText-fields. It feels that I have tried Everything, including putting everything inside a scrollview and setting layout_height for the ListView to wrap_content. But it just won't work.

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/scrollView1">
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:minWidth="25px"
        android:minHeight="25px"
        android:paddingLeft="15px"
        android:paddingRight="15px"
        android:paddingBottom="15px"
        android:paddingTop="15px"
        android:id="@+id/linearLayout1">
        <TextView
            android:text="Select algorithm:"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/textView1" />
        <RadioGroup
            android:minWidth="25px"
            android:minHeight="25px"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/radioGroup1"
            android:animateLayoutChanges="true"
            android:orientation="horizontal">
            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:checked="true"
                android:text="Greedy Best first Search"
                android:id="@+id/radioButton1" />
            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="A* Best First Search"
                android:id="@+id/radioButton2" />
        </RadioGroup>
        <TextView
            android:text="Add location coordinates:"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/linearLayout2"
            android:paddingTop="30px" />
        <ListView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/listViewCoords" />
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">
            <EditText
                android:inputType="numberDecimal"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_gravity="left"
                android:layout_weight="1"
                android:id="@+id/editTextX" />
            <EditText
                android:inputType="numberDecimal"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_gravity="right"
                android:layout_weight="1"
                android:id="@+id/editTextY" />
        </LinearLayout>
        <Button
            android:text="Add"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/buttonAdd" />
        <Button
            android:text="Clear all"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/buttonClear" />
        <Button
            android:text="Find shortest path"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/buttonSearch" />
    </LinearLayout>
</ScrollView>


问:
Omitting the datatype (e.g. "unsigned" instead of "unsigned int")
I know that if the data type declaration is omitted in C/C++ code in such way: unsigned test=5;, the compiler automatically makes this variable an int (an unsigned int in this case). I've heard that it's a C standard and it will work in all compilers.

But I've also heard that doing this is considered a bad practice.

What do you think? Should I really type unsigned int instead of just unsigned?

Are short, long and long long also datatypes?

答:
I would even take it one step further and use stdint's uint32_t type.

It might be a matter of taste, but I prefer to know what primitive I'm using over some ancient consideration of optimising per platform.


问:
Using Aggregate Function in sql
Why this query is not working:-

```<code>SELECT b.byhub,
       Count(awbno)
FROM   (SELECT awbno,
               byhub,
               entrydatetime,
               Max(entrydatetime)
        FROM   wbbooking
        GROUP  BY awbno,
                  byhub,
                  entrydatetime) B
       INNER JOIN (SELECT refno,
                          Max(entrydatetime)
                   FROM   wbmmreceiving
                   GROUP  BY refno) R
               ON B.awbno = R.refno
WHERE  CONVERT(DATE, b.entrydatetime) BETWEEN '2016-10-13' AND '2016-10-13'
GROUP  BY b.byhub
</code>```

After Execute this query I have obtain this type of Error:-

```<code>Msg 8155, Level 16, State 2, Line 2
No column name was specified for column 4 of 'b'.
Msg 8155, Level 16, State 2, Line 3
No column name was specified for column 2 of 'r'.
</code>```

答:
Just specify column names for your subqueries, like this:</p>

```<code>SELECT b.byhub,
       Count(awbno)
FROM   (SELECT awbno,
               byhub,
               entrydatetime,
               Max(entrydatetime) max_entrydatetime
        FROM   wbbooking
        GROUP  BY awbno,
                  byhub,
                  entrydatetime) B
       INNER JOIN (SELECT refno,
                          Max(entrydatetime) max_entrydatetime
                   FROM   wbmmreceiving
                   GROUP  BY refno) R
               ON B.awbno = R.refno
WHERE  CONVERT(DATE, b.entrydatetime) BETWEEN '2016-10-13' AND '2016-10-13'
GROUP  BY b.byhub
</code>```

Title: Using Aggregate Function in sql

Body:
Why this query is not working:-

SELECT b.byhub,
       Count(awbno)
FROM   (SELECT awbno,
               byhub,
               entrydatetime,
               Max(entrydatetime)
        FROM   wbbooking
        GROUP  BY awbno,
                  byhub,
                  entrydatetime) B
       INNER JOIN (SELECT refno,
                          Max(entrydatetime)
                   FROM   wbmmreceiving
                   GROUP  BY refno) R
               ON B.awbno = R.refno
WHERE  CONVERT(DATE, b.entrydatetime) BETWEEN '2016-10-13' AND '2016-10-13'
GROUP  BY b.byhub

After Execute this query I have obtain this type of Error:-

Msg 8155, Level 16, State 2, Line 2
No column name was specified for column 4 of 'b'.
Msg 8155, Level 16, State 2, Line 3
No column name was specified for column 2 of 'r'.

Body:
Just specify column names for your subqueries, like this:

SELECT b.byhub,
       Count(awbno)
FROM   (SELECT awbno,
               byhub,
               entrydatetime,
               Max(entrydatetime) max_entrydatetime
        FROM   wbbooking
        GROUP  BY awbno,
                  byhub,
                  entrydatetime) B
       INNER JOIN (SELECT refno,
                          Max(entrydatetime) max_entrydatetime
                   FROM   wbmmreceiving
                   GROUP  BY refno) R
               ON B.awbno = R.refno
WHERE  CONVERT(DATE, b.entrydatetime) BETWEEN '2016-10-13' AND '2016-10-13'
GROUP  BY b.byhub


问:
How can I make page slide onto the screen when button is clicked?
I basically have a menu that slides onto the screen when you press a button. And on the menu I have a few buttons that currently don't do anything. What I want them to do is whenever a user clicks on a button I want the page to slide in from the bottom of the screen. I have tried to do this myself but for some reason it just closes the menu whenever I press one of the buttons.

Here is what I have so far.

//About Page Transition
function expand(){
  $(this).toggleClass("on");
  $(".aboutContent").toggleClass("active");
};
$("#about").on('click', expand);

//Projects Page Transition
function expand(){
  $(this).toggleClass("on");
  $(".aboutContent").toggleClass("active");
};
$("#projects").on('click', expand);

//Contact Page Transition
function expand(){
  $(this).toggleClass("on");
  $(".aboutContent").toggleClass("active");
};
$("#contact").on('click', expand);

//Menu Transition
function expand(){
  $(this).toggleClass("on");
  $(".menu").toggleClass("active");
};
$(".button").on('click', expand);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  font-family: "Source Sans Pro", sans-serif;
  color: #ccc;
  z-index: -100;
  background-color: black;
  overflow: hidden;
}

#aboutContent {
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  padding: 0;
  overflow: hidden;
  width: 100%;
  height: 100%;
  transition: all 250ms;
  -webkit-transform: translateZ(0) translateX(-100%);
  transform: translateZ(0) translateX(-100%);
  background-color: blue;
  z-index: 1000;
}

#projectsContent {
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  padding: 0;
  overflow: hidden;
  width: 100%;
  height: 100%;
  transition: all 250ms;
  -webkit-transform: translateZ(0) translateX(-100%);
  transform: translateZ(0) translateX(-100%);
  background-color: black;
  z-index: 1000;
}

#contactContent {
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  padding: 0;
  overflow: hidden;
  width: 100%;
  height: 100%;
  transition: all 250ms;
  -webkit-transform: translateZ(0) translateX(-100%);
  transform: translateZ(0) translateX(-100%);
  background-color: white;
  z-index: 1000;
}

.menu {
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  padding: 0;
  overflow: hidden;
  background: rgba(60, 106, 152, 0.8);
  width: 18%;
  box-sizing: border-box;
  transition: all 250ms;
  -webkit-transform: translateZ(0) translateX(-100%);
  transform: translateZ(0) translateX(-100%);
  text-align:center;
  box-shadow: 0 0 20px #000000;
}

.active {
  transform: translateZ(0) translateX(0);
  transform: translateZ(0) translateX(0);
  -webkit-transition: 0.4s;
  transition: 0.4s;
  color: #e5e5e5;
}

h1 {
  margin-top:60%;
  font-size: 2.5em;
  cursor: default;
}

ul {
  padding:0;
  list-style:none;
  font-size:14px;
}

li {
  padding:10px 10px;
}

a {
  text-decoration:none;
  padding:10px 15px;
  color:#fff;
  font-family:"Roboto";
  font-size: 1.5em;
  font-weight: 300;
}

a:hover {
  text-decoration: line-through;
  color: #d66863;
}

.content {
  position:relative;
  width:300px;
}

.button {
  width:20px;
  height:40px;
  margin:24% 36%;
  padding: 14px;
  cursor:pointer;
}

.line {
 width: 40px;
 height: 2px;
    background-color: #fff;
 transition: transform 0.3s ease, background 0.3s ease, opacity 0.3s ease, top 0.3s ease;
}

.line.first {
  transform: translateX(-10px) translateY(22px) rotate(-90deg);
}

.line.second {
  transform: translateX(-10px) translateY(19px) rotate(0deg);
}

.button.on .line.top {
 transform: translateX(-10px) translateY(20px) rotate(45deg);
}

.button.on .line.bottom {
 transform: translateX(-10px) translateY(17px)rotate(-45deg);
}</code>```

<!DOCTYPE html>

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

    <title>Home</title>

    <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro|Play|Raleway" rel="stylesheet">

    <link rel='stylesheet prefetch' href='http://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css'>

    <link rel="stylesheet" type="text/css" href="css/style.css">

Title

 home

 about

 projects

 contact

```

答:
A very easy way to do this is with "animate.css".

All you do is dynamically apply the classes "animate slideInUp" (I think that's it anyway) to whatever element you want to slide in, and it just does.

You can do it with plain ol' JS, JQuery makes it braindead easy, bind it as a property in Angular/React (e.g. [ngClass]="theClasses"), however you want.

In your case in fact, you wouldn't even have to dynamically do anything. Just hardcode the classes to the topmost div (or whatever) of the HTML page that loads in. Every time that page loads in, it'll slide up.

Check out animate.css, it's a great and powerful tool and delivers exactly what it says it does, "just add water animations". For basic DOM element animation I've never had to look anywhere else.

You can see it at work on my little personal website:

http://www.tcoz.com

Every time you click a menu button, the page slides in.

Body:
I basically have a menu that slides onto the screen when you press a button. And on the menu I have a few buttons that currently don't do anything. What I want them to do is whenever a user clicks on a button I want the page to slide in from the bottom of the screen. I have tried to do this myself but for some reason it just closes the menu whenever I press one of the buttons.

Here is what I have so far.

//About Page Transition
function expand(){
  $(this).toggleClass("on");
  $(".aboutContent").toggleClass("active");
};
$("#about").on('click', expand);

//Projects Page Transition
function expand(){
  $(this).toggleClass("on");
  $(".aboutContent").toggleClass("active");
};
$("#projects").on('click', expand);

//Contact Page Transition
function expand(){
  $(this).toggleClass("on");
  $(".aboutContent").toggleClass("active");
};
$("#contact").on('click', expand);

//Menu Transition
function expand(){
  $(this).toggleClass("on");
  $(".menu").toggleClass("active");
};
$(".button").on('click', expand);

body {
  font-family: "Source Sans Pro", sans-serif;
  color: #ccc;
  z-index: -100;
  background-color: black;
  overflow: hidden;
}

#aboutContent {
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  padding: 0;
  overflow: hidden;
  width: 100%;
  height: 100%;
  transition: all 250ms;
  -webkit-transform: translateZ(0) translateX(-100%);
  transform: translateZ(0) translateX(-100%);
  background-color: blue;
  z-index: 1000;
}

#projectsContent {
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  padding: 0;
  overflow: hidden;
  width: 100%;
  height: 100%;
  transition: all 250ms;
  -webkit-transform: translateZ(0) translateX(-100%);
  transform: translateZ(0) translateX(-100%);
  background-color: black;
  z-index: 1000;
}

#contactContent {
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  padding: 0;
  overflow: hidden;
  width: 100%;
  height: 100%;
  transition: all 250ms;
  -webkit-transform: translateZ(0) translateX(-100%);
  transform: translateZ(0) translateX(-100%);
  background-color: white;
  z-index: 1000;
}

.menu {
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  padding: 0;
  overflow: hidden;
  background: rgba(60, 106, 152, 0.8);
  width: 18%;
  box-sizing: border-box;
  transition: all 250ms;
  -webkit-transform: translateZ(0) translateX(-100%);
  transform: translateZ(0) translateX(-100%);
  text-align:center;
  box-shadow: 0 0 20px #000000;
}

.active {
  transform: translateZ(0) translateX(0);
  transform: translateZ(0) translateX(0);
  -webkit-transition: 0.4s;
  transition: 0.4s;
  color: #e5e5e5;
}

h1 {
  margin-top:60%;
  font-size: 2.5em;
  cursor: default;
}

ul {
  padding:0;
  list-style:none;
  font-size:14px;
}

li {
  padding:10px 10px;
}

a {
  text-decoration:none;
  padding:10px 15px;
  color:#fff;
  font-family:"Roboto";
  font-size: 1.5em;
  font-weight: 300;
}

a:hover {
  text-decoration: line-through;
  color: #d66863;
}

.content {
  position:relative;
  width:300px;
}

.button {
  width:20px;
  height:40px;
  margin:24% 36%;
  padding: 14px;
  cursor:pointer;
}

.line {
 width: 40px;
 height: 2px;
    background-color: #fff;
 transition: transform 0.3s ease, background 0.3s ease, opacity 0.3s ease, top 0.3s ease;
}

.line.first {
  transform: translateX(-10px) translateY(22px) rotate(-90deg);
}

.line.second {
  transform: translateX(-10px) translateY(19px) rotate(0deg);
}

.button.on .line.top {
 transform: translateX(-10px) translateY(20px) rotate(45deg);
}

.button.on .line.bottom {
 transform: translateX(-10px) translateY(17px)rotate(-45deg);
}

<!DOCTYPE html>

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

    <title>Home</title>

    <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro|Play|Raleway" rel="stylesheet">

    <link rel='stylesheet prefetch' href='http://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css'>

    <link rel="stylesheet" type="text/css" href="css/style.css">

Title

 home

 about

 projects

 contact


问:
Not able to use enum in mysql
```<code>DROP TABLE IF EXISTS CountryLanguage;
CREATE TABLE CountryLanguage (
  CountryCode CHAR(3) NOT NULL DEFAULT '',
  Language CHAR(30) NOT NULL DEFAULT '',
  IsOfficial ENUM('True','False') NOT NUll default 'False',
  Percentage FLOAT(4,1) NOT NULL DEFAULT '0.0',
  PRIMARY KEY  (CountryCode,Language)
)
ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO CountryLanguage VALUES ('AND','Spanish',0,44.6);
</code>```

When I enter the insert statement it gives me an error:

'Data truncated for column IsOfficial'.

It only gives an error when I use 0 ,it works well for 1.

答:
your enum  is  IsOfficial ENUM('True','False')   ... then you should ue only the strin  'True' or 'False'  (not the boolean conceptually related)</p>

```<code>INSERT INTO CountryLanguage VALUES ('AND','Spanish','False',44.6);
</code>```

Title: Not able to use enum in mysql

Body:
DROP TABLE IF EXISTS CountryLanguage;
CREATE TABLE CountryLanguage (
  CountryCode CHAR(3) NOT NULL DEFAULT '',
  Language CHAR(30) NOT NULL DEFAULT '',
  IsOfficial ENUM('True','False') NOT NUll default 'False',
  Percentage FLOAT(4,1) NOT NULL DEFAULT '0.0',
  PRIMARY KEY  (CountryCode,Language)
)
ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO CountryLanguage VALUES ('AND','Spanish',0,44.6);

When I enter the insert statement it gives me an error:

'Data truncated for column IsOfficial'.

It only gives an error when I use 0 ,it works well for 1.

Body:
your enum  is  IsOfficial ENUM('True','False')   ... then you should ue only the strin  'True' or 'False'  (not the boolean conceptually related)

INSERT INTO CountryLanguage VALUES ('AND','Spanish','False',44.6);


问:
Why is HTML5 Drag and Drop so slow compared to mouse event
I wanted to implement a draggable window in Angular 2, and I first tried this in a codepen.

However, even using plain JavaScript, it seems to be very slow, compared to the plain old mouse event counterpart which are used everywhere.

My example is tested on Safari, I knew that the example doesn't work in Chrome/Firefox, I think Chrome fires an additional bad drag and Firefox doesn't expose mouse position in drag event.

Also, the example works much better in Chrome, producing zero to no lag. I found a reference on StackOverflow saying Safari is the only one that lags.

```<code>"use strict"
let el = document.getElementById("window")
let anchor = { x: 0, y: 0 }
let begin = { x: 0, y: 0 }
let newPosition = { x: 0, y: 0 }
let needsRedraw = false

let use = "drag"

if (use == "drag") {
  el.draggable = "true"
  el.addEventListener('dragstart', event => {
    begin = { x: Number.parseInt(el.style.left),
              y: Number.parseInt(el.style.top) }
    anchor = { x: event.clientX, y: event.clientY }
  })
  document.addEventListener('drag', event => {
    let dx = event.clientX - anchor.x
    let dy = event.clientY - anchor.y
    newPosition = { x: begin.x + dx, y: begin.y + dy }

    needsRedraw = true
  })
} else if (use == "click") {
  let moving = false
  el.addEventListener('mousedown', event => {
    moving = true
    begin = { x: Number.parseInt(el.style.left),
              y: Number.parseInt(el.style.top) }
    anchor = { x: event.clientX, y: event.clientY }
  })
  document.addEventListener('mousemove', event => {
    if (moving) {
      let dx = event.clientX - anchor.x
      let dy = event.clientY - anchor.y
      newPosition = { x: begin.x + dx, y: begin.y + dy }
      needsRedraw = true
    }
  })
  document.addEventListener('mouseup', event => {
    moving = false
  })
}

function draw() {
  requestAnimationFrame(draw)
  if (needsRedraw) {
    el.style.left = newPosition.x + "px"
    el.style.top = newPosition.y + "px"
    needsRedraw = false
  }
}

requestAnimationFrame(draw)
</code>```

答:
Testing with just Angular 2, I used direct element access through ElementRef to minimize performance impact.

Chrome did work a lot better, with or without requestAnimationFrame. However, if I close Safari's Developer Console, everything seems to work smoothly enough.

Discovering that, all seems to be a non-issue. (Also throttling dragover/drag events doesn't improve performance since the biggest performance impact is on DOM change and the browser had to redraw the element)

Body:
I wanted to implement a draggable window in Angular 2, and I first tried this in a codepen.

However, even using plain JavaScript, it seems to be very slow, compared to the plain old mouse event counterpart which are used everywhere.

My example is tested on Safari, I knew that the example doesn't work in Chrome/Firefox, I think Chrome fires an additional bad drag and Firefox doesn't expose mouse position in drag event.

Also, the example works much better in Chrome, producing zero to no lag. I found a reference on StackOverflow saying Safari is the only one that lags.

"use strict"
let el = document.getElementById("window")
let anchor = { x: 0, y: 0 }
let begin = { x: 0, y: 0 }
let newPosition = { x: 0, y: 0 }
let needsRedraw = false

let use = "drag"

if (use == "drag") {
  el.draggable = "true"
  el.addEventListener('dragstart', event => {
    begin = { x: Number.parseInt(el.style.left),
              y: Number.parseInt(el.style.top) }
    anchor = { x: event.clientX, y: event.clientY }
  })
  document.addEventListener('drag', event => {
    let dx = event.clientX - anchor.x
    let dy = event.clientY - anchor.y
    newPosition = { x: begin.x + dx, y: begin.y + dy }

    needsRedraw = true
  })
} else if (use == "click") {
  let moving = false
  el.addEventListener('mousedown', event => {
    moving = true
    begin = { x: Number.parseInt(el.style.left),
              y: Number.parseInt(el.style.top) }
    anchor = { x: event.clientX, y: event.clientY }
  })
  document.addEventListener('mousemove', event => {
    if (moving) {
      let dx = event.clientX - anchor.x
      let dy = event.clientY - anchor.y
      newPosition = { x: begin.x + dx, y: begin.y + dy }
      needsRedraw = true
    }
  })
  document.addEventListener('mouseup', event => {
    moving = false
  })
}

function draw() {
  requestAnimationFrame(draw)
  if (needsRedraw) {
    el.style.left = newPosition.x + "px"
    el.style.top = newPosition.y + "px"
    needsRedraw = false
  }
}

requestAnimationFrame(draw)


问:
Best way to disable entire form on PHP condition?
I have a site (like many). I want to show but disable a particular form based on whether they are logged in or not. The way I show if the user is logged in is via a cookie set by PHP. What I'm wondering is the best way to disable all the elements in the form when the user is not logged in.

The solution I have at the moment is to get PHP to echo some JavaScript (jQuery to be precise) to the page:

```
$("#form_name").children("input, textarea").attr("disabled", "disabled");
```

Is this the right way to go, or is there a better way to be doing things?

答:
Using jQuery you could find all input, select, and textarea elements that are not currently disabled and disable them, using the :enabled selector</p>

```<code>$("#form_id").find("input:enabled, select:enabled, textarea:enabled").attr("disabled", "disabled");
</code>```

Body:
I have a site (like many). I want to show but disable a particular form based on whether they are logged in or not. The way I show if the user is logged in is via a cookie set by PHP. What I'm wondering is the best way to disable all the elements in the form when the user is not logged in.

The solution I have at the moment is to get PHP to echo some JavaScript (jQuery to be precise) to the page:

$("#form_name").children("input, textarea").attr("disabled", "disabled");

Is this the right way to go, or is there a better way to be doing things?

Body:
Using jQuery you could find all input, select, and textarea elements that are not currently disabled and disable them, using the :enabled selector

$("#form_id").find("input:enabled, select:enabled, textarea:enabled").attr("disabled", "disabled");


问:
Is it possible to upload files' binary data via JSON to the server?
I'm creating an architecture for a SPL (software production line) and I need to make things as easy as possible for the purpose of industrial productivity. The architecture is RESTful, Web API at the server side, Angular 2 & Material 2 at the client side in a nutshell.

I just have this question

Since I write the front-end and back-end, is it possible that in my forms which have file-upload control, I just get binary data from that file and send it to the server in JSON alongside other properties?

In other words, instead of multipart/form-data, I want to send something like this:

```<code>{
   "title":"we in the garden",
   "tags":[
      "family",
      "holidy"
   ],
   "file":" is it possible to include file's binary data here? "
}
</code>```

If yes, what do I miss, If no, why not?

答:
Possible but not recommended

One can use the FileReader.readAsDataURL() API to bring the file into memory as a base64 encoded string.

```<code>  vm.previewFile = function() {
    readBase64(vm.files[0]).then(function(data) {
      vm.data = data;
    })
  }

  function readBase64(file) {
    var reader  = new FileReader();
    var future = $q.defer();

    reader.addEventListener("load", function () {
      future.resolve(reader.result);
    }, false);

    reader.addEventListener("error", function (event) {
      future.reject(event);
    }, false);

    reader.readAsDataURL(file);

    return future.promise;
  }
</code>```

The Demo on PLNKR.

However, base64 encoding is inefficient. Converting a binary file to a base64 encoded DOMstring (UTF-16) will take 266% more memory. The browser will likely crash with large video files.

It is more efficient to POST a file directly:

```<code>//RECOMMENDED
//Send binary file directly
var config = { headers: { "Content-Type": undefined },
               params: { filename: vm.files[0].name,
                         size: vm.files[0].size,
                         type: vm.files[0].type
                       }
             );
$http.post(url, vm.files[0], config);
</code>```

The $http service will use the XHR send method to stream the browser File object to the server.

```<code><input type="file" files-input
       ng-model="files" ng-change="previewFile()"
/>
</code>```

The files-input directive:

```<code>app.directive("filesInput", function() {
  return {
    require: "ngModel",
    link: function postLink(scope,elem,attrs,ngModel) {
      elem.on("change", function() {
        ngModel.$setViewValue(elem[0].files);
      });
    }
  };
});
</code>```

Body:
I'm creating an architecture for a SPL (software production line) and I need to make things as easy as possible for the purpose of industrial productivity. The architecture is RESTful, Web API at the server side, Angular 2 & Material 2 at the client side in a nutshell.

I just have this question

Since I write the front-end and back-end, is it possible that in my forms which have file-upload control, I just get binary data from that file and send it to the server in JSON alongside other properties?

In other words, instead of multipart/form-data, I want to send something like this:

{
   "title":"we in the garden",
   "tags":[
      "family",
      "holidy"
   ],
   "file":" is it possible to include file's binary data here? "
}

If yes, what do I miss, If no, why not?

Body:
Possible but not recommended

One can use the FileReader.readAsDataURL() API to bring the file into memory as a base64 encoded string.

  vm.previewFile = function() {
    readBase64(vm.files[0]).then(function(data) {
      vm.data = data;
    })
  }

  function readBase64(file) {
    var reader  = new FileReader();
    var future = $q.defer();

    reader.addEventListener("load", function () {
      future.resolve(reader.result);
    }, false);

    reader.addEventListener("error", function (event) {
      future.reject(event);
    }, false);

    reader.readAsDataURL(file);

    return future.promise;
  }

The Demo on PLNKR.

However, base64 encoding is inefficient. Converting a binary file to a base64 encoded DOMstring (UTF-16) will take 266% more memory. The browser will likely crash with large video files.

It is more efficient to POST a file directly:

//RECOMMENDED
//Send binary file directly
var config = { headers: { "Content-Type": undefined },
               params: { filename: vm.files[0].name,
                         size: vm.files[0].size,
                         type: vm.files[0].type
                       }
             );
$http.post(url, vm.files[0], config);

The $http service will use the XHR send method to stream the browser File object to the server.

<input type="file" files-input
       ng-model="files" ng-change="previewFile()"
/>

The files-input directive:

app.directive("filesInput", function() {
  return {
    require: "ngModel",
    link: function postLink(scope,elem,attrs,ngModel) {
      elem.on("change", function() {
        ngModel.$setViewValue(elem[0].files);
      });
    }
  };
});


问:
android vector background color transparent
My main layout look like this.

```<code><?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/transparent"
    android:orientation="vertical"
    android:padding="0dp"
    tools:context="com.send.apk.bluetoothappsend.MainActivity">

    <include
        android:id="@+id/tool_bar"
        layout="@layout/tool_bar" />

    <android.support.v7.widget.RecyclerView
        android:id="@+id/rv"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:background="@drawable/background" />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="@dimen/_80sdp"
        android:background="@drawable/ic_footer" />
</LinearLayout>
</code>```

And I use following vector

```<code><vector xmlns:android="http://schemas.android.com/apk/res/android"
        android:width="1124dp"
        android:height="306dp"
         android:tint="@android:color/transparent"
        android:viewportWidth="11240.0"
        android:viewportHeight="3060.0">
    <path
        android:pathData="M179,3046c-111,-20 -146,-55 -166,-170 -17,-96 -18,-1749 -2,-1861 18,-122 69,-172 194,-194 41,-7 417,-11 1126,-11 585,0 1168,-5 1294,-10 330,-14 760,-47 905,-70 415,-63 789,-207 1132,-437 277,-184 448,-251 718,-278 183,-19 297,-19 480,0 270,27 441,94 718,279 370,247 789,400 1238,451 462,52 862,65 2088,65 713,0 1090,4 1131,11 125,22 176,72 194,194 16,112 15,1765 -2,1861 -21,117 -54,150 -171,171 -100,17 -10778,17 -10877,-1z"
        android:strokeColor="#00000000"
        android:fillColor="#090b17"/>
</vector>
</code>```

But problem that , there exists some black background as picture , I need trasparent background

答:
First off, if you need a transparent view, you probably shouldn't even be using a vector image in the first place. But the issue is that you set your fill color to be #090b17, which should be #00000000.

Alternatively, you could set the background of your RelativeLayout to be:

```<code>android:background="@android:color/transparent"
</code>```

Body:
My main layout look like this.

<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/transparent"
    android:orientation="vertical"
    android:padding="0dp"
    tools:context="com.send.apk.bluetoothappsend.MainActivity">

    <include
        android:id="@+id/tool_bar"
        layout="@layout/tool_bar" />

    <android.support.v7.widget.RecyclerView
        android:id="@+id/rv"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:background="@drawable/background" />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="@dimen/_80sdp"
        android:background="@drawable/ic_footer" />
</LinearLayout>

And I use following vector

<vector xmlns:android="http://schemas.android.com/apk/res/android"
        android:width="1124dp"
        android:height="306dp"
         android:tint="@android:color/transparent"
        android:viewportWidth="11240.0"
        android:viewportHeight="3060.0">
    <path
        android:pathData="M179,3046c-111,-20 -146,-55 -166,-170 -17,-96 -18,-1749 -2,-1861 18,-122 69,-172 194,-194 41,-7 417,-11 1126,-11 585,0 1168,-5 1294,-10 330,-14 760,-47 905,-70 415,-63 789,-207 1132,-437 277,-184 448,-251 718,-278 183,-19 297,-19 480,0 270,27 441,94 718,279 370,247 789,400 1238,451 462,52 862,65 2088,65 713,0 1090,4 1131,11 125,22 176,72 194,194 16,112 15,1765 -2,1861 -21,117 -54,150 -171,171 -100,17 -10778,17 -10877,-1z"
        android:strokeColor="#00000000"
        android:fillColor="#090b17"/>
</vector>

But problem that , there exists some black background as picture , I need trasparent background

Body:
First off, if you need a transparent view, you probably shouldn't even be using a vector image in the first place. But the issue is that you set your fill color to be #090b17, which should be #00000000.

Alternatively, you could set the background of your RelativeLayout to be:

android:background="@android:color/transparent"