问:
how to center a webpage in both vertically and horizontally?
i like to have my webpage to be centered vertically and horizontally. i have tried many options but nothing successful. help me. Basically its a thumbnail image gallery page and i am using photoswipe. Everything is fine except i cannot make the page centered.

My HTML code

```<code><div class="my-gallery" itemscope itemtype="http://schema.org/ImageGallery">

    <figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
              <a href="images/rp1-1.jpg" itemprop="contentUrl" data-size="1400x2100">
          <img src="images/rp1.jpg" itemprop="thumbnail"></a>
        <figcaption>1</figcaption>
    </figure>

    <figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
              <a href="images/rp2-1.jpg" itemprop="contentUrl" data-size="1400x2100">
          <img src="images/rp2.jpg" itemprop="thumbnail"></a>
        <figcaption>2</figcaption>
    </figure>

    <figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
              <a href="images/rp3-1.jpg" itemprop="contentUrl" data-size="1400x2100">
          <img src="images/rp3.jpg" itemprop="thumbnail"></a>
        <figcaption>3</figcaption>
    </figure>

    <figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
              <a href="images/rp4-1.jpg" itemprop="contentUrl" data-size="1400x2100">
          <img src="images/rp4.jpg" itemprop="thumbnail"></a>
        <figcaption>4</figcaption>
    </figure>

    <figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
              <a href="images/rp5-1.jpg" itemprop="contentUrl" data-size="1400x2100">
          <img src="images/rp5.jpg" itemprop="thumbnail"></a>
        <figcaption>5</figcaption>
    </figure>

    <figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
              <a href="images/rp6-1.jpg" itemprop="contentUrl" data-size="1400x2100">
          <img src="images/rp6.jpg" itemprop="thumbnail"></a>
        <figcaption>6</figcaption>
    </figure>

    <figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
              <a href="images/rp7-1.jpg" itemprop="contentUrl" data-size="1400x2100">
          <img src="images/rp7.jpg" itemprop="thumbnail"></a>
        <figcaption>7</figcaption>
    </figure>

    <figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
              <a href="images/rp8-1.jpg" itemprop="contentUrl" data-size="1400x2100">
          <img src="images/rp8.jpg" itemprop="thumbnail"></a>
        <figcaption>8</figcaption>
    </figure>

    <figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
              <a href="images/rp9-1.jpg" itemprop="contentUrl" data-size="1400x2100">
          <img src="images/rp9.jpg" itemprop="thumbnail"></a>
        <figcaption>9</figcaption>
    </figure>

    <figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
              <a href="images/rp10-1.jpg" itemprop="contentUrl" data-size="1400x2100">
          <img src="images/rp10.jpg" itemprop="thumbnail"></a>
        <figcaption>10</figcaption>
    </figure>

    <figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
              <a href="images/rp11-1.jpg" itemprop="contentUrl" data-size="1400x2100">
          <img src="images/rp11.jpg" itemprop="thumbnail"></a>
        <figcaption>11</figcaption>
    </figure>

    <figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
              <a href="images/rp12-1.jpg" itemprop="contentUrl" data-size="1400x2100">
          <img src="images/rp12.jpg" itemprop="thumbnail"></a>
        <figcaption>12</figcaption>
    </figure>

    <figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
              <a href="images/rp13-1.jpg" itemprop="contentUrl" data-size="1400x2100">
          <img src="images/rp13.jpg" itemprop="thumbnail"></a>
        <figcaption>13</figcaption>
    </figure>

    <figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
              <a href="images/rp14-1.jpg" itemprop="contentUrl" data-size="1400x2100">
          <img src="images/rp14.jpg" itemprop="thumbnail"></a>
        <figcaption>14</figcaption>
    </figure>

    <figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
              <a href="images/rp15-1.jpg" itemprop="contentUrl" data-size="1400x2100">
          <img src="images/rp15.jpg" itemprop="thumbnail"></a>
        <figcaption>15</figcaption>
    </figure>

</div>
</code>```

My CSS code:

```<code>.my-gallery {
margin-left: auto;
margin-right: auto;
width:100%;

}
.my-gallery img {
width: 100%;
height: auto;
}
.my-gallery figure {
display: block;
float: left;
width: auto;
margin: 0 auto;
text-align: center;
font: 15px Arial, sans-serif;
border: thin silver solid;
margin: 5px 5px;
padding: 0.1em;

}
.my-gallery figcaption {
padding-top: 1px;
padding-bottom: 1px;

}
</code>```

How to make it centered?

My Full code

```<code><!DOCTYPE html>
<html>

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>Multiple PhotoSwipe galleries on page</title>

<link rel="stylesheet" href="css/photoswipe.min.css">
<link rel="stylesheet" href="css/default-skin/default-skin.min.css">

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

</head>

<body>

<div class="my-gallery" itemscope itemtype="http://schema.org/ImageGallery">

    <figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
              <a href="images/rp1-1.jpg" itemprop="contentUrl" data-size="1400x2100">
          <img src="images/rp1.jpg" itemprop="thumbnail"></a>
        <figcaption>1</figcaption>
    </figure>

    <figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
              <a href="images/rp2-1.jpg" itemprop="contentUrl" data-size="1400x2100">
          <img src="images/rp2.jpg" itemprop="thumbnail"></a>
        <figcaption>2</figcaption>
    </figure>

    <figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
              <a href="images/rp3-1.jpg" itemprop="contentUrl" data-size="1400x2100">
          <img src="images/rp3.jpg" itemprop="thumbnail"></a>
        <figcaption>3</figcaption>
    </figure>

    <figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
              <a href="images/rp4-1.jpg" itemprop="contentUrl" data-size="1400x2100">
          <img src="images/rp4.jpg" itemprop="thumbnail"></a>
        <figcaption>4</figcaption>
    </figure>

    <figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
              <a href="images/rp5-1.jpg" itemprop="contentUrl" data-size="1400x2100">
          <img src="images/rp5.jpg" itemprop="thumbnail"></a>
        <figcaption>5</figcaption>
    </figure>

    <figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
              <a href="images/rp6-1.jpg" itemprop="contentUrl" data-size="1400x2100">
          <img src="images/rp6.jpg" itemprop="thumbnail"></a>
        <figcaption>6</figcaption>
    </figure>

    <figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
              <a href="images/rp7-1.jpg" itemprop="contentUrl" data-size="1400x2100">
          <img src="images/rp7.jpg" itemprop="thumbnail"></a>
        <figcaption>7</figcaption>
    </figure>

    <figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
              <a href="images/rp8-1.jpg" itemprop="contentUrl" data-size="1400x2100">
          <img src="images/rp8.jpg" itemprop="thumbnail"></a>
        <figcaption>8</figcaption>
    </figure>

    <figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
              <a href="images/rp9-1.jpg" itemprop="contentUrl" data-size="1400x2100">
          <img src="images/rp9.jpg" itemprop="thumbnail"></a>
        <figcaption>9</figcaption>
    </figure>

    <figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
              <a href="images/rp10-1.jpg" itemprop="contentUrl" data-size="1400x2100">
          <img src="images/rp10.jpg" itemprop="thumbnail"></a>
        <figcaption>10</figcaption>
    </figure>

    <figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
              <a href="images/rp11-1.jpg" itemprop="contentUrl" data-size="1400x2100">
          <img src="images/rp11.jpg" itemprop="thumbnail"></a>
        <figcaption>11</figcaption>
    </figure>

    <figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
              <a href="images/rp12-1.jpg" itemprop="contentUrl" data-size="1400x2100">
          <img src="images/rp12.jpg" itemprop="thumbnail"></a>
        <figcaption>12</figcaption>
    </figure>

    <figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
              <a href="images/rp13-1.jpg" itemprop="contentUrl" data-size="1400x2100">
          <img src="images/rp13.jpg" itemprop="thumbnail"></a>
        <figcaption>13</figcaption>
    </figure>

    <figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
              <a href="images/rp14-1.jpg" itemprop="contentUrl" data-size="1400x2100">
          <img src="images/rp14.jpg" itemprop="thumbnail"></a>
        <figcaption>14</figcaption>
    </figure>

    <figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
              <a href="images/rp15-1.jpg" itemprop="contentUrl" data-size="1400x2100">
          <img src="images/rp15.jpg" itemprop="thumbnail"></a>
        <figcaption>15</figcaption>
    </figure>

</div>

<!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">

    <!-- Background of PhotoSwipe.
     It's a separate element, as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>

    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">

        <!-- Container that holds slides. PhotoSwipe keeps only 3 slides in DOM to save memory. -->
        <!-- don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>

        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">

            <div class="pswp__top-bar">

                <!--  Controls are self-explanatory. Order can be changed. -->

                <div class="pswp__counter"></div>

                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>

                <button class="pswp__button pswp__button--share" title="Share"></button>

                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>

                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                        <div class="pswp__preloader__cut">
                            <div class="pswp__preloader__donut"></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div>
            </div>

            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>

            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>

            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>

        </div>

    </div>

</div>
<script src="js/photoswipe.min.js"></script>
<script src="js/photoswipe-ui-default.min.js"></script>

<script src="js/index.js"></script>

</body>

</html>
</code>```

I want the class "my-gallery" to be centered. i can able to make the body center using section tag.

答:
Add this to your CSS and you're done</p>

```<code>body, html
{
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
    display:table;
}

body
{
    display:table-cell;
    vertical-align:middle;
}

.my-gallery
{
    text-align: center;
}

.my-gallery figure
{
    display: inline-block;
}
</code>```

Body:
i like to have my webpage to be centered vertically and horizontally. i have tried many options but nothing successful. help me. Basically its a thumbnail image gallery page and i am using photoswipe. Everything is fine except i cannot make the page centered.

My HTML code

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

My CSS code:

