问:
wavy divs border with css or any lib
Need to make wavy div borders like this:

here is two divs with image backgrounds..
everywhere I find solution to make svg or do something like this:

.wave {
  height: 50px;
  position: relative;
}

.wave::before {
  content: "";
  position: absolute;
  left: 0;
  bottom: 0;
  right: 0;
  background-repeat: repeat;
  height: 10px;
  background-size: 20px 20px;
  background-image: radial-gradient(circle at 10px -5px, transparent 12px, aquamarine 13px);
}

.wave::after {
  content: "";
  position: absolute;
  left: 0;
  bottom: 0;
  right: 0;
  background-repeat: repeat;
  height: 15px;
  background-size: 40px 20px;
  background-image: radial-gradient(circle at 10px 15px, aquamarine 12px, transparent 13px);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wave"></div></code>```

but in both solution if make background color transparent it has no effect..

so how could make div with curved edge?

Title: wavy divs border with css or any lib

Body:
Need to make wavy div borders like this:

here is two divs with image backgrounds..
everywhere I find solution to make svg or do something like this:

.wave {
  height: 50px;
  position: relative;
}

.wave::before {
  content: "";
  position: absolute;
  left: 0;
  bottom: 0;
  right: 0;
  background-repeat: repeat;
  height: 10px;
  background-size: 20px 20px;
  background-image: radial-gradient(circle at 10px -5px, transparent 12px, aquamarine 13px);
}

.wave::after {
  content: "";
  position: absolute;
  left: 0;
  bottom: 0;
  right: 0;
  background-repeat: repeat;
  height: 15px;
  background-size: 40px 20px;
  background-image: radial-gradient(circle at 10px 15px, aquamarine 12px, transparent 13px);
}

but in both solution if make background color transparent it has no effect..

so how could make div with curved edge?

Body:
You need a svg path to clip the first image with clip-path css/svg property.

SVG/CSS solution:

img{
  float:left;
  clear:both;
  width:260px;
  height:260px;
}

.clipped{
  z-index:10;
  position:relative;
  margin-bottom:-20px;
  -webkit-clip-path: url(#clip);
  clip-path: url(#clip);
}

<img class="clipped" src="http://www.freeimageslive.com/galleries/space/moon/pics/a11_h_40_5878.gif" alt="" />
<img src="http://www.freeimageslive.com/galleries/space/moon/pics/a12_h_55_8221.gif" alt="" />

<svg>
  <defs>
    <clipPath id="clip">
      <path d="M0,0 0,250
               q 15, -20 30,0 q 15, 20 30,0
               q 15, -20 30,0 q 15, 20 30,0
               q 15, -20 30,0 q 15, 20 30,0
               q 15, -20 30,0 q 15, 20 30,0
               q 15, -20 30,0 q 15, 20 30,0
               q 15, -20 30,0 q 15, 20 30,0
               q 15, -20 30,0 q 15, 20 30,0
               q 15, -20 30,0 q 15, 20 30,0
               q 15, -20 30,0 q 15, 20 30,0
               q 15, -20 30,0 q 15, 20 30,0
               v-250 z"/>
    </clipPath>
  </defs>
</svg>

Pure SVG solution (full cross-browser):

<svg width="400" height="600">
  <defs>
    <clipPath id="clip">
      <path fill="#ffffff" d="M0,0 0,250
               q 15, -20 30,0 q 15, 20 30,0
               q 15, -20 30,0 q 15, 20 30,0
               q 15, -20 30,0 q 15, 20 30,0
               q 15, -20 30,0 q 15, 20 30,0
               q 15, -20 30,0 q 15, 20 30,0
               q 15, -20 30,0 q 15, 20 30,0
               q 15, -20 30,0 q 15, 20 30,0
               q 15, -20 30,0 q 15, 20 30,0
               q 15, -20 30,0 q 15, 20 30,0
               q 15, -20 30,0 q 15, 20 30,0
               v-250 z"/>
    </clipPath>
  </defs>

  <image width="260" height="260" x="0" y="240" xlink:href="http://www.freeimageslive.com/galleries/space/moon/pics/a12_h_55_8221.gif" />

  <image width="260" height="260" x="0" y="0" clip-path="url(#clip)" xlink:href="http://www.freeimageslive.com/galleries/space/moon/pics/a11_h_40_5878.gif" />
</svg>

Example on Codepen


来源: stackexchange

问:
AutoMapper Entity to DTO got eror: has no key defined.Define the key for this EntityType(DTO)
I have a problem with AutoMapper between DTO class and Entity model. I used POCO generator to create Entity, after that i use autoMapper to map Entity to DTO, but i got an error like this:

```<code>Treasury.Model.EntityDTO: : EntityType 'EntityDTO' has no key defined. Define the key for this EntityType.
</code>```

I used some DTO in the partial class of Entity model.

Please help me solve the problem.
Thank in advance

答:
My guess is that you added EntityDTO to the DbContext as a DbSet property, but if this is the Dto and not the actual entity, you don't want that on DbContext.

If this is supposed to be the actual Entity, then you need to add the [Key] attribute to the PK or assign it via FluentAPI mapping.  If you don't have a PK on your table, you need to add one or EF won't work for you.

ContentLicense: CC BY-SA 3.0

Body:
I have a problem with AutoMapper between DTO class and Entity model. I used POCO generator to create Entity, after that i use autoMapper to map Entity to DTO, but i got an error like this:

Treasury.Model.EntityDTO: : EntityType 'EntityDTO' has no key defined. Define the key for this EntityType.

I used some DTO in the partial class of Entity model.

Please help me solve the problem.
Thank in advance


问:
WTL update status bar from child view
In my SDI application i am using the CWTLTabViewCtrl class from this article.

I would like to know how to update the status bar at the main frame from the child view.

The code at the mainfrm.h:

```<code>CreateSimpleStatusBar();

// create tabctrl
CTabViewCtrl m_MainTabCtrl;
m_hWndClient = m_MainTabCtrl.Create(
            m_hWnd, rcDefault, NULL,
            WS_CHILD | WS_VISIBLE, WS_EX_STATICEDGE );
m_MainTabCtrl.AddPeopleTab(L"People);
</code>```

The code at the CTabViewCtrl class:

```<code>class CTabViewCtrl : public CWTLTabViewCtrl
{
public:

    CTabViewCtrl()
    {
    }

    virtual ~CTabViewCtrl()
    {
    }
    void AddPeopleTab(LPCTSTR inTabName)
    {
        auto tabPeople = CTabPeople;
        tabPeople->Create(*this, rcDefault, nullptr, WS_CHILD, WS_EX_STATICEDGE);
        AddTab(inTabName, *tabPeople, FALSE, 0, (LPARAM)theProcessesView);
    }
public:
    DECLARE_WND_SUPERCLASS(NULL, CWTLTabViewCtrl::GetWndClassName())

    BOOL PreTranslateMessage(MSG* pMsg)
    {
            pMsg;
            return FALSE;
    }

    BEGIN_MSG_MAP_EX(CTabViewCtrl)
        REFLECT_NOTIFICATIONS()
        CHAIN_MSG_MAP(CWTLTabViewCtrl)
    END_MSG_MAP()
};
</code>```

The code at my CTabPeople class (from this view i want to update the status bar at the mainfrm.h):

```<code>class CTabPeople : public CWindowImpl<CTabPeople, CListViewCtrl>,
                            public CCustomDraw<CTabPeople>
{
[snip]

public:
    DECLARE_WND_SUPERCLASS(NULL, CListViewCtrl::GetWndClassName())

    BOOL PreTranslateMessage(MSG* pMsg)
    {
        pMsg;
        return FALSE;
    }

    BEGIN_MSG_MAP(CTabPeople)
        MESSAGE_HANDLER(WM_CREATE, OnCreate)
        MESSAGE_HANDLER(WM_CONTEXTMENU, OnContextMenu)
        COMMAND_ID_HANDLER(IDM_PROCESSTAB_REFRESH, OnMenuRefresh)
        REFLECTED_NOTIFY_CODE_HANDLER(LVN_COLUMNCLICK, OnColumnClick)
        CHAIN_MSG_MAP_ALT(CCustomDraw, 1)
    END_MSG_MAP()

    LRESULT OnMenuRefresh(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL&bHandled)
    {
        // Here i would like to update the status bar created at the mainfrm.h
        // something like UISetText(0, L"Updating..");
    }

  [snip]
}
</code>```

From the research i have done it seems that there is two ways to update the status bar:

Directly from the CTabPeople view using the handle of the status bar

By sending a message to the mainfrm loop to update the status bar

My question is how to implement one of the above options in my code.

Thanks.

答:
simply working version of mine:

MainFrm.h:

```<code>class CMainFrame :
    public CFrameWindowImpl<CMainFrame>,
    public CUpdateUI<CMainFrame>,
    public CMessageFilter, public CIdleHandler
{
public:
  DECLARE_FRAME_WND_CLASS(NULL, IDR_MAINFRAME)
  CMainFrame() { this_ptr = this; }
  static CMainFrame* this_ptr;
  void SetStatusText(std::wstring strText);
  //...
}
</code>```

MainFrm.cpp

```<code>CMainFrame* CMainFrame::this_ptr = nullptr;

// m_hWndStatusBar is from atlframe.h
void CMainFrame::SetStatusText(std::wstring strText)
{
  ::SetWindowText(m_hWndStatusBar, strText.c_str());
}
</code>```

other.cpp

```<code>CMainFrame::this_ptr->SetStatusText(L"program ready");
</code>```

Title: WTL update status bar from child view

Body:
In my SDI application i am using the CWTLTabViewCtrl class from this article.

I would like to know how to update the status bar at the main frame from the child view.

The code at the mainfrm.h:

CreateSimpleStatusBar();

// create tabctrl
CTabViewCtrl m_MainTabCtrl;
m_hWndClient = m_MainTabCtrl.Create(
            m_hWnd, rcDefault, NULL,
            WS_CHILD | WS_VISIBLE, WS_EX_STATICEDGE );
m_MainTabCtrl.AddPeopleTab(L"People);

The code at the CTabViewCtrl class:

class CTabViewCtrl : public CWTLTabViewCtrl
{
public:

    CTabViewCtrl()
    {
    }

    virtual ~CTabViewCtrl()
    {
    }
    void AddPeopleTab(LPCTSTR inTabName)
    {
        auto tabPeople = CTabPeople;
        tabPeople->Create(*this, rcDefault, nullptr, WS_CHILD, WS_EX_STATICEDGE);
        AddTab(inTabName, *tabPeople, FALSE, 0, (LPARAM)theProcessesView);
    }
public:
    DECLARE_WND_SUPERCLASS(NULL, CWTLTabViewCtrl::GetWndClassName())

    BOOL PreTranslateMessage(MSG* pMsg)
    {
            pMsg;
            return FALSE;
    }

    BEGIN_MSG_MAP_EX(CTabViewCtrl)
        REFLECT_NOTIFICATIONS()
        CHAIN_MSG_MAP(CWTLTabViewCtrl)
    END_MSG_MAP()
};

The code at my CTabPeople class (from this view i want to update the status bar at the mainfrm.h):

class CTabPeople : public CWindowImpl<CTabPeople, CListViewCtrl>,
                            public CCustomDraw<CTabPeople>
{
[snip]

public:
    DECLARE_WND_SUPERCLASS(NULL, CListViewCtrl::GetWndClassName())

    BOOL PreTranslateMessage(MSG* pMsg)
    {
        pMsg;
        return FALSE;
    }

    BEGIN_MSG_MAP(CTabPeople)
        MESSAGE_HANDLER(WM_CREATE, OnCreate)
        MESSAGE_HANDLER(WM_CONTEXTMENU, OnContextMenu)
        COMMAND_ID_HANDLER(IDM_PROCESSTAB_REFRESH, OnMenuRefresh)
        REFLECTED_NOTIFY_CODE_HANDLER(LVN_COLUMNCLICK, OnColumnClick)
        CHAIN_MSG_MAP_ALT(CCustomDraw, 1)
    END_MSG_MAP()

    LRESULT OnMenuRefresh(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL&bHandled)
    {
        // Here i would like to update the status bar created at the mainfrm.h
        // something like UISetText(0, L"Updating..");
    }

  [snip]
}

From the research i have done it seems that there is two ways to update the status bar:

Directly from the CTabPeople view using the handle of the status bar

By sending a message to the mainfrm loop to update the status bar

My question is how to implement one of the above options in my code.

Thanks.

Body:
simply working version of mine:

MainFrm.h:

class CMainFrame :
    public CFrameWindowImpl<CMainFrame>,
    public CUpdateUI<CMainFrame>,
    public CMessageFilter, public CIdleHandler
{
public:
  DECLARE_FRAME_WND_CLASS(NULL, IDR_MAINFRAME)
  CMainFrame() { this_ptr = this; }
  static CMainFrame* this_ptr;
  void SetStatusText(std::wstring strText);
  //...
}

MainFrm.cpp

CMainFrame* CMainFrame::this_ptr = nullptr;

// m_hWndStatusBar is from atlframe.h
void CMainFrame::SetStatusText(std::wstring strText)
{
  ::SetWindowText(m_hWndStatusBar, strText.c_str());
}

other.cpp

CMainFrame::this_ptr->SetStatusText(L"program ready");


问:
how to toggle expand row by click on button in table using bootstrap and jQuery
I have this example, I've successfully made table to be collapse but it is only click row in the table.

I wanna to change it , only if click on button the expand more datails

See this fiddle

Code Snippet

$('.flip').click(function() {
  $(this)
    .closest('tbody')
    .next('.section')
    .toggle('slow');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.section {
  display: none;
}</code>```

      CASINO
      BONUS
      HIGHLIGHTS
      DEPOSIT
      RATING

              <button>PLAY NOW!</button>

200% UP TO

$1000

+250 FREE SPINS

                   sfgfsjghsjghsjghjsghsjghsj

                   sfgfsjghsjghsjghjsghsjghsj

                   sfgfsjghsjghsjghjsghsjghsj

              <button id="acc1">READ MORE </button>

      item 111
      item 112
      item 113
      item 114

      item 121
      item 122
      item 123
      item 124

      item 131
      item 132
      item 133
      item 134

              <button>PLAY NOW!</button>

200% UP TO

$1000

+250 FREE SPINS

                   sfgfsjghsjghsjghjsghsjghsj

                   sfgfsjghsjghsjghjsghsjghsj

                   sfgfsjghsjghsjghjsghsjghsj

              <button id="acc1">READ MORE </button>

      item 211
      item 212
      item 213
      item 214

      item 221
      item 222
      item 223
      item 224

      item 231
      item 232
      item 233
      item 234

              <button>PLAY NOW!</button>

200% UP TO

$1000

+250 FREE SPINS

                   sfgfsjghsjghsjghjsghsjghsj

                   sfgfsjghsjghsjghjsghsjghsj

                   sfgfsjghsjghsjghjsghsjghsj

              <button id="acc1">READ MORE </button>

      item 311
      item 312
      item 313
      item 314

      item 321
      item 322
      item 323
      item 324

      item 331
      item 332
      item 333
      item 334

              <button>PLAY NOW!</button>

200% UP TO

$1000

+250 FREE SPINS

                   sfgfsjghsjghsjghjsghsjghsj

                   sfgfsjghsjghsjghjsghsjghsj

                   sfgfsjghsjghsjghjsghsjghsj

              <button id="acc1">READ MORE </button>

      item 311
      item 312
      item 313
      item 314

      item 321
      item 322
      item 323
      item 324

      item 331
      item 332
      item 333
      item 334

              <button>PLAY NOW!</button>

200% UP TO

$1000

+250 FREE SPINS

                   sfgfsjghsjghsjghjsghsjghsj

                   sfgfsjghsjghsjghjsghsjghsj

                   sfgfsjghsjghsjghjsghsjghsj

              <button id="acc1">READ MORE </button>

      item 311
      item 312
      item 313
      item 314

      item 321
      item 322
      item 323
      item 324

      item 331
      item 332
      item 333
      item 334

```

if can get class flip from td to button read more

答:
jQuery code

```<code>$('button').click(function() {
      $(this).parents('tr')
        .closest('tbody')
        .next('.section')
        .toggle('slow');
    });
 });
</code>```

Please edit your code like above.

Also look at working example

https://jsfiddle.net/bilawalkhan/2d1y1592/

Hope this would be helpful. Thanks

Body:
I have this example, I've successfully made table to be collapse but it is only click row in the table.

I wanna to change it , only if click on button the expand more datails

See this fiddle

Code Snippet

$('.flip').click(function() {
  $(this)
    .closest('tbody')
    .next('.section')
    .toggle('slow');
});

.section {
  display: none;
}

      CASINO
      BONUS
      HIGHLIGHTS
      DEPOSIT
      RATING

              <button>PLAY NOW!</button>

200% UP TO

$1000

+250 FREE SPINS

                   sfgfsjghsjghsjghjsghsjghsj

                   sfgfsjghsjghsjghjsghsjghsj

                   sfgfsjghsjghsjghjsghsjghsj

              <button id="acc1">READ MORE </button>

      item 111
      item 112
      item 113
      item 114

      item 121
      item 122
      item 123
      item 124

      item 131
      item 132
      item 133
      item 134

              <button>PLAY NOW!</button>

200% UP TO

$1000

+250 FREE SPINS

                   sfgfsjghsjghsjghjsghsjghsj

                   sfgfsjghsjghsjghjsghsjghsj

                   sfgfsjghsjghsjghjsghsjghsj

              <button id="acc1">READ MORE </button>

      item 211
      item 212
      item 213
      item 214

      item 221
      item 222
      item 223
      item 224

      item 231
      item 232
      item 233
      item 234

              <button>PLAY NOW!</button>

200% UP TO

$1000

+250 FREE SPINS

                   sfgfsjghsjghsjghjsghsjghsj

                   sfgfsjghsjghsjghjsghsjghsj

                   sfgfsjghsjghsjghjsghsjghsj

              <button id="acc1">READ MORE </button>

      item 311
      item 312
      item 313
      item 314

      item 321
      item 322
      item 323
      item 324

      item 331
      item 332
      item 333
      item 334

              <button>PLAY NOW!</button>

200% UP TO

$1000

+250 FREE SPINS

                   sfgfsjghsjghsjghjsghsjghsj

                   sfgfsjghsjghsjghjsghsjghsj

                   sfgfsjghsjghsjghjsghsjghsj

              <button id="acc1">READ MORE </button>

      item 311
      item 312
      item 313
      item 314

      item 321
      item 322
      item 323
      item 324

      item 331
      item 332
      item 333
      item 334

              <button>PLAY NOW!</button>

200% UP TO

$1000

+250 FREE SPINS

                   sfgfsjghsjghsjghjsghsjghsj

                   sfgfsjghsjghsjghjsghsjghsj

                   sfgfsjghsjghsjghjsghsjghsj

              <button id="acc1">READ MORE </button>

      item 311
      item 312
      item 313
      item 314

      item 321
      item 322
      item 323
      item 324

      item 331
      item 332
      item 333
      item 334

if can get class flip from td to button read more

Body:
jQuery code

$('button').click(function() {
      $(this).parents('tr')
        .closest('tbody')
        .next('.section')
        .toggle('slow');
    });
 });

Please edit your code like above.

Also look at working example

https://jsfiddle.net/bilawalkhan/2d1y1592/

Hope this would be helpful. Thanks


问:
How to open window or whatever while my method is doing something in background WPF
as much as we know,
programs are executing line by line, and now I am facing issue, I have a method which is taking few seconds to execute,
I thought I could solve it by threads but I will speak about it later, now what I would like to do is next:

How could I open a window with message like "Still executing..." when that method start execution and when method is done window could close himself,
I need that because I Would like to avoid UI freezing because that long method is not in another task/thread.

Here is how it looks like:

```<code>if (e.Key == Key.Delete)
{
    //Could I show window here like like "Loading please wait.."
    ExecuteLongMethod();
    //When this is done close this method
}
</code>```

Thanks guys,
Cheers

答:
If your ExecuteLongMethod() must be executed on the dispatcher thread for some reason, you could create a new window that launches in a separate thread and display this one during the time it takes for the long-running method to complete. Please refer to the following link for more information.

Wait screen during rendering UIElement in WPF

The other option would otherwise be to execute the long-running method on a background thread and display the loading window on the main thread.

The recommended way to do this would be to use the task parallel library (TPL) and start a task: https://msdn.microsoft.com/en-us/library/dd460717(v=vs.110).aspx

```<code>if (e.Key == Key.Delete)
{
    Window window = new Window();
    window.Show();

    Task.Factory.StartNew(() => ExecuteLongMethod())
    .ContinueWith(task =>
    {
        window.Close();
    },System.Threading.CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.FromCurrentSynchronizationContext());
}
</code>```

Body:
as much as we know,
programs are executing line by line, and now I am facing issue, I have a method which is taking few seconds to execute,
I thought I could solve it by threads but I will speak about it later, now what I would like to do is next:

How could I open a window with message like "Still executing..." when that method start execution and when method is done window could close himself,
I need that because I Would like to avoid UI freezing because that long method is not in another task/thread.

Here is how it looks like:

if (e.Key == Key.Delete)
{
    //Could I show window here like like "Loading please wait.."
    ExecuteLongMethod();
    //When this is done close this method
}

Thanks guys,
Cheers

Body:
If your ExecuteLongMethod() must be executed on the dispatcher thread for some reason, you could create a new window that launches in a separate thread and display this one during the time it takes for the long-running method to complete. Please refer to the following link for more information.

Wait screen during rendering UIElement in WPF

The other option would otherwise be to execute the long-running method on a background thread and display the loading window on the main thread.

The recommended way to do this would be to use the task parallel library (TPL) and start a task: https://msdn.microsoft.com/en-us/library/dd460717(v=vs.110).aspx

if (e.Key == Key.Delete)
{
    Window window = new Window();
    window.Show();

    Task.Factory.StartNew(() => ExecuteLongMethod())
    .ContinueWith(task =>
    {
        window.Close();
    },System.Threading.CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.FromCurrentSynchronizationContext());
}


问:
How can i fix SERVICE_NOT_AVAILABLE in Android
I want add firebase into my application and I added firebase with this path : Tools -> Firebase .

But when run application show me this error in logs :

```<code>03-30 16:33:14.741 1457-1575/com.example.mohammad.a1_firstfirebase W/GooglePlayServicesUtil: Google Play services out of date.  Requires 10084000 but found 6599430
03-30 16:33:14.742 1457-1457/com.example.mohammad.a1_firstfirebase W/FA: Service connection failed: ConnectionResult{statusCode=SERVICE_VERSION_UPDATE_REQUIRED, resolution=null, message=null}
03-30 16:33:34.846 1457-2691/com.example.mohammad.a1_firstfirebase D/FirebaseInstanceId: background sync failed: SERVICE_NOT_AVAILABLE, retry in 60s
</code>```

I added this dependencies :

```<code>{
      classpath 'com.google.gms:google-services:3.0.0'

     compile 'com.google.firebase:firebase-messaging:10.0.1'
}

apply plugin: 'com.google.gms.google-services'
</code>```

How can I fix this problem? I need this help, please help me

答: add google-services.json file to your resource file</p>

Body:
I want add firebase into my application and I added firebase with this path : Tools -> Firebase .

But when run application show me this error in logs :

03-30 16:33:14.741 1457-1575/com.example.mohammad.a1_firstfirebase W/GooglePlayServicesUtil: Google Play services out of date.  Requires 10084000 but found 6599430
03-30 16:33:14.742 1457-1457/com.example.mohammad.a1_firstfirebase W/FA: Service connection failed: ConnectionResult{statusCode=SERVICE_VERSION_UPDATE_REQUIRED, resolution=null, message=null}
03-30 16:33:34.846 1457-2691/com.example.mohammad.a1_firstfirebase D/FirebaseInstanceId: background sync failed: SERVICE_NOT_AVAILABLE, retry in 60s

I added this dependencies :

{
      classpath 'com.google.gms:google-services:3.0.0'

     compile 'com.google.firebase:firebase-messaging:10.0.1'
}

apply plugin: 'com.google.gms.google-services'

How can I fix this problem? I need this help, please help me


问:
Bootstrap 4 - Responsive cards in card-columns
I'm playing with Bootstrap 4 and I can't find a solution to add responsiveness to cards while in a div with class="card-columns" (this class applies a Masonry-like effect to the cards inside the div having this class).

In Bootstrap 3 it was easy to style and make "cards" responsive since it was possible to apply something like class="col-md-3 col-sm-6 col-xs-12" to a div containing thumbnail, caption, etc.

How to have the same effect while using cards in Bootstrap 4?

Here is the HTML:

here we put the map

                // here there's code for navbar

                    <?php
                    // Create and check connection

                    if ($result->num_rows > 0) {

                        // output card design
                        while($row = $result->fetch_assoc()) {

                            echo '

' . $row["name"] . '

Text. Card content.

14

';
                        }
                    } else {
                        echo "0 results";
                    }

                    $conn->close();
                    ?>

```
<p>And here is the CSS I've used:</p>
<pre class="lang-css prettyprint-override"><code>#map_container {
background-image: url(map.png);
height: 100vh;
}

.right_box {
-webkit-box-shadow: -2px 0px 2px 0px rgba(0,0,0,0.75);
-moz-box-shadow: -2px 0px 2px 0px rgba(0,0,0,0.75);
box-shadow: -2px 0px 2px 0px rgba(0,0,0,0.75);
}

.card {
border-radius: 0 !important;
border: 0 none;
-webkit-box-shadow: 0px 2px 5px 0px rgba(0,0,0,0.5);
-moz-box-shadow: 0px 2px 5px 0px rgba(0,0,0,0.5);
box-shadow: 0px 2px 5px 0px rgba(0,0,0,0.5);
margin-left: 1px;
margin-right: 1px;
}

.card-img-top {
width: 100%;
border-radius: 0 !important;
}

.card-columns {
padding-top: 15px;
}
</code>```

Given below are two images to make my situation clearer:

Large screen

Smaller screen

I'd like cards to stack up vertically on smaller screens.

Thanks for your suggestions!

答:
Update 2019 - Bootstrap 4

You can simply use the SASS mixin to change the number of cards across in each breakpoint / grid tier.

```<code>.card-columns {
  @include media-breakpoint-only(xl) {
    column-count: 5;
  }
  @include media-breakpoint-only(lg) {
    column-count: 4;
  }
  @include media-breakpoint-only(md) {
    column-count: 3;
  }
  @include media-breakpoint-only(sm) {
    column-count: 2;
  }
}
</code>```

SASS Demo: http://www.codeply.com/go/FPBCQ7sOjX

Or, CSS only like this...

```<code>@media (min-width: 576px) {
    .card-columns {
        column-count: 2;
    }
}

@media (min-width: 768px) {
    .card-columns {
        column-count: 3;
    }
}

@media (min-width: 992px) {
    .card-columns {
        column-count: 4;
    }
}

@media (min-width: 1200px) {
    .card-columns {
        column-count: 5;
    }
}
</code>```

CSS-only Demo: https://www.codeply.com/go/FIqYTyyWWZ

ContentLicense: CC BY-SA 4.0

Body:
I'm playing with Bootstrap 4 and I can't find a solution to add responsiveness to cards while in a div with class="card-columns" (this class applies a Masonry-like effect to the cards inside the div having this class).

In Bootstrap 3 it was easy to style and make "cards" responsive since it was possible to apply something like class="col-md-3 col-sm-6 col-xs-12" to a div containing thumbnail, caption, etc.

How to have the same effect while using cards in Bootstrap 4?

Here is the HTML:

here we put the map

                // here there's code for navbar

                    <?php
                    // Create and check connection

                    if ($result->num_rows > 0) {

                        // output card design
                        while($row = $result->fetch_assoc()) {

                            echo '

' . $row["name"] . '

Text. Card content.

14

';
                        }
                    } else {
                        echo "0 results";
                    }

                    $conn->close();
                    ?>

And here is the CSS I've used:

#map_container {
background-image: url(map.png);
height: 100vh;
}

.right_box {
-webkit-box-shadow: -2px 0px 2px 0px rgba(0,0,0,0.75);
-moz-box-shadow: -2px 0px 2px 0px rgba(0,0,0,0.75);
box-shadow: -2px 0px 2px 0px rgba(0,0,0,0.75);
}

.card {
border-radius: 0 !important;
border: 0 none;
-webkit-box-shadow: 0px 2px 5px 0px rgba(0,0,0,0.5);
-moz-box-shadow: 0px 2px 5px 0px rgba(0,0,0,0.5);
box-shadow: 0px 2px 5px 0px rgba(0,0,0,0.5);
margin-left: 1px;
margin-right: 1px;
}

.card-img-top {
width: 100%;
border-radius: 0 !important;
}

.card-columns {
padding-top: 15px;
}

Given below are two images to make my situation clearer:

Large screen

Smaller screen

I'd like cards to stack up vertically on smaller screens.

Thanks for your suggestions!

Body:
Update 2019 - Bootstrap 4

You can simply use the SASS mixin to change the number of cards across in each breakpoint / grid tier.

.card-columns {
  @include media-breakpoint-only(xl) {
    column-count: 5;
  }
  @include media-breakpoint-only(lg) {
    column-count: 4;
  }
  @include media-breakpoint-only(md) {
    column-count: 3;
  }
  @include media-breakpoint-only(sm) {
    column-count: 2;
  }
}

SASS Demo: http://www.codeply.com/go/FPBCQ7sOjX

Or, CSS only like this...

@media (min-width: 576px) {
    .card-columns {
        column-count: 2;
    }
}

@media (min-width: 768px) {
    .card-columns {
        column-count: 3;
    }
}

@media (min-width: 992px) {
    .card-columns {
        column-count: 4;
    }
}

@media (min-width: 1200px) {
    .card-columns {
        column-count: 5;
    }
}

CSS-only Demo: https://www.codeply.com/go/FIqYTyyWWZ


问:
Scrapyd not starting at boot-up - Ubuntu 14
I have Scrapyd installed on server.

I want it to start whenever my server restarts.

I created job here /etc/init/myjob.conf with following contents

```<code>description     "my job"
start on startup
task
cd /var/www/scrapers &&  scrapyd >& /dev/null &
</code>```

I also tried to put following command in crontab -e

@reboot cd /var/www/scrapers &&  scrapyd >& /dev/null &

Both of them did not work.

I checked cronlogs using grep CRON /var/log/syslog and here I see command ran but Scrapyd did not start

```<code>Mar 30 13:33:28 mani CRON[446]: (root) CMD (cd /var/www/scrapers && scrapyd >& /dev/null &)
</code>```

As you can see that command ran as ROOT user.

If I manually run that command in terminal it works!

PS:

I changed command to

@reboot cd /var/www/scrapers && scrapyd >> /var/www/log.txt

and log file is created but its empty!

答:
You must try to start process manually, and see what happens. The line:

```<code>cd /var/www/scrapers &&  scrapyd
</code>```

makes sense if: 1) directory /var/www/scrapers do exist 2) scrapyd is a binary that exists in that directory, and PATH environment variable includes actual directory ("." wildcard).

Maybe you could try:

```<code>cd /var/www/scrapers &&  ./scrapyd
</code>```

without redirect standar output to /dev/null, to see what happens. Always try manual before use cron.

Body:
I have Scrapyd installed on server.

I want it to start whenever my server restarts.

I created job here /etc/init/myjob.conf with following contents

description     "my job"
start on startup
task
cd /var/www/scrapers &&  scrapyd >& /dev/null &

I also tried to put following command in crontab -e

@reboot cd /var/www/scrapers &&  scrapyd >& /dev/null &

Both of them did not work.

I checked cronlogs using grep CRON /var/log/syslog and here I see command ran but Scrapyd did not start

Mar 30 13:33:28 mani CRON[446]: (root) CMD (cd /var/www/scrapers && scrapyd >& /dev/null &)

As you can see that command ran as ROOT user.

If I manually run that command in terminal it works!

PS:

I changed command to

@reboot cd /var/www/scrapers && scrapyd >> /var/www/log.txt

and log file is created but its empty!

Body:
You must try to start process manually, and see what happens. The line:

cd /var/www/scrapers &&  scrapyd

makes sense if: 1) directory /var/www/scrapers do exist 2) scrapyd is a binary that exists in that directory, and PATH environment variable includes actual directory ("." wildcard).

