问:
Sending keyboard key to browser in C# using sendkey function
Hello i am trying to send a key to browser using the code below, the new chrome window opens for me but it does not send the key to the browser.

When i debugged i found out chrome process does not have any title name how can i solve this problem?

```<code> Process.Start("chrome.exe", "https://labs.sketchfab.com/sculptfab/");
        System.Threading.Thread.Sleep(2000);
        foreach (System.Diagnostics.Process p in System.Diagnostics.Process.GetProcesses())
        {
            if (p.ProcessName == "chrome" && p.MainWindowTitle == "SculptFab - SculptGL + Sketchfab" &&
                p.MainWindowHandle != IntPtr.Zero)
            {
                System.Threading.Thread.Sleep(2000);
                for (int i = 0; i < 50; i++)
                {
                    KeyHandle.SetForeGround(p.MainWindowHandle);
                    SendKeys.Send("s");
                    System.Threading.Thread.Sleep(2000);
                }

            }
        }
</code>```

In the above mentioned page when "S" is pressed on the keyboard it zooms out of the object i want too achieve this using my C# code

答:
Here is an updated version of ChromeWrapper that:

Works also when chrome was already open (attaches to existing chrome window)

Works when the computer is locked (unlike SendKeys.SendWait)

.

```<code>public class ChromeWrapper
{
    [DllImport("user32.dll")]
    private static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
    // the keystroke signals. you can look them up at the msdn pages
    private static uint WM_KEYDOWN = 0x100, WM_KEYUP = 0x101;

    // the reference to the chrome process
    private Process chromeProcess;

    public ChromeWrapper(string url)
    {
        chromeProcess = new Process();
        chromeProcess.StartInfo = new ProcessStartInfo("chrome.exe", url);
        chromeProcess.StartInfo.UseShellExecute = true;
        chromeProcess.Start(); //no need to keep reference to this process, because if chrome is already opened, this is NOT the correct reference.
        Thread.Sleep(600); //without this behavior is altered (tap key presses operate on other objects on the page)

        Process[] procsChrome = Process.GetProcessesByName("chrome");
        foreach (Process chrome in procsChrome)
        {
            if (chrome.MainWindowHandle == IntPtr.Zero)// the chrome process must have a window
                continue;
            chromeProcess = chrome; //now you have a handle to the main chrome (either a new one or the one that was already open).
            return;
        }
    }

    public void SendKey(char key)
    {
        try
        {
            if (chromeProcess.MainWindowHandle != IntPtr.Zero)
            {
                // send the keydown signal
                SendMessage(chromeProcess.MainWindowHandle, ChromeWrapper.WM_KEYDOWN, (IntPtr)key, IntPtr.Zero);
                // give the process some time to "realize" the keystroke
                Thread.Sleep(30); //On my system it works fine without this Sleep.
                // send the keyup signal
                SendMessage(chromeProcess.MainWindowHandle, ChromeWrapper.WM_KEYUP, (IntPtr)key, IntPtr.Zero);
            }
        }
        catch (Exception e) //without the GetProcessesByName you'd get an exception.
        {
        }
    }
}
</code>```

I use it as below, for sending Tab and Enter keys.

```<code>ChromeWrapper chrome = new ChromeWrapper(@"https://stackoverflow.com");
Thread.Sleep(300);
chrome.SendKey((char)9);// tab
chrome.SendKey((char)13);//enter
</code>```

Body:
Hello i am trying to send a key to browser using the code below, the new chrome window opens for me but it does not send the key to the browser.

When i debugged i found out chrome process does not have any title name how can i solve this problem?

 Process.Start("chrome.exe", "https://labs.sketchfab.com/sculptfab/");
        System.Threading.Thread.Sleep(2000);
        foreach (System.Diagnostics.Process p in System.Diagnostics.Process.GetProcesses())
        {
            if (p.ProcessName == "chrome" && p.MainWindowTitle == "SculptFab - SculptGL + Sketchfab" &&
                p.MainWindowHandle != IntPtr.Zero)
            {
                System.Threading.Thread.Sleep(2000);
                for (int i = 0; i < 50; i++)
                {
                    KeyHandle.SetForeGround(p.MainWindowHandle);
                    SendKeys.Send("s");
                    System.Threading.Thread.Sleep(2000);
                }

            }
        }

In the above mentioned page when "S" is pressed on the keyboard it zooms out of the object i want too achieve this using my C# code

Body:
Here is an updated version of ChromeWrapper that:

Works also when chrome was already open (attaches to existing chrome window)

Works when the computer is locked (unlike SendKeys.SendWait)

.

public class ChromeWrapper
{
    [DllImport("user32.dll")]
    private static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
    // the keystroke signals. you can look them up at the msdn pages
    private static uint WM_KEYDOWN = 0x100, WM_KEYUP = 0x101;

    // the reference to the chrome process
    private Process chromeProcess;

    public ChromeWrapper(string url)
    {
        chromeProcess = new Process();
        chromeProcess.StartInfo = new ProcessStartInfo("chrome.exe", url);
        chromeProcess.StartInfo.UseShellExecute = true;
        chromeProcess.Start(); //no need to keep reference to this process, because if chrome is already opened, this is NOT the correct reference.
        Thread.Sleep(600); //without this behavior is altered (tap key presses operate on other objects on the page)

        Process[] procsChrome = Process.GetProcessesByName("chrome");
        foreach (Process chrome in procsChrome)
        {
            if (chrome.MainWindowHandle == IntPtr.Zero)// the chrome process must have a window
                continue;
            chromeProcess = chrome; //now you have a handle to the main chrome (either a new one or the one that was already open).
            return;
        }
    }

    public void SendKey(char key)
    {
        try
        {
            if (chromeProcess.MainWindowHandle != IntPtr.Zero)
            {
                // send the keydown signal
                SendMessage(chromeProcess.MainWindowHandle, ChromeWrapper.WM_KEYDOWN, (IntPtr)key, IntPtr.Zero);
                // give the process some time to "realize" the keystroke
                Thread.Sleep(30); //On my system it works fine without this Sleep.
                // send the keyup signal
                SendMessage(chromeProcess.MainWindowHandle, ChromeWrapper.WM_KEYUP, (IntPtr)key, IntPtr.Zero);
            }
        }
        catch (Exception e) //without the GetProcessesByName you'd get an exception.
        {
        }
    }
}

I use it as below, for sending Tab and Enter keys.

ChromeWrapper chrome = new ChromeWrapper(@"https://stackoverflow.com");
Thread.Sleep(300);
chrome.SendKey((char)9);// tab
chrome.SendKey((char)13);//enter


来源: stackexchange

问:
Website layout using flexbox
Sorry for bad english, i'm using google translate!

I have created a site using flexbox - codepen.io/anon/pen/zPwjRp. Applied @media for a width site of less than 700 pixels. It seems all right, but as soon as the width of the window becomes less than 717px the following problem appears:

Horizontal scrollbar

Right sidebar moves a little beyond the permissible border

Block with the main content also goes to the right (it is clear that there is an indent on the left, but there is no indent visible to the right).

Guys & girls, please help!

答:
Issues 1 and 3 happen because of the left and right margin.
Add this

```<code>.content-wrapper {
width: 100%;
margin-left: 0;
margin-right: 0;
</code>```

to your media query, check the full code below:

body {
  background: #111;
  font: 15px Tahoma;
  color: #00C8FF;
}

#header {
  display: flex;
  justify-content: center;
  height: 150px;
  background: #263238;
}

#header h3 {
  margin: 0;
  align-self: center;
}

/* Глобальный блок обертка */

#wrapper {
  width: 100%;
  display: flex;
  justify-content: space-between;
  margin: 10px auto 0 auto;
}

/* Все сайдбары фиксированной ширины */

.sidebar {
  width: 202px;
  min-width: 202px;
}

/* У первых сайдбаров убираем отступ */

.sidebar-item:first-child {
  margin-top: 0;
}

/* У остальных делаем отступ друг от друга */

.sidebar-item {
  margin-top: 10px;
}

/* Верхний и нижний фон сайдбара идентичного цвета и одинаковой высоты */

.sitem-top-bg,
.sitem-bottom-bg {
  height: 84px;
  background: #3e2723;
}

/* Средний фон с выравниванием текста по центру */

.sitem-middle-bg {
  background: #5d4037;
  text-align: center;
}

/* Обертка основного содержимого */

.content-wrapper {
  width: 68%;
  margin-left: 10px;
  margin-right: 10px;
}

/* Выстраиваем в одну линию несколько верхних фонов и поровну делим расстояние между блоками */

.cw-top-bg {
  display: flex;
  justify-content: space-between;
}

/* Все верхние фоны имеют идентичную высоту */

.cw-top-bg-left,
.cw-top-bg-middle,
.cw-top-bg-right {
  height: 40px;
}

/* Верхний левый и правый блок с минимальной шириной */

.cw-top-bg-left,
.cw-top-bg-right {
  min-width: 134px;
  background: #212121;
}

/* Верхний средний фон */

.cw-top-bg-middle {
  width: 100%;
  background: #424242;
}

/* Выстраиваем все средние и нижние блоки основного содержимого в линию */

.cw-middle-bg,
.cw-bottom-bg {
  display: flex;
  justify-content: space-between;
}

/* Боковые полосы */

.cw-middle-bg-left,
.cw-middle-bg-right {
  width: 30px;
  min-width: 30px;
  background: #607d8b;
}

/* Средний фон с основным содержимым */

.cw-middle-bg-center {
  color: #137DE6;
  padding: 10px;
  background: rgba(29, 26, 26, 0.64);
}

.cw-bottom-bg-left,
.cw-bottom-bg-right {
  width: 68px;
  min-width: 68px;
  height: 35px;
  background: #382f2f;
}

.cw-bottom-bg-middle {
  height: 35px;
  width: 100%;
  background: #222;
}