.my-gallery {
margin-left: auto;
margin-right: auto;
width:100%;

}
.my-gallery img {
width: 100%;
height: auto;
}
.my-gallery figure {
display: block;
float: left;
width: auto;
margin: 0 auto;
text-align: center;
font: 15px Arial, sans-serif;
border: thin silver solid;
margin: 5px 5px;
padding: 0.1em;

}
.my-gallery figcaption {
padding-top: 1px;
padding-bottom: 1px;

}

How to make it centered?

My Full code

<!DOCTYPE html>

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>Multiple PhotoSwipe galleries on page</title>

<link rel="stylesheet" href="css/photoswipe.min.css">
<link rel="stylesheet" href="css/default-skin/default-skin.min.css">

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>

                <button class="pswp__button pswp__button--share" title="Share"></button>

                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>

                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>

            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>

I want the class "my-gallery" to be centered. i can able to make the body center using section tag.

Body:
Add this to your CSS and you're done

body, html
{
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
    display:table;
}

body
{
    display:table-cell;
    vertical-align:middle;
}

.my-gallery
{
    text-align: center;
}

.my-gallery figure
{
    display: inline-block;
}


来源: stackexchange

问:
Garbage collector performance on different machines
I have a large memory consumption .NET 2.0 application. Ussually the GC handles the cleaning of the memory well.
However, I have a case where the application is installed in 2 different machines, one with 2gb of memory and one with 3gb of memory. In the 3gb of memory it crashes with Out Of Memory exception, while in the 2gb it nevers fails.
The .net runtime is the same in both machines and also the application installation is the same.
It is possible that when there is more memory the trigger to start the Grabage Collector is not raised on time?</p>

答:
You will find that GC will work if there is stuff to collect.  It sounds like you have some unknown memory leaks in code that are causing objects to be ignored by the GC, in other words, they aren't viable for collection according to the runtime.

Do you use a lot of events?

If you believe the GC is not collecting valid objects, you can force a collection (post-emptive defense: calling GC.Collect is hardly ever required and not a substitute for a memory profiling tool):

GC.Collect(GC.MaxGeneration)

http://msdn.microsoft.com/en-us/library/y46kxc5e.aspx

If object's are ready to collect, they will be collected here.  I suspect that references to objects are being held, stopping the GC.

Update: of course outside the box, the machine running out of memory is not necessarily because of your program.  Does this other computer run a lot more stuff concurrently as opposed to the 2Gb computer?

ContentLicense: CC BY-SA 2.5


问:
No response from jsonArray request
I am trying to fetch data from Android to Custom ListView but  I am not able to Fetch! Please help

MY JSON:_

```<code>{
   "College":[
      {
         "Name":"NITK",
         "Logo":"http:\/\/192.168.43.164\\Webapp\\Collegelogos\\nitk.jpg"
      },
      {
         "Name":"IITR",
         "Logo":"http:\/\/192.168.43.164\\Webapp\\Collegelogos\\iitr.jpg"
      },
      {
         "Name":"NITT",
         "Logo":"http:\/\/192.168.43.164\\Webapp\\Collegelogos\\nitt.jpg"
      },
      {
         "Name":"IITB",
         "Logo":"http:\/\/192.168.43.164\\Webapp\\Collegelogos\\iitb.png"
      },
      {
         "Name":"IITG",
         "Logo":"http:\/\/192.168.43.164\\Webapp\\Collegelogos\\iitg.png"
      },
      {
         "Name":"IITD",
         "Logo":"http:\/\/192.168.43.164\\Webapp\\Collegelogos\\iitd.png"
      },
      {
         "Name":"BITS",
         "Logo":"http:\/\/192.168.43.164\\Webapp\\Collegelogos\\bits.png"
      }
   ]
}
</code>```

CODE:-

```<code>public class MainActivity extends AppCompatActivity {
    private List<College> listcollege;

    //Creating Views
    private RecyclerView recyclerView;
    private RecyclerView.LayoutManager layoutManager;
    private RecyclerView.Adapter adapter;

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

        //Initializing Views
        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        recyclerView.setHasFixedSize(true);
        layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);

        listcollege = new ArrayList<>();
        getData();

    }

    private void getData(){
        //Showing a progress dialog
        final ProgressDialog loading = ProgressDialog.show(this,"Loading Data", "Please wait...",false,false);

        //Creating a json array request
        JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Config.DATA_URL,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        //Dismissing progress dialog
                        Toast.makeText(MainActivity.this, "sachin", Toast.LENGTH_SHORT).show();
                        loading.dismiss();

                        //calling method to parse json array
                        parseData(response);
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                });

        //Creating request queue
        RequestQueue requestQueue = Volley.newRequestQueue(this);

        //Adding request to the queue
        requestQueue.add(jsonArrayRequest);
    }
    public  void parseData(JSONArray array) {
        for (int i = 0; i < array.length(); i++) {
            College college = new College();
            JSONObject json = null;
            try {
                json = array.getJSONObject(i);
                college.setImageUrl(json.getString(Config.TAG_IMAGE_URL));
               String s = (json.getString(Config.TAG_NAME));
                Toast.makeText(this, s, Toast.LENGTH_SHORT).show();
                college.setName(s);

            } catch (JSONException e) {
                e.printStackTrace();
            }
            listcollege.add(college);

        }
            adapter = new CardAdapter(this, listcollege);
            recyclerView.setAdapter(adapter);
      //  adapter.notifyDataSetChanged();

    }

}
</code>```

LOG :- ANDROID MONITOR

```<code>07-04 13:02:42.289 16225-16256/com.example.sachin.volleyrecycle I/OpenGLRenderer: Initialized EGL, version 1.4
07-04 13:02:42.289 16225-16256/com.example.sachin.volleyrecycle D/OpenGLRenderer: Swap behavior 1
07-04 13:02:42.289 16225-16256/com.example.sachin.volleyrecycle W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
07-04 13:02:42.289 16225-16256/com.example.sachin.volleyrecycle D/OpenGLRenderer: Swap behavior 0
07-04 13:02:42.702 16225-16225/com.example.sachin.volleyrecycle E/RecyclerView: No adapter attached; skipping layout
07-04 13:02:42.946 16225-16225/com.example.sachin.volleyrecycle W/art: Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
</code>```

答:
1. Initialize your adapter and set it to RecyclerView from onCreate() method.

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

    //Initializing Views
    recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
    recyclerView.setHasFixedSize(true);
    layoutManager = new LinearLayoutManager(this);
    recyclerView.setLayoutManager(layoutManager);

    listcollege = new ArrayList<>();
    adapter = new CardAdapter(this, listcollege);
    recyclerView.setAdapter(adapter);

    getData();
}
</code>```

2. Instead of JsonArrayRequest, try using JsonObjectRequest:

```<code>//Creating a json object request
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest (Config.DATA_URL,
        new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                //Dismissing progress dialog
                Toast.makeText(MainActivity.this, "sachin", Toast.LENGTH_SHORT).show();
                loading.dismiss();

                // College
                JSONArray jsonArrayCollege = response.getJSONArray("College");

                // calling method to parse json array
                parseData(jsonArrayCollege);
            }
        },
        new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });

//Creating request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);