Maybe you could try:

cd /var/www/scrapers &&  ./scrapyd

without redirect standar output to /dev/null, to see what happens. Always try manual before use cron.


问:
PKCS12 Java Keystore from CA and User certificate in java
I've recently been put in charge of mocking up an Apple product (iPhone Configuration Utility) in Java. One of the sections I've been a bit stuck on is a part about Exchange ActiveSync. In there, it allows you to select a certificate from your Keychain to use as credentials for your EAS account. After some research, I found that it's actually creating a PKCS12 keystore, inserting the private key of the certificate I selected, and encoding that into XML. So far not a big deal. If I create a .p12 file with Keychain Access it uploads without a problem. But I run into a problem when I try to bring that over to Java.

Say I export one of those certs that I had used earlier with the .p12 file as a .cer file (this is what we are expecting to get in the environment). Now when I upload it into Java I get a Certificate object as follows...

```<code>KeyStore ks = java.security.KeyStore.getInstance("PKCS12");
ks.load(null, "somePassword".toCharArray());

CertificateFactory cf = CertificateFactory.getInstance("X.509", new BouncyCastleProvider());
java.security.cert.Certificate userCert  = cf.generateCertificate(new FileInputStream("/Users/me/Desktop/RecentlyExportedCert.cer"));
</code>```