@media (max-width: 700px) {
  #wrapper {
    flex-direction: column;
  }
  .sidebar {
    align-self: center;
  }
  .content-wrapper {
    width: 100%;
    margin-left: 0;
    margin-right: 0;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="header">
  <h3>Шапка с логотипом</h3>
</div>

<div id="wrapper">
  <!-- Обертка для сайдбаров !-->
  <div class="sidebar">

    <!-- Обертка для отдельных блоков сайдбаров !-->
    <div class="sidebar-item">
      <!-- Верхний фон сайдбара !-->
      <div class="sitem-top-bg"></div>
      <!-- Средний фон сайдбара!-->
      <div class="sitem-middle-bg">
        Какое нибудь содержимое
      </div>
      <!-- Нижний фон сайдбара !-->
      <div class="sitem-bottom-bg"></div>
    </div>

    <!-- Обертка для отдельных блоков сайдбаров !-->
    <div class="sidebar-item">
      <!-- Верхний фон сайдбара !-->
      <div class="sitem-top-bg"></div>
      <!-- Средний фон сайдбара!-->
      <div class="sitem-middle-bg">
        Какое нибудь содержимое
      </div>
      <!-- Нижний фон сайдбара !-->
      <div class="sitem-bottom-bg"></div>
    </div>

    <!-- Обертка для отдельных блоков сайдбаров !-->
    <div class="sidebar-item">
      <!-- Верхний фон сайдбара !-->
      <div class="sitem-top-bg"></div>
      <!-- Средний фон сайдбара!-->
      <div class="sitem-middle-bg">
        Какое нибудь содержимое
      </div>
      <!-- Нижний фон сайдбара !-->
      <div class="sitem-bottom-bg"></div>
    </div>

  </div>

  <!-- Обертка основного содержимого !-->
  <div class="content-wrapper">

    <div class="cw-top-bg">
      <div class="cw-top-bg-left"></div>
      <div class="cw-top-bg-middle"></div>
      <div class="cw-top-bg-right"></div>
    </div>

    <div class="cw-middle-bg">
      <div class="cw-middle-bg-left"></div>
      <div class="cw-middle-bg-center">
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum at dui mattis, convallis justo nec, auctor augue. Nulla vel lacinia nisi. Duis nec dolor nibh. Pellentesque elementum urna nec viverra venenatis. Aenean commodo pellentesque ante.
          Nullam quis mi egestas, volutpat ipsum sed, hendrerit diam. Fusce ut ligula a magna molestie feugiat sed at quam. Maecenas porta, metus sed sodales molestie, ex lacus porttitor nisl, vel lobortis sem tellus vel risus. Phasellus erat massa, scelerisque
          id augue vel, volutpat lacinia lectus. Etiam efficitur, purus vitae ultricies ultricies, massa est vestibulum nisi, eu tincidunt diam velit id diam. Duis elementum tristique pellentesque. Nunc erat tortor, convallis sed sodales a, luctus quis
          nunc.

      </div>
      <div class="cw-middle-bg-right"></div>
    </div>

    <div class="cw-bottom-bg">
      <div class="cw-bottom-bg-left"></div>
      <div class="cw-bottom-bg-middle"></div>
      <div class="cw-bottom-bg-right"></div>
    </div>

  </div>

  <!-- Обертка для сайдбаров !-->
  <div class="sidebar">

    <!-- Обертка для отдельных блоков сайдбаров !-->
    <div class="sidebar-item">
      <!-- Верхний фон сайдбара !-->
      <div class="sitem-top-bg"></div>
      <!-- Средний фон сайдбара!-->
      <div class="sitem-middle-bg">
        Какое нибудь содержимое
      </div>
      <!-- Нижний фон сайдбара !-->
      <div class="sitem-bottom-bg"></div>
    </div>

    <!-- Обертка для отдельных блоков сайдбаров !-->
    <div class="sidebar-item">
      <!-- Верхний фон сайдбара !-->
      <div class="sitem-top-bg"></div>
      <!-- Средний фон сайдбара!-->
      <div class="sitem-middle-bg">
        Какое нибудь содержимое
      </div>
      <!-- Нижний фон сайдбара !-->
      <div class="sitem-bottom-bg"></div>
    </div>

    <!-- Обертка для отдельных блоков сайдбаров !-->
    <div class="sidebar-item">
      <!-- Верхний фон сайдбара !-->
      <div class="sitem-top-bg"></div>
      <!-- Средний фон сайдбара!-->
      <div class="sitem-middle-bg">
        Какое нибудь содержимое
      </div>
      <!-- Нижний фон сайдбара !-->
      <div class="sitem-bottom-bg"></div>
    </div>

  </div>

</div></code>```

ContentLicense: CC BY-SA 3.0

Title: Website layout using flexbox

Body:
Issues 1 and 3 happen because of the left and right margin.
Add this

.content-wrapper {
width: 100%;
margin-left: 0;
margin-right: 0;

to your media query, check the full code below:

body {
  background: #111;
  font: 15px Tahoma;
  color: #00C8FF;
}

#header {
  display: flex;
  justify-content: center;
  height: 150px;
  background: #263238;
}

#header h3 {
  margin: 0;
  align-self: center;
}

/* Глобальный блок обертка */

#wrapper {
  width: 100%;
  display: flex;
  justify-content: space-between;
  margin: 10px auto 0 auto;
}

/* Все сайдбары фиксированной ширины */

.sidebar {
  width: 202px;
  min-width: 202px;
}

/* У первых сайдбаров убираем отступ */

.sidebar-item:first-child {
  margin-top: 0;
}

/* У остальных делаем отступ друг от друга */

.sidebar-item {
  margin-top: 10px;
}

/* Верхний и нижний фон сайдбара идентичного цвета и одинаковой высоты */

.sitem-top-bg,
.sitem-bottom-bg {
  height: 84px;
  background: #3e2723;
}

/* Средний фон с выравниванием текста по центру */

.sitem-middle-bg {
  background: #5d4037;
  text-align: center;
}

/* Обертка основного содержимого */

.content-wrapper {
  width: 68%;
  margin-left: 10px;
  margin-right: 10px;
}

/* Выстраиваем в одну линию несколько верхних фонов и поровну делим расстояние между блоками */

.cw-top-bg {
  display: flex;
  justify-content: space-between;
}

/* Все верхние фоны имеют идентичную высоту */

.cw-top-bg-left,
.cw-top-bg-middle,
.cw-top-bg-right {
  height: 40px;
}

/* Верхний левый и правый блок с минимальной шириной */

.cw-top-bg-left,
.cw-top-bg-right {
  min-width: 134px;
  background: #212121;
}

/* Верхний средний фон */

.cw-top-bg-middle {
  width: 100%;
  background: #424242;
}

/* Выстраиваем все средние и нижние блоки основного содержимого в линию */

.cw-middle-bg,
.cw-bottom-bg {
  display: flex;
  justify-content: space-between;
}

/* Боковые полосы */

.cw-middle-bg-left,
.cw-middle-bg-right {
  width: 30px;
  min-width: 30px;
  background: #607d8b;
}

/* Средний фон с основным содержимым */

.cw-middle-bg-center {
  color: #137DE6;
  padding: 10px;
  background: rgba(29, 26, 26, 0.64);
}

.cw-bottom-bg-left,
.cw-bottom-bg-right {
  width: 68px;
  min-width: 68px;
  height: 35px;
  background: #382f2f;
}

.cw-bottom-bg-middle {
  height: 35px;
  width: 100%;
  background: #222;
}

@media (max-width: 700px) {
  #wrapper {
    flex-direction: column;
  }
  .sidebar {
    align-self: center;
  }
  .content-wrapper {
    width: 100%;
    margin-left: 0;
    margin-right: 0;
  }
}

<div id="header">
  <h3>Шапка с логотипом</h3>
</div>

<div id="wrapper">
  <!-- Обертка для сайдбаров !-->
  <div class="sidebar">

    <!-- Обертка для отдельных блоков сайдбаров !-->
    <div class="sidebar-item">
      <!-- Верхний фон сайдбара !-->
      <div class="sitem-top-bg"></div>
      <!-- Средний фон сайдбара!-->
      <div class="sitem-middle-bg">
        Какое нибудь содержимое
      </div>
      <!-- Нижний фон сайдбара !-->
      <div class="sitem-bottom-bg"></div>
    </div>

    <!-- Обертка для отдельных блоков сайдбаров !-->
    <div class="sidebar-item">
      <!-- Верхний фон сайдбара !-->
      <div class="sitem-top-bg"></div>
      <!-- Средний фон сайдбара!-->
      <div class="sitem-middle-bg">
        Какое нибудь содержимое
      </div>
      <!-- Нижний фон сайдбара !-->
      <div class="sitem-bottom-bg"></div>
    </div>

    <!-- Обертка для отдельных блоков сайдбаров !-->
    <div class="sidebar-item">
      <!-- Верхний фон сайдбара !-->
      <div class="sitem-top-bg"></div>
      <!-- Средний фон сайдбара!-->
      <div class="sitem-middle-bg">
        Какое нибудь содержимое
      </div>
      <!-- Нижний фон сайдбара !-->
      <div class="sitem-bottom-bg"></div>
    </div>

  </div>

  <!-- Обертка основного содержимого !-->
  <div class="content-wrapper">

    <div class="cw-top-bg">
      <div class="cw-top-bg-left"></div>
      <div class="cw-top-bg-middle"></div>
      <div class="cw-top-bg-right"></div>
    </div>

    <div class="cw-middle-bg">
      <div class="cw-middle-bg-left"></div>
      <div class="cw-middle-bg-center">
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum at dui mattis, convallis justo nec, auctor augue. Nulla vel lacinia nisi. Duis nec dolor nibh. Pellentesque elementum urna nec viverra venenatis. Aenean commodo pellentesque ante.
          Nullam quis mi egestas, volutpat ipsum sed, hendrerit diam. Fusce ut ligula a magna molestie feugiat sed at quam. Maecenas porta, metus sed sodales molestie, ex lacus porttitor nisl, vel lobortis sem tellus vel risus. Phasellus erat massa, scelerisque
          id augue vel, volutpat lacinia lectus. Etiam efficitur, purus vitae ultricies ultricies, massa est vestibulum nisi, eu tincidunt diam velit id diam. Duis elementum tristique pellentesque. Nunc erat tortor, convallis sed sodales a, luctus quis
          nunc.

      </div>
      <div class="cw-middle-bg-right"></div>
    </div>

    <div class="cw-bottom-bg">
      <div class="cw-bottom-bg-left"></div>
      <div class="cw-bottom-bg-middle"></div>
      <div class="cw-bottom-bg-right"></div>
    </div>

  </div>

  <!-- Обертка для сайдбаров !-->
  <div class="sidebar">

    <!-- Обертка для отдельных блоков сайдбаров !-->
    <div class="sidebar-item">
      <!-- Верхний фон сайдбара !-->
      <div class="sitem-top-bg"></div>
      <!-- Средний фон сайдбара!-->
      <div class="sitem-middle-bg">
        Какое нибудь содержимое
      </div>
      <!-- Нижний фон сайдбара !-->
      <div class="sitem-bottom-bg"></div>
    </div>

    <!-- Обертка для отдельных блоков сайдбаров !-->
    <div class="sidebar-item">
      <!-- Верхний фон сайдбара !-->
      <div class="sitem-top-bg"></div>
      <!-- Средний фон сайдбара!-->
      <div class="sitem-middle-bg">
        Какое нибудь содержимое
      </div>
      <!-- Нижний фон сайдбара !-->
      <div class="sitem-bottom-bg"></div>
    </div>

    <!-- Обертка для отдельных блоков сайдбаров !-->
    <div class="sidebar-item">
      <!-- Верхний фон сайдбара !-->
      <div class="sitem-top-bg"></div>
      <!-- Средний фон сайдбара!-->
      <div class="sitem-middle-bg">
        Какое нибудь содержимое
      </div>
      <!-- Нижний фон сайдбара !-->
      <div class="sitem-bottom-bg"></div>
    </div>

  </div>

</div>


问:
Generate missing data from existing data
I have hourly level data of a unit, with its status and its value. The status and value of the unit changes after certain intervals (not necessarily at every hour). I want to generate hourly level data from existing data. Say for example: I have input such as:

and output required is:

Please find below scripts for required input and output:

Input

```<code>SELECT '3' as ID,'CName1' AS Name,'0' AS Status,'2017-10-25' AS CDate,'22' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'1' AS Status,'2017-10-26' AS CDate,'2' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'0' AS Status,'2017-10-26' AS CDate,'5' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'1' AS Status,'2017-10-26' AS CDate,'8' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'0' AS Status,'2017-10-26' AS CDate,'11' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'1' AS Status,'2017-10-26' AS CDate,'13' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'1' AS Status,'2017-10-26' AS CDate,'16' AS CHour,1.0 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'2' AS Status,'2017-10-26' AS CDate,'20' AS CHour,1.0 AS Value
</code>```

Output:

```<code>SELECT '3' as ID,'CName1' AS Name,'0' AS Status,'2017-10-25' AS CDate,'22' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'0' AS Status,'2017-10-25' AS CDate,'23' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'0' AS Status,'2017-10-26' AS CDate,'0' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'0' AS Status,'2017-10-26' AS CDate,'1' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'1' AS Status,'2017-10-26' AS CDate,'2' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'1' AS Status,'2017-10-26' AS CDate,'3' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'1' AS Status,'2017-10-26' AS CDate,'4' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'0' AS Status,'2017-10-26' AS CDate,'5' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'0' AS Status,'2017-10-26' AS CDate,'6' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'0' AS Status,'2017-10-26' AS CDate,'7' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'1' AS Status,'2017-10-26' AS CDate,'8' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'1' AS Status,'2017-10-26' AS CDate,'9' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'1' AS Status,'2017-10-26' AS CDate,'10' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'0' AS Status,'2017-10-26' AS CDate,'11' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'0' AS Status,'2017-10-26' AS CDate,'12' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'1' AS Status,'2017-10-26' AS CDate,'13' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'1' AS Status,'2017-10-26' AS CDate,'14' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'1' AS Status,'2017-10-26' AS CDate,'15' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'1' AS Status,'2017-10-26' AS CDate,'16' AS CHour,1.0 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'1' AS Status,'2017-10-26' AS CDate,'17' AS CHour,1.0 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'1' AS Status,'2017-10-26' AS CDate,'18' AS CHour,1.0 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'1' AS Status,'2017-10-26' AS CDate,'19' AS CHour,1.0 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'2' AS Status,'2017-10-26' AS CDate,'20' AS CHour,1.0 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'2' AS Status,'2017-10-26' AS CDate,'21' AS CHour,1.0 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'2' AS Status,'2017-10-26' AS CDate,'22' AS CHour,1.0 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'2' AS Status,'2017-10-26' AS CDate,'23' AS CHour,1.0 AS Value
</code>```

答:
If you have SQL Server > 2012 you can use LEAD to find the value of the next date together with a TALLY table to generate the in-between rows:

Set-Up

```<code>SELECT 3 as ID,'CName1' AS Name,0 AS Status,CAST('2017-10-25' AS DATE) AS CDate,22 AS CHour,0.5 AS Value
INTO #ChannelData
UNION ALL
SELECT 3 as ID,'CName1' AS Name,1 AS Status,CAST('2017-10-26' AS DATE)  AS CDate,2 AS CHour,0.5 AS Value
UNION ALL
SELECT 3 as ID,'CName1' AS Name,0 AS Status,CAST('2017-10-26' AS DATE)  AS CDate,5 AS CHour,0.5 AS Value
UNION ALL
SELECT 3 as ID,'CName1' AS Name,1 AS Status,CAST('2017-10-26' AS DATE)  AS CDate,8 AS CHour,0.5 AS Value
UNION ALL
SELECT 3 as ID,'CName1' AS Name,0 AS Status,CAST('2017-10-26' AS DATE)  AS CDate,11 AS CHour,0.5 AS Value
UNION ALL
SELECT 3 as ID,'CName1' AS Name,1 AS Status,CAST('2017-10-26' AS DATE)  AS CDate,13 AS CHour,0.5 AS Value
UNION ALL
SELECT 3 as ID,'CName1' AS Name,1 AS Status,CAST('2017-10-26' AS DATE)  AS CDate,16 AS CHour,1.0 AS Value
UNION ALL
SELECT 3 as ID,'CName1' AS Name,2 AS Status,CAST('2017-10-26' AS DATE)  AS CDate,20 AS CHour,1.0 AS Value
</code>```

Query:

```<code>;WITH Tally -- Generate Tally Table
As
(
    SELECT ROW_NUMBER() OVER (ORDER BY num.n) - 1 AS number
    FROM
        (VALUES (1), (2),(3),(4),(5),(6),(7),(8),(9),(10)) num(n)
    CROSS APPLY
        (VALUES (1), (2),(3),(4),(5),(6),(7),(8),(9),(10)) num2(n)
    CROSS APPLY
        (VALUES (1), (2),(3),(4),(5),(6),(7),(8),(9),(10)) num3(n)
),
MyRows
As
(
    SELECT  Id, Name, Status, CDate, CHour, Value
              -- Turn Date to DateTime
            , DATEADD(HH,CHour, CAST(CDate AS DateTime)) AS FullDate
              -- Get next date time
            , DATEADD(HH,LEAD(CHour) OVER (PARTITION BY Name ORDER BY CDate, CHour)
            , CAST(LEAD(CDATE) OVER (PARTITION BY Name ORDER BY CDate, CHour)AS DateTime))  AS NextFullDate
    FROM #ChannelData
)
SELECT  Id, Name, [Status],
        CAST(DATEADD(HH, number, FulLDate) AS Date) AS CDate,
        DATEPART(HH,DATEADD(HH, number, FulLDate)) AS CHour,
        Value
FROM MyRows
CROSS APPLY Tally
WHERE
    DATEADD(HH, number, FullDate) < COALESCE(NextFullDate, DATEADD(hh, 1, FullDate))
ORDER BY
    CAST(DATEADD(HH, number, FulLDate) AS Date),
    DATEPART(HH,DATEADD(HH, number, FulLDate))
</code>```

Body:
I have hourly level data of a unit, with its status and its value. The status and value of the unit changes after certain intervals (not necessarily at every hour). I want to generate hourly level data from existing data. Say for example: I have input such as:

and output required is:

Please find below scripts for required input and output:

Input

SELECT '3' as ID,'CName1' AS Name,'0' AS Status,'2017-10-25' AS CDate,'22' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'1' AS Status,'2017-10-26' AS CDate,'2' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'0' AS Status,'2017-10-26' AS CDate,'5' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'1' AS Status,'2017-10-26' AS CDate,'8' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'0' AS Status,'2017-10-26' AS CDate,'11' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'1' AS Status,'2017-10-26' AS CDate,'13' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'1' AS Status,'2017-10-26' AS CDate,'16' AS CHour,1.0 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'2' AS Status,'2017-10-26' AS CDate,'20' AS CHour,1.0 AS Value

Output:

SELECT '3' as ID,'CName1' AS Name,'0' AS Status,'2017-10-25' AS CDate,'22' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'0' AS Status,'2017-10-25' AS CDate,'23' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'0' AS Status,'2017-10-26' AS CDate,'0' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'0' AS Status,'2017-10-26' AS CDate,'1' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'1' AS Status,'2017-10-26' AS CDate,'2' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'1' AS Status,'2017-10-26' AS CDate,'3' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'1' AS Status,'2017-10-26' AS CDate,'4' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'0' AS Status,'2017-10-26' AS CDate,'5' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'0' AS Status,'2017-10-26' AS CDate,'6' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'0' AS Status,'2017-10-26' AS CDate,'7' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'1' AS Status,'2017-10-26' AS CDate,'8' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'1' AS Status,'2017-10-26' AS CDate,'9' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'1' AS Status,'2017-10-26' AS CDate,'10' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'0' AS Status,'2017-10-26' AS CDate,'11' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'0' AS Status,'2017-10-26' AS CDate,'12' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'1' AS Status,'2017-10-26' AS CDate,'13' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'1' AS Status,'2017-10-26' AS CDate,'14' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'1' AS Status,'2017-10-26' AS CDate,'15' AS CHour,0.5 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'1' AS Status,'2017-10-26' AS CDate,'16' AS CHour,1.0 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'1' AS Status,'2017-10-26' AS CDate,'17' AS CHour,1.0 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'1' AS Status,'2017-10-26' AS CDate,'18' AS CHour,1.0 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'1' AS Status,'2017-10-26' AS CDate,'19' AS CHour,1.0 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'2' AS Status,'2017-10-26' AS CDate,'20' AS CHour,1.0 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'2' AS Status,'2017-10-26' AS CDate,'21' AS CHour,1.0 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'2' AS Status,'2017-10-26' AS CDate,'22' AS CHour,1.0 AS Value
UNION ALL
SELECT '3' as ID,'CName1' AS Name,'2' AS Status,'2017-10-26' AS CDate,'23' AS CHour,1.0 AS Value

Body:
If you have SQL Server > 2012 you can use LEAD to find the value of the next date together with a TALLY table to generate the in-between rows:

Set-Up

SELECT 3 as ID,'CName1' AS Name,0 AS Status,CAST('2017-10-25' AS DATE) AS CDate,22 AS CHour,0.5 AS Value
INTO #ChannelData
UNION ALL
SELECT 3 as ID,'CName1' AS Name,1 AS Status,CAST('2017-10-26' AS DATE)  AS CDate,2 AS CHour,0.5 AS Value
UNION ALL
SELECT 3 as ID,'CName1' AS Name,0 AS Status,CAST('2017-10-26' AS DATE)  AS CDate,5 AS CHour,0.5 AS Value
UNION ALL
SELECT 3 as ID,'CName1' AS Name,1 AS Status,CAST('2017-10-26' AS DATE)  AS CDate,8 AS CHour,0.5 AS Value
UNION ALL
SELECT 3 as ID,'CName1' AS Name,0 AS Status,CAST('2017-10-26' AS DATE)  AS CDate,11 AS CHour,0.5 AS Value
UNION ALL
SELECT 3 as ID,'CName1' AS Name,1 AS Status,CAST('2017-10-26' AS DATE)  AS CDate,13 AS CHour,0.5 AS Value
UNION ALL
SELECT 3 as ID,'CName1' AS Name,1 AS Status,CAST('2017-10-26' AS DATE)  AS CDate,16 AS CHour,1.0 AS Value
UNION ALL
SELECT 3 as ID,'CName1' AS Name,2 AS Status,CAST('2017-10-26' AS DATE)  AS CDate,20 AS CHour,1.0 AS Value

Query:

;WITH Tally -- Generate Tally Table
As
(
    SELECT ROW_NUMBER() OVER (ORDER BY num.n) - 1 AS number
    FROM
        (VALUES (1), (2),(3),(4),(5),(6),(7),(8),(9),(10)) num(n)
    CROSS APPLY
        (VALUES (1), (2),(3),(4),(5),(6),(7),(8),(9),(10)) num2(n)
    CROSS APPLY
        (VALUES (1), (2),(3),(4),(5),(6),(7),(8),(9),(10)) num3(n)
),
MyRows
As
(
    SELECT  Id, Name, Status, CDate, CHour, Value
              -- Turn Date to DateTime
            , DATEADD(HH,CHour, CAST(CDate AS DateTime)) AS FullDate
              -- Get next date time
            , DATEADD(HH,LEAD(CHour) OVER (PARTITION BY Name ORDER BY CDate, CHour)
            , CAST(LEAD(CDATE) OVER (PARTITION BY Name ORDER BY CDate, CHour)AS DateTime))  AS NextFullDate
    FROM #ChannelData
)
SELECT  Id, Name, [Status],
        CAST(DATEADD(HH, number, FulLDate) AS Date) AS CDate,
        DATEPART(HH,DATEADD(HH, number, FulLDate)) AS CHour,
        Value
FROM MyRows
CROSS APPLY Tally
WHERE
    DATEADD(HH, number, FullDate) < COALESCE(NextFullDate, DATEADD(hh, 1, FullDate))
ORDER BY
    CAST(DATEADD(HH, number, FulLDate) AS Date),
    DATEPART(HH,DATEADD(HH, number, FulLDate))


问:
How to use assert in android?
I want to use assert obj != null : "object cannot be null" on Android device. The assert doesn't seem to work, so I searched online and I found this local solution:

adb shell setprop debug.assert 1

it does work on my local machine.

I want to run this command using my Eclipse project(so it would be in the source control).
How can I do it?

答:
Sharing my class which I use for assertions on Android, its simpler, has nice naming and very elegant because it allows you to write asserts like this:

```<code>Assert.that(obj!=null, "Object should not be null");
</code>```

Here's the code for the class:

```<code>public class Assert {
    public static void that(boolean condition, String message) {
        if (!condition) {
            throw new AssertionError(message);
        }
    }
}
</code>```

Hope it helps!

ContentLicense: CC BY-SA 4.0

Title: How to use assert in android?

Body:
Sharing my class which I use for assertions on Android, its simpler, has nice naming and very elegant because it allows you to write asserts like this:

Assert.that(obj!=null, "Object should not be null");

Here's the code for the class:

public class Assert {
    public static void that(boolean condition, String message) {
        if (!condition) {
            throw new AssertionError(message);
        }
    }
}

Hope it helps!


问:
SQL subquery: How to grap the record with both the min(date) and min(hour)
I have a table from which I want to grap the first record that gives a passage IN ('B410','B420','C430','C440'). So, I suppose this means looking for the record with the oldest date and within that oldest date the record with the oldest time stamp.

I wrote a query with 2 nested subqueries, but that query does not do the trick (it gives me an empty result). What am I doing wrong? The strange thing is that when changing the syntax to find the max(fromdate) and max(hour), I do find the record with timstamp 22:18. But I do not find the record with timestamp 16:40 with min(fromdate) and min(hour).

```<code>select v.id,
    h.fromdate,
    h.hour,
    h.department,
    h.room
from visit v
inner join visit_hist h
on  v.id = h.id
where v.id in ('10251183')
    and h.room in ('B410','B420','C430','C440')
    and h.fromdate =
    (select min(fromdate)
    from visit_hist
    where (id= h.id
        and h.hour =
        (select min(hour) from visit_hist where id= h.id and h.date = date
        ))
    )
order by v.date,
    v.visit_id;
</code>```

Can someone help me out here?

答:
Just use window functions:

```<code>select . . .
from visit v inner join
     (select vh.*, row_number() over (partition by vh.id order by date asc, hour asc) as seqnum
      from visit_hist vh
      where vh.room in ('B410', 'B420', 'C430', 'C440')
     ) vh
     on v.id = vh.id
where v.id in (10251183) and seqnum = 1;
</code>```

Note:  This gives the ids with the first room in the list.  If you want the ids whose first room is in the list, then move the condition on vh.room to the outer query.

Body:
I have a table from which I want to grap the first record that gives a passage IN ('B410','B420','C430','C440'). So, I suppose this means looking for the record with the oldest date and within that oldest date the record with the oldest time stamp.

I wrote a query with 2 nested subqueries, but that query does not do the trick (it gives me an empty result). What am I doing wrong? The strange thing is that when changing the syntax to find the max(fromdate) and max(hour), I do find the record with timstamp 22:18. But I do not find the record with timestamp 16:40 with min(fromdate) and min(hour).

select v.id,
    h.fromdate,
    h.hour,
    h.department,
    h.room
from visit v
inner join visit_hist h
on  v.id = h.id
where v.id in ('10251183')
    and h.room in ('B410','B420','C430','C440')
    and h.fromdate =
    (select min(fromdate)
    from visit_hist
    where (id= h.id
        and h.hour =
        (select min(hour) from visit_hist where id= h.id and h.date = date
        ))
    )
order by v.date,
    v.visit_id;

Can someone help me out here?

Body:
Just use window functions:

select . . .
from visit v inner join
     (select vh.*, row_number() over (partition by vh.id order by date asc, hour asc) as seqnum
      from visit_hist vh
      where vh.room in ('B410', 'B420', 'C430', 'C440')
     ) vh
     on v.id = vh.id
where v.id in (10251183) and seqnum = 1;

Note:  This gives the ids with the first room in the list.  If you want the ids whose first room is in the list, then move the condition on vh.room to the outer query.


问:
Compile errors with templates and new/delete operators (C++)
I'm trying to build a vector-style class and in order to use templates as well as the new, delete operators I have this piece of code:

```<code>template <class type2> class storage
{
         private:
                 type2 *organs;
         public:
                int num;
                storage(); //constructor
                ~storage(); //destructor
                void operator+(type2 newone);
                void operator-(int howmany);
                type2 operator[](int place);
};

storage<class type2>:: ~storage()
{
          delete[] organs; //~~~~~~~Error number 1~~~~~~~~~~
}

void storage<class type2>:: operator+(type2 newone)
{ //                        ~~~~~~~~~~~Error number 2~~~~~~~~~~~~~~
     organs = new type2[1];
     num++;
     oragns[num-1] = newone;
}
</code>```

The compiler (Dev C++) writes this error on Error number 1:

invalid use of undefined type `struct
  type2'

And this error on Error Number 2:

`newone' has incomplete type

However, I don't understand what's wrong. Any hints?

答:
There are major bugs in this code aside from the compilation error.

Totally wrong signature for operator+. You might use operator+= as an append, which presumably is what you are doing. You should probably return a reference to self.

operator- also perhaps make operator-=

If operator+ is supposed to append you are not doing so. You are just allocating a new element, losing whatever you had before with no way of recovering it, i.e. that memory has no pointers pointing to it and you cannot delete it.

As you have a destructor defined you need to handle copying and assignment

operator[] would ideally have 2 overloads, one const and one non-const. If you do really want to return by value you should probably make it const.

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to build a vector-style class and in order to use templates as well as the new, delete operators I have this piece of code:

template <class type2> class storage
{
         private:
                 type2 *organs;
         public:
                int num;
                storage(); //constructor
                ~storage(); //destructor
                void operator+(type2 newone);
                void operator-(int howmany);
                type2 operator[](int place);
};

storage<class type2>:: ~storage()
{
          delete[] organs; //~~~~~~~Error number 1~~~~~~~~~~
}

void storage<class type2>:: operator+(type2 newone)
{ //                        ~~~~~~~~~~~Error number 2~~~~~~~~~~~~~~
     organs = new type2[1];
     num++;
     oragns[num-1] = newone;
}

The compiler (Dev C++) writes this error on Error number 1:

invalid use of undefined type `struct
  type2'

And this error on Error Number 2:

`newone' has incomplete type

However, I don't understand what's wrong. Any hints?


问:
pandas read_csv ignores separator
I have a CSV file with the following text in French:

```<code> "Dune!;Jeux"
 "Snapchat;Photo et vidéo"
 "Instagram;Photo et vidéo"
 "YouTube: Regarder & Découvrir;Photo et vidéo"
 "WhatsApp Messenger;Réseaux sociaux"
 "Wish - Acheter en s'amusant;Shopping"
 "Messenger;Réseaux sociaux"
</code>```

I am unable to read this file as two columns using ; as a separator:

```<code>df = pd.read_csv("src.csv",delimiter=';',header=None,encoding="latin-1")
print(df.head())
</code>```

It gives the following:

```<code>                                              0
0                                    Dune!;Jeux
1                       Snapchat;Photo et vidéo
2                      Instagram;Photo et vidéo
3  YouTube: Regarder & Découvrir;Photo et vidéo
4            WhatsApp Messenger;Réseaux sociaux
</code>```

Looks like the ; as a separator was ignored. What's wrong with my code sample?

答:
it should be sep=';' not delimeter=';':

```<code>In[41]:
import io
import pandas as pd
df = pd.read_csv(io.StringIO(t), sep=';', header=None)
df

Out[41]:
                                0                1
0                           Dune!             Jeux
1                        Snapchat   Photo et vidéo
2                       Instagram   Photo et vidéo
3   YouTube: Regarder & Découvrir   Photo et vidéo
4              WhatsApp Messenger  Réseaux sociaux
5     Wish - Acheter en s'amusant         Shopping
6                       Messenger  Réseaux sociaux
</code>```

update

Looking at your data, every line is wrapped in quotations so it's not able to parse this correctly, you could just do this as a post processing step using .str.split(';',expand=True)

```<code>In[61]:
df1 = df[0].str.split(';',expand=True)
df1

Out[61]:
                                           0                 1     2
0                                      Dune!              Jeux  None
1                                   Snapchat   Photo et vidÃ©o  None
2                                  Instagram   Photo et vidÃ©o  None
3             YouTube: Regarder & DÃ©couvrir   Photo et vidÃ©o  None
4                         WhatsApp Messenger  RÃ©seaux sociaux  None
5                Wish - Acheter en s'amusant          Shopping  None
6                                  Messenger  RÃ©seaux sociaux  None
7                                    Bitmoji       Utilitaires  None
8                 Sonic Forces: Speed Battle              Jeux  None
9                                  Dunk Shot              Jeux  None
10                                  Facebook  RÃ©seaux sociaux  None
11                                   Netflix    Divertissement  None
12                           Super Mario Run              Jeux  None
13       Tu prÃ©fÃ¨res? Â Choix impossibles              Jeux  None
14            Waze - GPS et trafic en direct        Navigation  None
15                            Pro des MotsÂ              Jeux  None
16                                 Bravoloto              Jeux  None
17                                   Groupon          Shopping  None
18                                 Leboncoin       Utilitaires  None
19                             Spotify Music           Musique  None
20                    Molotov - TV en direct            replay  None
21                          Enlight Photofox   Photo et vidÃ©o  None
22                                   Sarahah  RÃ©seaux sociaux  None
23                    Perte de poids Fitness   Forme et santÃ©  None
24                                 Vinted.fr      Style de vie  None
25                   AliExpress Shopping App          Shopping  None
26                                 Amazon FR          Shopping  None
27                   Yuka - Scan de produits   Forme et santÃ©  None
28            Google Maps - GPS & Transports        Navigation  None
29                                      Joom          Shopping  None
..                                       ...               ...   ...
170           MosaLingua Apprendre l'Anglais        Ãducation  None
171                                 Ventusky           MÃ©tÃ©o  None
172                              Guitare Pro              Jeux  None
173                                   Sense.      Style de vie  None
174            Les aventures de Petit Chaton    Divertissement  None
175                              Lumino City              Jeux  None
176                 ARIMOJI by Ariana Grande    Divertissement  None
177                      A Normal Lost Phone              Jeux  None
178                               Tiny Wings              Jeux  None
179                         Rugby Nations 16              Jeux  None
180  Full Fitness : Exercise Workout Trainer   Forme et santÃ©  None
181                                 LetterÂ²              Jeux  None
182    R-Play - Lecture Ã  distance pour PS4    Divertissement  None
183                            Baby Phone 3G      Style de vie  None
184              Runtastic Mountain Bike PRO   Forme et santÃ©  None
185                     Apprendre l'Espagnol        Ãducation  None
186                            Earn to Die 2              Jeux  None
187                               Samorost 3              Jeux  None
188                      Cut the Rope: Magic              Jeux  None
189               Simulateur MÃ©tro de Paris              Jeux  None
190               Plotagraph+ Photo Animator   Photo et vidÃ©o  None
191   LÂOfficiel du SCRABBLEÂ® Dictionnaire      RÃ©fÃ©rences  None
192      VidÃ©o Royal Pro - Ultimate Edition   Photo et vidÃ©o  None
193                Dictionnaire de franÃ§ais      RÃ©fÃ©rences  None
194                             Ana The Game              Jeux  None
195                                 Facetune   Photo et vidÃ©o  None
196                                    FROST              Jeux  None
197                                   Catane              Jeux  None
198                               Punch Kidd              Jeux  None
199             Antidote Mobile Â FranÃ§ais      RÃ©fÃ©rences  None

[200 rows x 3 columns]
</code>```

You can drop that last column using fancy indexing:

```<code>In[69]:
df1 = df1.loc[:,:1]
df1.head()

Out[69]:
                                0                 1
0                           Dune!              Jeux
1                        Snapchat   Photo et vidÃ©o
2                       Instagram   Photo et vidÃ©o
3  YouTube: Regarder & DÃ©couvrir   Photo et vidÃ©o
4              WhatsApp Messenger  RÃ©seaux sociaux
</code>```

Title: pandas read_csv ignores separator

Body:
I have a CSV file with the following text in French:

 "Dune!;Jeux"
 "Snapchat;Photo et vidéo"
 "Instagram;Photo et vidéo"
 "YouTube: Regarder & Découvrir;Photo et vidéo"
 "WhatsApp Messenger;Réseaux sociaux"
 "Wish - Acheter en s'amusant;Shopping"
 "Messenger;Réseaux sociaux"

I am unable to read this file as two columns using ; as a separator:

df = pd.read_csv("src.csv",delimiter=';',header=None,encoding="latin-1")
print(df.head())

It gives the following:

                                              0
0                                    Dune!;Jeux
1                       Snapchat;Photo et vidéo
2                      Instagram;Photo et vidéo
3  YouTube: Regarder & Découvrir;Photo et vidéo
4            WhatsApp Messenger;Réseaux sociaux

Looks like the ; as a separator was ignored. What's wrong with my code sample?

Body:
it should be sep=';' not delimeter=';':

In[41]:
import io
import pandas as pd
df = pd.read_csv(io.StringIO(t), sep=';', header=None)
df

Out[41]:
                                0                1
0                           Dune!             Jeux
1                        Snapchat   Photo et vidéo
2                       Instagram   Photo et vidéo
3   YouTube: Regarder & Découvrir   Photo et vidéo
4              WhatsApp Messenger  Réseaux sociaux
5     Wish - Acheter en s'amusant         Shopping
6                       Messenger  Réseaux sociaux

update

Looking at your data, every line is wrapped in quotations so it's not able to parse this correctly, you could just do this as a post processing step using .str.split(';',expand=True)

In[61]:
df1 = df[0].str.split(';',expand=True)
df1

Out[61]:
                                           0                 1     2
0                                      Dune!              Jeux  None
1                                   Snapchat   Photo et vidÃ©o  None
2                                  Instagram   Photo et vidÃ©o  None
3             YouTube: Regarder & DÃ©couvrir   Photo et vidÃ©o  None
4                         WhatsApp Messenger  RÃ©seaux sociaux  None
5                Wish - Acheter en s'amusant          Shopping  None
6                                  Messenger  RÃ©seaux sociaux  None
7                                    Bitmoji       Utilitaires  None
8                 Sonic Forces: Speed Battle              Jeux  None
9                                  Dunk Shot              Jeux  None
10                                  Facebook  RÃ©seaux sociaux  None
11                                   Netflix    Divertissement  None
12                           Super Mario Run              Jeux  None
13       Tu prÃ©fÃ¨res? Â Choix impossibles              Jeux  None
14            Waze - GPS et trafic en direct        Navigation  None
15                            Pro des MotsÂ              Jeux  None
16                                 Bravoloto              Jeux  None
17                                   Groupon          Shopping  None
18                                 Leboncoin       Utilitaires  None
19                             Spotify Music           Musique  None
20                    Molotov - TV en direct            replay  None
21                          Enlight Photofox   Photo et vidÃ©o  None
22                                   Sarahah  RÃ©seaux sociaux  None
23                    Perte de poids Fitness   Forme et santÃ©  None
24                                 Vinted.fr      Style de vie  None
25                   AliExpress Shopping App          Shopping  None
26                                 Amazon FR          Shopping  None
27                   Yuka - Scan de produits   Forme et santÃ©  None
28            Google Maps - GPS & Transports        Navigation  None
29                                      Joom          Shopping  None
..                                       ...               ...   ...
170           MosaLingua Apprendre l'Anglais        Ãducation  None
171                                 Ventusky           MÃ©tÃ©o  None
172                              Guitare Pro              Jeux  None
173                                   Sense.      Style de vie  None
174            Les aventures de Petit Chaton    Divertissement  None
175                              Lumino City              Jeux  None
176                 ARIMOJI by Ariana Grande    Divertissement  None
177                      A Normal Lost Phone              Jeux  None
178                               Tiny Wings              Jeux  None
179                         Rugby Nations 16              Jeux  None
180  Full Fitness : Exercise Workout Trainer   Forme et santÃ©  None
181                                 LetterÂ²              Jeux  None
182    R-Play - Lecture Ã  distance pour PS4    Divertissement  None
183                            Baby Phone 3G      Style de vie  None
184              Runtastic Mountain Bike PRO   Forme et santÃ©  None
185                     Apprendre l'Espagnol        Ãducation  None
186                            Earn to Die 2              Jeux  None
187                               Samorost 3              Jeux  None
188                      Cut the Rope: Magic              Jeux  None
189               Simulateur MÃ©tro de Paris              Jeux  None
190               Plotagraph+ Photo Animator   Photo et vidÃ©o  None
191   LÂOfficiel du SCRABBLEÂ® Dictionnaire      RÃ©fÃ©rences  None
192      VidÃ©o Royal Pro - Ultimate Edition   Photo et vidÃ©o  None
193                Dictionnaire de franÃ§ais      RÃ©fÃ©rences  None
194                             Ana The Game              Jeux  None
195                                 Facetune   Photo et vidÃ©o  None
196                                    FROST              Jeux  None
197                                   Catane              Jeux  None
198                               Punch Kidd              Jeux  None
199             Antidote Mobile Â FranÃ§ais      RÃ©fÃ©rences  None

[200 rows x 3 columns]

You can drop that last column using fancy indexing:

In[69]:
df1 = df1.loc[:,:1]
df1.head()

Out[69]:
                                0                 1
0                           Dune!              Jeux
1                        Snapchat   Photo et vidÃ©o
2                       Instagram   Photo et vidÃ©o
3  YouTube: Regarder & DÃ©couvrir   Photo et vidÃ©o
4              WhatsApp Messenger  RÃ©seaux sociaux


问:
Google Chrome Ignoring Hosts File
Google Chrome is ignoring the settings in C:/Windows/System32/drivers/etc/hosts file.  Both IE11 and Firefox are installed on the same machine and work as expected.

I've tried all the solutions I could find online including:

Open chrome://net-internals/#dns and click the Clear Hosts Cache button.

Go in Settings, Show Advanced Settings and uncheck the following three options:  (X) Use a web service to help resolve navigation errors (X) Use a prediction service to help complete searches and URLs typed in the address bar (X) Use a prediction service to load pages more quickly

Go in Settings, Show Advanced Settings, click the Clear Browsing Data button, selected Cached Images And Files from the beginning of time, and click Clear Browsing Data.

Restart Chrome.exe.

Restart the computer.

Make sure to add http:// to the front of the web address.

Make sure proxy settings are turned off

Run cmd.exe and run ipconfig /flushdns

Uninstall and reinstall Chrome

I'm at a loss... Is there anything I missed that I can try or check?

答:
While it was stated that no proxy is being used, I have had the same issue on OS X while using a proxy and the eventual solution was to add a proxy-exception for this domain.

What the OP could try is turn off async DNS via command-line switch as
mentioned here in 2015:

Async DNS: Remove toggle from about:flags

Async DNS is fairly stable at the moment, so we don't really need the
  toggle in about:flags anymore. (Note that the --enable-async-dns and
  --disable-async-dns command-line flags will still work for now.)

This, however, seems to have no effect in my case, as chrome://net-internals/#dns still displays the internal DNS-client as enabled with no obvious way to turn it off.

Title: Google Chrome Ignoring Hosts File


问:
Cannot install Chrome on Ubuntu 16.04
Doenloaded the .deb package of Chrome from Google's site. The installation doesn't work when trying to install from the GUI. What's up with that?</p>

答:
I had same issue. on running google-chrome from terminal, found that it need new version of NSS. Chrome 62 need NSS>=3.26. So installed libnss3.

```<code>$google-chrome
</code>```

[6999:7036:1113/200616.549496:FATAL:nss_util.cc(632)] NSS_VersionCheck("3.26") failed. NSS >= 3.26 is required. Please upgrade to the latest NSS, and if you still get this error, contact your distribution maintainer.
Aborted (core dumped)

```<code>sudo apt-get install --reinstall libnss3
</code>```

and it worked for me :)

Title: Cannot install Chrome on Ubuntu 16.04

Body:
I had same issue. on running google-chrome from terminal, found that it need new version of NSS. Chrome 62 need NSS>=3.26. So installed libnss3.

$google-chrome

[6999:7036:1113/200616.549496:FATAL:nss_util.cc(632)] NSS_VersionCheck("3.26") failed. NSS >= 3.26 is required. Please upgrade to the latest NSS, and if you still get this error, contact your distribution maintainer.
Aborted (core dumped)

sudo apt-get install --reinstall libnss3

and it worked for me :)


问:
Not able to apply filter to the property of a collection object in odata
I am using the following code in C# Web API OData and trying to do a filter on the LanguageId, but I am getting the below given error when applying the filter

Models

```<code>namespace ODataSample
{
    public class Project
    {
        [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public long Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public DateTime CreatedOn { get; set; }
        public DateTime UpdatedOn { get; set; }
        public long CreatedBy { get; set; }
        public long UpdatedBy { get; set; }
        public decimal Cost { get; set; }
        public long StatusId { get; set; }
        [ForeignKey("StatusId")]
        public virtual ProjectStatus Status { get; set; }
    }

    public class ProjectStatus
    {
        public ProjectStatus()
        {
            ProjectStatusTexts = new HashSet<ProjectStatusText>();
        }
        [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public long StatusId { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public bool IsActive { get; set; }
        public virtual ICollection<ProjectStatusText> ProjectStatusTexts { get; set; }
        public virtual ICollection<Project> Projects { get; set; }
    }

    public class ProjectStatusText
    {
        public ProjectStatusText()
        {
            ProjectStatus = new HashSet<ProjectStatus>();
        }

        [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public long Id { get; set; }
        public long StatusId { get; set; }
        [ForeignKey("StatusId")]
        public IEnumerable<ProjectStatus> ProjectStatus { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public long LanguageId { get; set; }
        [ForeignKey("LanguageId")]
        public virtual Language Language { get; set; }
        public bool IsActive { get; set; }
    }

    public class Language
    {
        [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public long LanguageId { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public bool IsActive { get; set; }
    }

    public class User
    {
        public User()
        {
            this.Projects = new HashSet<Project>();
        }

        [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public long UserId { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
        public bool IsActive { get; set; }
        public virtual ICollection<Project> Projects { get; set; }
    }
}
</code>```

The services for the above model

```<code>namespace ODataSample.Services
{
    public class ProjectsService
    {
        public IQueryable<Project> GetProjects()
        {
            var ctx = new ProjectsContext();

            return ctx.Projects;
        }
    }
}
</code>```

The DbContext with the Seed data and DbInitializer

```<code>namespace ODataSample.Contexts
{
    public class ProjectsContext : DbContext
    {
        public ProjectsContext() : base("ProjectsConnectionString") { Database.SetInitializer(new ProjectDBInitializer()); }
        public ProjectsContext(string nameOrConnectionString) : base(nameOrConnectionString)
        {
            Database.SetInitializer(new ProjectDBInitializer());
        }

        public DbSet<Project> Projects { get; set; }
        public DbSet<User> Users { get; set; }
        public DbSet<ProjectStatus> ProjectStatuses { get; set; }
        public DbSet<ProjectStatusText> ProjectStatusTexts { get; set; }
        public DbSet<Language> Languages { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
        }
    }

    public class ProjectDBInitializer : DropCreateDatabaseAlways<ProjectsContext>
    {
        public ProjectDBInitializer()
        {
        }

        protected override void Seed(ProjectsContext context)
        {
            context.Languages.AddRange(new[]
            {
                new Language { Description = "Spanish", IsActive = true, LanguageId = 1, Name = "es" },
                new Language { Description = "English", IsActive = true, LanguageId = 2, Name = "en" }
            });

            context.ProjectStatuses.AddRange(new[]
            {
                new ProjectStatus { StatusId=1, Name="Active", Description="Active", IsActive= true },
                new ProjectStatus { StatusId=2, Name="Closed", Description="Closed", IsActive= true },
                new ProjectStatus { StatusId=3, Name="InProgress", Description="In Progress", IsActive= true }
            });

            context.ProjectStatusTexts.AddRange(new[]
            {
                new ProjectStatusText {Id = 1, LanguageId=1, StatusId = 1,Name = Path.GetRandomFileName(),Description = Path.GetRandomFileName(),IsActive=true },
                new ProjectStatusText {Id = 2, LanguageId=2, StatusId = 1,Name = "Active",Description = "Active",IsActive=true },
                new ProjectStatusText {Id = 3, LanguageId=1, StatusId = 2,Name = Path.GetRandomFileName(),Description = Path.GetRandomFileName(),IsActive=true },
                new ProjectStatusText {Id = 4, LanguageId=2, StatusId = 3,Name = "InProgress",Description = "InProgress",IsActive=true }
            });

            context.Projects.AddRange(new[]
            {
                new Project{ Cost = default(decimal),  Id=1,Name="project 1",StatusId = 1, Description="project 1", CreatedOn = DateTime.Now, UpdatedOn = DateTime.Now,  CreatedBy = 1, UpdatedBy =1},
                new Project{ Cost = default(decimal), Id=2,Name="project 2",StatusId = 1, Description="project 2", CreatedOn = DateTime.Now, UpdatedOn = DateTime.Now,  CreatedBy = 1, UpdatedBy =1},
                new Project{ Cost = default(decimal), Id=3,Name="project 3",StatusId = 1, Description="project 3", CreatedOn = DateTime.Now, UpdatedOn = DateTime.Now, CreatedBy = 1, UpdatedBy =1 }
            });

            base.Seed(context);
        }
    }
}
</code>```

The following is the WebApiConfig registrations made

```<code>var modelBuilder = new ODataConventionModelBuilder();
modelBuilder.EntitySet<Project>("Projects");
modelBuilder.EntitySet<ProjectStatus>("ProjectStatusses");
modelBuilder.EntitySet<ProjectStatusText>("ProjectStatusTexts");
modelBuilder.EntitySet<Language>("Languages");
modelBuilder.EntitySet<User>("Users");
var edmModel = modelBuilder.GetEdmModel();
config.Routes.MapODataRoute("odata", "odata", edmModel);
</code>```

The Problem:
I am having the Project entity for which the statuses are available like new, active, inprogress etc. When I try to do a localization of these values, i find that the approach of having a text class / table will be easy. Hence the creation of the ProjectStatusTexts class / table.

When I try to get the projects with the translated values, I am using the following OData Query from the Browser,but it does not filter the records because the where condition generated by the EF for the any clause in the URI returns all the records from the ProjectStatusTexts table.

I have also tried the following approach given in StackOverflow, but could not be able to fix. Is there something wrong with this model that C# does not understand or is there something wrong with OData Query URI, please help.

Query URI:
http://localhost:64046/odata/Projects?$expand=Status/ProjectStatusTexts&$filter=Status/ProjectStatusTexts/any(l:l/Language/LanguageId%20eq%202)

```<code>var projects = (EdmEntitySet)edmModel.EntityContainers().Single().FindEntitySet("Projects");
var projectStatusTexts = (EdmEntitySet)edmModel.EntityContainers().Single().FindEntitySet("ProjectStatusTexts");
var projectType = (EdmEntityType)edmModel.FindDeclaredType("ODataSample.Project");
var projectStatusTextsType = (EdmEntityType)edmModel.FindDeclaredType("ODataSample.ProjectStatusText");

var partsProperty = new EdmNavigationPropertyInfo();
partsProperty.TargetMultiplicity = EdmMultiplicity.Many;
partsProperty.Target = projectStatusTextsType;
partsProperty.ContainsTarget = false;
partsProperty.OnDelete = EdmOnDeleteAction.Cascade;
partsProperty.Name = "ProjectStatusTexts";

//projects.AddNavigationTarget(projectType.AddUnidirectionalNavigation(partsProperty), projectStatusTexts);

var navigationProperty = projectType.AddUnidirectionalNavigation(partsProperty);
projects.AddNavigationTarget(navigationProperty, projectStatusTexts);

var linkBuilder = edmModel.GetEntitySetLinkBuilder(projects);
linkBuilder.AddNavigationPropertyLinkBuilder(navigationProperty,
    new NavigationLinkBuilder((context, property) =>
        context.GenerateNavigationPropertyLink(property, false), true));

config.Routes.MapODataRoute("odata", "odata", edmModel);
</code>```

答:
I think that what you are trying to achieve is to get all of the projects and then to expand to the ProjectStatusTexts that have the correct language. If that is the case then the filter is part of the expand not part of the query for the Projects themselves so it should be added in brackets after the expand like this:

http://localhost:64046/odata/Projects?$expand=Status/ProjectStatusTexts($filter=Language/LanguageId%20eq%202)

Body:
I am using the following code in C# Web API OData and trying to do a filter on the LanguageId, but I am getting the below given error when applying the filter

Models

namespace ODataSample
{
    public class Project
    {
        [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public long Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public DateTime CreatedOn { get; set; }
        public DateTime UpdatedOn { get; set; }
        public long CreatedBy { get; set; }
        public long UpdatedBy { get; set; }
        public decimal Cost { get; set; }
        public long StatusId { get; set; }
        [ForeignKey("StatusId")]
        public virtual ProjectStatus Status { get; set; }
    }

    public class ProjectStatus
    {
        public ProjectStatus()
        {
            ProjectStatusTexts = new HashSet<ProjectStatusText>();
        }
        [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public long StatusId { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public bool IsActive { get; set; }
        public virtual ICollection<ProjectStatusText> ProjectStatusTexts { get; set; }
        public virtual ICollection<Project> Projects { get; set; }
    }

    public class ProjectStatusText
    {
        public ProjectStatusText()
        {
            ProjectStatus = new HashSet<ProjectStatus>();
        }

        [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public long Id { get; set; }
        public long StatusId { get; set; }
        [ForeignKey("StatusId")]
        public IEnumerable<ProjectStatus> ProjectStatus { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public long LanguageId { get; set; }
        [ForeignKey("LanguageId")]
        public virtual Language Language { get; set; }
        public bool IsActive { get; set; }
    }

    public class Language
    {
        [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public long LanguageId { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public bool IsActive { get; set; }
    }

    public class User
    {
        public User()
        {
            this.Projects = new HashSet<Project>();
        }

        [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public long UserId { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
        public bool IsActive { get; set; }
        public virtual ICollection<Project> Projects { get; set; }
    }
}

The services for the above model

namespace ODataSample.Services
{
    public class ProjectsService
    {
        public IQueryable<Project> GetProjects()
        {
            var ctx = new ProjectsContext();

            return ctx.Projects;
        }
    }
}

The DbContext with the Seed data and DbInitializer

namespace ODataSample.Contexts
{
    public class ProjectsContext : DbContext
    {
        public ProjectsContext() : base("ProjectsConnectionString") { Database.SetInitializer(new ProjectDBInitializer()); }
        public ProjectsContext(string nameOrConnectionString) : base(nameOrConnectionString)
        {
            Database.SetInitializer(new ProjectDBInitializer());
        }

        public DbSet<Project> Projects { get; set; }
        public DbSet<User> Users { get; set; }
        public DbSet<ProjectStatus> ProjectStatuses { get; set; }
        public DbSet<ProjectStatusText> ProjectStatusTexts { get; set; }
        public DbSet<Language> Languages { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
        }
    }

    public class ProjectDBInitializer : DropCreateDatabaseAlways<ProjectsContext>
    {
        public ProjectDBInitializer()
        {
        }

        protected override void Seed(ProjectsContext context)
        {
            context.Languages.AddRange(new[]
            {
                new Language { Description = "Spanish", IsActive = true, LanguageId = 1, Name = "es" },
                new Language { Description = "English", IsActive = true, LanguageId = 2, Name = "en" }
            });

            context.ProjectStatuses.AddRange(new[]
            {
                new ProjectStatus { StatusId=1, Name="Active", Description="Active", IsActive= true },
                new ProjectStatus { StatusId=2, Name="Closed", Description="Closed", IsActive= true },
                new ProjectStatus { StatusId=3, Name="InProgress", Description="In Progress", IsActive= true }
            });

            context.ProjectStatusTexts.AddRange(new[]
            {
                new ProjectStatusText {Id = 1, LanguageId=1, StatusId = 1,Name = Path.GetRandomFileName(),Description = Path.GetRandomFileName(),IsActive=true },
                new ProjectStatusText {Id = 2, LanguageId=2, StatusId = 1,Name = "Active",Description = "Active",IsActive=true },
                new ProjectStatusText {Id = 3, LanguageId=1, StatusId = 2,Name = Path.GetRandomFileName(),Description = Path.GetRandomFileName(),IsActive=true },
                new ProjectStatusText {Id = 4, LanguageId=2, StatusId = 3,Name = "InProgress",Description = "InProgress",IsActive=true }
            });

            context.Projects.AddRange(new[]
            {
                new Project{ Cost = default(decimal),  Id=1,Name="project 1",StatusId = 1, Description="project 1", CreatedOn = DateTime.Now, UpdatedOn = DateTime.Now,  CreatedBy = 1, UpdatedBy =1},
                new Project{ Cost = default(decimal), Id=2,Name="project 2",StatusId = 1, Description="project 2", CreatedOn = DateTime.Now, UpdatedOn = DateTime.Now,  CreatedBy = 1, UpdatedBy =1},
                new Project{ Cost = default(decimal), Id=3,Name="project 3",StatusId = 1, Description="project 3", CreatedOn = DateTime.Now, UpdatedOn = DateTime.Now, CreatedBy = 1, UpdatedBy =1 }
            });

            base.Seed(context);
        }
    }
}

The following is the WebApiConfig registrations made

var modelBuilder = new ODataConventionModelBuilder();
modelBuilder.EntitySet<Project>("Projects");
modelBuilder.EntitySet<ProjectStatus>("ProjectStatusses");
modelBuilder.EntitySet<ProjectStatusText>("ProjectStatusTexts");
modelBuilder.EntitySet<Language>("Languages");
modelBuilder.EntitySet<User>("Users");
var edmModel = modelBuilder.GetEdmModel();
config.Routes.MapODataRoute("odata", "odata", edmModel);

The Problem:
I am having the Project entity for which the statuses are available like new, active, inprogress etc. When I try to do a localization of these values, i find that the approach of having a text class / table will be easy. Hence the creation of the ProjectStatusTexts class / table.

When I try to get the projects with the translated values, I am using the following OData Query from the Browser,but it does not filter the records because the where condition generated by the EF for the any clause in the URI returns all the records from the ProjectStatusTexts table.

I have also tried the following approach given in StackOverflow, but could not be able to fix. Is there something wrong with this model that C# does not understand or is there something wrong with OData Query URI, please help.

Query URI:
http://localhost:64046/odata/Projects?$expand=Status/ProjectStatusTexts&$filter=Status/ProjectStatusTexts/any(l:l/Language/LanguageId%20eq%202)

var projects = (EdmEntitySet)edmModel.EntityContainers().Single().FindEntitySet("Projects");
var projectStatusTexts = (EdmEntitySet)edmModel.EntityContainers().Single().FindEntitySet("ProjectStatusTexts");
var projectType = (EdmEntityType)edmModel.FindDeclaredType("ODataSample.Project");
var projectStatusTextsType = (EdmEntityType)edmModel.FindDeclaredType("ODataSample.ProjectStatusText");

var partsProperty = new EdmNavigationPropertyInfo();
partsProperty.TargetMultiplicity = EdmMultiplicity.Many;
partsProperty.Target = projectStatusTextsType;
partsProperty.ContainsTarget = false;
partsProperty.OnDelete = EdmOnDeleteAction.Cascade;
partsProperty.Name = "ProjectStatusTexts";

//projects.AddNavigationTarget(projectType.AddUnidirectionalNavigation(partsProperty), projectStatusTexts);

var navigationProperty = projectType.AddUnidirectionalNavigation(partsProperty);
projects.AddNavigationTarget(navigationProperty, projectStatusTexts);

var linkBuilder = edmModel.GetEntitySetLinkBuilder(projects);
linkBuilder.AddNavigationPropertyLinkBuilder(navigationProperty,
    new NavigationLinkBuilder((context, property) =>
        context.GenerateNavigationPropertyLink(property, false), true));

config.Routes.MapODataRoute("odata", "odata", edmModel);


问:
How to run the .exe file that is made by visual foxpro 6.0 in a different computer?
My brother installed an application (.exe) in my laptop it is working. Now i want to change my laptop and copy all the applications. Out of all application one is 'xyz.exe' which is developed in visual foxpro. And when i simply copy this application into my new laptop it tried to run it shows "Cannot locate the Microsoft Visual FoxPro support library".
I am unable to figure this out.  </p>

答:
You will need to install the appropriate VFP runtime libraries on that PC.

Here is a link to a site that contains installs of all the different VFP runtime libraries:

```<code>http://www.foxpert.com/download/runtime.html
</code>```

Down and install the correct file to fix your problem.

Body:
You will need to install the appropriate VFP runtime libraries on that PC.

Here is a link to a site that contains installs of all the different VFP runtime libraries:

http://www.foxpert.com/download/runtime.html

Down and install the correct file to fix your problem.


问:
QGIS heatmap not showing in plugin administrator
I am trying to create a heatmap in QGIS, and most guides suggests using the heatmap plugin. The only problem is that it is not showing up in my QGIS installation. Do you have any suggestions?

答:
SOLVED:
Apparantly in the new version of QGIS, you just go to the properties of your points, and then you can do a heatmap there under styles.


问:
jquery validate and error styles

how do i get rid of the borders in ul > li ?

i have :

```<code>    errorLabelContainer: $("ul", $('div.error')), wrapper: 'li',

errorContainer: $('div.error'),
</code>```

i tried :

```<code> div.message{
background: transparent url(images\ad_next.png) no-repeat scroll left center;
padding-left: 17px; border:0px;
}
div.message ul, li { border:0px; }
div.error{
    background-color:#F3E6E6;
    border-color: #924949;
    border-style: solid solid solid solid;
    border-width: 2px;
    padding: 5px;
}
</code>```

答:
the class="error" was declared in an included css. when i commented that out and used:

```<code>  div.error li { border:0px; }
</code>```

it worked. thanks

Title: jquery validate and error styles

Body:
how do i get rid of the borders in ul > li ?

i have :

    errorLabelContainer: $("ul", $('div.error')), wrapper: 'li',

errorContainer: $('div.error'),

i tried :

 div.message{
background: transparent url(images\ad_next.png) no-repeat scroll left center;
padding-left: 17px; border:0px;
}
div.message ul, li { border:0px; }
div.error{
    background-color:#F3E6E6;
    border-color: #924949;
    border-style: solid solid solid solid;
    border-width: 2px;
    padding: 5px;
}

Body:
the class="error" was declared in an included css. when i commented that out and used:

  div.error li { border:0px; }

it worked. thanks


问:
Editing an object property in an array of objects without referencing array while editing
I have an application using Angular with Ionic 3 and i have an array of questions. These questions can be edited if the user has made something wrong.

The case is when i click to edit any queston it kind of references that question in the array and any edit reflects immediately to the array that's showing in the *ngFor.

Let me explain a little more before showing some code:

I create a question and save it, showing the questions and answers in an *ngFor in a list where i can edit the question or delete it.

After i click in "edit" i send the question data back to my form where i can edit. While editing the listing on the right side changes the answer while i'm editing. But when i click to cancel editing it stays the value i've changed, but i need to change ONLY if the user clicks to save again.

Here's my HTML code:

```<code><ion-row>
<ion-col col-12 col-md-6>

  <!-- THE FORM I'M USING TO CREATE AND EDIT -->
  <form novalidate [formGroup]="novaQuestaoMultipla">
    <ion-item no-lines>
      <ion-label stacked>
        Título
        <p text-right [ngClass]="{'green': novaQuestaoMultipla.get('titulo').value.length <= 70, 'yellow': novaQuestaoMultipla.get('titulo').value.length > 70 && novaQuestaoMultipla.get('titulo').value.length <= 140, 'red': novaQuestaoMultipla.get('titulo').value.length > 140 }">({{novaQuestaoMultipla.get('titulo').value.length}}/160)</p>
      </ion-label>
      <ion-textarea rows="4" formControlName="titulo" maxlength="160" [ngClass]="{'campo-invalido': !novaQuestaoMultipla.get('titulo').valid && (novaQuestaoMultipla.get('titulo').dirty || multiplaInvalida)}"></ion-textarea>
    </ion-item>
    <div *ngIf="titulosQuestoesFiltradas.length > 0" class="titulos" text-center>
    </div>

    <p text-center class="texto-campo-invalido" *ngIf="!novaQuestaoMultipla.get('titulo').valid && (novaQuestaoMultipla.get('titulo').dirty || multiplaInvalida)">Inválido</p>
    <br />

    <ion-row class="campo-respostas">
      <ion-col text-right col-8>
        <h3>Opções de Respostas</h3>
      </ion-col>
      <ion-col text-left col-4>
        <button ion-button round icon-only color="gold" [disabled]="quantidadeRespostasMultipla == 5" (click)="novaOpcao()">
          <ion-icon name="add"></ion-icon>
        </button>
      </ion-col>
    </ion-row>
    <ion-row *ngIf="quantidadeRespostasMultipla > 0">
      <ion-col text-left>
        <h3>Texto</h3>
      </ion-col>
      <ion-col text-right>
        <h3>Correta</h3>
      </ion-col>
    </ion-row>

    <ion-row *ngFor="let r of respostasMultipla; let i = index" class="resposta-multipla" align-items-end>
      <ion-col col-12 col-md-8>
        <ion-item no-lines>
          <ion-label stacked>
            <p text-right [ngClass]="{'green': r.texto.length <= 20, 'yellow': r.texto.length > 20 && r.texto.length <= 35, 'red': r.texto.length > 35 }">({{r.texto.length}}/40)</p>
          </ion-label>
          <ion-input type="text" maxlength="40" [(ngModel)]="r.texto" [ngModelOptions]="{standalone: true}"></ion-input>
        </ion-item>
      </ion-col>
      <ion-col col-6 col-md-2 text-center>
        <button ion-button color="danger" round (click)="excluirOpcao(i)">
          <ion-icon name="ios-trash-outline"></ion-icon>
        </button>
      </ion-col>
      <ion-col col-6 col-md-2>
        <ion-item no-lines>
          <ion-toggle (ionChange)="escolheuCorreta(r, index)" [(ngModel)]="r.correto" [ngModelOptions]="{standalone: true}"></ion-toggle>
        </ion-item>
      </ion-col>
    </ion-row>
    <br />

    <div text-center>
      <button ion-button round color="danger" *ngIf="hasEditQuestao" (click)="cancelarEdicao()">Cancelar edição</button>
      <button ion-button round (click)="salvarMultipla()">Salvar Questão</button>
    </div>
  </form>
</ion-col>

<!-- THE LISTING I SHOW MY QUESTIONS AND WHERE I CAN CLICK TO EDIT THEM-->
<ion-col col-12 col-md-6 >
  <ion-item *ngFor="let q of questoesEscolhidasExibicao; let i = index" text-wrap>
    <h2>{{q.titulo}}</h2>
    <p *ngFor="let r of q.respostas">{{r.texto}}</p>
    <button ion-button outline color="gold" item-end icon-only (click)="editarQuestao(q, i)">
      <ion-icon name="create"></ion-icon>
    </button>
    <button ion-button outline color="danger" item-end icon-only (click)="removerQuestao(q, i)">
      <ion-icon name="trash"></ion-icon>
    </button>
  </ion-item>
</ion-col>
</code>```

And here's my JS code for editing:

```<code>// EDIT QUESTION
editarQuestao(questao, index) {
    // HERE I TRY SAVING THE QUESTION IN ANOTHER VARIABLE SO IT CAN "LOSE" THE REFERENCE, BUT NO LUCK
    const respostas = questao.respostas;

    // SAVE THE QUESTION ID THAT'S THE OBJECT KEY
    this.hasEditQuestao = questao.id;
    // THE ARRAY INDEX WHERE THE QUESTION IS SAVED
    this.editQuestaoIndex = index;
    // THE QUESTION DATA
    this.questData = questao;

    // UPDATE THE FORM WITH THE QUESTION DATA
    this.novaQuestaoMultipla.get('titulo').setValue(questao.titulo);
    //this.novaQuestaoMultipla.get('tempo').setValue(10);
    this.respostasMultipla = respostas;
    this.quantidadeRespostasMultipla = this.respostasMultipla.length;
}
</code>```

FIY i have an object and an array of objects. The object i'm using so i can simply push data only one time to Firebase. The array i use for showing purpouses.

How can i achieve this? How can i edit my question WITHOUT automatically changing it so i can update it ONLY when i click save? How can i remove that reference from my array?

答:
You have these issues due to 2-way data-bind with [(ngModel)].You can easily avoid these issues if you use Reactive forms.

Angular reactive forms facilitate a reactive style of programming that
  favors explicit management of the data flowing between a non-UI data
  model (typically retrieved from a server) and a UI-oriented form model
  that retains the states and values of the HTML controls on screen.
  Reactive forms offer the ease of using reactive patterns, testing, and
  validation.

You create and manipulate form control objects directly in the
  component class. As the component class has immediate access to both
  the data model and the form control structure, you can push data model
  values into the form controls and pull user-changed values back out.
  The component can observe changes in form control state and react to
  those changes

Body:
I have an application using Angular with Ionic 3 and i have an array of questions. These questions can be edited if the user has made something wrong.

The case is when i click to edit any queston it kind of references that question in the array and any edit reflects immediately to the array that's showing in the *ngFor.

Let me explain a little more before showing some code:

I create a question and save it, showing the questions and answers in an *ngFor in a list where i can edit the question or delete it.

After i click in "edit" i send the question data back to my form where i can edit. While editing the listing on the right side changes the answer while i'm editing. But when i click to cancel editing it stays the value i've changed, but i need to change ONLY if the user clicks to save again.

Here's my HTML code:

<ion-row>
<ion-col col-12 col-md-6>

  <form novalidate [formGroup]="novaQuestaoMultipla">
    <ion-item no-lines>
      <ion-label stacked>
        Título
        <p text-right [ngClass]="{'green': novaQuestaoMultipla.get('titulo').value.length <= 70, 'yellow': novaQuestaoMultipla.get('titulo').value.length > 70 && novaQuestaoMultipla.get('titulo').value.length <= 140, 'red': novaQuestaoMultipla.get('titulo').value.length > 140 }">({{novaQuestaoMultipla.get('titulo').value.length}}/160)

      </ion-label>
      <ion-textarea rows="4" formControlName="titulo" maxlength="160" [ngClass]="{'campo-invalido': !novaQuestaoMultipla.get('titulo').valid && (novaQuestaoMultipla.get('titulo').dirty || multiplaInvalida)}"></ion-textarea>
    </ion-item>

 0" class="titulos" text-center>

Inválido

    <ion-row class="campo-respostas">
      <ion-col text-right col-8>

Opções de Respostas

      </ion-col>
      <ion-col text-left col-4>
        <button ion-button round icon-only color="gold" [disabled]="quantidadeRespostasMultipla == 5" (click)="novaOpcao()">
          <ion-icon name="add"></ion-icon>
        </button>
      </ion-col>
    </ion-row>
    <ion-row *ngIf="quantidadeRespostasMultipla > 0">
      <ion-col text-left>

Texto

      </ion-col>
      <ion-col text-right>

Correta

      </ion-col>
    </ion-row>

    <ion-row *ngFor="let r of respostasMultipla; let i = index" class="resposta-multipla" align-items-end>
      <ion-col col-12 col-md-8>
        <ion-item no-lines>
          <ion-label stacked>
            <p text-right [ngClass]="{'green': r.texto.length <= 20, 'yellow': r.texto.length > 20 && r.texto.length <= 35, 'red': r.texto.length > 35 }">({{r.texto.length}}/40)

          </ion-label>
          <ion-input type="text" maxlength="40" [(ngModel)]="r.texto" [ngModelOptions]="{standalone: true}"></ion-input>
        </ion-item>
      </ion-col>
      <ion-col col-6 col-md-2 text-center>
        <button ion-button color="danger" round (click)="excluirOpcao(i)">
          <ion-icon name="ios-trash-outline"></ion-icon>
        </button>
      </ion-col>
      <ion-col col-6 col-md-2>
        <ion-item no-lines>
          <ion-toggle (ionChange)="escolheuCorreta(r, index)" [(ngModel)]="r.correto" [ngModelOptions]="{standalone: true}"></ion-toggle>
        </ion-item>
      </ion-col>
    </ion-row>

      <button ion-button round color="danger" *ngIf="hasEditQuestao" (click)="cancelarEdicao()">Cancelar edição</button>
      <button ion-button round (click)="salvarMultipla()">Salvar Questão</button>

  </form>
</ion-col>

<ion-col col-12 col-md-6 >
  <ion-item *ngFor="let q of questoesEscolhidasExibicao; let i = index" text-wrap>

{{q.titulo}}

{{r.texto}}

    <button ion-button outline color="gold" item-end icon-only (click)="editarQuestao(q, i)">
      <ion-icon name="create"></ion-icon>
    </button>
    <button ion-button outline color="danger" item-end icon-only (click)="removerQuestao(q, i)">
      <ion-icon name="trash"></ion-icon>
    </button>
  </ion-item>
</ion-col>

And here's my JS code for editing:

// EDIT QUESTION
editarQuestao(questao, index) {
    // HERE I TRY SAVING THE QUESTION IN ANOTHER VARIABLE SO IT CAN "LOSE" THE REFERENCE, BUT NO LUCK
    const respostas = questao.respostas;

    // SAVE THE QUESTION ID THAT'S THE OBJECT KEY
    this.hasEditQuestao = questao.id;
    // THE ARRAY INDEX WHERE THE QUESTION IS SAVED
    this.editQuestaoIndex = index;
    // THE QUESTION DATA
    this.questData = questao;

    // UPDATE THE FORM WITH THE QUESTION DATA
    this.novaQuestaoMultipla.get('titulo').setValue(questao.titulo);
    //this.novaQuestaoMultipla.get('tempo').setValue(10);
    this.respostasMultipla = respostas;
    this.quantidadeRespostasMultipla = this.respostasMultipla.length;
}

FIY i have an object and an array of objects. The object i'm using so i can simply push data only one time to Firebase. The array i use for showing purpouses.

How can i achieve this? How can i edit my question WITHOUT automatically changing it so i can update it ONLY when i click save? How can i remove that reference from my array?


问:
Cant click on an img with Sikili
I want to click on an ing with Sikuli. I use this:

```<code>Screen screen - new screen()
screen.click(getData("ImagePath") + imageName);
</code>```

** getData - I take the path from XML.

The test is passed but the img is not clicked.

I received this msg:

[log] CLICK on L(1269,364)@S(0)[0,0 1366x768] (526 msec)

What is the problem?

答:
This seems to be either a sync issue or wrong region

Use img.highlight method to first check if you're actually working on the expected region

Use conditions such as if exists(img, timeout) or wait(img, timeout) to make sure your image is appearing on the screen at the right time.

Title: Cant click on an img with Sikili

Body:
I want to click on an ing with Sikuli. I use this:

Screen screen - new screen()
screen.click(getData("ImagePath") + imageName);

** getData - I take the path from XML.

The test is passed but the img is not clicked.

I received this msg:

[log] CLICK on L(1269,364)@S(0)[0,0 1366x768] (526 msec)

What is the problem?


问:
C++ Vector Magnitude
I have been tasked with making a vector magnitude function in C++ as part of a maths library for a class project, however I am unsure how to go about this, if someone could recommend some pages to read and or give me some help that would be great

Edit: My C++ knowledge isn't that great, I'm looking for pages to help me learn how to do functions for vectors

答:
A quick google comes up with

magnitudes

As this is a class project I'll let you read the link rather than giving full details here.

You may want to read up on using vectors, for instance here.

Personally I prefer to use C++ standard algorithms where possible. You can do this sort of thing quickly and efficiently with std::accumulate.

```<code>#include <iostream>
#include <vector>
#include <numeric>
#include <string>
#include <functional>

int main()
{
    std::vector<double> v{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    double ssq = std::accumulate(v.begin(), v.end(),
                                    0.0,
                                    /* add here */);

    std::cout << "ssq: " << ssq << '\n';
}
</code>```

The line marked /* add here */ is where you need to add an operator that takes the current running sum of squares and the next value to add to it, and returns the new running sum of squares.

Alternatively, you could just write a for loop

```<code>double ssq = 0.0;
std::vector<double> v{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
for (auto e : v)
{
    // calculate sum of squares here
}
</code>```

Title: C++ Vector Magnitude

Body:
A quick google comes up with

magnitudes

As this is a class project I'll let you read the link rather than giving full details here.

You may want to read up on using vectors, for instance here.

Personally I prefer to use C++ standard algorithms where possible. You can do this sort of thing quickly and efficiently with std::accumulate.

#include <iostream>
#include <vector>
#include <numeric>
#include <string>
#include <functional>

int main()
{
    std::vector<double> v{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    double ssq = std::accumulate(v.begin(), v.end(),
                                    0.0,
                                    /* add here */);

    std::cout << "ssq: " << ssq << '\n';
}

The line marked /* add here */ is where you need to add an operator that takes the current running sum of squares and the next value to add to it, and returns the new running sum of squares.

Alternatively, you could just write a for loop

double ssq = 0.0;
std::vector<double> v{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
for (auto e : v)
{
    // calculate sum of squares here
}


问:
How to tell what triggered jQuery focus()?
I have an input field and a button. It is necessary that when the button is clicked the input field gets focus.

I need the behaviour to be slightly different depending on whether the input field was focused manually by the user or if it was focused due the button being clicked.

It seems this would be relatively simple, but I couldn't come up with a solution so far. Any ideas very welcome.

```<code>$("button").click(function() {
    target_input = $("input");
    target_input.focus();
});

$("input").focus(function() {
    // if focus done manually by user
    //    do something
    // if focus done via button
    //    do something else
});
</code>```

答:
You should be able to use Event.isTrusted for this:

The isTrusted read-only property of the Event interface is a boolean
  that is true when the event was generated by a user action, and false
  when the event was created or modified by a script or dispatched via
  dispatchEvent.

```<code>$("input").focus(function(e) {
    if(e.isTrusted) {...} else {...}
});
</code>```

As noted in the comments, neither IE nor Safari like this.

Body:
I have an input field and a button. It is necessary that when the button is clicked the input field gets focus.

I need the behaviour to be slightly different depending on whether the input field was focused manually by the user or if it was focused due the button being clicked.

It seems this would be relatively simple, but I couldn't come up with a solution so far. Any ideas very welcome.

$("button").click(function() {
    target_input = $("input");
    target_input.focus();
});

$("input").focus(function() {
    // if focus done manually by user
    //    do something
    // if focus done via button
    //    do something else
});

Body:
You should be able to use Event.isTrusted for this:

The isTrusted read-only property of the Event interface is a boolean
  that is true when the event was generated by a user action, and false
  when the event was created or modified by a script or dispatched via
  dispatchEvent.

$("input").focus(function(e) {
    if(e.isTrusted) {...} else {...}
});

As noted in the comments, neither IE nor Safari like this.


问:
QuitApplication Button on unity
I am trying to create a Quit button in Unity, but when I add my script to the button and click it, it doesn't quit.

Here is my C# script:

```<code>    using UnityEngine;
using System.Collections;

public class Quit_App : MonoBehaviour {
    void OnClick() {
        Application.Quit();
    }
}
</code>```

I have created it and assigned to the canvas using the UI, and I use the Button(Script) box in order to execute this code using the OnClick() box.
There, I selected it as object MyButton and the Quit_App() function using a string name.

答:
Your script assumes that calling the method OnClick will magically make the click detected, but that is not the case.

You need a Menu Manager script added to the scene exposing a public method to be binded to the Button component.

Here the setup you need:

The script MenuManager is attached to the MenuManager game object:

The code in the MenuManager script is real simple:

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MenuManager : MonoBehaviour {

    public void ExitNow()
    {
        Application.Quit();
    }

}
</code>```

I uploaded the package with a fully functional implementation here.

Title: QuitApplication Button on unity

Body:
I am trying to create a Quit button in Unity, but when I add my script to the button and click it, it doesn't quit.

Here is my C# script:

    using UnityEngine;
using System.Collections;

public class Quit_App : MonoBehaviour {
    void OnClick() {
        Application.Quit();
    }
}

I have created it and assigned to the canvas using the UI, and I use the Button(Script) box in order to execute this code using the OnClick() box.
There, I selected it as object MyButton and the Quit_App() function using a string name.

Body:
Your script assumes that calling the method OnClick will magically make the click detected, but that is not the case.

You need a Menu Manager script added to the scene exposing a public method to be binded to the Button component.

Here the setup you need:

The script MenuManager is attached to the MenuManager game object:

The code in the MenuManager script is real simple:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MenuManager : MonoBehaviour {

    public void ExitNow()
    {
        Application.Quit();
    }

}

I uploaded the package with a fully functional implementation here.