//Adding request to the queue
requestQueue.add(jsonObjectRequest);
</code>```

3. Update parseData() method as below:

```<code>public  void parseData(JSONArray array) {
    for (int i = 0; i < array.length(); i++) {
        College college = new College();
        JSONObject json = null;
        try {
            json = array.getJSONObject(i);
            college.setImageUrl(json.getString(Config.TAG_IMAGE_URL));
           String s = (json.getString(Config.TAG_NAME));
            Toast.makeText(this, s, Toast.LENGTH_SHORT).show();
            college.setName(s);

        } catch (JSONException e) {
            e.printStackTrace();
        }
        listcollege.add(college);
    }
    adapter.notifyDataSetChanged();
}
</code>```

Hope this will help~

ContentLicense: CC BY-SA 3.0

Title: No response from jsonArray request

Body:
I am trying to fetch data from Android to Custom ListView but  I am not able to Fetch! Please help

MY JSON:_

{
   "College":[
      {
         "Name":"NITK",
         "Logo":"http:\/\/192.168.43.164\\Webapp\\Collegelogos\\nitk.jpg"
      },
      {
         "Name":"IITR",
         "Logo":"http:\/\/192.168.43.164\\Webapp\\Collegelogos\\iitr.jpg"
      },
      {
         "Name":"NITT",
         "Logo":"http:\/\/192.168.43.164\\Webapp\\Collegelogos\\nitt.jpg"
      },
      {
         "Name":"IITB",
         "Logo":"http:\/\/192.168.43.164\\Webapp\\Collegelogos\\iitb.png"
      },
      {
         "Name":"IITG",
         "Logo":"http:\/\/192.168.43.164\\Webapp\\Collegelogos\\iitg.png"
      },
      {
         "Name":"IITD",
         "Logo":"http:\/\/192.168.43.164\\Webapp\\Collegelogos\\iitd.png"
      },
      {
         "Name":"BITS",
         "Logo":"http:\/\/192.168.43.164\\Webapp\\Collegelogos\\bits.png"
      }
   ]
}

CODE:-

public class MainActivity extends AppCompatActivity {
    private List<College> listcollege;

    //Creating Views
    private RecyclerView recyclerView;
    private RecyclerView.LayoutManager layoutManager;
    private RecyclerView.Adapter adapter;

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

        //Initializing Views
        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        recyclerView.setHasFixedSize(true);
        layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);

        listcollege = new ArrayList<>();
        getData();

    }

    private void getData(){
        //Showing a progress dialog
        final ProgressDialog loading = ProgressDialog.show(this,"Loading Data", "Please wait...",false,false);

        //Creating a json array request
        JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Config.DATA_URL,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        //Dismissing progress dialog
                        Toast.makeText(MainActivity.this, "sachin", Toast.LENGTH_SHORT).show();
                        loading.dismiss();

                        //calling method to parse json array
                        parseData(response);
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                });

        //Creating request queue
        RequestQueue requestQueue = Volley.newRequestQueue(this);

        //Adding request to the queue
        requestQueue.add(jsonArrayRequest);
    }
    public  void parseData(JSONArray array) {
        for (int i = 0; i < array.length(); i++) {
            College college = new College();
            JSONObject json = null;
            try {
                json = array.getJSONObject(i);
                college.setImageUrl(json.getString(Config.TAG_IMAGE_URL));
               String s = (json.getString(Config.TAG_NAME));
                Toast.makeText(this, s, Toast.LENGTH_SHORT).show();
                college.setName(s);

            } catch (JSONException e) {
                e.printStackTrace();
            }
            listcollege.add(college);

        }
            adapter = new CardAdapter(this, listcollege);
            recyclerView.setAdapter(adapter);
      //  adapter.notifyDataSetChanged();

    }

}

LOG :- ANDROID MONITOR

07-04 13:02:42.289 16225-16256/com.example.sachin.volleyrecycle I/OpenGLRenderer: Initialized EGL, version 1.4
07-04 13:02:42.289 16225-16256/com.example.sachin.volleyrecycle D/OpenGLRenderer: Swap behavior 1
07-04 13:02:42.289 16225-16256/com.example.sachin.volleyrecycle W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
07-04 13:02:42.289 16225-16256/com.example.sachin.volleyrecycle D/OpenGLRenderer: Swap behavior 0
07-04 13:02:42.702 16225-16225/com.example.sachin.volleyrecycle E/RecyclerView: No adapter attached; skipping layout
07-04 13:02:42.946 16225-16225/com.example.sachin.volleyrecycle W/art: Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView

Body:
1. Initialize your adapter and set it to RecyclerView from onCreate() method.

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

    //Initializing Views
    recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
    recyclerView.setHasFixedSize(true);
    layoutManager = new LinearLayoutManager(this);
    recyclerView.setLayoutManager(layoutManager);

    listcollege = new ArrayList<>();
    adapter = new CardAdapter(this, listcollege);
    recyclerView.setAdapter(adapter);

    getData();
}

2. Instead of JsonArrayRequest, try using JsonObjectRequest:

//Creating a json object request
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest (Config.DATA_URL,
        new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                //Dismissing progress dialog
                Toast.makeText(MainActivity.this, "sachin", Toast.LENGTH_SHORT).show();
                loading.dismiss();

                // College
                JSONArray jsonArrayCollege = response.getJSONArray("College");

                // calling method to parse json array
                parseData(jsonArrayCollege);
            }
        },
        new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });

//Creating request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);

//Adding request to the queue
requestQueue.add(jsonObjectRequest);

3. Update parseData() method as below:

public  void parseData(JSONArray array) {
    for (int i = 0; i < array.length(); i++) {
        College college = new College();
        JSONObject json = null;
        try {
            json = array.getJSONObject(i);
            college.setImageUrl(json.getString(Config.TAG_IMAGE_URL));
           String s = (json.getString(Config.TAG_NAME));
            Toast.makeText(this, s, Toast.LENGTH_SHORT).show();
            college.setName(s);

        } catch (JSONException e) {
            e.printStackTrace();
        }
        listcollege.add(college);
    }
    adapter.notifyDataSetChanged();
}

Hope this will help~


问:
Hide Mouse Cursor when it's within HTML5 Canvas Javascript
I'm in the process of making a game using Javascript and the html5 canvas element as an alternative to Flash. My question is: is there any bit of code I can use to hide the mouse cursor/pointer as it passes within the canvas?
Help is much appreciated!</p>

答:
The simplest way (on modern browsers) is to set the cursor to none on the canvas.

If your canvas is created in HTML, do:

```<code><canvas id="canvas" style="cursor: none;"></canvas>
</code>```

I would favour this over a style-sheet because you want to guarantee the cursor value is not over-ridden.

If your canvas is created in JavaScript, do:

```<code>const canvas = document.createElement('canvas');
canvas.style.cursor = 'none';
document.body.appendChild(canvas);
</code>```

Body:
The simplest way (on modern browsers) is to set the cursor to none on the canvas.

If your canvas is created in HTML, do:

<canvas id="canvas" style="cursor: none;"></canvas>

I would favour this over a style-sheet because you want to guarantee the cursor value is not over-ridden.

If your canvas is created in JavaScript, do:

const canvas = document.createElement('canvas');
canvas.style.cursor = 'none';
document.body.appendChild(canvas);


问:
What should my database be for Ionic?
I'm new with Ionic and I was wondering what should I use as my Database. I tried to research and it seems that they were using SQLite as the database. Any other options?

Intended use:

I will store a small number of user data like the name, password, and email only. Also, for the large part, where I can save long text, audio, and images. What database should I use? Any advice from you guys?

Thanks!

答:
Take a look at Google Firebase. I used it for few of my projects. They have real-time database, file storage...
https://firebase.google.com/</p>

Title: What should my database be for Ionic?


问:
How to target bootstrap datepicker's its own '.datepicker-dropdown' when there is multiple datepickers in a page.?(without container option)
In my project - which is a App, I have multiple datepicker which is Version 2.0. My Client wants me to customise my datepicker by showing the date of the calendar top, so I did some tweaks, it is working on the page with one datepicker but it's an another story when it comes to multiple datepicekers on one page.my code is as follows.

```<code>$(elem).datepicker(options);
  //Customized Datepicker Plugin 03/07/2017
  //Author - Jithin Raj
  var date = new Date();
  var today = new Date(date.getFullYear(), date.getMonth(), date.getDate());
      $(elem).on('show', function() {
        var cPicVal = '',
            yPicVal = '';
            if ($('.datepicker-dropdown').find('.new-date-wrap').length <= 0) {
                    $('.datepicker-dropdown').prepend('<div class="new-date-wrap"><div class="custom-year-pic-view"><span></span></div><div class="custom-day-pic-view"><span></span></div></div>');
            }
            if ($(elem).val() == '') {
                    cPicVal = (Date.parse(today).toString('ddd, MMM dd'));
                    yPicVal = (Date.parse(today).toString('yyyy'));
            } else {
                    cPicVal = (Date.parse($(elem).val()).toString('ddd, MMM dd'));
                    yPicVal = (Date.parse($(elem).val()).toString('yyyy'));
            }
            $('.custom-day-pic-view').find('span').text(cPicVal);
            $('.custom-year-pic-view').find('span').text(yPicVal);
     });
});
</code>```

Can anyone suggest me a another fullprofe method, thankyou Cheers..

答:
I think I found an answer.

I changed my code a little bit and added moment.js and now it's working all over my app.

```<code>$(elem).datepicker(options);
 //Customized Datepicker Plugin 03/07/2017
 //Author - Jithin Raj
   var date = new Date();
   var today = new Date(date.getFullYear(), date.getMonth(), date.getDate());
   $(elem).on('show', function() {
              var cPicVal = '',
              yPicVal = '';
              elem = $(this)
            if ($('.datepicker-dropdown').find('.new-date-wrap').length <= 0) {
                    $('.datepicker-dropdown').prepend('<div class="row-fluid new-date-wrap"><div class="row-fluid custom-year-pic-view"><span></span></div><div class="row-fluid custom-day-pic-view"><span></span></div></div>');
            }
            if ($(elem).val() == '') {
                    cPicVal = (moment(today).format('ddd, MMM DD'));
                    yPicVal = (moment(today).format('YYYY'));
            } else {
                    cPicVal = (moment($(elem).val()).format('ddd, MMM DD'));
                    yPicVal = (moment($(elem).val()).format('YYYY'));
            }
            $('.custom-day-pic-view').find('span').text(cPicVal);
            $('.custom-year-pic-view').find('span').text(yPicVal);
});
</code>```

Body:
In my project - which is a App, I have multiple datepicker which is Version 2.0. My Client wants me to customise my datepicker by showing the date of the calendar top, so I did some tweaks, it is working on the page with one datepicker but it's an another story when it comes to multiple datepicekers on one page.my code is as follows.

$(elem).datepicker(options);
  //Customized Datepicker Plugin 03/07/2017
  //Author - Jithin Raj
  var date = new Date();
  var today = new Date(date.getFullYear(), date.getMonth(), date.getDate());
      $(elem).on('show', function() {
        var cPicVal = '',
            yPicVal = '';
            if ($('.datepicker-dropdown').find('.new-date-wrap').length <= 0) {
                    $('.datepicker-dropdown').prepend('

');
            }
            if ($(elem).val() == '') {
                    cPicVal = (Date.parse(today).toString('ddd, MMM dd'));
                    yPicVal = (Date.parse(today).toString('yyyy'));
            } else {
                    cPicVal = (Date.parse($(elem).val()).toString('ddd, MMM dd'));
                    yPicVal = (Date.parse($(elem).val()).toString('yyyy'));
            }
            $('.custom-day-pic-view').find('span').text(cPicVal);
            $('.custom-year-pic-view').find('span').text(yPicVal);
     });
});

Can anyone suggest me a another fullprofe method, thankyou Cheers..

Body:
I think I found an answer.

I changed my code a little bit and added moment.js and now it's working all over my app.

$(elem).datepicker(options);
 //Customized Datepicker Plugin 03/07/2017
 //Author - Jithin Raj
   var date = new Date();
   var today = new Date(date.getFullYear(), date.getMonth(), date.getDate());
   $(elem).on('show', function() {
              var cPicVal = '',
              yPicVal = '';
              elem = $(this)
            if ($('.datepicker-dropdown').find('.new-date-wrap').length <= 0) {
                    $('.datepicker-dropdown').prepend('<div class="row-fluid new-date-wrap"><div class="row-fluid custom-year-pic-view"><span></span></div><div class="row-fluid custom-day-pic-view"><span></span></div></div>');
            }
            if ($(elem).val() == '') {
                    cPicVal = (moment(today).format('ddd, MMM DD'));
                    yPicVal = (moment(today).format('YYYY'));
            } else {
                    cPicVal = (moment($(elem).val()).format('ddd, MMM DD'));
                    yPicVal = (moment($(elem).val()).format('YYYY'));
            }
            $('.custom-day-pic-view').find('span').text(cPicVal);
            $('.custom-year-pic-view').find('span').text(yPicVal);
});


问:
Hortonworks Oozie Spark Action - NullPointerException
I am running on HDP 2.5.3 with oozie 4.2.0. The spark action is set to run in yarn-client mode. The Spark Job is for getting the data from hive table, process it and store it in HDFS. But when I try submitting the Spark Application from Spark Action, I am getting NullPointerException.

workflow.xml

```<code><workflow-app xmlns="uri:oozie:workflow:0.5" name="Spark_Test">
   <global>
      <job-tracker>${job_tracker}</job-tracker>
      <name-node>${name_node}</name-node>
   </global>
   <credentials>
      <credential name="hiveCredentials" type="hive2">
         <property>
            <name>hive2.jdbc.url</name>
            <value>${hive_beeline_server}</value>
         </property>
         <property>
            <name>hive2.server.principal</name>
            <value>${hive_kerberos_principal}</value>
         </property>
      </credential>
   </credentials>
   <start to="SparkTest" />
   <action name="SparkTest" cred="hiveCredentials">
      <spark xmlns="uri:oozie:spark-action:0.1">
         <job-tracker>${job_tracker}</job-tracker>
         <name-node>${name_node}</name-node>
         <master>yarn-client</master>
         <name>Spark Hive Example</name>
         <class>com.fbr.genjson.exec.GenExecJson</class>
         <jar>${jarPath}/fedebomrpt_genjson.jar</jar>
         <spark-opts>--jars /usr/hdp/current/spark-client/lib/datanucleus-api-jdo-3.2.6.jar,/usr/hdp/current/spark-client/lib/datanucleus-rdbms-3.2.9.jar,/usr/hdp/current/spark-client/lib/datanucleus-core-3.2.10.jar --files /etc/hive/conf/hive-site.xml --conf spark.sql.hive.convertMetastoreOrc=false --driver-memory 2g --executor-memory 16g --executor-cores 4 --conf spark.ui.port=5051 --queue fbr</spark-opts>
         <arg>${arg1}</arg>
         <arg>${arg2}</arg>
      </spark>
      <ok to="end" />
      <error to="fail" />
   </action>
   <kill name="fail">
      <message>Spark Java PatentCitation failed, error message[${wf:errorMessage(wf:lastErrorNode())}]</message>
   </kill>
   <end name="end" />