But when I try...

```<code>ks.setCertificateEntry("SomeAlias", userCert);
</code>```

I get the exception...

```<code>java.security.KeyStoreException: TrustedCertEntry not supported
</code>```

So from certs I move onto keys. But with those Certificates (I got the CA Cert as well), I'm only able to access the public key, not the private. And if I attempt to add the public key like so...

```<code>java.security.cert.Certificate[] chain = {CACert};
ks.setKeyEntry("SomeAlias", userCert.getPublicKey().getEncoded(), chain);
</code>```

I get...

```<code>java.security.KeyStoreException: Private key is not stored as PKCS#8 EncryptedPrivateKeyInfo: java.io.IOException: DerValue.getOctetString, not an Octet String: 3
</code>```

So now I'm here. Does anyone have any idea how to get a private key from a .cer file into a PKCS12 keystore in Java? Am I even on the right track?

Thanks in advance!

答:
http://www.docjar.com/html/api/org/bouncycastle/jce/examples/PKCS12Example.java.html

This is how to add a certificate with a associating private key to a PKCS12 keystore.
When you are using client authentication, the keystore needs to contain also the private key, in that case you use KeyStore.getInstance("PKCS12").

When youre not using client authentication but only server authentication(and private key will not be added to keystore, since it belongs to the server), its better to use
KeyStore.getInstance("JKS"), than you can add multiple certificates with an alias to that one keystore.

When you are using PKCS12, as far as I know,  you can only add 1 certificate(you have to add the whole certificate chain) associated with the private key, you want to use for that certificate.

ContentLicense: CC BY-SA 2.5

Body:
I've recently been put in charge of mocking up an Apple product (iPhone Configuration Utility) in Java. One of the sections I've been a bit stuck on is a part about Exchange ActiveSync. In there, it allows you to select a certificate from your Keychain to use as credentials for your EAS account. After some research, I found that it's actually creating a PKCS12 keystore, inserting the private key of the certificate I selected, and encoding that into XML. So far not a big deal. If I create a .p12 file with Keychain Access it uploads without a problem. But I run into a problem when I try to bring that over to Java.