</workflow-app>
</code>```

Exception:

```<code>SERVER[xxx.hpc.xx.com] USER[prxtcbrd] GROUP[-] TOKEN[] APP[Spark_Test] JOB[0004629-170625082345353-oozie-oozi-W] ACTION[0004629-170625082345353-oozie-oozi-W@SparkTest] Error starting action [SparkTest]. ErrorType [ERROR], ErrorCode [NullPointerException], Message [NullPointerException: null]
org.apache.oozie.action.ActionExecutorException: NullPointerException: null
    at org.apache.oozie.action.ActionExecutor.convertException(ActionExecutor.java:446)
    at org.apache.oozie.action.hadoop.JavaActionExecutor.submitLauncher(JavaActionExecutor.java:1202)
    at org.apache.oozie.action.hadoop.JavaActionExecutor.start(JavaActionExecutor.java:1373)
    at org.apache.oozie.command.wf.ActionStartXCommand.execute(ActionStartXCommand.java:232)
    at org.apache.oozie.command.wf.ActionStartXCommand.execute(ActionStartXCommand.java:63)
    at org.apache.oozie.command.XCommand.call(XCommand.java:287)
    at org.apache.oozie.service.CallableQueueService$CompositeCallable.call(CallableQueueService.java:331)
    at org.apache.oozie.service.CallableQueueService$CompositeCallable.call(CallableQueueService.java:260)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at org.apache.oozie.service.CallableQueueService$CallableWrapper.run(CallableQueueService.java:178)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NullPointerException
    at org.apache.oozie.action.hadoop.SparkActionExecutor.setupActionConf(SparkActionExecutor.java:85)
    at org.apache.oozie.action.hadoop.JavaActionExecutor.submitLauncher(JavaActionExecutor.java:1091)
    ... 11 more
</code>```

I dont know where I am doing mistake.. Do I need add any config xmls other than hive-site.xml ?

答:
In your example you import jars, files(hive-site.xml). I think there is no need to import these thing oozie already import these thing. Can you check with below spark action I think it might solve your problem.

```<code><action name="myfirstsparkjob" cred="hive_credentials">
    <spark xmlns="uri:oozie:spark-action:0.1">
        <job-tracker>${jobTracker}</job-tracker>
        <name-node>${nameNode}</name-node>
        <configuration>
            <property>
                <name>mapred.compress.map.output</name>
                <value>true</value>
            </property>
            <property>
                <name>mapred.job.queue.name</name>
                <value>${queueName}</value>
            </property>
        </configuration>
        <master>yarn</master>
        <mode>cluster</mode>
        <name>Spark Hive Example</name>
        <class>com.fbr.genjson.exec.GenExecJson</class>
        <jar>${jarPath}/fedebomrpt_genjson.jar</jar>
        <spark-opts>--queue queue_name --executor-memory 28G --num-executors 70 --executor-cores 5</spark-opts>
    </spark>
  <ok to="end" />
  <error to="fail" />
</code>```

And also set below oozie properties in you workflow.xml file

oozie.use.system.libpath=true
oozie.libpath=${jarPath}

Make sure you put all your user created libs and files inside your ${jarFile}

Body:
I am running on HDP 2.5.3 with oozie 4.2.0. The spark action is set to run in yarn-client mode. The Spark Job is for getting the data from hive table, process it and store it in HDFS. But when I try submitting the Spark Application from Spark Action, I am getting NullPointerException.

workflow.xml

<workflow-app xmlns="uri:oozie:workflow:0.5" name="Spark_Test">
   <global>
      <job-tracker>${job_tracker}</job-tracker>
      <name-node>${name_node}</name-node>
   </global>
   <credentials>
      <credential name="hiveCredentials" type="hive2">
         <property>
            <name>hive2.jdbc.url</name>
            <value>${hive_beeline_server}</value>
         </property>
         <property>
            <name>hive2.server.principal</name>
            <value>${hive_kerberos_principal}</value>
         </property>
      </credential>
   </credentials>
   <start to="SparkTest" />
   <action name="SparkTest" cred="hiveCredentials">
      <spark xmlns="uri:oozie:spark-action:0.1">
         <job-tracker>${job_tracker}</job-tracker>
         <name-node>${name_node}</name-node>
         <master>yarn-client</master>
         <name>Spark Hive Example</name>
         <class>com.fbr.genjson.exec.GenExecJson</class>
         <jar>${jarPath}/fedebomrpt_genjson.jar</jar>
         <spark-opts>--jars /usr/hdp/current/spark-client/lib/datanucleus-api-jdo-3.2.6.jar,/usr/hdp/current/spark-client/lib/datanucleus-rdbms-3.2.9.jar,/usr/hdp/current/spark-client/lib/datanucleus-core-3.2.10.jar --files /etc/hive/conf/hive-site.xml --conf spark.sql.hive.convertMetastoreOrc=false --driver-memory 2g --executor-memory 16g --executor-cores 4 --conf spark.ui.port=5051 --queue fbr</spark-opts>
         <arg>${arg1}</arg>
         <arg>${arg2}</arg>
      </spark>
      <ok to="end" />
      <error to="fail" />
   </action>
   <kill name="fail">
      <message>Spark Java PatentCitation failed, error message[${wf:errorMessage(wf:lastErrorNode())}]</message>
   </kill>
   <end name="end" />
</workflow-app>

Exception:

SERVER[xxx.hpc.xx.com] USER[prxtcbrd] GROUP[-] TOKEN[] APP[Spark_Test] JOB[0004629-170625082345353-oozie-oozi-W] ACTION[0004629-170625082345353-oozie-oozi-W@SparkTest] Error starting action [SparkTest]. ErrorType [ERROR], ErrorCode [NullPointerException], Message [NullPointerException: null]
org.apache.oozie.action.ActionExecutorException: NullPointerException: null
    at org.apache.oozie.action.ActionExecutor.convertException(ActionExecutor.java:446)
    at org.apache.oozie.action.hadoop.JavaActionExecutor.submitLauncher(JavaActionExecutor.java:1202)
    at org.apache.oozie.action.hadoop.JavaActionExecutor.start(JavaActionExecutor.java:1373)
    at org.apache.oozie.command.wf.ActionStartXCommand.execute(ActionStartXCommand.java:232)
    at org.apache.oozie.command.wf.ActionStartXCommand.execute(ActionStartXCommand.java:63)
    at org.apache.oozie.command.XCommand.call(XCommand.java:287)
    at org.apache.oozie.service.CallableQueueService$CompositeCallable.call(CallableQueueService.java:331)
    at org.apache.oozie.service.CallableQueueService$CompositeCallable.call(CallableQueueService.java:260)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at org.apache.oozie.service.CallableQueueService$CallableWrapper.run(CallableQueueService.java:178)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NullPointerException
    at org.apache.oozie.action.hadoop.SparkActionExecutor.setupActionConf(SparkActionExecutor.java:85)
    at org.apache.oozie.action.hadoop.JavaActionExecutor.submitLauncher(JavaActionExecutor.java:1091)
    ... 11 more

I dont know where I am doing mistake.. Do I need add any config xmls other than hive-site.xml ?

Body:
In your example you import jars, files(hive-site.xml). I think there is no need to import these thing oozie already import these thing. Can you check with below spark action I think it might solve your problem.

<action name="myfirstsparkjob" cred="hive_credentials">
    <spark xmlns="uri:oozie:spark-action:0.1">
        <job-tracker>${jobTracker}</job-tracker>
        <name-node>${nameNode}</name-node>
        <configuration>
            <property>
                <name>mapred.compress.map.output</name>
                <value>true</value>
            </property>
            <property>
                <name>mapred.job.queue.name</name>
                <value>${queueName}</value>
            </property>
        </configuration>
        <master>yarn</master>
        <mode>cluster</mode>
        <name>Spark Hive Example</name>
        <class>com.fbr.genjson.exec.GenExecJson</class>
        <jar>${jarPath}/fedebomrpt_genjson.jar</jar>
        <spark-opts>--queue queue_name --executor-memory 28G --num-executors 70 --executor-cores 5</spark-opts>
    </spark>
  <ok to="end" />
  <error to="fail" />

And also set below oozie properties in you workflow.xml file

oozie.use.system.libpath=true
oozie.libpath=${jarPath}

Make sure you put all your user created libs and files inside your ${jarFile}


问:
How to correctly get new issues list via redmine API?
I'm creating a small tool that will fetch new issues from our redmine repository and do some utility task on them. I'm planning the tool to run in background and to poll redmine for new issues ~ every minute.

I have no problems getting all issues via GET /issues.xml API, but I don't know how to correctly poll new issues since last call. The only way i can suggest is to use updated_on field and get issues that has update time > last poll time. Is it correct? And if this is correct, how I can get issues with update time > specified time?

The API documentation page has examples like GET /issues.xml?project_id=2, but this is equality comparison and i need to compare if "update_time" is GREATER THAN specified time.

Of course, GET /issues.xml?update_time>'01.10.10 12:08:41', and I suggest that it must be special syntax for comparison.

Any hints on correct API request I can use?

答:
```<code>/issues.xml?sort=updated_on%3Adesc&limit=100
</code>```

This worked for me to get the most recently updated issues. Could not find a solution to only get issues updated after time x. Use &offset=100 ... &offset=200 and so on to get the following issues if you need them.

Body:
/issues.xml?sort=updated_on%3Adesc&limit=100

This worked for me to get the most recently updated issues. Could not find a solution to only get issues updated after time x. Use &offset=100 ... &offset=200 and so on to get the following issues if you need them.


问:
how can we show/hide div tags using value of radio buttons in jquery or javascript?
hi i am very new to jquery and i am working on show and hide div tags using values of radio buttons. here is my HTML.

    <input type="radio" name="vehicleList" id="two" onclick="fuelList()" value="1" />Two Wheeler

    <input type="radio" name="vehicleList" id="four" onclick="fuelList()" value="2" />Four Wheeler

    <input type="radio" name="TwoWheeler" value="6" />Electric

    <input type="radio" name="TwoWheeler" value="7" />Petrol

    <input type="radio" name="FourWheeler" value="1" />Electric

    <input type="radio" name="FourWheeler" value="2" />Petrol

    <input type="radio" name="FourWheeler" value="3" />Diesel

    <input type="radio" name="FourWheeler" value="4" />CNG

    <input type="radio" name="FourWheeler" value="5" />LPG

```