Say I export one of those certs that I had used earlier with the .p12 file as a .cer file (this is what we are expecting to get in the environment). Now when I upload it into Java I get a Certificate object as follows...

KeyStore ks = java.security.KeyStore.getInstance("PKCS12");
ks.load(null, "somePassword".toCharArray());

CertificateFactory cf = CertificateFactory.getInstance("X.509", new BouncyCastleProvider());
java.security.cert.Certificate userCert  = cf.generateCertificate(new FileInputStream("/Users/me/Desktop/RecentlyExportedCert.cer"));

But when I try...

ks.setCertificateEntry("SomeAlias", userCert);

I get the exception...

java.security.KeyStoreException: TrustedCertEntry not supported

So from certs I move onto keys. But with those Certificates (I got the CA Cert as well), I'm only able to access the public key, not the private. And if I attempt to add the public key like so...

java.security.cert.Certificate[] chain = {CACert};
ks.setKeyEntry("SomeAlias", userCert.getPublicKey().getEncoded(), chain);

I get...

java.security.KeyStoreException: Private key is not stored as PKCS#8 EncryptedPrivateKeyInfo: java.io.IOException: DerValue.getOctetString, not an Octet String: 3

So now I'm here. Does anyone have any idea how to get a private key from a .cer file into a PKCS12 keystore in Java? Am I even on the right track?

Thanks in advance!


问:
TabelView Delegate methods using RxSwift
I am using RxSwift for TableView.I need to calculate height of dynamic cells previously I did it in WillDisplayCell delegate method. I don't know how to bind TableView Delegate methods with RxSwift. Can any one help?</p>

答:
Conform your View Controller

```<code>class YourViewController: UIViewController, UITableViewDelegate
</code>```

Then add this in viewDidLoad()

```<code>tableView.rx.setDelegate(self).addDisposableTo(disposeBag)
</code>```

then you write UITableViewDelegate methods.

Body:
Conform your View Controller

class YourViewController: UIViewController, UITableViewDelegate

Then add this in viewDidLoad()

tableView.rx.setDelegate(self).addDisposableTo(disposeBag)

then you write UITableViewDelegate methods.


问:
Additional values in 2d array
I created the following code in Java (1.8.0.121) for parsing of iMatrix array into matrixOutput one.
Once I run it I noticed that appears additional values in cells 1,0 and 1,1.

Could someone advice me how should I change to avoid such additions for other arrays (I plan a generic code which will take different arrays in format like iMatrix array)

    public class Dbg {

```<code>private static int[][] matrixOutput = { { 0, 2, 0, 0, 0 },
                                        { 0, 0, 0, 4, 0 },
                                        { 1, 2, 0, 0, 5 },
                                        { 0, 0, 0, 0, 0 },
                                        { 0, 0, 0, 0, 0 } };
private static int[][] iMatrix = {
        {1, -1, 0, 0, 0},
        {0, 1, 0, -1, 0},
        {-1, 0, 1, 0, 0},
        {0, -1, 1, 0, 0},
        {0, 0, 1, 0, -1},
        {0, 0, 0, 2, 0}};
private static int i = 0;
private static int j = 0;
private static int val = 0;

public static void main(String[] args) {

    int[][] list = new int[5][5];

    for (int m = 0; m < iMatrix.length; m++) {
        for (int n = 0; n < iMatrix[m].length; n++) {
            if (iMatrix[m][n] == 1){
                i = n;
            }
            if (iMatrix[m][n] == -1){
                j = n;
                val = n + 1;

            }
            list[i][j] = val;
        }
    }

    for (i = 0; i < list.length; i++) {
        for (j = 0; j < list.length; j++) {
            System.out.print(list[i][j]);
        }
        System.out.println();
    }

}
}
</code>```

Insead of MatrixOutput it gives me the following result:

```<code>02000
12040
12005
00000
00000
</code>```

When I changed places for 3 and 4 rows viceverso I saw that value 1 from 1,0 disappears. All values from iMatrix are stored correctly.

答:
Initialize val = 0 inside the 2nd for loop while creating list. Because your code will print previous value of 'val' if iMatrix[m][n] is not equal to '1' or '-1'.

Code:

```<code>for (int m = 0; m < iMatrix.length; m++)
{
    for (int n = 0; n < iMatrix[m].length; n++)
    {
        val = 0;
        if (iMatrix[m][n] == 1)
        {
            i = n;
        }
        if (iMatrix[m][n] == -1)
        {
            j = n;
            val = n + 1;
        }
        list[i][j] = val;
    }
}
</code>```

Title: Additional values in 2d array

Body:
I created the following code in Java (1.8.0.121) for parsing of iMatrix array into matrixOutput one.
Once I run it I noticed that appears additional values in cells 1,0 and 1,1.

Could someone advice me how should I change to avoid such additions for other arrays (I plan a generic code which will take different arrays in format like iMatrix array)

    public class Dbg {

private static int[][] matrixOutput = { { 0, 2, 0, 0, 0 },
                                        { 0, 0, 0, 4, 0 },
                                        { 1, 2, 0, 0, 5 },
                                        { 0, 0, 0, 0, 0 },
                                        { 0, 0, 0, 0, 0 } };
private static int[][] iMatrix = {
        {1, -1, 0, 0, 0},
        {0, 1, 0, -1, 0},
        {-1, 0, 1, 0, 0},
        {0, -1, 1, 0, 0},
        {0, 0, 1, 0, -1},
        {0, 0, 0, 2, 0}};
private static int i = 0;
private static int j = 0;
private static int val = 0;

public static void main(String[] args) {

    int[][] list = new int[5][5];

    for (int m = 0; m < iMatrix.length; m++) {
        for (int n = 0; n < iMatrix[m].length; n++) {
            if (iMatrix[m][n] == 1){
                i = n;
            }
            if (iMatrix[m][n] == -1){
                j = n;
                val = n + 1;

            }
            list[i][j] = val;
        }
    }

    for (i = 0; i < list.length; i++) {
        for (j = 0; j < list.length; j++) {
            System.out.print(list[i][j]);
        }
        System.out.println();
    }

}
}

Insead of MatrixOutput it gives me the following result:

02000
12040
12005
00000
00000

When I changed places for 3 and 4 rows viceverso I saw that value 1 from 1,0 disappears. All values from iMatrix are stored correctly.

Body:
Initialize val = 0 inside the 2nd for loop while creating list. Because your code will print previous value of 'val' if iMatrix[m][n] is not equal to '1' or '-1'.

Code:

for (int m = 0; m < iMatrix.length; m++)
{
    for (int n = 0; n < iMatrix[m].length; n++)
    {
        val = 0;
        if (iMatrix[m][n] == 1)
        {
            i = n;
        }
        if (iMatrix[m][n] == -1)
        {
            j = n;
            val = n + 1;
        }
        list[i][j] = val;
    }
}


问:
Filter a two dimensional array in table view for searching in Swift
I have a two dimensional array

```<code>fileprivate var Food : [[FoodModel]] = [[]]

Food = [["Apple","Mango"],["Chocolate","Biscuit"]]
</code>```

and two sections

```<code>let section = ["Fruits","Dry Food"]
</code>```

for a table view. It's displaying the value nicely. Now I added a search bar for searching value from Food. My problem is that I can't filter Food by my searching keyword.

```<code>Food.filter({}) //what to write here?
self.tableView.reloadData()
</code>```

答:
You could try the following:

```<code>var searchResult = Food.flatMap({ $0 }).filter { $0.lowercased().contains(searchedKeyword) }
</code>```

Firstly, the flatMap flattens the array of array to single array, then filters to that resulting array.

Body:
I have a two dimensional array

fileprivate var Food : [[FoodModel]] = [[]]

Food = [["Apple","Mango"],["Chocolate","Biscuit"]]

and two sections

let section = ["Fruits","Dry Food"]

for a table view. It's displaying the value nicely. Now I added a search bar for searching value from Food. My problem is that I can't filter Food by my searching keyword.

Food.filter({}) //what to write here?
self.tableView.reloadData()

Body:
You could try the following:

var searchResult = Food.flatMap({ $0 }).filter { $0.lowercased().contains(searchedKeyword) }

Firstly, the flatMap flattens the array of array to single array, then filters to that resulting array.


问:
How to ensure that keys in object are strings with jsonschema
I need a jsonschema to validate JSON where all keys are required to be strings. All keys are arbitrary.

For example this should be valid

```<code>{

    "123": "GET",
    "key2": "/mellons/and/strawberries",
    "arbitrary_key": {
        "SomeKey": "some data",
    },
}
</code>```

while this should not

```<code>{

    123: "GET",
    "key2": "/mellons/and/strawberries",
    "arbitrary_key": {
        "SomeKey": "some data",
    },
}
</code>```

Validating with patternProperties does not work, as this regex "^.*$" seems to match numbers as well as strings.

答:
```<code>a={

    123: "GET",
    "key2": "/mellons/and/strawberries",
    "arbitrary_key": {
        "SomeKey": "some data",
    },
};
Object.keys(a) // this gives array of keys can assign check here
</code>```

Body:
I need a jsonschema to validate JSON where all keys are required to be strings. All keys are arbitrary.

For example this should be valid

{

    "123": "GET",
    "key2": "/mellons/and/strawberries",
    "arbitrary_key": {
        "SomeKey": "some data",
    },
}

while this should not

{

    123: "GET",
    "key2": "/mellons/and/strawberries",
    "arbitrary_key": {
        "SomeKey": "some data",
    },
}

Validating with patternProperties does not work, as this regex "^.*$" seems to match numbers as well as strings.


问:
Why do i have to link OpenGL lib manually with MinGW?
I have the following gcc command that work correctly:

```<code>gcc -Wall -g hello_gl.c -lglut32 -lopengl32 -lglu32 -o hello_gl && hello_gl
</code>```

I would like to avoid the pain to link manually each OpenGl lib, and thus find a way to make MinGW understand that glut32, openGL32, glu32 are all located in C:\MinGW\lib .

I have try to set the following windows envar following MinGW official doc :

```<code>CPATH        = C:\MinGW\include
LIBRARY_PATH = C:\MinGW\lib
</code>```

But when i try to simply run this:

```<code>gcc -Wall -g hello_gl.c -o hello_gl && hello_gl
</code>```

MinGW can't find the OpenGL lib.

I have also try to force the lib path in the gcc command:

```<code>gcc -Wall -g -IC:\MinGW\include hello_gl.c -LC:\MinGW\lib -o hello_gl && hello_gl
</code>```

But again MinGW was not able to find the OpenGL lib.

So i would like to know if

Linking manually all lib included is an obligation with OpenGL Lib ?

If yes why is that so ?

If not how could i do to solve my problem and force MinGW to find them ?

Cheers

答:
The below command doesn't tell gcc to build with any libraries, just where to find them.

```<code>gcc -Wall -g -IC:\MinGW\include hello_gl.c -LC:\MinGW\lib -o hello_gl && hello_gl
</code>```

you have to include the -l[libraryname] options, otherwise, how else would it know which libraries you wanted to link with, in much the same way that you have to tell it which source or object files you want to build with.

Body:
I have the following gcc command that work correctly:

gcc -Wall -g hello_gl.c -lglut32 -lopengl32 -lglu32 -o hello_gl && hello_gl

I would like to avoid the pain to link manually each OpenGl lib, and thus find a way to make MinGW understand that glut32, openGL32, glu32 are all located in C:\MinGW\lib .

I have try to set the following windows envar following MinGW official doc :

CPATH        = C:\MinGW\include
LIBRARY_PATH = C:\MinGW\lib

But when i try to simply run this:

gcc -Wall -g hello_gl.c -o hello_gl && hello_gl

MinGW can't find the OpenGL lib.

I have also try to force the lib path in the gcc command:

gcc -Wall -g -IC:\MinGW\include hello_gl.c -LC:\MinGW\lib -o hello_gl && hello_gl

But again MinGW was not able to find the OpenGL lib.

So i would like to know if

Linking manually all lib included is an obligation with OpenGL Lib ?

If yes why is that so ?

If not how could i do to solve my problem and force MinGW to find them ?

Cheers

Body:
The below command doesn't tell gcc to build with any libraries, just where to find them.

gcc -Wall -g -IC:\MinGW\include hello_gl.c -LC:\MinGW\lib -o hello_gl && hello_gl

you have to include the -l[libraryname] options, otherwise, how else would it know which libraries you wanted to link with, in much the same way that you have to tell it which source or object files you want to build with.


问:
How can I find the normals for each vertex of an object so that I can apply smooth shading with OpenGL?
I'm loading an object from a .off file. This file format does not define the normals for an object's faces or vertices. I have found the face normals using a vector product. But I'm at a loss about finding the normals for each vertex, any ideas? </p>

答:
Some .obj files doesn't have normals at all. You should at first compute per-face normals:

Given a face composed of 3 vertices v1, v2, v3 you can compute the normal :
The normal is the normalized cross product between v1 - v2 and v1 - v3

```<code>N = Normalize( (v1 - v2) x (v1 - v3) )

Normalize(V) = V / length(V)

length(V) = SQRT (V.x * V.x + V.y * V.y + V.z * V.z)
</code>```

The cross product :

```<code>v × u = (v.y * u.z − v.z * u.y, v.z * u.x − v.x * u.z, v.x * u.y − v.y * u.x).
</code>```

After that you can compute the "smooth" normals by averaging all the normals of adjacent faces.

Body:
Some .obj files doesn't have normals at all. You should at first compute per-face normals:

Given a face composed of 3 vertices v1, v2, v3 you can compute the normal :
The normal is the normalized cross product between v1 - v2 and v1 - v3

N = Normalize( (v1 - v2) x (v1 - v3) )

Normalize(V) = V / length(V)

length(V) = SQRT (V.x * V.x + V.y * V.y + V.z * V.z)

The cross product :

v × u = (v.y * u.z − v.z * u.y, v.z * u.x − v.x * u.z, v.x * u.y − v.y * u.x).

After that you can compute the "smooth" normals by averaging all the normals of adjacent faces.


问:
Receive null values with SwiftyJSONModel in Swift 3.0
After successful webservice call I get following json

```<code>"balance_details":{
         "raw_balance":"13157.70",
         "raw_credit_adeded":"4035000.00",
         "raw_credit_deducted":"0.00",
         "raw_tot_paid_amount":6000,
         "tot_paid_amount":"Rs.6000.00",
         "tot_paid_invoices":2,
         "balance":"13157.7",
         "current_balance":"Rs.13157.70",
         "credit_added":"Rs.4035000.00",
         "credit_deducted":"Rs.0.00",
         "last_recharge_amt":null,
         "raw_amount":null,
         "last_recharge_date":""
      }
</code>```

For this web call I'm using Alamofire. To map this JSON into SWIFT OBJECT, I'm using SwiftyJSONModel library. But I'm not able to set type for stoaring null values into JSON object.

```<code>class BalanceDetails: JSONObjectInitializable {

    // FIXME: - properties
    var rawBalance: String
    var rawCreditAdeded: String
    var rawCreditDeducted: String
    var rawTotalPaidAmount: Int
    var totalPaidAmount: String
    var totalPaidInvoices: Int
    var balance: String
    var currentBalance: String
    var creditAdded: String
    var creditDeducted: String
    //    var lastRechargeAmount: NSObject
    //    var rawAmount: NSObject
    var lastRechargeDate: String

    // FIXME: - json properties
    enum PropertyKey: String {
        case raw_balance
        case raw_credit_adeded
        case raw_credit_deducted
        case raw_tot_paid_amount
        case tot_paid_amount
        case tot_paid_invoices
        case balance
        case current_balance
        case credit_added
        case credit_deducted
        //        case last_recharge_amt
        //        case raw_amount
        case last_recharge_date
    }

    // FIXME: - initializer
    required init(object: JSONObject<PropertyKey>) throws {
        rawBalance = try object.value(for: .raw_credit_adeded)
        rawCreditAdeded = try object.value(for: .raw_credit_adeded)
        rawCreditDeducted = try object.value(for: .raw_credit_deducted)
        rawTotalPaidAmount = try object.value(for: .raw_tot_paid_amount)
        totalPaidAmount = try object.value(for: .tot_paid_amount)
        totalPaidInvoices = try object.value(for: .tot_paid_invoices)
        balance = try object.value(for: .balance)
        currentBalance = try object.value(for: .current_balance)
        creditAdded = try object.value(for: .credit_added)
        creditDeducted = try object.value(for: .credit_deducted)
        //        lastRechargeAmount = try object.value(for: .last_recharge_amt)
        //        rawAmount = try object.value(for: .raw_amount)
        lastRechargeDate = try object.value(for: .last_recharge_date)
    }
}
</code>```

When I uncomment the commented lines from above code, xcode giving me error telling that "No 'value' candidates produce the expected contextual result type 'NSObject'". So my question is how I can set type for that JSON value so that it gets stored with class field.

答:
I cannot comment so I answer you here:

Think that maybe it is because the value of those keys are null, so I will try this:

```<code>     lastRechargeAmount = try? object.value(for: .last_recharge_amt) as? String
     rawAmount = try? object.value(for: .raw_amount) as? String
</code>```

Body:
After successful webservice call I get following json

"balance_details":{
         "raw_balance":"13157.70",
         "raw_credit_adeded":"4035000.00",
         "raw_credit_deducted":"0.00",
         "raw_tot_paid_amount":6000,
         "tot_paid_amount":"Rs.6000.00",
         "tot_paid_invoices":2,
         "balance":"13157.7",
         "current_balance":"Rs.13157.70",
         "credit_added":"Rs.4035000.00",
         "credit_deducted":"Rs.0.00",
         "last_recharge_amt":null,
         "raw_amount":null,
         "last_recharge_date":""
      }

For this web call I'm using Alamofire. To map this JSON into SWIFT OBJECT, I'm using SwiftyJSONModel library. But I'm not able to set type for stoaring null values into JSON object.

class BalanceDetails: JSONObjectInitializable {

    // FIXME: - properties
    var rawBalance: String
    var rawCreditAdeded: String
    var rawCreditDeducted: String
    var rawTotalPaidAmount: Int
    var totalPaidAmount: String
    var totalPaidInvoices: Int
    var balance: String
    var currentBalance: String
    var creditAdded: String
    var creditDeducted: String
    //    var lastRechargeAmount: NSObject
    //    var rawAmount: NSObject
    var lastRechargeDate: String

    // FIXME: - json properties
    enum PropertyKey: String {
        case raw_balance
        case raw_credit_adeded
        case raw_credit_deducted
        case raw_tot_paid_amount
        case tot_paid_amount
        case tot_paid_invoices
        case balance
        case current_balance
        case credit_added
        case credit_deducted
        //        case last_recharge_amt
        //        case raw_amount
        case last_recharge_date
    }

    // FIXME: - initializer
    required init(object: JSONObject<PropertyKey>) throws {
        rawBalance = try object.value(for: .raw_credit_adeded)
        rawCreditAdeded = try object.value(for: .raw_credit_adeded)
        rawCreditDeducted = try object.value(for: .raw_credit_deducted)
        rawTotalPaidAmount = try object.value(for: .raw_tot_paid_amount)
        totalPaidAmount = try object.value(for: .tot_paid_amount)
        totalPaidInvoices = try object.value(for: .tot_paid_invoices)
        balance = try object.value(for: .balance)
        currentBalance = try object.value(for: .current_balance)
        creditAdded = try object.value(for: .credit_added)
        creditDeducted = try object.value(for: .credit_deducted)
        //        lastRechargeAmount = try object.value(for: .last_recharge_amt)
        //        rawAmount = try object.value(for: .raw_amount)
        lastRechargeDate = try object.value(for: .last_recharge_date)
    }
}

When I uncomment the commented lines from above code, xcode giving me error telling that "No 'value' candidates produce the expected contextual result type 'NSObject'". So my question is how I can set type for that JSON value so that it gets stored with class field.

Body:
I cannot comment so I answer you here:

Think that maybe it is because the value of those keys are null, so I will try this:

     lastRechargeAmount = try? object.value(for: .last_recharge_amt) as? String
     rawAmount = try? object.value(for: .raw_amount) as? String


问:
Android - Detect when the last item in a RecyclerView is visible
I have a method that will check if the last element in a RecyclerView is completely visible by the user, so far I have this code
The problem is how to check  if the RecyclerView has reached it's bottom ?

PS I have items dividers

```<code>public void scroll_btn_visibility_controller(){
    if(/**last item is visible to user*/){
        //This is the Bottom of the RecyclerView
        Scroll_Top_Btn.setVisibility(View.VISIBLE);
    }
    else(/**last item is not visible to user*/){
        Scroll_Top_Btn.setVisibility(View.INVISIBLE);
    }
}
</code>```

UPDATE : This is one of the attempts I tried

```<code>boolean isLastVisible() {
    LinearLayoutManager layoutManager = ((LinearLayoutManager)rv.getLayoutManager());
    int pos = layoutManager.findLastCompletelyVisibleItemPosition();
    int numItems =  disp_adapter.getItemCount();
    return (pos >= numItems);
}
public void scroll_btn_visibility_controller(){

    if(isLastVisible()){
        Scroll_Top.setVisibility(View.VISIBLE);
    }
    else{
        Scroll_Top.setVisibility(View.INVISIBLE);
    }
}
</code>```

so far no success I think there is something wrong within these lines :

```<code>int pos = layoutManager.findLastCompletelyVisibleItemPosition();
int numItems =  disp_adapter.getItemCount();
</code>```

答: try working with onScrollStateChanged it will solve your issue

Body:
I have a method that will check if the last element in a RecyclerView is completely visible by the user, so far I have this code
The problem is how to check  if the RecyclerView has reached it's bottom ?

PS I have items dividers

public void scroll_btn_visibility_controller(){
    if(/**last item is visible to user*/){
        //This is the Bottom of the RecyclerView
        Scroll_Top_Btn.setVisibility(View.VISIBLE);
    }
    else(/**last item is not visible to user*/){
        Scroll_Top_Btn.setVisibility(View.INVISIBLE);
    }
}

UPDATE : This is one of the attempts I tried

boolean isLastVisible() {
    LinearLayoutManager layoutManager = ((LinearLayoutManager)rv.getLayoutManager());
    int pos = layoutManager.findLastCompletelyVisibleItemPosition();
    int numItems =  disp_adapter.getItemCount();
    return (pos >= numItems);
}
public void scroll_btn_visibility_controller(){

    if(isLastVisible()){
        Scroll_Top.setVisibility(View.VISIBLE);
    }
    else{
        Scroll_Top.setVisibility(View.INVISIBLE);
    }
}

so far no success I think there is something wrong within these lines :

int pos = layoutManager.findLastCompletelyVisibleItemPosition();
int numItems =  disp_adapter.getItemCount();


问:
Why does a Missing Partial error occur occasionally when the file exists?
While running Cucumber tests, from time to time it will fail intermittently. The error is:

```<code>*** ActionView::Template::Error Exception: Missing partial items/_fields with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :haml]}. Searched in:
  * "/my/path/to/application/app/views"
  * "/my/path/to/rvm/gems/ruby-2.1.5/gems/kaminari-0.16.3/app/views"
  * "/my/path/to/rvm/gems/ruby-2.1.5/gems/devise-3.5.4/app/views"
</code>```

Yes, the partial file does exist in /my/path/to/application/app/views/items/_fields.html.haml

The kicker is that sometimes the test will pass, other times it will fail. I am running on a Red Hat 5 machine.

So to debug this, I decided to throw in a begin/rescue.

```<code>.fields
  - begin
    = render partial: 'items/fields', locals: {f: f}
  - rescue Exception => e
    = byebug

  - if f.can_modify?(:object_a)
    = render partial: 'layouts/object_a_field', locals: {f: f, field: :object_a}
   - else
    .field#object_a
      = render partial: 'layouts/attribute', locals: {label: 'Object A', value: f.object.object_a_id ? f.object.object_a_number : 'Not Assigned'}

    .field#name
    - if f.can_modify?(:name)
      = f.label :name
      = f.text_field :name, {class: 'inputbox large_field', readonly: f.cannot_modify?(:name)}
      .smltxt (short description of the item)
    - else
      = render partial: 'layouts/attribute', object: f.object, locals: {field: :name}
</code>```

For those curious what's in the partial items/fields:

```<code>.field
  - if f.can_modify?(:name)
    = f.label :name, 'Item'
    = f.text_field :name, {class: 'inputbox uppercase', maxlength: 16, readonly: !f.object.identifier.new_record?}
    .smltxt (character identifier)
  - else
    = render partial: 'layouts/attribute', object: f.object, locals: {field: :name, label: 'Item'}
</code>```

When it passes, I obviously don't hit the byebug, but when it fails, I do! Which allows me to play with it in a Rails Console type environment.

So I decided to run that specific command:

```<code>(byebug) render partial: 'items/fields', locals: {f: f}
</code>```

And I get:

```<code>*** ActionView::Template::Error Exception: Missing partial items/_fields with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :haml]}. Searched in:
  * "/my/path/to/application/app/views"
  * "/my/path/to/rvm/gems/ruby-2.1.5/gems/kaminari-0.16.3/app/views"
  * "/my/path/to/rvm/gems/ruby-2.1.5/gems/devise-3.5.4/app/views"
</code>```

So I thought I'd remove the locals to see if anything changed:

```<code>(byebug) render partial: 'items/fields'
</code>```

And I get:

```<code>*** ActionView::Template::Error Exception: undefined local variable or method `f' for #<#<Class:0x0000002a907610>:0x00000027beae48>
</code>```

So obviously it's now magically finding the partial, and it knows that it is missing a local variable f.

Update 1

I added the rest of the view that is calling the partial above for clarity.

In an attempt to troubleshoot, I also took the contents of items/_fields.html.haml and placed it where I had the render partial: 'items/fields', locals: {f: f}... then the test passed, which means that the other partials in the file didn't have an issue either. So it doesn't seem like it could be related to the content of the file.

Update 2

It seems by adding the @javascript tag to our very first Cucumber feature often fixes this issue. Somehow having the browser loaded before the other tests, improves the chances of it passing. Makes no sense to me, maybe someone else has an idea about this?

Update 3

It has been discovered today that the error is not related to Cucumber at all. The same error was found in production. The web interface showed a Missing Partial error, but for a file that did indeed exist. After restarting the Passenger server with touch tmp/restart.txt and then the error went away. So it's still very intermittent.

Update 4

I added the content of the partial that seems to be missing randomly.

How would I go about discovering why Rails cannot find a partial that is actually there?

答:
I strongly believe upgrading to Ruby 2.3.1 solved this for us. I am not certain what may have changed. When we were investigating this, my colleague and I thought we found a line in the Rails source code that was rendering partials differently based on the Ruby version.

I'm having trouble finding that now, but I still wanted to post that the problems seems to have vanished ever since we upgraded to a newer Ruby.

Body:
While running Cucumber tests, from time to time it will fail intermittently. The error is:

*** ActionView::Template::Error Exception: Missing partial items/_fields with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :haml]}. Searched in:
  * "/my/path/to/application/app/views"
  * "/my/path/to/rvm/gems/ruby-2.1.5/gems/kaminari-0.16.3/app/views"
  * "/my/path/to/rvm/gems/ruby-2.1.5/gems/devise-3.5.4/app/views"

Yes, the partial file does exist in /my/path/to/application/app/views/items/_fields.html.haml

The kicker is that sometimes the test will pass, other times it will fail. I am running on a Red Hat 5 machine.

So to debug this, I decided to throw in a begin/rescue.

.fields
  - begin
    = render partial: 'items/fields', locals: {f: f}
  - rescue Exception => e
    = byebug

  - if f.can_modify?(:object_a)
    = render partial: 'layouts/object_a_field', locals: {f: f, field: :object_a}
   - else
    .field#object_a
      = render partial: 'layouts/attribute', locals: {label: 'Object A', value: f.object.object_a_id ? f.object.object_a_number : 'Not Assigned'}

    .field#name
    - if f.can_modify?(:name)
      = f.label :name
      = f.text_field :name, {class: 'inputbox large_field', readonly: f.cannot_modify?(:name)}
      .smltxt (short description of the item)
    - else
      = render partial: 'layouts/attribute', object: f.object, locals: {field: :name}

For those curious what's in the partial items/fields:

.field
  - if f.can_modify?(:name)
    = f.label :name, 'Item'
    = f.text_field :name, {class: 'inputbox uppercase', maxlength: 16, readonly: !f.object.identifier.new_record?}
    .smltxt (character identifier)
  - else
    = render partial: 'layouts/attribute', object: f.object, locals: {field: :name, label: 'Item'}

When it passes, I obviously don't hit the byebug, but when it fails, I do! Which allows me to play with it in a Rails Console type environment.

So I decided to run that specific command:

(byebug) render partial: 'items/fields', locals: {f: f}

And I get:

*** ActionView::Template::Error Exception: Missing partial items/_fields with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :haml]}. Searched in:
  * "/my/path/to/application/app/views"
  * "/my/path/to/rvm/gems/ruby-2.1.5/gems/kaminari-0.16.3/app/views"
  * "/my/path/to/rvm/gems/ruby-2.1.5/gems/devise-3.5.4/app/views"

So I thought I'd remove the locals to see if anything changed:

(byebug) render partial: 'items/fields'

And I get:

*** ActionView::Template::Error Exception: undefined local variable or method `f' for #<#<Class:0x0000002a907610>:0x00000027beae48>

So obviously it's now magically finding the partial, and it knows that it is missing a local variable f.

Update 1

I added the rest of the view that is calling the partial above for clarity.

In an attempt to troubleshoot, I also took the contents of items/_fields.html.haml and placed it where I had the render partial: 'items/fields', locals: {f: f}... then the test passed, which means that the other partials in the file didn't have an issue either. So it doesn't seem like it could be related to the content of the file.

Update 2

It seems by adding the @javascript tag to our very first Cucumber feature often fixes this issue. Somehow having the browser loaded before the other tests, improves the chances of it passing. Makes no sense to me, maybe someone else has an idea about this?

Update 3

It has been discovered today that the error is not related to Cucumber at all. The same error was found in production. The web interface showed a Missing Partial error, but for a file that did indeed exist. After restarting the Passenger server with touch tmp/restart.txt and then the error went away. So it's still very intermittent.

Update 4

I added the content of the partial that seems to be missing randomly.

How would I go about discovering why Rails cannot find a partial that is actually there?


问:
calculate method execution time in Visual Studio Express (No profiler available)?
I am using Visual Studio Express Edition and it don't have any profiler or code analyzer.

Code having two delegate performing same task, one by using anonymous method and one by Lambda expression. I want to compare which one is taking less time.

How can I do this in VS express? (not only for delegate for methods also)

If it is Duplicate, please link it.

Thanks

I tried Like This:

```<code>        /** Start Date time**/
        DateTime startTime = DateTime.Now;
        /********do the square of a number by using LAMBDA EXPRESSIONS********/
        returnSqr myDel = x => x * x;
        Console.WriteLine("By Lambda Expression Square of {0} is: {1}", a,myDel(a));
        /** Stop Date time**/
        DateTime stopTime = DateTime.Now;
        TimeSpan duration = stopTime - startTime;
        Console.WriteLine("Execution time 1:" + duration.Milliseconds);

        /** Start Date time**/
        DateTime startTime2 = DateTime.Now;
        /*****do the square of a number by using ANONYMOUS EXPRESSIONS********/
        returnSqr myDel1 = delegate(int x) { return x * x;};
        Console.WriteLine("By Anonymous Method Square of  {0} is: {1}", a, myDel1(a));
        /** Stop Date time**/
        DateTime stopTime2 = DateTime.Now;
        TimeSpan duration2 = stopTime2 - startTime2;
        Console.WriteLine("Execution Time 2:" + duration.Milliseconds);
</code>```

Output gives:

Execution time 1 : 0

Execution time 2 : 0

Why like this?

答: Just using the stopwatch class should do the trick.</p>

Body:
I am using Visual Studio Express Edition and it don't have any profiler or code analyzer.

Code having two delegate performing same task, one by using anonymous method and one by Lambda expression. I want to compare which one is taking less time.

How can I do this in VS express? (not only for delegate for methods also)

If it is Duplicate, please link it.

Thanks

I tried Like This:

        /** Start Date time**/
        DateTime startTime = DateTime.Now;
        /********do the square of a number by using LAMBDA EXPRESSIONS********/
        returnSqr myDel = x => x * x;
        Console.WriteLine("By Lambda Expression Square of {0} is: {1}", a,myDel(a));
        /** Stop Date time**/
        DateTime stopTime = DateTime.Now;
        TimeSpan duration = stopTime - startTime;
        Console.WriteLine("Execution time 1:" + duration.Milliseconds);

        /** Start Date time**/
        DateTime startTime2 = DateTime.Now;
        /*****do the square of a number by using ANONYMOUS EXPRESSIONS********/
        returnSqr myDel1 = delegate(int x) { return x * x;};
        Console.WriteLine("By Anonymous Method Square of  {0} is: {1}", a, myDel1(a));
        /** Stop Date time**/
        DateTime stopTime2 = DateTime.Now;
        TimeSpan duration2 = stopTime2 - startTime2;
        Console.WriteLine("Execution Time 2:" + duration.Milliseconds);

Output gives:

Execution time 1 : 0

Execution time 2 : 0

Why like this?


问:
How to set false to ASP Button if Ajax result is success?
I am calling Ajax when user click the button. When calling ajax it will check the data with textbox whether the textbox value is already exist or not. If exist, then it should not return false, if the record is not found in database, jquery button should return true let it to save on database through server side.

Note:

My Ajax code is working. But when I the is exist and set return false this statement is not execute.

Here is my code:

```<code>$('#btnSaveFile').click(function () {
    var fileNames = $('#txtFileName').val();
    var flags = 'test';
    alert('test='+flags);
    $.ajax({
        url: 'ReportTotalSalesPivot.aspx/getFileExistOrNot',
        method: 'post',
        async:false,
        contentType: 'application/json',
        data: '{fileName:"' + fileNames + '",reportName:"TotalSales"}',
        dataType: 'json',
        success: function (data) {
            if (data.d === 'dataExist') {

                 // it execute this loop, but after it execute it's going to server

                $('#lblSaveErrorMsg').text('This filename already exist. Please change the name');
                return false;

            }
            else {
                return true;
            }
        },
        error: function (error) {
            alert('Please Call Administrator');
        }
    });
});
</code>```

答:
I found result myself.

Ajax is an Asynchronous. We cannot do return false when the result is success.

So I declare one variable outside of ajax and with the certain condition in success I set return false in outside of ajax code

This is my Jquery code

```<code>    $('#btnSaveFile').click(function () {
    var fileNames = $('#txtFileName').val();
    var flag = 'returnTrue';
    $.ajax({
        url: 'ReportTotalSalesPivot.aspx/getFileExistOrNot',
        method: 'post',
        async: false,
        contentType: 'application/json',
        data: '{fileName:"' + fileNames + '",reportName:"TotalSales"}',
        dataType: 'json',
        success: function (data) {
            if (data.d === 'dataExist') {
                flag = 'returnFalse';
                $('#lblSaveErrorMsg').text('This filename already exist. Please change the name');
            }
            else {
                alert('else');
                return true;
            }
        },
        error: function (error) {
            alert('Please Call Administrator');

        }
    });

    if (flag === 'returnFalse') {
        return false;
    }

});
</code>```

Body:
I am calling Ajax when user click the button. When calling ajax it will check the data with textbox whether the textbox value is already exist or not. If exist, then it should not return false, if the record is not found in database, jquery button should return true let it to save on database through server side.

Note:

My Ajax code is working. But when I the is exist and set return false this statement is not execute.

Here is my code:

$('#btnSaveFile').click(function () {
    var fileNames = $('#txtFileName').val();
    var flags = 'test';
    alert('test='+flags);
    $.ajax({
        url: 'ReportTotalSalesPivot.aspx/getFileExistOrNot',
        method: 'post',
        async:false,
        contentType: 'application/json',
        data: '{fileName:"' + fileNames + '",reportName:"TotalSales"}',
        dataType: 'json',
        success: function (data) {
            if (data.d === 'dataExist') {

                 // it execute this loop, but after it execute it's going to server

                $('#lblSaveErrorMsg').text('This filename already exist. Please change the name');
                return false;

            }
            else {
                return true;
            }
        },
        error: function (error) {
            alert('Please Call Administrator');
        }
    });
});

Body:
I found result myself.

Ajax is an Asynchronous. We cannot do return false when the result is success.

So I declare one variable outside of ajax and with the certain condition in success I set return false in outside of ajax code

This is my Jquery code

    $('#btnSaveFile').click(function () {
    var fileNames = $('#txtFileName').val();
    var flag = 'returnTrue';
    $.ajax({
        url: 'ReportTotalSalesPivot.aspx/getFileExistOrNot',
        method: 'post',
        async: false,
        contentType: 'application/json',
        data: '{fileName:"' + fileNames + '",reportName:"TotalSales"}',
        dataType: 'json',
        success: function (data) {
            if (data.d === 'dataExist') {
                flag = 'returnFalse';
                $('#lblSaveErrorMsg').text('This filename already exist. Please change the name');
            }
            else {
                alert('else');
                return true;
            }
        },
        error: function (error) {
            alert('Please Call Administrator');

        }
    });

    if (flag === 'returnFalse') {
        return false;
    }

});


问:
Center overflown text container

As the picture shows, I need to get rid of the area roughly indicated with the red circle. The aim is to horizontally center the second radio button with its label like the one above and below. This extra undesired width comes about due to the text overflow and the word breaking to the next line when there is not enough width for it all to go on one line.

Note that the aim is to center the radio button and label together i.e. the space between the radio button's right edge and the label's left edge should remain the same.

Also, the second line should not center horizontally, but start from below the radio button as it is already.

Here's a barebone example of the issue:
http://codepen.io/KristjanLaane/pen/ryQZoM

HTML

```<code><body>
  <div>
    <input id="radio1" type="radio" name="choice">
    <label for="radio1">Lorem ipsum dolor sit amet.</label>
  </div>
  <div>
    <input id="radio2" type="radio" name="choice">
    <label for="radio2">Phasellus rutrum scelerisque. Aenean longwordhere tomakethepoint ultricies.</label>
  </div>
  <div>
    <input id="radio3" type="radio" name="choice">
    <label for="radio3">Cras auctor justo metus.</label>
  </div>
</body>
</code>```

CSS

```<code>body {
  display: flex;
  flex-direction: column;
  align-items: center;
}

div {
  border: 1px solid blue;
}

label {
  background: yellow;
  font-size: 25px;
}
</code>```

答:
Break the lengthy word to cover the white space by using     word-break: break-all;

```<code>label {
    background: yellow;
    font-size: 25px;
    word-break: break-all;
  }
</code>```

DEMO

Title: Center overflown text container

Body:
As the picture shows, I need to get rid of the area roughly indicated with the red circle. The aim is to horizontally center the second radio button with its label like the one above and below. This extra undesired width comes about due to the text overflow and the word breaking to the next line when there is not enough width for it all to go on one line.

Note that the aim is to center the radio button and label together i.e. the space between the radio button's right edge and the label's left edge should remain the same.

Also, the second line should not center horizontally, but start from below the radio button as it is already.

Here's a barebone example of the issue:
http://codepen.io/KristjanLaane/pen/ryQZoM

HTML

    <input id="radio1" type="radio" name="choice">
    Lorem ipsum dolor sit amet.

    <input id="radio2" type="radio" name="choice">
    Phasellus rutrum scelerisque. Aenean longwordhere tomakethepoint ultricies.

    <input id="radio3" type="radio" name="choice">
    Cras auctor justo metus.

CSS

body {
  display: flex;
  flex-direction: column;
  align-items: center;
}

div {
  border: 1px solid blue;
}

label {
  background: yellow;
  font-size: 25px;
}

Body:
Break the lengthy word to cover the white space by using     word-break: break-all;

label {
    background: yellow;
    font-size: 25px;
    word-break: break-all;
  }

DEMO


问:
C# Join two DataTables Linq to obtain flatten results
There are 2 datatables structured in this way:

First DataTAble has two cols: Customer, Email_Key

Second DataTAble has two cols: IdCustomer (equals Email_Key), Email

Foreach row in Dt1 can correspond many rows in Dt2 (1 to N) joining EmailKey on CustomerId, so I want to flatten result inside 1 record by using the SelectMany func. How can I achieve this?

答:
I don't think SelectMany is what you're looking for.
SelectMany.

Depending on what you are trying to do, You can try Union or distinct.
You might want to rephrase your question slightly, including if you are trying to "flatten" the results in the select or in code(after you have populated the DataTables).


问:
How to get client computer name using php from remote server
I have already used following php script in remote server application but got null value ::

```<code>exec('wmic COMPUTERSYSTEM Get UserName', $user);
$pc_user = (explode('\\',$user[1]));
$download_location = "c:/users/$pc_user[1]/downloads/";
</code>```

Result :: Array()

But in local pc I got the pc user name properly.

答:
You can get following thorough PHP scripts</p>

```<code>$_SERVER['REMOTE_ADDR']; // Returns the IP address of client
$_SERVER['RREMOTE_HOST']; // Returns the Host name of client
$_SERVER['REMOTE_PORT']; // Returns the port being used to communicate
</code>```

Body:
I have already used following php script in remote server application but got null value ::

exec('wmic COMPUTERSYSTEM Get UserName', $user);
$pc_user = (explode('\\',$user[1]));
$download_location = "c:/users/$pc_user[1]/downloads/";

Result :: Array()

But in local pc I got the pc user name properly.

Body:
You can get following thorough PHP scripts

$_SERVER['REMOTE_ADDR']; // Returns the IP address of client
$_SERVER['RREMOTE_HOST']; // Returns the Host name of client
$_SERVER['REMOTE_PORT']; // Returns the port being used to communicate


问:
CriteriaBuilder order by result of operations
Suppose the following entity:

```<code>Entity {
    Integer id;
    Boolean imported;
    Integer status;
}
</code>```

The task is: When selecting entities those with imported = true AND status != 1 should go to the bottom of search result. It is also necessary to use CriteriaBuilder.

I decided to compute the value which will indicate them to be pulled down by the following expression: imported = true AND status != 1

If writing direct SQL it works as intended having a look:

```<code>SELECT .. FROM .. ORDER BY (imported = true AND status != 1) ASC
</code>```

However I cannot transcode it in context of CriteriaBuilder

I tried to do it like this:

```<code>Predicate eqTruePredicate = cb.equal(root.get(Entity_.imported), true);
Predicate neqStatusPredicate = cb.notEqual(root.get(Entity_.status)), 1);

Predicate andExp = cb.and(eqTruePredicate, neqStatusPredicate);
order.add(0, new OrderImpl(cb.isTrue(andExp)));
</code>```

The generated query is the following:

```<code>order by ( generatedAlias0.imported=:param2 ) and ( generatedAlias0.status<>:param3 ) asc
</code>```

But when execute the exception is thrown saying: "unexpected AST node" pointing at token and

Is there a way to perform ordering by computed value using CriteriaBuilder and what would be necessary to be done?

Addition: Hibernate ORM version: 4.3.5

答:
I managed to do it using CASE statement:

```<code>Expression<Integer> caseExp = cb.<Integer>selectCase()
    .when(
        cb.and(
            cb.equal(root.get(Entity_.imported), true),
            cb.notEqual(root.get(Entity_.status), 1)
        ),
        1
    )
    .otherwise(0);

order.add(0, cb.asc(caseExp));
</code>```

This results into an ORDER BY statement like this:

```<code>order by case when ( entity.imported=true ) and ( entity.status<>1 ) then 1 else 0 end asc
</code>```

Body:
Suppose the following entity:

Entity {
    Integer id;
    Boolean imported;
    Integer status;
}

The task is: When selecting entities those with imported = true AND status != 1 should go to the bottom of search result. It is also necessary to use CriteriaBuilder.

I decided to compute the value which will indicate them to be pulled down by the following expression: imported = true AND status != 1

If writing direct SQL it works as intended having a look:

SELECT .. FROM .. ORDER BY (imported = true AND status != 1) ASC

However I cannot transcode it in context of CriteriaBuilder

I tried to do it like this:

Predicate eqTruePredicate = cb.equal(root.get(Entity_.imported), true);
Predicate neqStatusPredicate = cb.notEqual(root.get(Entity_.status)), 1);