now i need help in writing a jquery code for showing the div tag with id = "two wheeler" when radio button value = 1 and div tag with id = "four wheeler" when radio button value = 2.

thnaks in advance.

sorry for anyone who couldnt understand my question.

答:
My first suggestion is to change your onclick="" to onchange="".

```<code><input type="radio" name="vehicleList" id="four" onchange="fuelList(this)" value="2"  class="radioButtons" />Four Wheeler

<script>
 function fuelList(element)
{
   var id = element.value;
   if( id == 1)
     {
      $(".wheels")hide(); //hides all the elements with class = wheels
      $("#twoWheelers")show(); //shows the div with id = twoWheelers
     }
    else if( id == 2 )
     {
      $(".wheels")hide(); //hides all the elements with class = wheels
      $("#fourWheelers")show(); //shows the div with id = fourWheelers
      }
}
</script>
</code>```

and put a class to the div of your "twoWheeler" and "fourWheeler"

I just make it "wheels"

```<code> <div id="twoWheelers" class="wheels">
 ...
 </div>

 <div id="fourWheelers" class="wheels">
 ...
 </div>
</code>```

Body:
hi i am very new to jquery and i am working on show and hide div tags using values of radio buttons. here is my HTML.

    <input type="radio" name="vehicleList" id="two" onclick="fuelList()" value="1" />Two Wheeler

    <input type="radio" name="vehicleList" id="four" onclick="fuelList()" value="2" />Four Wheeler

    <input type="radio" name="TwoWheeler" value="6" />Electric

    <input type="radio" name="TwoWheeler" value="7" />Petrol

    <input type="radio" name="FourWheeler" value="1" />Electric

    <input type="radio" name="FourWheeler" value="2" />Petrol

    <input type="radio" name="FourWheeler" value="3" />Diesel

    <input type="radio" name="FourWheeler" value="4" />CNG

    <input type="radio" name="FourWheeler" value="5" />LPG

now i need help in writing a jquery code for showing the div tag with id = "two wheeler" when radio button value = 1 and div tag with id = "four wheeler" when radio button value = 2.

thnaks in advance.

sorry for anyone who couldnt understand my question.

Body:
My first suggestion is to change your onclick="" to onchange="".

<input type="radio" name="vehicleList" id="four" onchange="fuelList(this)" value="2"  class="radioButtons" />Four Wheeler

<script>
 function fuelList(element)
{
   var id = element.value;
   if( id == 1)
     {
      $(".wheels")hide(); //hides all the elements with class = wheels
      $("#twoWheelers")show(); //shows the div with id = twoWheelers
     }
    else if( id == 2 )
     {
      $(".wheels")hide(); //hides all the elements with class = wheels
      $("#fourWheelers")show(); //shows the div with id = fourWheelers
      }
}
</script>

and put a class to the div of your "twoWheeler" and "fourWheeler"

I just make it "wheels"

 <div id="twoWheelers" class="wheels">
 ...
 </div>

 <div id="fourWheelers" class="wheels">
 ...
 </div>


问:
Update UITableView height when tweet loaded
I have a UITableViewCell which contains a TWTRTweetView with auto layout. I am loading a tweet like this:

```<code>- (void)loadTweetWithId:(NSString *)tweetId {

    if (mTweetId == nil || ![mTweetId isEqualToString:tweetId]) {
        mTweetId = tweetId;
        [[[TWTRAPIClient alloc] init] loadTweetWithID:tweetId completion:^(TWTRTweet *tweet, NSError *error) {
            if (tweet) {
                NSLog(@"Tweet loaded!");
                [mTweetView configureWithTweet:tweet];
                [mTweetView setShowActionButtons:YES];
                //[mTweetView setDelegate:self];
                [mTweetView setPresenterViewController:self.viewController];
                [mTweetView setNeedsLayout];
                [mTweetView layoutIfNeeded];
                [mTweetView layoutSubviews];
                hc.constant = mTweetView.frame.size.height;
                [self updateConstraints];
                [self layoutIfNeeded];
                [self layoutSubviews];
                [self.tableView setNeedsLayout];
                [self.tableView layoutIfNeeded];
                [self.tableView layoutSubviews];
            } else {
                NSLog(@"Tweet load error: %@", [error localizedDescription]);
            }
        }];
    }
}
</code>```

When tweet loaded cell doesn't resize unless I scroll it out and scroll it to back. I have tried several approaches as you can see in code snippet. But non of these works. My table view uses full auto layout approach which doesn't implement cell height for row function. How can i fix this?

UPDATE:

Using:

```<code>[self.tableView beginUpdates];
[self.tableView endUpdates];
</code>```

is not possible because when I do that all cells being redrawn and very big jumping happens and that is not acceptable. Also I have confirmed that tweet completion block runs in main thread.

UPDATE 2:

I have also tried to cache tweet view with tweet id and reload cell for related index path and give the same tweet view for tweet id. The cell height is corrected but it doesn't become visible until scroll out/in.

UPDATE 3:

I give constraints to tweet view in xib of the cell and height constraint is connected. So this is not a main thread issue. I have also mentioned that reloading particular cell at index doesn't work.

While working an other solution I have seen some sample TwitterKit codes that uses TWTRTweetTableViewCell but was preloading tweets to configure the cells. So I have done the same. This is a workaround of course.

答:
I had the similar issue and i got that fixed by adding all my code in dispatch_async to make sure its running on main thread.

```<code> dispatch_async(dispatch_get_main_queue(), ^{
      /*CODE HERE*/
 });
</code>```

So your code should be like this:

```<code>- (void)loadTweetWithId:(NSString *)tweetId {

  if (mTweetId == nil || ![mTweetId isEqualToString:tweetId]) {
      mTweetId = tweetId;
    [[[TWTRAPIClient alloc] init] loadTweetWithID:tweetId completion:^(TWTRTweet *tweet, NSError *error) {

        dispatch_async(dispatch_get_main_queue(), ^{

        if (tweet) {
            NSLog(@"Tweet loaded!");
            [mTweetView configureWithTweet:tweet];
            [mTweetView setShowActionButtons:YES];
            //[mTweetView setDelegate:self];
            [mTweetView setPresenterViewController:self.viewController];
            [mTweetView setNeedsLayout];
            [mTweetView layoutIfNeeded];
            [mTweetView layoutSubviews];
            hc.constant = mTweetView.frame.size.height;
            [self updateConstraints];
            [self layoutIfNeeded];
            [self layoutSubviews];
            [self.tableView setNeedsLayout];
            [self.tableView layoutIfNeeded];
            [self.tableView layoutSubviews];
        } else {
            NSLog(@"Tweet load error: %@", [error localizedDescription]);
        }

    });

    }];
  }
 }
</code>```

Body:
I have a UITableViewCell which contains a TWTRTweetView with auto layout. I am loading a tweet like this:

- (void)loadTweetWithId:(NSString *)tweetId {

    if (mTweetId == nil || ![mTweetId isEqualToString:tweetId]) {
        mTweetId = tweetId;
        [[[TWTRAPIClient alloc] init] loadTweetWithID:tweetId completion:^(TWTRTweet *tweet, NSError *error) {
            if (tweet) {
                NSLog(@"Tweet loaded!");
                [mTweetView configureWithTweet:tweet];
                [mTweetView setShowActionButtons:YES];
                //[mTweetView setDelegate:self];
                [mTweetView setPresenterViewController:self.viewController];
                [mTweetView setNeedsLayout];
                [mTweetView layoutIfNeeded];
                [mTweetView layoutSubviews];
                hc.constant = mTweetView.frame.size.height;
                [self updateConstraints];
                [self layoutIfNeeded];
                [self layoutSubviews];
                [self.tableView setNeedsLayout];
                [self.tableView layoutIfNeeded];
                [self.tableView layoutSubviews];
            } else {
                NSLog(@"Tweet load error: %@", [error localizedDescription]);
            }
        }];
    }
}