Predicate andExp = cb.and(eqTruePredicate, neqStatusPredicate);
order.add(0, new OrderImpl(cb.isTrue(andExp)));

The generated query is the following:

order by ( generatedAlias0.imported=:param2 ) and ( generatedAlias0.status<>:param3 ) asc

But when execute the exception is thrown saying: "unexpected AST node" pointing at token and

Is there a way to perform ordering by computed value using CriteriaBuilder and what would be necessary to be done?

Addition: Hibernate ORM version: 4.3.5

Body:
I managed to do it using CASE statement:

Expression<Integer> caseExp = cb.<Integer>selectCase()
    .when(
        cb.and(
            cb.equal(root.get(Entity_.imported), true),
            cb.notEqual(root.get(Entity_.status), 1)
        ),
        1
    )
    .otherwise(0);

order.add(0, cb.asc(caseExp));

This results into an ORDER BY statement like this:

order by case when ( entity.imported=true ) and ( entity.status<>1 ) then 1 else 0 end asc


问:
Is there a way to abort a download from onDeterminingFilename
Is there a way to abort/prevent files save dialog during or after</p>

```<code>chrome.downloads.onDeterminingFilename.addListener(function (item, suggest) {

        suggest({
            filename:item.filename,
            conflict_action: 'prompt',
            conflictAction: 'prompt'
        });
        // conflict_action was renamed to conflictAction in
        // https://chromium.googlesource.com/chromium/src/+/f1d784d6938b8fe8e0d257e41b26341992c2552c
        // which was first picked up in branch 1580.
    });
</code>```