When tweet loaded cell doesn't resize unless I scroll it out and scroll it to back. I have tried several approaches as you can see in code snippet. But non of these works. My table view uses full auto layout approach which doesn't implement cell height for row function. How can i fix this?

UPDATE:

Using:

[self.tableView beginUpdates];
[self.tableView endUpdates];

is not possible because when I do that all cells being redrawn and very big jumping happens and that is not acceptable. Also I have confirmed that tweet completion block runs in main thread.

UPDATE 2:

I have also tried to cache tweet view with tweet id and reload cell for related index path and give the same tweet view for tweet id. The cell height is corrected but it doesn't become visible until scroll out/in.

UPDATE 3:

I give constraints to tweet view in xib of the cell and height constraint is connected. So this is not a main thread issue. I have also mentioned that reloading particular cell at index doesn't work.

While working an other solution I have seen some sample TwitterKit codes that uses TWTRTweetTableViewCell but was preloading tweets to configure the cells. So I have done the same. This is a workaround of course.

Body:
I had the similar issue and i got that fixed by adding all my code in dispatch_async to make sure its running on main thread.

 dispatch_async(dispatch_get_main_queue(), ^{
      /*CODE HERE*/
 });

So your code should be like this:

- (void)loadTweetWithId:(NSString *)tweetId {

  if (mTweetId == nil || ![mTweetId isEqualToString:tweetId]) {
      mTweetId = tweetId;
    [[[TWTRAPIClient alloc] init] loadTweetWithID:tweetId completion:^(TWTRTweet *tweet, NSError *error) {

        dispatch_async(dispatch_get_main_queue(), ^{

        if (tweet) {
            NSLog(@"Tweet loaded!");
            [mTweetView configureWithTweet:tweet];
            [mTweetView setShowActionButtons:YES];
            //[mTweetView setDelegate:self];
            [mTweetView setPresenterViewController:self.viewController];
            [mTweetView setNeedsLayout];
            [mTweetView layoutIfNeeded];
            [mTweetView layoutSubviews];
            hc.constant = mTweetView.frame.size.height;
            [self updateConstraints];
            [self layoutIfNeeded];
            [self layoutSubviews];
            [self.tableView setNeedsLayout];
            [self.tableView layoutIfNeeded];
            [self.tableView layoutSubviews];
        } else {
            NSLog(@"Tweet load error: %@", [error localizedDescription]);
        }

    });

    }];
  }
 }


问:
Mobile Website Optimization
I'm making a new website. It will be blog style, but made from scratch rather than using existing templates or software (like WordPress) mainly for the sake of experimentation.

My question is, what should I do to make the site optimized for mobile devices? I'd like to optimize it with a style that's made to fit on smaller screens, but without creating a separate page and redirecting based on the device the user is viewing on. Basically, I want to create one page of content, two stylesheets, and a surefire way of the making the appropriate stylesheet apply based on what type of device the user is viewing on.

What's the best method of doing this?

答:
Creating separate stylesheets for both variations is a great idea but as you said "optimized for mobile", simply having customized CSS is not enough.
There are other factors which make a website mobile friendly like website loading speed, content, user experience on mobile etc.

To dive more into this topic you can take help of this post on mobile optimization.

Title: Mobile Website Optimization


问:
Why does spread syntax convert my string into an array?
Why does spread syntax convert my string into an array?

```<code>var v = 'hello';
var [, ...w] = v; // ["e", "l", "l", "o"]
</code>```

Why is w not a string?