答:
Use chrome.downloads.cancel:

chrome.downloads.onDeterminingFilename.addListener(function (item, suggest) {
    suggest({
        filename:item.filename,
        conflict_action: 'prompt',
        conflictAction: 'prompt'
    });

    if(true) { // your cancel condition
        chrome.downloads.cancel(item.id);
    }
});
```

And yeah, you still need to call suggest because only items which are in progress may be canceled.

Body:
Is there a way to abort/prevent files save dialog during or after

chrome.downloads.onDeterminingFilename.addListener(function (item, suggest) {

        suggest({
            filename:item.filename,
            conflict_action: 'prompt',
            conflictAction: 'prompt'
        });
        // conflict_action was renamed to conflictAction in
        // https://chromium.googlesource.com/chromium/src/+/f1d784d6938b8fe8e0d257e41b26341992c2552c
        // which was first picked up in branch 1580.
    });

Body:
Use chrome.downloads.cancel:

chrome.downloads.onDeterminingFilename.addListener(function (item, suggest) {
    suggest({
        filename:item.filename,
        conflict_action: 'prompt',
        conflictAction: 'prompt'
    });

    if(true) { // your cancel condition
        chrome.downloads.cancel(item.id);
    }
});

And yeah, you still need to call suggest because only items which are in progress may be canceled.


问:
Python: Read CSV file and write to another text file
I have this .csv file ...

```<code>    id,first_name,last_name,email,date,opt-in,unique_code
    1,Jimmy,Reyes,jreyes0@macromedia.com,12/29/2016,FALSE,ER45DH
    2,Doris,Wood,dwood1@1und1.de,04/22/2016,,MU34T3
    3,Steven,Miller,smiller2@go.com,07/31/2016,FALSE,G34FGH
    4,Earl,Parker,eparker3@ucoz.com,01-08-17,FALSE,ASY67J
    5,Barbara,Cruz,bcruz4@zdnet.com,12/30/2016,FALSE,NHG67P