答:
Spread syntax (actually a punctuator as noted by RobG) allows for iterables to be spread into smaller bits. Since strings are iterables (they're character arrays internally, more specifically ordered sequences of integers representing characters), they can be spread into individual characters.

Next, destructuring assignment is performed on the array to unpack and group the spread values. Since you ommit the first element of the character array with , and don't assign a reference, it's lost, and the rest of the iterable object is saved into w, spread into it's individual parts, single characters of the character array.

The specific semantics of this operation are defined in the ECMAScript 2015 Specification by the ArrayAssignmentPattern : [ Elisionopt AssignmentRestElement ] production:

12.14.5.2 Runtime Semantics: DestructuringAssignmentEvaluation

with parameter value

[...]

ArrayAssignmentPattern : [ Elisionopt AssignmentRestElement ]

Let iterator be GetIterator(value).

ReturnIfAbrupt(iterator).

Let iteratorRecord be Record {[[iterator]]: iterator, [[done]]: false}.

If Elision is present, then

a. Let status be the result of performing IteratorDestructuringAssignmentEvaluation of Elision with iteratorRecord as the argument.

b. If status is an abrupt completion, then

    i. If iteratorRecord.[[done]] is false, return IteratorClose(iterator, status).

    ii. Return Completion(status).

Let result be the result of performing IteratorDestructuringAssignmentEvaluation of AssignmentRestElement with iteratorRecord as the argument.

If iteratorRecord.[[done]] is false, return IteratorClose(iterator, result).

Return result.

Here, Elision refers to an omitted element when spreading with one or more commas (,), comparable to omitted syllables as the name suggests, and AssignmentRestElement refers to the target that will receive the spread and destructured values, w in this case.

What this does is first get the iterator of the object, from the internal @@iterator method and steps through that iterator, skipping however many elements indicated by the elision's width by the Elision production in IteratorDestructuringAssignmentEvaluation. Once that's done, it will step through the iterator of the AssignmentRestElement production, and assign a new array with all the spread values -- that's what w is. It receives the spread out single-character array, unpacked to exclude the first character.

The @@iterator method in which the iteration is gotten from is a well-known Symbol and changing it for an object can change how it's iterated, as in Emissary's answer. Specifically, the default implementation of the @@iterator method for String is as follows:

21.1.3.27 String.prototype [ @@iterator ]( )

When the @@iterator method is called it returns an Iterator object (25.1.1.2) that iterates over the code points of a String value, returning each code point as a String value.

Thus, the iterator allows for iteration through single code points, or characters of a string -- and consequently spreading the string will result in an array of its characters.

Body:
Why does spread syntax convert my string into an array?

var v = 'hello';
var [, ...w] = v; // ["e", "l", "l", "o"]

Why is w not a string?


问:
How to export MYSQL Database tables from one server to another
How do I export and import MYSQL database selected tables(not all) from one machine to another machine ?

cheers

答:
mysqldump [options] db_name [tables] and then load them using mysql -u root -p < backup.sql

Or rsync /var/lib/mysql/ ...

OwnerDisplayName: Neel

OwnerDisplayName: Aif


问:
Convert to date format dd/mm/yyyy
I have the following date: 2010-04-19 18:31:27. I would like to convert this date to the dd/mm/yyyy format.

答:
```<code>$source    =    'your varible name';
$date    =     new DateTime($source);
$_REQUEST["date"]    =     $date->format('d-m-Y');

echo $_REQUEST["date"];
</code>```

Title: Convert to date format dd/mm/yyyy


问:
Angular UI-Router: How to call child state without its parent?
We have recently move our application to Ui-Router from ng-route. And we are trying to refactor some points in our code regarding routing.

We have a list view and a detail view in our application. The detail view will be shown as a pop-up on top of the list view, so in order not to initialize all list controller logic again and again, we have defined our detail view as a child view-state. It looks like this:

```<code>  $stateProvider
    .state('list',
      {
        url: "/",
        template: '<list-directive></list-directive>'
      })
    .state('list.detail',
      {
        url: "/detail/{item_id}",
        template: '<detail-directive></detail-directive>'
      })
</code>```

It actually works as expected. When i open a detail view from a list view, the list view (i mean the controller) does not run again, and when i close the detail view, the list view remains.

But now we would also like to call the detail view DIRECTLY, without revoking the parent. Currently when i directly call the detail state, the parent controller runs also.. How can i achieve this?

Is a parent - child relationship not a appropriate one for our scenario?

答:
According ui-router doc :

Child states can be used to drill down from a more general feature to
  more specific one, or to implement a master/detail pattern. (...) The child state’s view usually renders inside a viewport that the parent state created. This is referred to as Nested Views (...) These substates share the common parent state contacts and inherit data and behavior from the parent.

So I think you should use it if you don't want these behaviour .

Body:
We have recently move our application to Ui-Router from ng-route. And we are trying to refactor some points in our code regarding routing.

We have a list view and a detail view in our application. The detail view will be shown as a pop-up on top of the list view, so in order not to initialize all list controller logic again and again, we have defined our detail view as a child view-state. It looks like this:

  $stateProvider
    .state('list',
      {
        url: "/",
        template: '<list-directive></list-directive>'
      })
    .state('list.detail',
      {
        url: "/detail/{item_id}",
        template: '<detail-directive></detail-directive>'
      })

It actually works as expected. When i open a detail view from a list view, the list view (i mean the controller) does not run again, and when i close the detail view, the list view remains.

But now we would also like to call the detail view DIRECTLY, without revoking the parent. Currently when i directly call the detail state, the parent controller runs also.. How can i achieve this?

Is a parent - child relationship not a appropriate one for our scenario?


问:
xmppframework - enable log for send / receive
I'm working on chat app using xmppframework in iOS. The framework contain sample demo that print send and receive log for xml. Now I implement same things in my app but no log is showing.

Example of log for sample app

```<code>2014-05-08 16:34:15:993 iPhoneXMPP[4839:1403] SEND: <?xml version='1.0'?>
2014-05-08 16:34:15:994 iPhoneXMPP[4839:1403] SEND: <stream:stream xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' version='1.0' to='meinantrieb.net'>
2014-05-08 16:34:16:384 iPhoneXMPP[4839:3503] RECV: <stream:stream xmlns="jabber:client" xmlns:stream="http://etherx.jabber.org/streams" id="1364620848" from="meinantrieb.net" version="1.0" stream1:lang="en"/>
2014-05-08 16:34:16:384 iPhoneXMPP[4839:3503] RECV: <stream:features xmlns:stream="http://etherx.jabber.org/streams"><starttls xmlns="urn:ietf:params:xml:ns:xmpp-tls"/><mechanisms xmlns="urn:ietf:params:xml:ns:xmpp-sasl"><mechanism>SCRAM-SHA-1</mechanism><mechanism>ANONYMOUS</mechanism><mechanism>DIGEST-MD5</mechanism><mechanism>PLAIN</mechanism></mechanisms><c xmlns="http://jabber.org/protocol/caps" hash="sha-1" node="http://www.process-one.net/en/ejabberd/" ver="GgBjinftMQ4H81m+4jSVXMg/dVU="/><register xmlns="http://jabber.org/features/iq-register"/></stream:features>
</code>```

Code For Adding Log in AppDelegate.m

```#import "DDLog.h"
#import "DDTTYLogger.h"

// Log levels: off, error, warn, info, verbose
#if DEBUG
static const int ddLogLevel = LOG_LEVEL_VERBOSE;
#else
static const int ddLogLevel = LOG_LEVEL_INFO;
#endif```

```<code>- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Configure logging framework
    [DDLog addLogger:[DDTTYLogger sharedInstance]];
}
</code>```

Any help or suggestion will be well appreciated.

答:
With Swift 3.x, DDLog log levels are an enum, so it's not immediately possible to apply the XMPPFramework log levels.

One can enable all log messages:

DDLog.add(DDTTYLogger.sharedInstance, with: .all)
```

Body:
I'm working on chat app using xmppframework in iOS. The framework contain sample demo that print send and receive log for xml. Now I implement same things in my app but no log is showing.

Example of log for sample app

2014-05-08 16:34:15:993 iPhoneXMPP[4839:1403] SEND: <?xml version='1.0'?>
2014-05-08 16:34:15:994 iPhoneXMPP[4839:1403] SEND: <stream:stream xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' version='1.0' to='meinantrieb.net'>
2014-05-08 16:34:16:384 iPhoneXMPP[4839:3503] RECV: <stream:stream xmlns="jabber:client" xmlns:stream="http://etherx.jabber.org/streams" id="1364620848" from="meinantrieb.net" version="1.0" stream1:lang="en"/>
2014-05-08 16:34:16:384 iPhoneXMPP[4839:3503] RECV: <stream:features xmlns:stream="http://etherx.jabber.org/streams"><starttls xmlns="urn:ietf:params:xml:ns:xmpp-tls"/><mechanisms xmlns="urn:ietf:params:xml:ns:xmpp-sasl"><mechanism>SCRAM-SHA-1</mechanism><mechanism>ANONYMOUS</mechanism><mechanism>DIGEST-MD5</mechanism><mechanism>PLAIN</mechanism></mechanisms><c xmlns="http://jabber.org/protocol/caps" hash="sha-1" node="http://www.process-one.net/en/ejabberd/" ver="GgBjinftMQ4H81m+4jSVXMg/dVU="/><register xmlns="http://jabber.org/features/iq-register"/></stream:features>

Code For Adding Log in AppDelegate.m

#import "DDLog.h"
#import "DDTTYLogger.h"

// Log levels: off, error, warn, info, verbose
#if DEBUG
static const int ddLogLevel = LOG_LEVEL_VERBOSE;
#else
static const int ddLogLevel = LOG_LEVEL_INFO;
#endif

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Configure logging framework
    [DDLog addLogger:[DDTTYLogger sharedInstance]];
}

Any help or suggestion will be well appreciated.


问:
Best practice to implement classes if every object behaves differently in Java
Let's take a real-world example.

Suppose, I have three Dogs, but one dog can differ from the other.

The first dog likes barking and eating, the second dog likes playing and chasing cats and the third dog likes running and jogging (consider these actions as methods).

How do I implement this in Java? What I have to use, what is the best practice? Abstract classes, interfaces or both of them?

答:
I'd implement this as using a single Dog class and composition for behaviours

```<code>public interface Behaviour { void action(); }

public class Bark implements Behaviour {...}
public class ChaseCat implements Behaviour { ... }
public class Eat implements Behaviour {...}
public class Sleep implements Behaviour {...}
... others
public class Dog {

  private List<Behaviour> behaviours;

  public Dog(Behaviour...behaviors) { this.behaviors = Arrays.asList(behaviours); }

  public void play() {
   // choose random behaviour
   behaviour.action();
  }
}

Dog dog1 = new Dog(new ChaseCat(), new Bark());
Dog dog2 = new Dog(new Eat(), new Sleep());
</code>```

The benefit of this approach is if you expose methods to manage behaviours on the Dog class you can even modify the behaviour as your application is running. For example if a cat scares a dog you can have a method to remove that behaviour for a while and your dog will not do it. Then you can add it later. You get the point.

Body:
I'd implement this as using a single Dog class and composition for behaviours

public interface Behaviour { void action(); }

public class Bark implements Behaviour {...}
public class ChaseCat implements Behaviour { ... }
public class Eat implements Behaviour {...}
public class Sleep implements Behaviour {...}
... others
public class Dog {

  private List<Behaviour> behaviours;

  public Dog(Behaviour...behaviors) { this.behaviors = Arrays.asList(behaviours); }

  public void play() {
   // choose random behaviour
   behaviour.action();
  }
}

Dog dog1 = new Dog(new ChaseCat(), new Bark());
Dog dog2 = new Dog(new Eat(), new Sleep());

The benefit of this approach is if you expose methods to manage behaviours on the Dog class you can even modify the behaviour as your application is running. For example if a cat scares a dog you can have a method to remove that behaviour for a while and your dog will not do it. Then you can add it later. You get the point.


问:
issue with extracting metadata of an image
I wrote a python code to get metadata of a certain image but I get this error:

NameError: global name '_get_if_exist' is not defined

Have you any idea how to fixe it.

```<code>from PIL import Image
from PIL.ExifTags import TAGS, GPSTAGS

def get_exif_data(image):
exif_data = {}
info = getattr(image, '_getexif', lambda: None)()
if info:
    for tag, value in info.items():
        decoded = TAGS.get(tag, tag)
        if decoded == "GPSInfo":
            gps_data = {}
            for t in value:
                sub_decoded = GPSTAGS.get(t, t)
                gps_data[sub_decoded] = value[t]

            exif_data[decoded] = gps_data
        else:
            exif_data[decoded] = value

return exif_data

return data.get(key, None)

 def _convert_to_degress(value):
  d0 = value[0][0]
  d1 = value[0][1]
  d = float(d0) / float(d1)

 m0 = value[1][0]
 m1 = value[1][1]
 m = float(m0) / float(m1)

 s0 = value[2][0]
 s1 = value[2][1]
 s = float(s0) / float(s1)

return d + (m / 60.0) + (s / 3600.0)

def get_lat_lon(exif_data):

 lat = None
 lon = None

if "GPSInfo" in exif_data:
    gps_info = exif_data["GPSInfo"]

    gps_latitude = _get_if_exist(gps_info, "GPSLatitude")
    gps_latitude_ref = _get_if_exist(gps_info, 'GPSLatitudeRef')
    gps_longitude = _get_if_exist(gps_info, 'GPSLongitude')
    gps_longitude_ref = _get_if_exist(gps_info, 'GPSLongitudeRef')

    if gps_latitude and gps_latitude_ref and gps_longitude and
    gps_longitude_ref:
        lat = _convert_to_degress(gps_latitude)
        if gps_latitude_ref != "N":
            lat = 0 - lat

        lon = _convert_to_degress(gps_longitude)
        if gps_longitude_ref != "E":
            lon = 0 - lon

return lat, lon

if __name__ == "__main__":
image =
Image.open("C:\\Users\\Mouqsit\\Desktop\\Bouznika_Panos_Complement\\*.jp
g")
exif_data = get_exif_data(image)
print get_lat_lon(exif_data)
</code>```

this code is to extract gps metadata from an image

答:
_get_if_exist() helper does not exist by default nor it's imported. Its code is:

```<code>def _get_if_exist(data, key):
    if key in data:
        return data[key]
    return None
</code>```

The original is here

Body:
I wrote a python code to get metadata of a certain image but I get this error:

NameError: global name '_get_if_exist' is not defined

Have you any idea how to fixe it.

from PIL import Image
from PIL.ExifTags import TAGS, GPSTAGS

def get_exif_data(image):
exif_data = {}
info = getattr(image, '_getexif', lambda: None)()
if info:
    for tag, value in info.items():
        decoded = TAGS.get(tag, tag)
        if decoded == "GPSInfo":
            gps_data = {}
            for t in value:
                sub_decoded = GPSTAGS.get(t, t)
                gps_data[sub_decoded] = value[t]

            exif_data[decoded] = gps_data
        else:
            exif_data[decoded] = value

return exif_data

return data.get(key, None)

 def _convert_to_degress(value):
  d0 = value[0][0]
  d1 = value[0][1]
  d = float(d0) / float(d1)

 m0 = value[1][0]
 m1 = value[1][1]
 m = float(m0) / float(m1)

 s0 = value[2][0]
 s1 = value[2][1]
 s = float(s0) / float(s1)

return d + (m / 60.0) + (s / 3600.0)

def get_lat_lon(exif_data):

 lat = None
 lon = None

if "GPSInfo" in exif_data:
    gps_info = exif_data["GPSInfo"]

    gps_latitude = _get_if_exist(gps_info, "GPSLatitude")
    gps_latitude_ref = _get_if_exist(gps_info, 'GPSLatitudeRef')
    gps_longitude = _get_if_exist(gps_info, 'GPSLongitude')
    gps_longitude_ref = _get_if_exist(gps_info, 'GPSLongitudeRef')

    if gps_latitude and gps_latitude_ref and gps_longitude and
    gps_longitude_ref:
        lat = _convert_to_degress(gps_latitude)
        if gps_latitude_ref != "N":
            lat = 0 - lat

        lon = _convert_to_degress(gps_longitude)
        if gps_longitude_ref != "E":
            lon = 0 - lon

return lat, lon

if __name__ == "__main__":
image =
Image.open("C:\\Users\\Mouqsit\\Desktop\\Bouznika_Panos_Complement\\*.jp
g")
exif_data = get_exif_data(image)
print get_lat_lon(exif_data)

this code is to extract gps metadata from an image

Body:
_get_if_exist() helper does not exist by default nor it's imported. Its code is:

def _get_if_exist(data, key):
    if key in data:
        return data[key]
    return None

The original is here


问:
Files images, docx corrupted/cant open when download from server
Pdf files are OK but files images, docx cant open/corrupted when I download from server   </p>

```<code>$file = APPPATH . '/upload/filename.jpg';

if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');

    header('Content-Disposition: attachment; filename="'.basename($file).'"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    readfile($file);
    exit;
}
</code>```

答: The official way with Codeigniter is to use the Download helper: https://www.codeigniter.com/user_guide/helpers/download_helper.html. In your instance you may be better off trying http://php.net/manual/en/function.is-readable.php is_readable() as this checks for existance as well as if PHP can read (to then use) it.

Body:
Pdf files are OK but files images, docx cant open/corrupted when I download from server

$file = APPPATH . '/upload/filename.jpg';

if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');

    header('Content-Disposition: attachment; filename="'.basename($file).'"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    readfile($file);
    exit;
}


问:
deleting multiple numbered folders in the terminal
I have directories numbered from 0-1000, for example. I want to delete the directories within the range 400-699, for example, and all their contents on the terminal. Is there a way to do this without me having to do rm -rf XXX where XXX is the directory number?

I have seen this post link but the numbering system we have is a bit different.

答: Use wildcards so you won't have to do this 300 times. Try this: rm -rf 4* 5* 6*


答:
Because a string in javascript is sort of treated like an array of characters.

For example, when you do a for each loop over a string (let's say hello), with lodash:

```<code>_.forEach('hello', function(i) {
    console.log(i)
})
</code>```

it outputs:

```<code>h
e
l
l
o
</code>```

Functions like slice() also work on both strings and arrays.

Title: Why does spread syntax convert my string into an array?

Body:
Because a string in javascript is sort of treated like an array of characters.

For example, when you do a for each loop over a string (let's say hello), with lodash:

_.forEach('hello', function(i) {
    console.log(i)
})

it outputs:

h
e
l
l
o

Functions like slice() also work on both strings and arrays.


问:
Spring @AutoWired always null
I'm trying to call SOAP service from another system on my program. I've generated the java classes needed from WSDL by using wsimport command.

Here's my program's configuration

 web.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <display-name>PTDAM Promo Engine</display-name>
    <description>Promo Engine using Elastic Search</description>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/cxf-servlet.xml</param-value>

    </context-param>

    <context-param>
        <param-name>webAppRootKey</param-name>
        <param-value>promoengine</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <servlet>
        <servlet-name>CXFServlet</servlet-name>
        <display-name>CXF Servlet</display-name>
        <servlet-class>
            org.apache.cxf.transport.servlet.CXFServlet
        </servlet-class>
        <load-on-startup>2</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>CXFServlet</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>

</web-app>
</code>```

and here's my xml configuration file where i store the config location

UPDATE: added ESCreditRunner class as a bean below, and still got the same error

cxf-servlet.xml

```<code>    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:context="http://www.springframework.org/schema/context"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxrs="http://cxf.apache.org/jaxrs"
           xmlns:cxf="http://cxf.apache.org/core" xmlns:jaxws="http://cxf.apache.org/jaxws"
           xmlns:sec="http://cxf.apache.org/configuration/security" xmlns:http="http://cxf.apache.org/transports/http/configuration"
           xmlns:http-conf="http://cxf.apache.org/transports/http/configuration"

           xsi:schemaLocation="http://www.springframework.org/schema/beans
                      http://www.springframework.org/schema/beans/spring-beans.xsd
                      http://cxf.apache.org/transports/http/configuration
                      http://cxf.apache.org/schemas/configuration/http-conf.xsd
                  http://cxf.apache.org/configuration/security
                  http://cxf.apache.org/schemas/configuration/security.xsd
                  http://cxf.apache.org/jaxrs
                  http://cxf.apache.org/schemas/jaxrs.xsd
                  http://cxf.apache.org/core
                  http://cxf.apache.org/schemas/core.xsd
                  http://cxf.apache.org/jaxws
                  http://cxf.apache.org/schemas/jaxws.xsd
                  http://www.springframework.org/schema/context
                  http://www.springframework.org/schema/context/spring-context-3.0.xsd">

         <!-- use this to enable @AutoWired -->
         <context:annotation-config />
         <context:component-scan base-package="ptdam.emoney.webservice.transactions" />

         <import resource="classpath:META-INF/cxf/cxf.xml" />
         <import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" />
         <import resource="classpath:META-INF/cxf/cxf-servlet.xml" />

        <!-- Client -->
        <jaxws:client id="topupWebService"
            serviceClass="ptdam.emoney.webservice.transactions.TopupWebService"
            address="http://localhost:8080/ecash-core-engine-dev-mitigasi/services/emoneytopup"

<!-- Beans -->
    <bean id="esCreditRunner" class="com.ptdam.promo.services.ESCreditRunner" />
        />
    </beans>
</code>```

and here's how i use the @AutoWired, to call the SOAP service topupWebService.. on the testCall() method

ESCreditRunner.java

```<code>package ptdam.emoney.webservice.transactions;
public class ESCreditRunner {
        private File statusFile;
        private Properties status;
        private static final Logger logger = Logger.getLogger(ESCreditRunner.class);

        @Autowired
        private TopupWebService topupWebService;
        public void setTopupWebService(TopupWebService topupWebService) {
            this.topupWebService = topupWebService;
        }

        // testing 04/07/2017
        public void testCall(){
            topupWebService.echoTest("Luki");
        }
    }
</code>```

when i run the testCall() method, i always get NullPointerException on the topupWebService variable. It looks like it's not injected properly..

what i'm missing here?

Update:
i've made another thread as a continuation of this thread. Kindly check it here :) Spring WebService with Endpoint vs no Endpoint

答: You should set the annotation @Component on the class ESCreditRunner

Title: Spring @AutoWired always null

Body:
I'm trying to call SOAP service from another system on my program. I've generated the java classes needed from WSDL by using wsimport command.

Here's my program's configuration

 web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <display-name>PTDAM Promo Engine</display-name>
    <description>Promo Engine using Elastic Search</description>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/cxf-servlet.xml</param-value>

    </context-param>

    <context-param>
        <param-name>webAppRootKey</param-name>
        <param-value>promoengine</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <servlet>
        <servlet-name>CXFServlet</servlet-name>
        <display-name>CXF Servlet</display-name>
        <servlet-class>
            org.apache.cxf.transport.servlet.CXFServlet
        </servlet-class>
        <load-on-startup>2</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>CXFServlet</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>

</web-app>

and here's my xml configuration file where i store the config location

UPDATE: added ESCreditRunner class as a bean below, and still got the same error

cxf-servlet.xml

    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:context="http://www.springframework.org/schema/context"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxrs="http://cxf.apache.org/jaxrs"
           xmlns:cxf="http://cxf.apache.org/core" xmlns:jaxws="http://cxf.apache.org/jaxws"
           xmlns:sec="http://cxf.apache.org/configuration/security" xmlns:http="http://cxf.apache.org/transports/http/configuration"
           xmlns:http-conf="http://cxf.apache.org/transports/http/configuration"

           xsi:schemaLocation="http://www.springframework.org/schema/beans
                      http://www.springframework.org/schema/beans/spring-beans.xsd
                      http://cxf.apache.org/transports/http/configuration
                      http://cxf.apache.org/schemas/configuration/http-conf.xsd
                  http://cxf.apache.org/configuration/security
                  http://cxf.apache.org/schemas/configuration/security.xsd
                  http://cxf.apache.org/jaxrs
                  http://cxf.apache.org/schemas/jaxrs.xsd
                  http://cxf.apache.org/core
                  http://cxf.apache.org/schemas/core.xsd
                  http://cxf.apache.org/jaxws
                  http://cxf.apache.org/schemas/jaxws.xsd
                  http://www.springframework.org/schema/context
                  http://www.springframework.org/schema/context/spring-context-3.0.xsd">

         <context:annotation-config />
         <context:component-scan base-package="ptdam.emoney.webservice.transactions" />

         <import resource="classpath:META-INF/cxf/cxf.xml" />
         <import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" />
         <import resource="classpath:META-INF/cxf/cxf-servlet.xml" />

        <jaxws:client id="topupWebService"
            serviceClass="ptdam.emoney.webservice.transactions.TopupWebService"
            address="http://localhost:8080/ecash-core-engine-dev-mitigasi/services/emoneytopup"

    <bean id="esCreditRunner" class="com.ptdam.promo.services.ESCreditRunner" />
        />
    </beans>

and here's how i use the @AutoWired, to call the SOAP service topupWebService.. on the testCall() method

ESCreditRunner.java

package ptdam.emoney.webservice.transactions;
public class ESCreditRunner {
        private File statusFile;
        private Properties status;
        private static final Logger logger = Logger.getLogger(ESCreditRunner.class);

        @Autowired
        private TopupWebService topupWebService;
        public void setTopupWebService(TopupWebService topupWebService) {
            this.topupWebService = topupWebService;
        }

        // testing 04/07/2017
        public void testCall(){
            topupWebService.echoTest("Luki");
        }
    }

when i run the testCall() method, i always get NullPointerException on the topupWebService variable. It looks like it's not injected properly..

what i'm missing here?

Update:
i've made another thread as a continuation of this thread. Kindly check it here :) Spring WebService with Endpoint vs no Endpoint