</code>```

If the opt-in value is empty, its should print "0". The last value in csv should print first, and then all the name, value pairs in a specific format,  like shown in the expected output file below.

My expected output

```<code>ER45DH<tab>"id"="1","first_name"="Jimmy","last_name"="Reyes","email"="jreyes0@macromedia.com","date"="12/29/2016","opt-in"="FALSE"
MU34T3<tab>"id"="2","first_name"="Doris","last_name"="Wood","email"="dwood1@1und1.de","date"="04/22/2016,"opt-in"="0"
.......
</code>```

My code so far ..

```<code>import csv

with open('newfilename.csv', 'w') as f2:
    with open('mycsvfile.csv', mode='r') as infile:
        reader = csv.reader(infile)
        for i,rows in enumerate(reader):
            if i == 0:
               header = rows
            else:
                if rows[5] == '':
                   rows[5] = 0;
                pat = rows[0]+'\t'+'''"%s"="%%s",'''*(len(header)-2)+'''"%s"="%%s"\n'''
                print pat
                f2.write(pat % tuple(header[1:]) % tuple(rows[1:]))
    f2.close()
</code>```

This code produces this output

```<code>1   "first_name"="Jimmy","last_name"="Reyes","email"="jreyes0@macromedia.com","date"="12/29/2016","opt-in"="FALSE","unique_code"="ASD34R"
2   "first_name"="Doris","last_name"="Wood","email"="dwood1@1und1.de","date"="04/22/2016","opt-in"="0","unique_code"="SDS56N"
</code>```

As you can see column "id" is missing, and I want unque_code at first place.

I will really appreciate any help/ideas/pointers.

Thanks

答:
You should process separately the header line, and then correctly process each line. You code could become:

```<code>with open('newfilename.csv', 'w') as f2:
    with open('mycsvfile.csv', mode='r') as infile:
        reader = csv.reader(infile)
        header = next(reader)  # store the headers and advance reader pointer
        for rows in reader:
            if rows[5]=="": rows[5] = "0"  # special processing for 6th field
            # uses last field here
            pat = rows[-1]+'\t'+'''"%s"="%%s",'''*(len(header)-2)+'''"%s"="%%s"\n'''
            # process everything except last field
            fd2.write((pat % tuple(header[:-1])) % tuple(rows[:-1]))
</code>```

No need to load the whole file in memory...

Body:
I have this .csv file ...

    id,first_name,last_name,email,date,opt-in,unique_code
    1,Jimmy,Reyes,jreyes0@macromedia.com,12/29/2016,FALSE,ER45DH
    2,Doris,Wood,dwood1@1und1.de,04/22/2016,,MU34T3
    3,Steven,Miller,smiller2@go.com,07/31/2016,FALSE,G34FGH
    4,Earl,Parker,eparker3@ucoz.com,01-08-17,FALSE,ASY67J
    5,Barbara,Cruz,bcruz4@zdnet.com,12/30/2016,FALSE,NHG67P

If the opt-in value is empty, its should print "0". The last value in csv should print first, and then all the name, value pairs in a specific format,  like shown in the expected output file below.

My expected output

ER45DH<tab>"id"="1","first_name"="Jimmy","last_name"="Reyes","email"="jreyes0@macromedia.com","date"="12/29/2016","opt-in"="FALSE"
MU34T3<tab>"id"="2","first_name"="Doris","last_name"="Wood","email"="dwood1@1und1.de","date"="04/22/2016,"opt-in"="0"
.......

My code so far ..

import csv

with open('newfilename.csv', 'w') as f2:
    with open('mycsvfile.csv', mode='r') as infile:
        reader = csv.reader(infile)
        for i,rows in enumerate(reader):
            if i == 0:
               header = rows
            else:
                if rows[5] == '':
                   rows[5] = 0;
                pat = rows[0]+'\t'+'''"%s"="%%s",'''*(len(header)-2)+'''"%s"="%%s"\n'''
                print pat
                f2.write(pat % tuple(header[1:]) % tuple(rows[1:]))
    f2.close()

This code produces this output

1   "first_name"="Jimmy","last_name"="Reyes","email"="jreyes0@macromedia.com","date"="12/29/2016","opt-in"="FALSE","unique_code"="ASD34R"
2   "first_name"="Doris","last_name"="Wood","email"="dwood1@1und1.de","date"="04/22/2016","opt-in"="0","unique_code"="SDS56N"

As you can see column "id" is missing, and I want unque_code at first place.

I will really appreciate any help/ideas/pointers.

Thanks

Body:
You should process separately the header line, and then correctly process each line. You code could become:

with open('newfilename.csv', 'w') as f2:
    with open('mycsvfile.csv', mode='r') as infile:
        reader = csv.reader(infile)
        header = next(reader)  # store the headers and advance reader pointer
        for rows in reader:
            if rows[5]=="": rows[5] = "0"  # special processing for 6th field
            # uses last field here
            pat = rows[-1]+'\t'+'''"%s"="%%s",'''*(len(header)-2)+'''"%s"="%%s"\n'''
            # process everything except last field
            fd2.write((pat % tuple(header[:-1])) % tuple(rows[:-1]))

No need to load the whole file in memory...


问:
Creating stored procedures in mysql
what is wrong in this code

```<code>CREATE DEFINER=`root`@`localhost` PROCEDURE `diff`()
BEGIN
    declare max_date datetime;
    declare tday_date datetime;
    declare main_id varchar(20);

    select concat('#GNC', '3') into main_id;  #error shows here

    declare m1 int;
    declare m2 int;
    select max(order_date) into max_date from `order`;
    #select max_date;
    select curdate() into tday_date;
    select extract(month from max_date) into m1;
    select extract(month from tday_date) into m2;

    if m1 != m2 then
        TRUNCATE `grocery`.`order_seqid`;
    end if;

    select m1, m2, main_id;
END
</code>```

It is giving error like missing end. if I remove the if statement it works fine.

答:
You are missing delimeter ,as well as declare section does not contains any simple SELECT Statement.
In your code just replace

```<code>   declare main_id varchar(20);
    select concat('#GNC', '3') into main_id;  #error shows here
    declare m1 int;
    declare m2 int;
</code>```

with

```<code>declare main_id varchar(20);
declare m1 int;
declare m2 int;
select concat('#GNC', '3') into main_id;  #error shows here
</code>```

Try below code

```<code>DELIMITER $$
CREATE DEFINER=`root`@`localhost` PROCEDURE `diff`()
BEGIN
    declare max_date datetime;
    declare tday_date datetime;
    declare main_id varchar(20);
    declare m1 int;
    declare m2 int;
    select concat('#GNC', '3') into main_id  ;
    select max(order_date) into max_date from `order`;
    #select max_date;
    select curdate() into tday_date;
    select extract(month from max_date) into m1;
    select extract(month from tday_date) into m2;

    if m1 != m2 then
        TRUNCATE `grocery`.`order_seqid`;
    end if;

    select m1, m2, main_id;
END
</code>```

Hope this will helps.

Title: Creating stored procedures in mysql

Body:
what is wrong in this code

CREATE DEFINER=`root`@`localhost` PROCEDURE `diff`()
BEGIN
    declare max_date datetime;
    declare tday_date datetime;
    declare main_id varchar(20);

    select concat('#GNC', '3') into main_id;  #error shows here

    declare m1 int;
    declare m2 int;
    select max(order_date) into max_date from `order`;
    #select max_date;
    select curdate() into tday_date;
    select extract(month from max_date) into m1;
    select extract(month from tday_date) into m2;

    if m1 != m2 then
        TRUNCATE `grocery`.`order_seqid`;
    end if;

    select m1, m2, main_id;
END

It is giving error like missing end. if I remove the if statement it works fine.

Body:
You are missing delimeter ,as well as declare section does not contains any simple SELECT Statement.
In your code just replace

   declare main_id varchar(20);
    select concat('#GNC', '3') into main_id;  #error shows here
    declare m1 int;
    declare m2 int;

with

declare main_id varchar(20);
declare m1 int;
declare m2 int;
select concat('#GNC', '3') into main_id;  #error shows here

Try below code

DELIMITER $$
CREATE DEFINER=`root`@`localhost` PROCEDURE `diff`()
BEGIN
    declare max_date datetime;
    declare tday_date datetime;
    declare main_id varchar(20);
    declare m1 int;
    declare m2 int;
    select concat('#GNC', '3') into main_id  ;
    select max(order_date) into max_date from `order`;
    #select max_date;
    select curdate() into tday_date;
    select extract(month from max_date) into m1;
    select extract(month from tday_date) into m2;

    if m1 != m2 then
        TRUNCATE `grocery`.`order_seqid`;
    end if;

    select m1, m2, main_id;
END

Hope this will helps.


问:
Correct way to use encryption in Xamarin shared project
I'm currently developing a Xamarin Forms Project and I need to use a few encryption methods that would normally be available through namespace System.Security.Cryptography namely RSACryptoServiceProvider. So far I have been using PCLCrypto nuget package to use other methods such MD5 hashing but I haven't figured out how to use RSA specifically. I was also wondering if it would be better to implement those methods directly on each native Project instead and then use them on the shared one instead of using the nuget.

Any thoughts on this? If someone could point me towards some documentation for PCLCrypto equivalent to what I need it would be fine as well, I just need some lights on this concern and some clarification since I've read some other questions but there isn't really a consensus.

答:
I don't know if AES could be interesting for you but maybe you can take at look at this sample.

```<code>byte[] keyMaterial;
byte[] data;
var provider = WinRTCrypto.SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithm.AesCbcPkcs7);
var key = provider.CreateSymmetricKey(keyMaterial);

// The IV may be null, but supplying a random IV increases security.
// The IV is not a secret like the key is.
// You can transmit the IV (w/o encryption) alongside the ciphertext.
var iv = WinRTCrypto.CryptographicBuffer.GenerateRandom(provider.BlockLength);

byte[] cipherText = WinRTCrypto.CryptographicEngine.Encrypt(key, data, iv);

// When decrypting, use the same IV that was passed to encrypt.
byte[] plainText = WinRTCrypto.CryptographicEngine.Decrypt(key, cipherText, iv);
</code>```

Source: PCLCrypto Github

Maybe this link could help you with crypto on Xamarin.Forms project (Using Cryptography in Portable Xamarin Forms (Windows Phone, Android and IOS))

Body:
I don't know if AES could be interesting for you but maybe you can take at look at this sample.

byte[] keyMaterial;
byte[] data;
var provider = WinRTCrypto.SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithm.AesCbcPkcs7);
var key = provider.CreateSymmetricKey(keyMaterial);

// The IV may be null, but supplying a random IV increases security.
// The IV is not a secret like the key is.
// You can transmit the IV (w/o encryption) alongside the ciphertext.
var iv = WinRTCrypto.CryptographicBuffer.GenerateRandom(provider.BlockLength);

byte[] cipherText = WinRTCrypto.CryptographicEngine.Encrypt(key, data, iv);

// When decrypting, use the same IV that was passed to encrypt.
byte[] plainText = WinRTCrypto.CryptographicEngine.Decrypt(key, cipherText, iv);

Source: PCLCrypto Github

Maybe this link could help you with crypto on Xamarin.Forms project (Using Cryptography in Portable Xamarin Forms (Windows Phone, Android and IOS))