问:
SQL to merge rows in Oracle
I want to merge some rows.

First, my table and data exist as below

```<code>GRP     CRRO_NO  TYPE_CD  TYPE_ID
PERSON  1111     FATHER   Tom
PERSON  1111     MOTHER   Jennifer
PERSON  1111     JOB_     Teacher
PERSON  1111     FRIEND   Jimmy
PERSON  1111     FRIEND   Kim
PERSON  1111     FRIEND   Michael
</code>```

And I want to get the result like

```<code>GRP     CRRO_NO   FATHER    MOTHER     JOB_      FRIEND
PERSON  1111      Tom       Jennifer   Teacher   Jimmy
PERSON  1111      Tom       Jennifer   Teacher   Kim
PERSON  1111      Tom       Jennifer   Teacher   Michael
</code>```

With this situation, how to write SQL?

I've been trying like

```<code>SELECT  T1.GRP_CD GRP, T1.CRRO_NO CRRO
      , MAX(T1.MOTHER) MOTHER, MAX(T1.FATHER) FATHER, MAX(T1.JOB_) JOB, T1.FRIEND FRIEND
  FROM (
        SELECT  DISTINCT
                GRP_CD
               ,CRRO_NO
               ,CASE WHEN TYPE_CD  = 'FATHER'  THEN TYPE_ID   ELSE '' END FATHER
               ,CASE WHEN TYPE_CD  = 'MOTHER'  THEN TYPE_ID   ELSE '' END MOTHER
               ,CASE WHEN TYPE_CD  = 'JOB_'    THEN TYPE_ID    ELSE '' END JOB_
               ,CASE WHEN TYPE_CD  = 'FRIEND'  THEN TYPE_ID   ELSE '' END FRIEND
         FROM    TMP
        WHERE   1=1   AND     TRIM(CRRO_NO) = '1111'
       ) T1
  WHERE T1.CRRO_NO = '1111'
        GROUP BY T1.GRP_CD, T1.CRRO_NO, T1.FRIEND
;
</code>```

Then, the result of sql above is

```<code>GRP      CRRO_NO  MOTHER     FATHER    JOB       FRIEND
PERSON   1111     Jennifer   Tom       Teacher   (null)
PERSON   1111     (null)     (null)    (null)    Jimmy
PERSON   1111     (null)     (null)    (null)    Kim
PERSON   1111     (null)     (null)    (null)    Michael
</code>```

Now I know why the result of my query is wrong(not the one I want), but still I can't find the way.

Actually, there are strict rules to classify which one would be duplicated (Mother, Father, Job) and which would not (friend)

For some reasons, I can't modify the structure of my table.
(I've changed contents of this question from my business terms and simplified the situation to explain)

Please give any advice to try again

答:
A self-joined table will do the trick:

```<code>select distinct t1.GRP, t1.CRRO_NO, t2.TYPE_ID as father, t3.TYPE_ID as mother, t4.TYPE_ID as JOB_, t5.TYPE_ID as FRIEND
from TMP t1
inner join TMP t2   on  t2.CRRO_NO = t1.CRRO_NO
                    and t2.TYPE_CD = 'FATHER'
inner join TMP t3   on  t3.CRRO_NO = t1.CRRO_NO
                    and t3.TYPE_CD = 'MOTHER'
inner join TMP t4   on  t4.CRRO_NO = t1.CRRO_NO
                    and t4.TYPE_CD = 'JOB_'
inner join TMP t5   on  t5.CRRO_NO = t1.CRRO_NO
                    and t5.TYPE_CD = 'FRIEND';
</code>```

However note that since you're not specifying a filter predicate (a WHERE clause), all results in table TMP will be processed and you'll have duplicate results, hence the use of 'distinct' would be mandatory, and of course it can be discarded if you use a filter such as: WHERE t1.type_cd = 'FATHER'

Title: SQL to merge rows in Oracle

Body:
I want to merge some rows.

First, my table and data exist as below

GRP     CRRO_NO  TYPE_CD  TYPE_ID
PERSON  1111     FATHER   Tom
PERSON  1111     MOTHER   Jennifer
PERSON  1111     JOB_     Teacher
PERSON  1111     FRIEND   Jimmy
PERSON  1111     FRIEND   Kim
PERSON  1111     FRIEND   Michael

And I want to get the result like

GRP     CRRO_NO   FATHER    MOTHER     JOB_      FRIEND
PERSON  1111      Tom       Jennifer   Teacher   Jimmy
PERSON  1111      Tom       Jennifer   Teacher   Kim
PERSON  1111      Tom       Jennifer   Teacher   Michael

With this situation, how to write SQL?

I've been trying like

SELECT  T1.GRP_CD GRP, T1.CRRO_NO CRRO
      , MAX(T1.MOTHER) MOTHER, MAX(T1.FATHER) FATHER, MAX(T1.JOB_) JOB, T1.FRIEND FRIEND
  FROM (
        SELECT  DISTINCT
                GRP_CD
               ,CRRO_NO
               ,CASE WHEN TYPE_CD  = 'FATHER'  THEN TYPE_ID   ELSE '' END FATHER
               ,CASE WHEN TYPE_CD  = 'MOTHER'  THEN TYPE_ID   ELSE '' END MOTHER
               ,CASE WHEN TYPE_CD  = 'JOB_'    THEN TYPE_ID    ELSE '' END JOB_
               ,CASE WHEN TYPE_CD  = 'FRIEND'  THEN TYPE_ID   ELSE '' END FRIEND
         FROM    TMP
        WHERE   1=1   AND     TRIM(CRRO_NO) = '1111'
       ) T1
  WHERE T1.CRRO_NO = '1111'
        GROUP BY T1.GRP_CD, T1.CRRO_NO, T1.FRIEND
;

Then, the result of sql above is

GRP      CRRO_NO  MOTHER     FATHER    JOB       FRIEND
PERSON   1111     Jennifer   Tom       Teacher   (null)
PERSON   1111     (null)     (null)    (null)    Jimmy
PERSON   1111     (null)     (null)    (null)    Kim
PERSON   1111     (null)     (null)    (null)    Michael

Now I know why the result of my query is wrong(not the one I want), but still I can't find the way.

Actually, there are strict rules to classify which one would be duplicated (Mother, Father, Job) and which would not (friend)

For some reasons, I can't modify the structure of my table.
(I've changed contents of this question from my business terms and simplified the situation to explain)

Please give any advice to try again

Body:
A self-joined table will do the trick:

select distinct t1.GRP, t1.CRRO_NO, t2.TYPE_ID as father, t3.TYPE_ID as mother, t4.TYPE_ID as JOB_, t5.TYPE_ID as FRIEND
from TMP t1
inner join TMP t2   on  t2.CRRO_NO = t1.CRRO_NO
                    and t2.TYPE_CD = 'FATHER'
inner join TMP t3   on  t3.CRRO_NO = t1.CRRO_NO
                    and t3.TYPE_CD = 'MOTHER'
inner join TMP t4   on  t4.CRRO_NO = t1.CRRO_NO
                    and t4.TYPE_CD = 'JOB_'
inner join TMP t5   on  t5.CRRO_NO = t1.CRRO_NO
                    and t5.TYPE_CD = 'FRIEND';

However note that since you're not specifying a filter predicate (a WHERE clause), all results in table TMP will be processed and you'll have duplicate results, hence the use of 'distinct' would be mandatory, and of course it can be discarded if you use a filter such as: WHERE t1.type_cd = 'FATHER'


来源: stackexchange

问:
Resources and control position in win32 programming
I'm new in win32 programming and I've some questions about resources.

Must I use a resource editor (from Visual Studio) to make controls? I know it can be post-edited using a Resource Hacker editor. How to prevent it?

GUI created in Windows Forms (.net) or Borland Delphi (VCL) can't be edited using res hacker, maybe it creates controls at runtime.

Is a pointless work make all controls by runtime to prevent it to be edited by res hacker?

```<code>HWND hButton = CreateWindowEx(
    0,
    _T("BUTTON"),
    _T("Click!"),
    WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | BS_LEFTTEXT,
    5, 5, 80, 25, hwnd, (HMENU)IDC_BUTTON1,
    GetModuleHandle(NULL),
    NULL
);
</code>```

Second question: isn't there a easy way to set position of a control in top right of parent window?

Today I'm doing it in this way:

```<code>case WM_SIZE:
    {
        HWND hButton;
        RECT rcParent, rcButton;

        hButton = GetDlgItem(hwnd, IDC_BUTTON1);

        GetClientRect(hwnd, &rcParent);
        GetClientRect(hButton, &rcButton);

        if(!SetWindowPos(hButton, 0, rcParent.right - (rcButton.right - rcButton.left + 5), 5, 0, 0, SWP_NOSIZE))
        {
            MessageBox(hwnd, _T("Error at WM_SIZE"), _T("Error!"), MB_OK | MB_ICONERROR);
        }
    }
    break;
</code>```

Are there something like Anchors in pure win32 programming?

答:
Is a pointless work make all controls
  by runtime to prevent it to be edited
  by res hacker?

It's not pointless, it's only extra work. You will need also to code a resource editor and/or a layout manager to ease your work. You can define and handle your own resource definition file, and put it as a custom resource.

Are there something like Anchors in
  pure win32 programming?

No layout manager in pure win32. But you may find some free source code to do this. It's rather easy to do some minimal layout manager.

ContentLicense: CC BY-SA 2.5

Body:
I'm new in win32 programming and I've some questions about resources.

Must I use a resource editor (from Visual Studio) to make controls? I know it can be post-edited using a Resource Hacker editor. How to prevent it?

GUI created in Windows Forms (.net) or Borland Delphi (VCL) can't be edited using res hacker, maybe it creates controls at runtime.

Is a pointless work make all controls by runtime to prevent it to be edited by res hacker?

HWND hButton = CreateWindowEx(
    0,
    _T("BUTTON"),
    _T("Click!"),
    WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | BS_LEFTTEXT,
    5, 5, 80, 25, hwnd, (HMENU)IDC_BUTTON1,
    GetModuleHandle(NULL),
    NULL
);

Second question: isn't there a easy way to set position of a control in top right of parent window?

Today I'm doing it in this way:

case WM_SIZE:
    {
        HWND hButton;
        RECT rcParent, rcButton;

        hButton = GetDlgItem(hwnd, IDC_BUTTON1);

        GetClientRect(hwnd, &rcParent);
        GetClientRect(hButton, &rcButton);

        if(!SetWindowPos(hButton, 0, rcParent.right - (rcButton.right - rcButton.left + 5), 5, 0, 0, SWP_NOSIZE))
        {
            MessageBox(hwnd, _T("Error at WM_SIZE"), _T("Error!"), MB_OK | MB_ICONERROR);
        }
    }
    break;

Are there something like Anchors in pure win32 programming?


问:
How to fetch all the child nodes of an XML using python?
This is my XML file

```<code><?xml version="1.0"?>
<data>
    <country name="Liechtenstein">
        <rank>1</rank>
        <year>2008</year>
        <gdp>141100</gdp>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
</data>
</code>```

How to pull all the child nodes of country?

For Example, I need the output as ['rank','year','gdp','neighbor']

答:
Have a look up to python documentation. It verily uses this xml tree as example.

```<code>import xml.etree.ElementTree as ET
tree = ET.parse('country_data.xml')
root = tree.getroot()

country = root[0].getchildren()
map(lambda e: e.tag, r)
# ['rank', 'year', 'gdp', 'neighbor', 'neighbor']
</code>```

Btw, when you are stuck, open repl and go step by step. I do not remember all those stuff above. And last used xml parser 2 or 3 years ago. But I know, "try and see" is the best teacher.

Those are steps, how I come up with a solution.

```<code># imports and other stuff.
>>> tree = ET.parse('data.xml')
>>> root = tree.getroot()
>>> country = root[0]
>>> dir(country)
['__class__', '__delattr__', '__delitem__', '__dict__', '__doc__', '__format__', '__getattribute__', '__getitem__', '__hash__', '__init__', '__len__', '__module__', '__new__', '__nonzero__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_children', 'append', 'attrib', 'clear', 'copy', 'extend', 'find', 'findall', 'findtext', 'get', 'getchildren', 'getiterator', 'insert', 'items', 'iter', 'iterfind', 'itertext', 'keys', 'makeelement', 'remove', 'set', 'tag', 'tail', 'text']
>>> country.keys()
['name']
>>> country.getchildren()
[<Element 'rank' at 0x7f873cf53910>, <Element 'year' at 0x7f873cf539d0>, <Element 'gdp' at 0x7f873cf53a90>, <Element 'neighbor' at 0x7f873cf53c10>, <Element 'neighbor' at 0x7f873cf53c50>]
>>> country.getchildren()[0]
<Element 'rank' at 0x7f873cf53910>
>>> r = country.getchildren()[0]
>>> dir(r)
['__class__', '__delattr__', '__delitem__', '__dict__', '__doc__', '__format__', '__getattribute__', '__getitem__', '__hash__', '__init__', '__len__', '__module__', '__new__', '__nonzero__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_children', 'append', 'attrib', 'clear', 'copy', 'extend', 'find', 'findall', 'findtext', 'get', 'getchildren', 'getiterator', 'insert', 'items', 'iter', 'iterfind', 'itertext', 'keys', 'makeelement', 'remove', 'set', 'tag', 'tail', 'text']
>>> r.tag
'rank'
>>> r = country.getchildren()[0]
>>> r
<Element 'rank' at 0x7f873cf53910>
>>> r = country.getchildren()
>>> r
[<Element 'rank' at 0x7f873cf53910>, <Element 'year' at 0x7f873cf539d0>, <Element 'gdp' at 0x7f873cf53a90>, <Element 'neighbor' at 0x7f873cf53c10>, <Element 'neighbor' at 0x7f873cf53c50>]
>>> map(lambda e: e.tag, r)
['rank', 'year', 'gdp', 'neighbor', 'neighbor']
</code>```

ContentLicense: CC BY-SA 3.0

Body:
This is my XML file

<?xml version="1.0"?>
<data>
    <country name="Liechtenstein">
        <rank>1</rank>
        <year>2008</year>
        <gdp>141100</gdp>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
</data>

How to pull all the child nodes of country?

For Example, I need the output as ['rank','year','gdp','neighbor']

Body:
Have a look up to python documentation. It verily uses this xml tree as example.

import xml.etree.ElementTree as ET
tree = ET.parse('country_data.xml')
root = tree.getroot()

country = root[0].getchildren()
map(lambda e: e.tag, r)
# ['rank', 'year', 'gdp', 'neighbor', 'neighbor']

Btw, when you are stuck, open repl and go step by step. I do not remember all those stuff above. And last used xml parser 2 or 3 years ago. But I know, "try and see" is the best teacher.

Those are steps, how I come up with a solution.

# imports and other stuff.
>>> tree = ET.parse('data.xml')
>>> root = tree.getroot()
>>> country = root[0]
>>> dir(country)
['__class__', '__delattr__', '__delitem__', '__dict__', '__doc__', '__format__', '__getattribute__', '__getitem__', '__hash__', '__init__', '__len__', '__module__', '__new__', '__nonzero__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_children', 'append', 'attrib', 'clear', 'copy', 'extend', 'find', 'findall', 'findtext', 'get', 'getchildren', 'getiterator', 'insert', 'items', 'iter', 'iterfind', 'itertext', 'keys', 'makeelement', 'remove', 'set', 'tag', 'tail', 'text']
>>> country.keys()
['name']
>>> country.getchildren()
[<Element 'rank' at 0x7f873cf53910>, <Element 'year' at 0x7f873cf539d0>, <Element 'gdp' at 0x7f873cf53a90>, <Element 'neighbor' at 0x7f873cf53c10>, <Element 'neighbor' at 0x7f873cf53c50>]
>>> country.getchildren()[0]
<Element 'rank' at 0x7f873cf53910>
>>> r = country.getchildren()[0]
>>> dir(r)
['__class__', '__delattr__', '__delitem__', '__dict__', '__doc__', '__format__', '__getattribute__', '__getitem__', '__hash__', '__init__', '__len__', '__module__', '__new__', '__nonzero__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_children', 'append', 'attrib', 'clear', 'copy', 'extend', 'find', 'findall', 'findtext', 'get', 'getchildren', 'getiterator', 'insert', 'items', 'iter', 'iterfind', 'itertext', 'keys', 'makeelement', 'remove', 'set', 'tag', 'tail', 'text']
>>> r.tag
'rank'
>>> r = country.getchildren()[0]
>>> r
<Element 'rank' at 0x7f873cf53910>
>>> r = country.getchildren()
>>> r
[<Element 'rank' at 0x7f873cf53910>, <Element 'year' at 0x7f873cf539d0>, <Element 'gdp' at 0x7f873cf53a90>, <Element 'neighbor' at 0x7f873cf53c10>, <Element 'neighbor' at 0x7f873cf53c50>]
>>> map(lambda e: e.tag, r)
['rank', 'year', 'gdp', 'neighbor', 'neighbor']


问:
Which one is best: Apache Ambari cluster on Physical system with 5 Machine or install on virtual machine with diffrent 5 VM?
Hi I am working on One of my project which I have created VM of 5 Machine and it is working fine in development environment but I have some confusion regarding VM cluster is good or need to go with physical system cluster.</p>

答:
If you are going to use virtual machines for HDFS, be careful with replication. By default, HDFS stores all data in 64mb chunks and replicates every chunk to 3 different nodes. Also, at least one replica should be located in a different physical rack - see "rack awareness" feature. If all 3 replicas of your virtualized data happen to be located on a single physical host/HDD, you may run into a problem in a case of hardware failure.

Another potential caveat may be I/O performance. If you are using file-based disk image for VM and not direct disc access, the I/O overhead may be considerable. Also, in many cases, virtual machines can not take advantage of filesystem cache on a physical host.

On the other hand, VM management and provisioning should be easier.

Otherwise, refer to https://stackoverflow.com/a/44355754/1421254 answer.


问:
How to select all the text in a Grid cell
I'm developing an app using dhtmlxGrid and have such a question:

How can I make the full text in a cell selected when the cell is selected?

I mean when I click on the cell, and the editor opens, I would like to have all the text selected so as I could delete it or start editing at once. I've gone through the documentation, but haven't found any event or method for this.

答:
Please, try to add the following code to select all the text value after the edit start:</p>

```<code>myGrid.attachEvent("onEditCell",function(stage,rowId,colInd){
if (stage==1 && this.editor && this.editor.obj){
this.editor.obj.select();
}
return true
})
</code>```

Body:
Please, try to add the following code to select all the text value after the edit start:

myGrid.attachEvent("onEditCell",function(stage,rowId,colInd){
if (stage==1 && this.editor && this.editor.obj){
this.editor.obj.select();
}
return true
})


问:
Location Based Ad system In Laravel
How to find which ad show to user using location(longitude and latitude)

DataBase structure

Ad Table

```<code>`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`user_id` INT(11) NOT NULL,
`title` VARCHAR(1000) NOT NULL COLLATE 'utf8mb4_unicode_ci',
`images` VARCHAR(1000) NOT NULL COLLATE 'utf8mb4_unicode_ci',
`source_url` VARCHAR(1000) NOT NULL COLLATE 'utf8mb4_unicode_ci',
`target` VARCHAR(20) NOT NULL COLLATE 'utf8mb4_unicode_ci',
`radius` VARCHAR(50) NULL DEFAULT NULL COLLATE 'utf8mb4_unicode_ci',
`distance` VARCHAR(50) NULL DEFAULT NULL COLLATE 'utf8mb4_unicode_ci',
`lat` VARCHAR(50) NULL DEFAULT NULL COLLATE 'utf8mb4_unicode_ci',
`lng` VARCHAR(50) NULL DEFAULT NULL COLLATE 'utf8mb4_unicode_ci',
`description` LONGTEXT NOT NULL COLLATE 'utf8mb4_unicode_ci',
`deleted_at` TIMESTAMP NULL DEFAULT NULL,
`created_at` TIMESTAMP NULL DEFAULT NULL,
`updated_at` TIMESTAMP NULL DEFAULT NULL,
`disable_admin` ENUM('Y','N') NULL DEFAULT 'N' COLLATE 'utf8mb4_unicode_ci',
</code>```

User Table

```<code>`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`name` VARCHAR(191) NOT NULL COLLATE 'utf8mb4_unicode_ci',
`full_name` VARCHAR(500) NULL DEFAULT NULL COLLATE 'utf8mb4_unicode_ci',
`email` VARCHAR(191) NOT NULL COLLATE 'utf8mb4_unicode_ci',
`gender` ENUM('Male','Female') NOT NULL DEFAULT 'Male' COLLATE
`birthday_date` DATETIME NULL DEFAULT NULL,
`current_city` VARCHAR(255) NULL DEFAULT NULL COLLATE 'utf8mb4_unicode_ci',
`email_verif` ENUM('Y','N') NULL DEFAULT 'N' COLLATE 'utf8mb4_unicode_ci',
`created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`updated_at` TIMESTAMP NOT NULL DEFAULT '0000-00-00 00:00:00',
`current_lat` VARCHAR(500) NULL DEFAULT 'N' COLLATE 'utf8mb4_unicode_ci',
`current_lng` VARCHAR(500) NULL DEFAULT 'N' COLLATE 'utf8mb4_unicode_ci',
</code>```

When User login in system then ad will be show using user current_lat ,current_lng

Problem is if admin create a ad with 28524.9203 radius and 40.32 distance from current lng or lat then how to find which ad will be show to user

Please Help i am stack in

Thanks

答:
This might help: Finding Points Within a Distance of a Latitude/Longitude Using Bounding Coordinates

Particularly the section "3.1 Computing the Minimum and Maximum Latitude". Or this: Selecting points within a bounding circle

Title: Location Based Ad system In Laravel

Body:
How to find which ad show to user using location(longitude and latitude)

DataBase structure

Ad Table

`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`user_id` INT(11) NOT NULL,
`title` VARCHAR(1000) NOT NULL COLLATE 'utf8mb4_unicode_ci',
`images` VARCHAR(1000) NOT NULL COLLATE 'utf8mb4_unicode_ci',
`source_url` VARCHAR(1000) NOT NULL COLLATE 'utf8mb4_unicode_ci',
`target` VARCHAR(20) NOT NULL COLLATE 'utf8mb4_unicode_ci',
`radius` VARCHAR(50) NULL DEFAULT NULL COLLATE 'utf8mb4_unicode_ci',
`distance` VARCHAR(50) NULL DEFAULT NULL COLLATE 'utf8mb4_unicode_ci',
`lat` VARCHAR(50) NULL DEFAULT NULL COLLATE 'utf8mb4_unicode_ci',
`lng` VARCHAR(50) NULL DEFAULT NULL COLLATE 'utf8mb4_unicode_ci',
`description` LONGTEXT NOT NULL COLLATE 'utf8mb4_unicode_ci',
`deleted_at` TIMESTAMP NULL DEFAULT NULL,
`created_at` TIMESTAMP NULL DEFAULT NULL,
`updated_at` TIMESTAMP NULL DEFAULT NULL,
`disable_admin` ENUM('Y','N') NULL DEFAULT 'N' COLLATE 'utf8mb4_unicode_ci',

User Table

`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`name` VARCHAR(191) NOT NULL COLLATE 'utf8mb4_unicode_ci',
`full_name` VARCHAR(500) NULL DEFAULT NULL COLLATE 'utf8mb4_unicode_ci',
`email` VARCHAR(191) NOT NULL COLLATE 'utf8mb4_unicode_ci',
`gender` ENUM('Male','Female') NOT NULL DEFAULT 'Male' COLLATE
`birthday_date` DATETIME NULL DEFAULT NULL,
`current_city` VARCHAR(255) NULL DEFAULT NULL COLLATE 'utf8mb4_unicode_ci',
`email_verif` ENUM('Y','N') NULL DEFAULT 'N' COLLATE 'utf8mb4_unicode_ci',
`created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`updated_at` TIMESTAMP NOT NULL DEFAULT '0000-00-00 00:00:00',
`current_lat` VARCHAR(500) NULL DEFAULT 'N' COLLATE 'utf8mb4_unicode_ci',
`current_lng` VARCHAR(500) NULL DEFAULT 'N' COLLATE 'utf8mb4_unicode_ci',

When User login in system then ad will be show using user current_lat ,current_lng

Problem is if admin create a ad with 28524.9203 radius and 40.32 distance from current lng or lat then how to find which ad will be show to user

Please Help i am stack in

Thanks


问:
How to add a white line below every ListView Item in xml?
My Problem is --> I put a white line as a view in the Fragment item xml but it doesn't appear when i debug it. How can i get the changes i make in the fragment item xml file. Because i tried some little changes like alpha property change but it didnt change is it because of this is a listview and has itself design? Please help me about that problem.

The xml code and adapter code are below.

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:gravity="center"
    >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:orientation="vertical"
        android:gravity="center"
        android:paddingTop="5dp"
        >

        <ImageView
            android:id="@+id/menulogo"
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:src="@drawable/infoicon"
            android:layout_gravity="center"
            android:paddingTop="5dp"
            />

    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:orientation="vertical"
        android:gravity="center">
        <TextView
            android:id="@+id/txtMenu"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center"
            android:text="Company Name"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:layout_weight="1" />
    </LinearLayout>
    <View
        android:id="@+id/line"
        android:layout_width="match_parent"
        android:layout_height="5dp"
        android:layout_below="@+id/txtMenu"
        android:background="#FFFFFF"
        />

</LinearLayout>
</code>```

My listview adapter codes right down below.

```<code>    public class MenuListAdapter extends ArrayAdapter<Menu_Item> {
        private final ArrayList<Menu_Item> list;
        private final Activity context;
    private int[] colors = new int[]{0x34a4a4a4, 0x34fafafa};

    public MenuListAdapter(Activity context, ArrayList<Menu_Item> list) {
        super(context, R.layout.menu_item, list);
        this.context = context;
        this.list = list;
    }

    static class ViewHolder {
        public ImageView menulogo;
        public TextView txtMenu;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = null;
        if (convertView == null) {
            LayoutInflater inflator = context.getLayoutInflater();
            view = inflator.inflate(R.layout.menu_item, null);
            final ViewHolder viewHolder = new ViewHolder();
            viewHolder.menulogo = (ImageView) view.findViewById(R.id.menulogo);
            viewHolder.txtMenu = (TextView) view.findViewById(R.id.txtMenu);
            view.setTag(viewHolder);
            int colorPos = position % colors.length;
            view.setBackgroundColor(colors[colorPos]);
        } else {
            view = convertView;
        }
        ViewHolder holder = (ViewHolder) view.getTag();
        holder.txtMenu.setText(list.get(position).getMenuName());
        //holder.menulogo.setImageBitmap(list.get(position).getMenuImage());
        String menuName=list.get(position).getMenuName();
        if (menuName.equals("Info")){
            holder.menulogo.setImageResource(R.drawable.infoicon);
        }
        if (menuName.equals("Odalar")){
            holder.menulogo.setImageResource(R.drawable.accomodation);
        }
        if (menuName.equals("Galeri")){
            holder.menulogo.setImageResource(R.drawable.galeryicon);
        }
        if (menuName.equals("Aktiviteler")){
            holder.menulogo.setImageResource(R.drawable.activitiesicon);
        }
        if (menuName.equals("Robin's Kids Club")){
            holder.menulogo.setImageResource(R.drawable.kidsclub);
        }
        if (menuName.equals("Restaurants")){
            holder.menulogo.setImageResource(R.drawable.restaurantsicon);
        }
        view.setId(list.get(position).getMenu_id());
        return view;
    }

    @Override
    public int getViewTypeCount() {
        if (getCount() != 0)
            return getCount();

        return 1;
    }

    }
</code>```

答:
Try to change the View with id line for a Space component. It is an extension of View, and works better for what you want.

Here is a description of the widget:
https://developer.android.com/reference/android/widget/Space.html

Body:
My Problem is --> I put a white line as a view in the Fragment item xml but it doesn't appear when i debug it. How can i get the changes i make in the fragment item xml file. Because i tried some little changes like alpha property change but it didnt change is it because of this is a listview and has itself design? Please help me about that problem.

The xml code and adapter code are below.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:gravity="center"
    >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:orientation="vertical"
        android:gravity="center"
        android:paddingTop="5dp"
        >

        <ImageView
            android:id="@+id/menulogo"
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:src="@drawable/infoicon"
            android:layout_gravity="center"
            android:paddingTop="5dp"
            />

    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:orientation="vertical"
        android:gravity="center">
        <TextView
            android:id="@+id/txtMenu"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center"
            android:text="Company Name"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:layout_weight="1" />
    </LinearLayout>
    <View
        android:id="@+id/line"
        android:layout_width="match_parent"
        android:layout_height="5dp"
        android:layout_below="@+id/txtMenu"
        android:background="#FFFFFF"
        />

</LinearLayout>

My listview adapter codes right down below.

    public class MenuListAdapter extends ArrayAdapter<Menu_Item> {
        private final ArrayList<Menu_Item> list;
        private final Activity context;
    private int[] colors = new int[]{0x34a4a4a4, 0x34fafafa};

    public MenuListAdapter(Activity context, ArrayList<Menu_Item> list) {
        super(context, R.layout.menu_item, list);
        this.context = context;
        this.list = list;
    }

    static class ViewHolder {
        public ImageView menulogo;
        public TextView txtMenu;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = null;
        if (convertView == null) {
            LayoutInflater inflator = context.getLayoutInflater();
            view = inflator.inflate(R.layout.menu_item, null);
            final ViewHolder viewHolder = new ViewHolder();
            viewHolder.menulogo = (ImageView) view.findViewById(R.id.menulogo);
            viewHolder.txtMenu = (TextView) view.findViewById(R.id.txtMenu);
            view.setTag(viewHolder);
            int colorPos = position % colors.length;
            view.setBackgroundColor(colors[colorPos]);
        } else {
            view = convertView;
        }
        ViewHolder holder = (ViewHolder) view.getTag();
        holder.txtMenu.setText(list.get(position).getMenuName());
        //holder.menulogo.setImageBitmap(list.get(position).getMenuImage());
        String menuName=list.get(position).getMenuName();
        if (menuName.equals("Info")){
            holder.menulogo.setImageResource(R.drawable.infoicon);
        }
        if (menuName.equals("Odalar")){
            holder.menulogo.setImageResource(R.drawable.accomodation);
        }
        if (menuName.equals("Galeri")){
            holder.menulogo.setImageResource(R.drawable.galeryicon);
        }
        if (menuName.equals("Aktiviteler")){
            holder.menulogo.setImageResource(R.drawable.activitiesicon);
        }
        if (menuName.equals("Robin's Kids Club")){
            holder.menulogo.setImageResource(R.drawable.kidsclub);
        }
        if (menuName.equals("Restaurants")){
            holder.menulogo.setImageResource(R.drawable.restaurantsicon);
        }
        view.setId(list.get(position).getMenu_id());
        return view;
    }

    @Override
    public int getViewTypeCount() {
        if (getCount() != 0)
            return getCount();

        return 1;
    }

    }


问:
What database tests should I write so that refactoring database is easy
Are there any guidelines on writing database tests so that you can refactor database "without fear" while doing evolutionary database design?

What aspects of database should be put to test while developing it? Any example would be great..

答:
The concept of having tests, according to TDD, is that you test the way things are meant to work now.  When you need to change something, you change the tests that address that, (ensure the current codebase fails), and then make the code changes until the tests pass.  The tests that didn't change give you confidence that other aspects of your software is still doing what it used to and that your refactoring hasn't broken anything.

So you don't write tests with refactoring in mind; rather, you test your requirements, and then when your requirements change you update the tests accordingly, and refactor the code so it passes the new tests.

OwnerDisplayName: StackUnderflow

LastEditorDisplayName: StackUnderflow

OwnerDisplayName: dtsazza


问:
What to do with the token data when the user signs out from android app?
The questions is pretty simple.I am also a novice regarding token authentication.

I know that, in case of token authentication, in case of android apps, token is used so that the user credentials does not remain in the app.i.e. whenever the user fetches data from server, it does not send the user credentials everytime but he sends token.

When the user signs in for the first time, from the app, a token is generated from the server and is "entried" in the database beside the user data.This token is send back to the app from the server and it is this token that the user, from the app, has to send everytime it plans to fetch some data from the server.When the user has to fetch data, it sends the required parameters and with them the token.This token is matched with all the tokens present in the database.If the token is present,it also gets the user associated with that token.And as the token is present so the user session is valid and then the required data from the server is send back to the android app.

What i want to know is that what to do with the token, in both client and server side, when the user logs out?

If any doubt please comment.I know its a simple question but dont know much about token authentication.Thanks everyone for their time.

Note:- Also if any of my concepts, in the question, is wrong please feel free to correct me.

答:
Basically all tokens have an expiry. This is intended for security purposes. But you can choose whether to set an expiry for your token. But I suggest that you must put an expiry for your token. And also delete that tokens from both server and client, and set user session to login again. Use timestamps to create the tokens. They are also useful when comparing tokens.

Happy Coding.... :-)


问:
Creating a custom widget in PyQT5
I would like to know how one can create a custom widget in pyqt. I've seen many different examples for C++, and a couple non descript examples for pyqt, but nothing that really explains how to do it and implement it. There is especially no examples that basically aren't just modified qt-designer output, and I'm writing my code from scratch so that's not very helpful.

So far, the best example I could find was basically just someone modifying qt-designer code and not really explaining what any of it was doing.

Could someone please show me an example of how to create a custom widget?

Edit:
I'm attempting to create a widget with an embedded QStackedWidget, and buttons on the bottom to cycle the pages.

I also planned on having a seperate widget for each page, but considering I can't actually accomplish step one, I figured I would cross that bridge when I get to it.

答:
Here are some nice advises, examples and approaches.

I think you can divide a custom Widget or any Custom "thing" you want in three ways.

Behavior: When you override its default methods with the behavior you want.

Layout: All the qt objects, be Items, or Widgets you add inside the layout will follow it's position rules and its policies.

StyleSheet: In case of Widget objects where you set the style of the Widget let's say setting its "CSS", just to be concise. Here are some references and examples.

Note: In case of non Widget objects you will not be able to set a StyleSheet so you will have to override some paint methods, create your own Painters and so on.

Here are some random examples with some comments along approaching the 3 topics I mentioned above:

```<code>import random
import sys

from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication
from PyQt5.QtWidgets import QDialog
from PyQt5.QtWidgets import QHBoxLayout
from PyQt5.QtWidgets import QPushButton
from PyQt5.QtWidgets import QVBoxLayout
from PyQt5.QtWidgets import QWidget

class MovableWidget(QWidget):

    def __init__(self):
        super(MovableWidget, self).__init__()

        #remove the frame
        self.setWindowFlags(Qt.CustomizeWindowHint)
        self.pressing = False

    # overriding the three next methods is a way to customize your Widgets
    # not just in terms of appearance but also behavioral.

    def mousePressEvent(self, QMouseEvent):
        #the pos of the widget when you first pressed it.
        self.start = QMouseEvent.pos()
        #to make sure you are holding mouse button down
        self.pressing = True

    def mouseMoveEvent(self, QMouseEvent):

        # You can Verify if it's also the left button and some other things
        # you need.
        if self.pressing : #and QMouseEvent.type() == Qt.LeftButton
            self.end = QMouseEvent.pos()
            self.delta = self.mapToGlobal(self.end-self.start)
            self.move(self.delta)
            self.end = self.start

    def mouseReleaseEvent(self, QMouseEvent):
        self.pressing = False

# inherits from QDialog and from MovableWidget so we can have its properties.
class CustomDialog(QDialog, MovableWidget):

    def __init__(self):
        super(CustomDialog, self).__init__()

        #Make the Dialog transparent
        self.setAttribute(Qt.WA_TranslucentBackground)

        # the widget will dispose itself according to the layout rules he's
        # inserted into.
        self.inner_widget = QWidget()
        self.inner_widget.setFixedSize(300,300)
        self.inner_layout = QHBoxLayout()
        self.inner_widget.setLayout(self.inner_layout)

        self.btn_change_color = QPushButton("Roll Color")

        self.btn_change_color.setStyleSheet("""
            background-color: green;
        """)

        # will connect to a function to be executed when the button is clicked.
        self.btn_change_color.clicked.connect(self.change_color)
        self.inner_layout.addWidget(self.btn_change_color)

        # Choose among many layouts according to your needs, QVBoxLayout,
        # QHBoxLayout, QStackedLayout, ... you can set its orientation
        # you can set its policies, spacing, margins. That's one of the main
        # concepts you have to learn to customize your Widget in the way
        # you want.
        self.layout = QVBoxLayout()

        # stylesheet have basically CSS syntax can call it QSS.
        # it can be used only on objects that come from Widgets
        # Also one of the main things to learn about customizing Widgets.

        # Note: The stylesheet you set in the "father" will be applied to its
        # children. Unless you tell it to be applied only to it and/or specify
        # each children's style.

        # The point I used inside the StyleSheet before the QDialog
        # e.g .QDialog and .QWidget says it'll be applied only to that
        # instance.

        self.setStyleSheet("""
            .QDialog{
                border-radius: 10px;
            }
        """)
        self.inner_widget.setStyleSheet("""
            .QWidget{
                background-color: red;
            }
        """)

        self.layout.addWidget(self.inner_widget)
        self.setLayout(self.layout)

    def change_color(self):
        red = random.choice(range(0,256))
        green = random.choice(range(0,256))
        blue = random.choice(range(0,256))
        self.inner_widget.setStyleSheet(
        """
            background-color: rgb({},{},{});
        """.format(red,green,blue)
        )

# since MovableWidget inherits from QWidget it also have QWidget properties.
class ABitMoreCustomizedWidget(MovableWidget):

    def __init__(self):
        super(ABitMoreCustomizedWidget, self).__init__()

        self.layout = QHBoxLayout()
        self.setLayout(self.layout)

        self.custom_button1 = CustomButton("Button 1")
        self.custom_button1.clicked.connect(self.btn_1_pressed)
        self.custom_button2 = CustomButton("Button 2")
        self.custom_button2.clicked.connect(self.btn_2_pressed)

        self.layout.addWidget(self.custom_button1)
        self.layout.addWidget(self.custom_button2)

    def btn_1_pressed(self):
        self.custom_button1.hide()
        self.custom_button2.show()

    def btn_2_pressed(self):
        self.custom_button2.hide()
        self.custom_button1.show()

class CustomButton(QPushButton):

    # it could receive args and keys** so all the QPushButton initializer
    # would work for here too.
    def __init__(self, txt):
        super(CustomButton, self).__init__()
        self.setText(txt)
        self.setStyleSheet("""
            QPushButton{
                background-color: black;
                border-radius: 5px;
                color: white;
            }
            QPushButton::pressed{
                background-color: blue;
            }
            QPushButton::released{
                background-color: gray;
            }
        """)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    custom_dialog = CustomDialog()
    custom_widget = ABitMoreCustomizedWidget()
    custom_dialog.show()
    custom_widget.show()
    sys.exit(app.exec_())
</code>```

Tips:

You are also able to make use of masks in your widget changing it's format in "crazy" ways. For example if you need a hollow ringed widget you can have a image with this format and some transparency, create a QPixMap from that and apply it as a mask to your widget. Not a trivial work but kind of cool.

Since I showed you examples with no "TopBar" with no Frame you can also have a look in this other question where I show how to create your own top bar, move around and resize concepts.

Title: Creating a custom widget in PyQT5

Body:
Here are some nice advises, examples and approaches.

I think you can divide a custom Widget or any Custom "thing" you want in three ways.

Behavior: When you override its default methods with the behavior you want.

Layout: All the qt objects, be Items, or Widgets you add inside the layout will follow it's position rules and its policies.

StyleSheet: In case of Widget objects where you set the style of the Widget let's say setting its "CSS", just to be concise. Here are some references and examples.

Note: In case of non Widget objects you will not be able to set a StyleSheet so you will have to override some paint methods, create your own Painters and so on.

Here are some random examples with some comments along approaching the 3 topics I mentioned above:

import random
import sys

from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication
from PyQt5.QtWidgets import QDialog
from PyQt5.QtWidgets import QHBoxLayout
from PyQt5.QtWidgets import QPushButton
from PyQt5.QtWidgets import QVBoxLayout
from PyQt5.QtWidgets import QWidget

class MovableWidget(QWidget):

    def __init__(self):
        super(MovableWidget, self).__init__()

        #remove the frame
        self.setWindowFlags(Qt.CustomizeWindowHint)
        self.pressing = False

    # overriding the three next methods is a way to customize your Widgets
    # not just in terms of appearance but also behavioral.

    def mousePressEvent(self, QMouseEvent):
        #the pos of the widget when you first pressed it.
        self.start = QMouseEvent.pos()
        #to make sure you are holding mouse button down
        self.pressing = True

    def mouseMoveEvent(self, QMouseEvent):

        # You can Verify if it's also the left button and some other things
        # you need.
        if self.pressing : #and QMouseEvent.type() == Qt.LeftButton
            self.end = QMouseEvent.pos()
            self.delta = self.mapToGlobal(self.end-self.start)
            self.move(self.delta)
            self.end = self.start

    def mouseReleaseEvent(self, QMouseEvent):
        self.pressing = False

# inherits from QDialog and from MovableWidget so we can have its properties.
class CustomDialog(QDialog, MovableWidget):

    def __init__(self):
        super(CustomDialog, self).__init__()

        #Make the Dialog transparent
        self.setAttribute(Qt.WA_TranslucentBackground)

        # the widget will dispose itself according to the layout rules he's
        # inserted into.
        self.inner_widget = QWidget()
        self.inner_widget.setFixedSize(300,300)
        self.inner_layout = QHBoxLayout()
        self.inner_widget.setLayout(self.inner_layout)

        self.btn_change_color = QPushButton("Roll Color")

        self.btn_change_color.setStyleSheet("""
            background-color: green;
        """)

        # will connect to a function to be executed when the button is clicked.
        self.btn_change_color.clicked.connect(self.change_color)
        self.inner_layout.addWidget(self.btn_change_color)

        # Choose among many layouts according to your needs, QVBoxLayout,
        # QHBoxLayout, QStackedLayout, ... you can set its orientation
        # you can set its policies, spacing, margins. That's one of the main
        # concepts you have to learn to customize your Widget in the way
        # you want.
        self.layout = QVBoxLayout()

        # stylesheet have basically CSS syntax can call it QSS.
        # it can be used only on objects that come from Widgets
        # Also one of the main things to learn about customizing Widgets.

        # Note: The stylesheet you set in the "father" will be applied to its
        # children. Unless you tell it to be applied only to it and/or specify
        # each children's style.

        # The point I used inside the StyleSheet before the QDialog
        # e.g .QDialog and .QWidget says it'll be applied only to that
        # instance.

        self.setStyleSheet("""
            .QDialog{
                border-radius: 10px;
            }
        """)
        self.inner_widget.setStyleSheet("""
            .QWidget{
                background-color: red;
            }
        """)

        self.layout.addWidget(self.inner_widget)
        self.setLayout(self.layout)

    def change_color(self):
        red = random.choice(range(0,256))
        green = random.choice(range(0,256))
        blue = random.choice(range(0,256))
        self.inner_widget.setStyleSheet(
        """
            background-color: rgb({},{},{});
        """.format(red,green,blue)
        )

# since MovableWidget inherits from QWidget it also have QWidget properties.
class ABitMoreCustomizedWidget(MovableWidget):

    def __init__(self):
        super(ABitMoreCustomizedWidget, self).__init__()

        self.layout = QHBoxLayout()
        self.setLayout(self.layout)

        self.custom_button1 = CustomButton("Button 1")
        self.custom_button1.clicked.connect(self.btn_1_pressed)
        self.custom_button2 = CustomButton("Button 2")
        self.custom_button2.clicked.connect(self.btn_2_pressed)

        self.layout.addWidget(self.custom_button1)
        self.layout.addWidget(self.custom_button2)

    def btn_1_pressed(self):
        self.custom_button1.hide()
        self.custom_button2.show()

    def btn_2_pressed(self):
        self.custom_button2.hide()
        self.custom_button1.show()

class CustomButton(QPushButton):

    # it could receive args and keys** so all the QPushButton initializer
    # would work for here too.
    def __init__(self, txt):
        super(CustomButton, self).__init__()
        self.setText(txt)
        self.setStyleSheet("""
            QPushButton{
                background-color: black;
                border-radius: 5px;
                color: white;
            }
            QPushButton::pressed{
                background-color: blue;
            }
            QPushButton::released{
                background-color: gray;
            }
        """)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    custom_dialog = CustomDialog()
    custom_widget = ABitMoreCustomizedWidget()
    custom_dialog.show()
    custom_widget.show()
    sys.exit(app.exec_())

Tips:

You are also able to make use of masks in your widget changing it's format in "crazy" ways. For example if you need a hollow ringed widget you can have a image with this format and some transparency, create a QPixMap from that and apply it as a mask to your widget. Not a trivial work but kind of cool.

Since I showed you examples with no "TopBar" with no Frame you can also have a look in this other question where I show how to create your own top bar, move around and resize concepts.


问:
How to extract a url from a webpage?
Twitter returns a webpage that these lines are among others:

```<code><link rel="dns-prefetch" href="//video.twimg.com" />
<link rel="preload" as="script" crossorigin="anonymous" href="https://ma-0.twimg.com/twitter-assets/responsive-web/web/ltr/vendor.69f9ac19fa493004.js" />
<link rel="preload" as="script" crossorigin="anonymous" href="https://ma-0.twimg.com/twitter-assets/responsive-web/web/ltr/i18n/en.312d3f56908013c9.js" />
<link rel="preload" as="script" crossorigin="anonymous" href="https://ma-0.twimg.com/twitter-assets/responsive-web/web/ltr/main.da8c0a0fbf03fdac.js" />
<meta property="fb:app_id" content="2231777543" />
</code>```

I need the url that contains the main.*.js file. How can I get it?

I tried this:

```<code>var mainIndex = content.IndexOf("main.");
var startIndex = content.LastIndexOf("href=\"", mainIndex) + 6;
var endIndex = content.IndexOf(".js", startIndex) + 3;
var url = content.Substring(startIndex, endIndex - startIndex);
</code>```

but it's a bad unsafe implementation. Thanks.

答:
it is definitely a good idea to use regex for it.
first one regex for the prefix part that should be replaced with empty string and same thing for end.

you will need to escape the chars like < with \< and to use the normal regex syntax to exactly define what is required.

Title: How to extract a url from a webpage?

Body:
Twitter returns a webpage that these lines are among others:

<link rel="dns-prefetch" href="//video.twimg.com" />
<link rel="preload" as="script" crossorigin="anonymous" href="https://ma-0.twimg.com/twitter-assets/responsive-web/web/ltr/vendor.69f9ac19fa493004.js" />
<link rel="preload" as="script" crossorigin="anonymous" href="https://ma-0.twimg.com/twitter-assets/responsive-web/web/ltr/i18n/en.312d3f56908013c9.js" />
<link rel="preload" as="script" crossorigin="anonymous" href="https://ma-0.twimg.com/twitter-assets/responsive-web/web/ltr/main.da8c0a0fbf03fdac.js" />
<meta property="fb:app_id" content="2231777543" />

I need the url that contains the main.*.js file. How can I get it?

I tried this:

var mainIndex = content.IndexOf("main.");
var startIndex = content.LastIndexOf("href=\"", mainIndex) + 6;
var endIndex = content.IndexOf(".js", startIndex) + 3;
var url = content.Substring(startIndex, endIndex - startIndex);

but it's a bad unsafe implementation. Thanks.


问:
How to keep comments inside a view definition with PostgreSQL?
I need to keep the comments I add inside a SQL query when I create views from complex queries, in order to come back to views definition more easily. Within pgAdminIII, when I create a view and then consult the view definition, the comments are deleted and indentation completely revised... Is there a way to change this behaviour?

View creation:

```<code>CREATE OR REPLACE VIEW public.v_test AS

-- Count number of null lines within table 'test'
(SELECT * FROM public.test WHERE client IS NULL);
</code>```

View definition after creation, as displayed in pgAdminIII:

```<code>-- View: v_test

-- DROP VIEW v_test;

CREATE OR REPLACE VIEW v_test AS
 SELECT test.gid,
    test.client
   FROM test
  WHERE test.client IS NULL;

ALTER TABLE v_test
  OWNER TO postgres;
</code>```

Thanks for help!

答:
No, Postgres saves views as parse trees, so it does not remember whitespace or comments.

However, if you really need it, functions can remember comments.

Body:
I need to keep the comments I add inside a SQL query when I create views from complex queries, in order to come back to views definition more easily. Within pgAdminIII, when I create a view and then consult the view definition, the comments are deleted and indentation completely revised... Is there a way to change this behaviour?

View creation:

CREATE OR REPLACE VIEW public.v_test AS

-- Count number of null lines within table 'test'
(SELECT * FROM public.test WHERE client IS NULL);

View definition after creation, as displayed in pgAdminIII:

-- View: v_test

-- DROP VIEW v_test;

CREATE OR REPLACE VIEW v_test AS
 SELECT test.gid,
    test.client
   FROM test
  WHERE test.client IS NULL;

ALTER TABLE v_test
  OWNER TO postgres;

Thanks for help!


问:
How to structure REGEX in C#
I currently have a regex that checks if a US State is spelled correctly

var r = new Regex(string.Format(@"\b(?:{0})\b", pattern), RegexOptions.IgnoreCase)

pattern is a pipe delimited string containing all US states.

It was working as intended today until one of the states was spelled like "Florida.." I would have liked it picked up the fact there was a fullstop character.

I found this regex that will only match letters.
    ^[a-zA-Z]+

How do I combine this with my current Regex or is it not possible?

I tried some variations of this but it didn't work

```<code>var r = new Regex(string.Format(@"\b^[a-zA-Z]+(?:{0})\b", pattern), RegexOptions.IgnoreCase);
</code>```

EDIT: Florida.. was in my input string. My pattern string hasn't changed at all. Apologies for not being clearer.

答:
It seems you need start of string (^) and end of string ($) anchors:

```<code>var r = new Regex(string.Format(@"^(?:{0})$", pattern), RegexOptions.IgnoreCase);
</code>```

The regex above would match any string comprising a name of a state only.

Title: How to structure REGEX in C#

Body:
I currently have a regex that checks if a US State is spelled correctly

var r = new Regex(string.Format(@"\b(?:{0})\b", pattern), RegexOptions.IgnoreCase)

pattern is a pipe delimited string containing all US states.

It was working as intended today until one of the states was spelled like "Florida.." I would have liked it picked up the fact there was a fullstop character.

I found this regex that will only match letters.
    ^[a-zA-Z]+

How do I combine this with my current Regex or is it not possible?

I tried some variations of this but it didn't work

var r = new Regex(string.Format(@"\b^[a-zA-Z]+(?:{0})\b", pattern), RegexOptions.IgnoreCase);

EDIT: Florida.. was in my input string. My pattern string hasn't changed at all. Apologies for not being clearer.

Body:
It seems you need start of string (^) and end of string ($) anchors:

var r = new Regex(string.Format(@"^(?:{0})$", pattern), RegexOptions.IgnoreCase);

The regex above would match any string comprising a name of a state only.


问:
onchange="" doesn't work in select tag
I have two tags of select. Their IDs is "study-phase" and "study-year".
I want when the value of study phase to process a CSS code.

HTML:

```<code><select name="study-phase" onchange="myFunction()" id="study-phase" class="sp-input">
    <option value=""></option>
    <option id="pri" value="pri">Primary</option>
    <option id="pre" value="pre">Prep</option>
    <option id="sec" value="sec">Secondary</option>
</select>
<select name="study-year" id="study-year" class="sp-input">
    <option value=""></option>
    <option id="a" value="aa">Grade 1</option>
    <option id="b" value="">Grade 2</option>
    <option id="c" value="">Grade 3</option>
    <option id="d" value="">Grade 4</option>
    <option id="e" value="">Grade 5</option>
    <option id="f" value="">Grade 6</option>
    <option id="g" value="">Grade 7</option>
    <option id="h" value="">Grade 8</option>
    <option id="i" value="">Grade 9</option>
    <option id="j" value="">Grade 10</option>
</select>
<style type="text/css">
    #a , #b , #c , #d , #f , #g , #h , #j , #k , #e , #i {
        display: none;
    }
</style>
</code>```

JS:

```<code>$(function(myFunction()){
   if (document.getElementById("study-phase").value == "pri") {
       document.getElementById("a").style.display = "block";
   }
});
</code>```

And after run the code the css code which I  want don't launch.
What's the problem here ?

答:
HTML

```<code><select name="study-phase" onchange="myFunction()" id="study-phase" class="sp-input">
    <option value=""></option>
    <option id="pri" value="pri">Primary</option>
    <option id="pre" value="pre">Prep</option>
    <option id="sec" value="sec">Secondary</option>
</select>
<select name="study-year" id="study-year" class="sp-input">
    <option value=""></option>
    <option id="a" value="aa">Grade 1</option>
    <option id="b" value="">Grade 2</option>
    <option id="c" value="">Grade 3</option>
    <option id="d" value="">Grade 4</option>
    <option id="e" value="">Grade 5</option>
    <option id="f" value="">Grade 6</option>
    <option id="g" value="">Grade 7</option>
    <option id="h" value="">Grade 8</option>
    <option id="i" value="">Grade 9</option>
    <option id="j" value="">Grade 10</option>
</select>
<style type="text/css">
  #a,
  #b,
  #c,
  #d,
  #f,
  #g,
  #h,
  #j,
  #k,
  #e,
  #i {
    display: none;
  }
</style>
</code>```

JS:

```<code>function myFunction(){
     console.log("myFunction gets called");
    if (document.getElementById("study-phase").value == "pri") {
        document.getElementById("a").style.display = "block";
    }}
</code>```

Just declare your function like this.
And add a console.log to make sure that function is getting called "onchange" or not, which is after this change.

Title: onchange="" doesn't work in select tag

Body:
I have two tags of select. Their IDs is "study-phase" and "study-year".
I want when the value of study phase to process a CSS code.

HTML:

<select name="study-phase" onchange="myFunction()" id="study-phase" class="sp-input">
    <option value=""></option>
    <option id="pri" value="pri">Primary</option>
    <option id="pre" value="pre">Prep</option>
    <option id="sec" value="sec">Secondary</option>
</select>
<select name="study-year" id="study-year" class="sp-input">
    <option value=""></option>
    <option id="a" value="aa">Grade 1</option>
    <option id="b" value="">Grade 2</option>
    <option id="c" value="">Grade 3</option>
    <option id="d" value="">Grade 4</option>
    <option id="e" value="">Grade 5</option>
    <option id="f" value="">Grade 6</option>
    <option id="g" value="">Grade 7</option>
    <option id="h" value="">Grade 8</option>
    <option id="i" value="">Grade 9</option>
    <option id="j" value="">Grade 10</option>
</select>

JS:

$(function(myFunction()){
   if (document.getElementById("study-phase").value == "pri") {
       document.getElementById("a").style.display = "block";
   }
});

And after run the code the css code which I  want don't launch.
What's the problem here ?

Body:
HTML

<select name="study-phase" onchange="myFunction()" id="study-phase" class="sp-input">
    <option value=""></option>
    <option id="pri" value="pri">Primary</option>
    <option id="pre" value="pre">Prep</option>
    <option id="sec" value="sec">Secondary</option>
</select>
<select name="study-year" id="study-year" class="sp-input">
    <option value=""></option>
    <option id="a" value="aa">Grade 1</option>
    <option id="b" value="">Grade 2</option>
    <option id="c" value="">Grade 3</option>
    <option id="d" value="">Grade 4</option>
    <option id="e" value="">Grade 5</option>
    <option id="f" value="">Grade 6</option>
    <option id="g" value="">Grade 7</option>
    <option id="h" value="">Grade 8</option>
    <option id="i" value="">Grade 9</option>
    <option id="j" value="">Grade 10</option>
</select>
<style type="text/css">
  #a,
  #b,
  #c,
  #d,
  #f,
  #g,
  #h,
  #j,
  #k,
  #e,
  #i {
    display: none;
  }
</style>

JS:

function myFunction(){
     console.log("myFunction gets called");
    if (document.getElementById("study-phase").value == "pri") {
        document.getElementById("a").style.display = "block";
    }}

Just declare your function like this.
And add a console.log to make sure that function is getting called "onchange" or not, which is after this change.


问:
Search within a big vector in C++
I have following vectors:

```<code>std::vector<A*> vec;
std::vector<std::pair<A*, A*>> vec_pair;
</code>```

vec_pair size is much more than vec size. I would like to find a pair within vec_pair which both members are inside vec.

contents of the vec_pair are constant. However after each iteration the contents of the vec will change and I would like to do the test again.

I know I can do a for loop and do the check. However considering size difference and recurrence of the job, I am looking for a smart and efficient way to do it.

答:
How much smaller is vec than vec_pair? Is the square of the size of vec still much smaller than the size of vec_pair? If so, you make an unordered_set out of vec_pair, and then search it for every possible pair generated from two things from vec.

Why can't you sort the two containers? Can you make a sorted copy of each? If so, take a pointer to the start of both lists, and increment both looking for matches. You would still be O(size of vec_pair) but your constant would be really small -- often just a single pointer comparison.

Title: Search within a big vector in C++

Body:
I have following vectors:

std::vector vec;
std::vector<std::pair> vec_pair;

vec_pair size is much more than vec size. I would like to find a pair within vec_pair which both members are inside vec.

contents of the vec_pair are constant. However after each iteration the contents of the vec will change and I would like to do the test again.

I know I can do a for loop and do the check. However considering size difference and recurrence of the job, I am looking for a smart and efficient way to do it.


问:
Default property for class in delphi 7
I'd like to ask on how to set default property in a delphi 7 class? So it can be accesed by just writing >> class := '..'; << that's if the default property set to text. so we dont have to write class.text := '..';</p>

答: I'm afraid you can't. A class can have an array default property or an ordinal-type default property but not a string.</p>

Title: Default property for class in delphi 7


问:
Unit testing HttpResponseMessage with Autofac and Moq
I'm going round in circles. So my WebApi returns the output it needs to the browser when i am running in debug. Firefox and IE display the List i need. However when i am trying to unit test the response using Mock and Autofac the HttpResponseMessage I am getting back has no Contents. I get the feeling it is returning on a different context or something like that. I am not totally sure, hence asking the question. I have stringed the below unit test together via googling and the Autofac documentation.

WebApiMethod (contained within InScrapController, _WebScrapSprocService is injected by Autofac in the constructor)

```<code>public HttpResponseMessage GetFormItemsByFormNumber(int FormNumber)
{
    HttpResponseMessage response;
    try
    {
        //response = Request.CreateResponse(HttpStatusCode.OK, _WebScrapSprocService.GetFormItemsByFormNumber(FormNumber),new MediaTypeHeaderValue("application/json"));
        response = Request.CreateResponse(HttpStatusCode.OK, new MediaTypeHeaderValue("application/json"));
        response.Content = new StringContent(JsonConvert.SerializeObject(_WebScrapSprocService.GetFormItemsByFormNumber(FormNumber)),Encoding.UTF8, "application/json");
    } catch (Exception e)
    {
        response = Request.CreateResponse(HttpStatusCode.InternalServerError, new StringContent(e.Message), new MediaTypeHeaderValue("application/json"));
    }
    //Checking if bob knows anything about this...
    string bob = response.Content.ReadAsStringAsync().Result;
    return response;
}
</code>```

Unit Test

```<code>public void GetFormItemsByFormNumber()
{
    using (var mock = AutoMock.GetLoose())
    {

        var Service = mock.Mock<IWebScrapSprocService>().Setup(x => x.GetFormItemsByFormNumber(3392));
        var service = mock.Create<InScrapController>();
        service.Request = new HttpRequestMessage();
        service.Request.SetConfiguration(new HttpConfiguration());
        var HttpResponse = service.Request.CreateResponse(HttpStatusCode.OK, Service, new MediaTypeHeaderValue("application/json"));
        var response = service.GetFormItemsByFormNumber(3392);
        mock.Mock<IWebScrapSprocService>().Verify(x => x.GetFormItemsByFormNumber(3392));
        Assert.AreEqual(HttpResponse, response);
    }
}
</code>```

答:
Those responses are not going to be the same. Also that method under test should be refactored. You are also not getting back any content because you have not setup the service to return anything.

```<code>public IHttpActionResult GetFormItemsByFormNumber(int FormNumber) {
    IHttpActionResult response;
    try {
        var result = _WebScrapSprocService.GetFormItemsByFormNumber(FormNumber);
        response = Ok(result);
    } catch (Exception e) {
        response = InternalServerError(e);
    }
    return response;
}
</code>```

Next update the test

```<code>public void GetFormItemsByFormNumber() {
    using (var mock = AutoMock.GetLoose()) {
        // Arrange.
        var formNumber = 3392;
        var items = new List<FormItemsByFormNumber> {
            new FormItemsByFormNumber {
                //Populate as needed
            },
            new FormItemsByFormNumber {
                //Populate as needed
            },
            //...etc
        };
        var serviceMock = mock.Mock<IWebScrapSprocService>();
        serviceMock.Setup(x => x.GetFormItemsByFormNumber(formNumber)) // Calling this...
            .Returns(items) // should return some value...
            .Verifiable();  // and I want to verify that it was called.
        var sut = mock.Create<InScrapController>();

        // Act.
        var response = sut.GetFormItemsByFormNumber(formNumber) as OkNegotiatedContentResult<List<FormItemsByFormNumber>>();

        // Assert.
        serviceMock.Verify(); //verify setups were exercised as expected.
        Assert.IsNotNull(response);
    }
}
</code>```

Body:
I'm going round in circles. So my WebApi returns the output it needs to the browser when i am running in debug. Firefox and IE display the List i need. However when i am trying to unit test the response using Mock and Autofac the HttpResponseMessage I am getting back has no Contents. I get the feeling it is returning on a different context or something like that. I am not totally sure, hence asking the question. I have stringed the below unit test together via googling and the Autofac documentation.

WebApiMethod (contained within InScrapController, _WebScrapSprocService is injected by Autofac in the constructor)

public HttpResponseMessage GetFormItemsByFormNumber(int FormNumber)
{
    HttpResponseMessage response;
    try
    {
        //response = Request.CreateResponse(HttpStatusCode.OK, _WebScrapSprocService.GetFormItemsByFormNumber(FormNumber),new MediaTypeHeaderValue("application/json"));
        response = Request.CreateResponse(HttpStatusCode.OK, new MediaTypeHeaderValue("application/json"));
        response.Content = new StringContent(JsonConvert.SerializeObject(_WebScrapSprocService.GetFormItemsByFormNumber(FormNumber)),Encoding.UTF8, "application/json");
    } catch (Exception e)
    {
        response = Request.CreateResponse(HttpStatusCode.InternalServerError, new StringContent(e.Message), new MediaTypeHeaderValue("application/json"));
    }
    //Checking if bob knows anything about this...
    string bob = response.Content.ReadAsStringAsync().Result;
    return response;
}

Unit Test

public void GetFormItemsByFormNumber()
{
    using (var mock = AutoMock.GetLoose())
    {

        var Service = mock.Mock<IWebScrapSprocService>().Setup(x => x.GetFormItemsByFormNumber(3392));
        var service = mock.Create<InScrapController>();
        service.Request = new HttpRequestMessage();
        service.Request.SetConfiguration(new HttpConfiguration());
        var HttpResponse = service.Request.CreateResponse(HttpStatusCode.OK, Service, new MediaTypeHeaderValue("application/json"));
        var response = service.GetFormItemsByFormNumber(3392);
        mock.Mock<IWebScrapSprocService>().Verify(x => x.GetFormItemsByFormNumber(3392));
        Assert.AreEqual(HttpResponse, response);
    }
}

Body:
Those responses are not going to be the same. Also that method under test should be refactored. You are also not getting back any content because you have not setup the service to return anything.

public IHttpActionResult GetFormItemsByFormNumber(int FormNumber) {
    IHttpActionResult response;
    try {
        var result = _WebScrapSprocService.GetFormItemsByFormNumber(FormNumber);
        response = Ok(result);
    } catch (Exception e) {
        response = InternalServerError(e);
    }
    return response;
}

Next update the test

public void GetFormItemsByFormNumber() {
    using (var mock = AutoMock.GetLoose()) {
        // Arrange.
        var formNumber = 3392;
        var items = new List<FormItemsByFormNumber> {
            new FormItemsByFormNumber {
                //Populate as needed
            },
            new FormItemsByFormNumber {
                //Populate as needed
            },
            //...etc
        };
        var serviceMock = mock.Mock<IWebScrapSprocService>();
        serviceMock.Setup(x => x.GetFormItemsByFormNumber(formNumber)) // Calling this...
            .Returns(items) // should return some value...
            .Verifiable();  // and I want to verify that it was called.
        var sut = mock.Create<InScrapController>();

        // Act.
        var response = sut.GetFormItemsByFormNumber(formNumber) as OkNegotiatedContentResult<List<FormItemsByFormNumber>>();

        // Assert.
        serviceMock.Verify(); //verify setups were exercised as expected.
        Assert.IsNotNull(response);
    }
}


问:
Should I always use virtualenvs in Django?
I'm a beginner, and I'm learning Django for web development. So I want to know for my little test, should in always have a virtualenv or can I continue to learn without installing it? I've asked because in youtube Django videos, some instructors are installing it, and others aren't.</p>

答:
Your question is:

Can I continue without installing it?

So the answer is yes.

The virtualenv is not a requirement to set up a Django project. Nevertheless, you will eventually use virtualenvs in the future when you are more aware of dependencies, so why don't you start to learn now how to use them?

A virtualenv is not the only solution to isolate your project's dependencies but is the most commonly used in Python developments.


问:
Select columns with NULL values only
How do I select all the columns in a table that only contain NULL values for all the rows?  I'm using MS SQL Server 2005.  I'm trying to find out which columns are not used in the table so I can delete them.

答:
Not actually sure about 2005, but 2008 ate it:</p>

```<code>USE [DATABASE_NAME] -- !
GO

DECLARE @SQL NVARCHAR(MAX)
DECLARE @TableName VARCHAR(255)

SET @TableName = 'TABLE_NAME'   -- !

SELECT @SQL =
(
    SELECT
        CHAR(10)
        +'DELETE FROM ['+t1.TABLE_CATALOG+'].['+t1.TABLE_SCHEMA+'].['+t1.TABLE_NAME+'] WHERE '
        +(
            SELECT
            CASE t2.ORDINAL_POSITION
                WHEN (SELECT MIN(t3.ORDINAL_POSITION) FROM INFORMATION_SCHEMA.COLUMNS t3 WHERE t3.TABLE_NAME=t2.TABLE_NAME) THEN ''
                ELSE  'AND '
            END
            +'['+COLUMN_NAME+'] IS NULL' AS 'data()'
            FROM INFORMATION_SCHEMA.COLUMNS t2 WHERE t2.TABLE_NAME=t1.TABLE_NAME FOR XML PATH('')
         )  AS 'data()'
    FROM INFORMATION_SCHEMA.TABLES t1 WHERE t1.TABLE_NAME = @TableName FOR XML PATH('')
)

SELECT @SQL -- EXEC(@SQL)
</code>```

OwnerDisplayName: Bryan Roth

ContentLicense: CC BY-SA 4.0

Title: Select columns with NULL values only

LastEditorDisplayName: Nigel Campbell

Body:
Not actually sure about 2005, but 2008 ate it:

USE [DATABASE_NAME] -- !
GO

DECLARE @SQL NVARCHAR(MAX)
DECLARE @TableName VARCHAR(255)

SET @TableName = 'TABLE_NAME'   -- !

SELECT @SQL =
(
    SELECT
        CHAR(10)
        +'DELETE FROM ['+t1.TABLE_CATALOG+'].['+t1.TABLE_SCHEMA+'].['+t1.TABLE_NAME+'] WHERE '
        +(
            SELECT
            CASE t2.ORDINAL_POSITION
                WHEN (SELECT MIN(t3.ORDINAL_POSITION) FROM INFORMATION_SCHEMA.COLUMNS t3 WHERE t3.TABLE_NAME=t2.TABLE_NAME) THEN ''
                ELSE  'AND '
            END
            +'['+COLUMN_NAME+'] IS NULL' AS 'data()'
            FROM INFORMATION_SCHEMA.COLUMNS t2 WHERE t2.TABLE_NAME=t1.TABLE_NAME FOR XML PATH('')
         )  AS 'data()'
    FROM INFORMATION_SCHEMA.TABLES t1 WHERE t1.TABLE_NAME = @TableName FOR XML PATH('')
)

SELECT @SQL -- EXEC(@SQL)


问:
How do I find which row is using the most space in my database?
I have a SQL Server 2012 database which users can attach files to (mainly Jpgs) however the table size is 130mb with only 20 records.

I need to find out which row is using the most amount of space.

The data is stored as varbinary

Thanks

答:
You can use DATALENGTH to get the length of the varbinary column:

```<code>SELECT Id, Name, DATALENGTH(BinaryColumn)
FROM dbo.YourTable
ORDER BY DATALENGTH(BinaryColumn) DESC
</code>```

Body:
You can use DATALENGTH to get the length of the varbinary column:

SELECT Id, Name, DATALENGTH(BinaryColumn)
FROM dbo.YourTable
ORDER BY DATALENGTH(BinaryColumn) DESC


答:
You need to define the function before calling it,

For example, in the first select (example 1) im calling a function that isn't defined yet and nothing happens (see console for error)

in the second select (example 2) i define it first then call it.

This makes for a messy html layout with random scripts in it, so instead, you can use jquery to listen for the event (example 3).

```<code>$('.myselect').change(function(){})
</code>```

Examples: https://jsfiddle.net/hbmrktbj/

Title: onchange="" doesn't work in select tag

Body:
You need to define the function before calling it,

For example, in the first select (example 1) im calling a function that isn't defined yet and nothing happens (see console for error)

in the second select (example 2) i define it first then call it.

This makes for a messy html layout with random scripts in it, so instead, you can use jquery to listen for the event (example 3).

$('.myselect').change(function(){})

Examples: https://jsfiddle.net/hbmrktbj/


问:
Powershell - parsing through JSON to create CSV
I am extracting a JSON from Facebook, this is what it looks like:

```<code>pressions_by_paid_non_paid_unique/day
{
  "data": [
    {
      "name": "page_impressions_by_paid_non_paid_unique",
  "period": "day",
  "values": [
    {
      "value": {
        "total": 549215,
        "unpaid": 549215,
        "paid": 0
      },
      "end_time": "2017-06-02T07:00:00+0000"
    },
</code>```

What I would like is to create a CSV that would either looks like this:

total,unpaid,paid,endtime

  549215,549215,0,2017-06-02T07:00:00+0000

or

value,num,end_time

total,549215,2017-06-02T07:00:00+0000

unpaid,549215,2017-06-02T07:00:00+0000

paid,0,2017-06-02T07:00:00+0000

What I came up with is:

```<code>$file = "D:\BI_LP\001-Solutions_Sources\script\Powershell\curl\facebook21.json"
Get-Content $file -Raw |
ConvertFrom-Json |
Select -Expand data |
Select -Expand values | % {
$end_time = $_.end_time
$value = $_.value
$_.value | select @{n='end_time';e={$end_time}}, @{n='value';e={$value}}
}
</code>```

Which gives me:

```<code>end_time                 value

--------                 -----

2017-05-21T07:00:00+0000 @{total=608837; unpaid=608837; paid=0}

2017-05-22T07:00:00+0000 @{total=682090; unpaid=682090; paid=0}

2017-05-23T07:00:00+0000 @{total=885274; unpaid=885274; paid=0}

2017-05-24T07:00:00+0000 @{total=810845; unpaid=810845; paid=0}

2017-05-25T07:00:00+0000 @{total=755453; unpaid=755453; paid=0}

2017-05-26T07:00:00+0000 @{total=629096; unpaid=629096; paid=0}
</code>```

Does anyone have any suggestions?

答:
Thanks Charlie, you got me in the right direction :)</p>

```<code>$file = "D:\BI_LP\001-Solutions_Sources\script\Powershell\curl\facebook21.json"
Get-Content $file -Raw |
ConvertFrom-Json |
Select -Expand data |
Select -Expand values | % {
$end_time = $_.end_time
$total    = $_.value.total
$unpaid   = $_.value.unpaid
$paid     = $_.value.paid
$_.value | select @{n='end_time';e={$end_time}}, @{n='total';e={$total}},@{n='unpaid';e={$unpaid}},@{n='paid';e={$paid}}
}
</code>```

Body:
I am extracting a JSON from Facebook, this is what it looks like:

pressions_by_paid_non_paid_unique/day
{
  "data": [
    {
      "name": "page_impressions_by_paid_non_paid_unique",
  "period": "day",
  "values": [
    {
      "value": {
        "total": 549215,
        "unpaid": 549215,
        "paid": 0
      },
      "end_time": "2017-06-02T07:00:00+0000"
    },

What I would like is to create a CSV that would either looks like this:

total,unpaid,paid,endtime

  549215,549215,0,2017-06-02T07:00:00+0000

or

value,num,end_time

total,549215,2017-06-02T07:00:00+0000

unpaid,549215,2017-06-02T07:00:00+0000

paid,0,2017-06-02T07:00:00+0000

What I came up with is:

$file = "D:\BI_LP\001-Solutions_Sources\script\Powershell\curl\facebook21.json"
Get-Content $file -Raw |
ConvertFrom-Json |
Select -Expand data |
Select -Expand values | % {
$end_time = $_.end_time
$value = $_.value
$_.value | select @{n='end_time';e={$end_time}}, @{n='value';e={$value}}
}

Which gives me:

end_time                 value

--------                 -----

2017-05-21T07:00:00+0000 @{total=608837; unpaid=608837; paid=0}

2017-05-22T07:00:00+0000 @{total=682090; unpaid=682090; paid=0}

2017-05-23T07:00:00+0000 @{total=885274; unpaid=885274; paid=0}

2017-05-24T07:00:00+0000 @{total=810845; unpaid=810845; paid=0}

2017-05-25T07:00:00+0000 @{total=755453; unpaid=755453; paid=0}

2017-05-26T07:00:00+0000 @{total=629096; unpaid=629096; paid=0}

Does anyone have any suggestions?

Body:
Thanks Charlie, you got me in the right direction :)

$file = "D:\BI_LP\001-Solutions_Sources\script\Powershell\curl\facebook21.json"
Get-Content $file -Raw |
ConvertFrom-Json |
Select -Expand data |
Select -Expand values | % {
$end_time = $_.end_time
$total    = $_.value.total
$unpaid   = $_.value.unpaid
$paid     = $_.value.paid
$_.value | select @{n='end_time';e={$end_time}}, @{n='total';e={$total}},@{n='unpaid';e={$unpaid}},@{n='paid';e={$paid}}
}


问:
Correct way of implementing Finalize and Dispose(When parent class implements IDisposable)
I was implementing Finalize and Dispose in my classes, I implemented IDisposable on my parent class and override the Dispose(bool) overload in my child classes. I was not sure

whether to use a duplicate isDisposed variable(as its already there in base class) or not?

Whether to implement a finalizer in child class too or not?

Both these things are done in example given here -

http://guides.brucejmack.biz/CodeRules/FxCop/Docs/Rules/Usage/DisposeMethodsShouldCallBaseClassDispose.html

Whereas example in this MSDN article doesn't have any of these two -
http://msdn.microsoft.com/en-us/library/b1yfkh5e.aspx

whereas this example in MSDN is not complete -
http://msdn.microsoft.com/en-us/library/ms182330.aspx

答:
Duplicate is needed

If you don't have any clean-up in child class simply call base.Dispose() and if there are some class level clean-up, do it after a call to base.Dispose(). You need to separate state of these two classes so there should be a IsDisposed boolean for each class. This way you can add clean-up code whenever you need.

When you determine a class as IDisposable, you simply tell GC I'm taking care of it's clean-up procedure and you should SuppressFinilize on this class so GC would remove it from it's queue. Unless you call GC.SupressFinalize(this) nothing happens special to an IDisposable class. So if you implement it as I mentioned there's no need for a Finilizer since you just told GC not to finalize it.

OwnerDisplayName: Tomas Van Joseph

LastEditorDisplayName: Tomas Van Joseph


问:
onclick coding html css jquery to highlight 2 buttons
I want to change this coding

2

Basically I have 4 buttons 1  2  3  4
When I click 1 1 highlights
When I click 2 (the code above ) 2 highlights

What I want to do is when I click 2 In want 1 and 2 to highlight.

if I change the code using F12 to

2

when clicking 2 the number 3 highlights

答:
Is this what you need?

$(document).on("click", ".yellow", function() {
  $(this).css("background-color", "yellow");
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="yellow">Click me </button>
<button class="yellow">Click me </button>
<button class="yellow">Click me </button></code>```

Body:
Is this what you need?

$(document).on("click", ".yellow", function() {
  $(this).css("background-color", "yellow");
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="yellow">Click me </button>
<button class="yellow">Click me </button>
<button class="yellow">Click me </button>


问:
How to change formatting of Html.DisplayFor for a user-defined class in MVC
My main model, Project, has a property called "ProjectAddress" which is of type "Address"--a class that I defined. Address has the properties Line1, Line2, City, State, and ZipCode. When I use @Html.DisplayFor(model => model.ProjectAddress), it displays as:

```<code>Line 1
<Line1 value here>
Line 2
<Line2 value here>
City
<City value here>
...
</code>```

and so on. I would like it to display as:

```<code><Line 1>
<Line 2 if defined>
<City>, <State>, <ZipCode>
<County> County
</code>```

without the property headers above each value. I can do this manually each time I want to display the address by hard coding

```<code>@Html.DisplayFor(model => model.ProjectAddress.Line1)
@if (!String.IsEmptyOrNull(model.ProjectAddress.Line2))
{
    @Html.DisplayFor(model => model.ProjectAddress.Line2)
}
@Html.DisplayFor(model => model.ProjectAddress.City), @Html.DisplayFor(model => model.ProjectAddress.State), @Html.DisplayFor(model => model.ProjectAddress.ZipCode)
</code>```

but that's very tedious and if I change the format of my address class for whatever reason I'll have to go through my code and change each instance of that. Is there a way that I can change the formatting of @Html.DisplayFor(model => model.ProjectAddress) to be the block of code above?

答:
You need to add a custom display template. Add the file, Views\Shared\DisplayTemplates\Address.cshtml, and put the following code inside:

```<code>@model Namespace.To.Address
@Html.DisplayFor(m => m.Line1)
@if (!String.IsEmptyOrNull(Model.Line2))
{
    @Html.DisplayFor(m => m.Line2)
}
@Html.DisplayFor(m => m.City), @Html.DisplayFor(m => m.State),
@Html.DisplayFor(m => m.ZipCode)
</code>```

Then, you can use DisplayFor as you tried originally in your view:

```<code>@Html.DisplayFor(m => m.ProjectAddress)
</code>```

Razor will use the template you defined to render the ProjectAddress instance.

Body:
My main model, Project, has a property called "ProjectAddress" which is of type "Address"--a class that I defined. Address has the properties Line1, Line2, City, State, and ZipCode. When I use @Html.DisplayFor(model => model.ProjectAddress), it displays as:

Line 1
<Line1 value here>
Line 2
<Line2 value here>
City
<City value here>
...

and so on. I would like it to display as:

<Line 1>
<Line 2 if defined>
<City>, <State>, <ZipCode>
<County> County

without the property headers above each value. I can do this manually each time I want to display the address by hard coding

@Html.DisplayFor(model => model.ProjectAddress.Line1)
@if (!String.IsEmptyOrNull(model.ProjectAddress.Line2))
{
    @Html.DisplayFor(model => model.ProjectAddress.Line2)
}
@Html.DisplayFor(model => model.ProjectAddress.City), @Html.DisplayFor(model => model.ProjectAddress.State), @Html.DisplayFor(model => model.ProjectAddress.ZipCode)

but that's very tedious and if I change the format of my address class for whatever reason I'll have to go through my code and change each instance of that. Is there a way that I can change the formatting of @Html.DisplayFor(model => model.ProjectAddress) to be the block of code above?

Body:
You need to add a custom display template. Add the file, Views\Shared\DisplayTemplates\Address.cshtml, and put the following code inside:

@model Namespace.To.Address
@Html.DisplayFor(m => m.Line1)
@if (!String.IsEmptyOrNull(Model.Line2))
{
    @Html.DisplayFor(m => m.Line2)
}
@Html.DisplayFor(m => m.City), @Html.DisplayFor(m => m.State),
@Html.DisplayFor(m => m.ZipCode)

Then, you can use DisplayFor as you tried originally in your view:

@Html.DisplayFor(m => m.ProjectAddress)

Razor will use the template you defined to render the ProjectAddress instance.


答:
Check out a thing called Display Templates. The short of it is this..

You create a new folder under views/shared called 'DisplayTemplates` (you can also have editor templates.

Add a new cshtml file called Address.cshtml. Set its model to My.LongNamespace.Address

Add the code you want to use to 'mark-up' the address type.

Example Address.cshtml (untested)

```<code>@model My.LongNamespace.Address

@Html.DisplayFor(model => model.Line1)
@if (!String.IsEmptyOrNull(model.Line2))
{
    @Html.DisplayFor(model => model.Line2)
}
@Html.DisplayFor(model => model.City),
@Html.DisplayFor(model => model.State),
@Html.DisplayFor(model => model.ZipCode)
</code>```

Title: How to change formatting of Html.DisplayFor for a user-defined class in MVC

Body:
Check out a thing called Display Templates. The short of it is this..

You create a new folder under views/shared called 'DisplayTemplates` (you can also have editor templates.

Add a new cshtml file called Address.cshtml. Set its model to My.LongNamespace.Address

Add the code you want to use to 'mark-up' the address type.

Example Address.cshtml (untested)

@model My.LongNamespace.Address

@Html.DisplayFor(model => model.Line1)
@if (!String.IsEmptyOrNull(model.Line2))
{
    @Html.DisplayFor(model => model.Line2)
}
@Html.DisplayFor(model => model.City),
@Html.DisplayFor(model => model.State),
@Html.DisplayFor(model => model.ZipCode)


问:
JavaScript’s Date.now() returning 0 (zero)
I basically copy-pasted the Mocha.js Base reporter to build a custom reporter.

Now for some reason, inside the on "end" callback, Date.now() returns 0,

while new Date() returns a date for Thu Jan 01 1970 01:00:00 GMT+0100 (CET).

And I really don’t get it. This language is driving me nuts.

Hope someone knows what’s going on here.

答:
You might be using sinon's fake timer somewhere in another test

```<code>clock = sinon.useFakeTimers()
</code>```

but forgetting to restore it after the tests finished running:

```<code>clock.restore()
</code>```

Body:
You might be using sinon's fake timer somewhere in another test

clock = sinon.useFakeTimers()

but forgetting to restore it after the tests finished running:

clock.restore()


问:
KnpSnappyBundle - wkhtmltopdf.exe.bat: Permission denied
In dev environment (windows) using xampp my pdf files are generated successfully, but in prod (linux):

string(545) "The exit status code '126' says something went wrong:

stderr: "sh: /home/trainingexperience/beta.trainingexperience.org/app/../bin/wkhtmltopdf.exe.bat: Permission denied"

stdout: ""

command: /home/trainingexperience/beta.trainingexperience.org/app/../bin/wkhtmltopdf.exe.bat --lowquality --encoding 'utf-8' '/home/trainingexperience/beta.trainingexperience.org/app/cache/prod/snappy/knp_snappy5936b3644fdf62.71499624.html' '/home/trainingexperience/beta.trainingexperience.org/app/../web/uploads/company/payments/test_cXrfA4L99zsiKi6Cfl5a.pdf'."

My config:

```<code>knp_snappy:
    pdf:
        binary: %kernel.root_dir%/../bin/wkhtmltopdf.exe.bat
    temporary_folder: %kernel.cache_dir%/snappy
</code>```

Could it be because of Linux? What is the problem?

UPDATE

I tried:

```<code>knp_snappy:
    pdf:
        binary: %kernel.root_dir%/../bin/wkhtmltopdf
    temporary_folder: %kernel.cache_dir%/snappy
</code>```

I got:

No such file or directory

I think could be the problem (composer.json): "wemersonjanuario/wkhtmltopdf-windows": "0.12.2.3". Is there a version to that could work on windows and linux at the same time?

答:
You should define a shell executable for your production environement and your developement environment.

for linux

```<code>binary:     /usr/local/bin/wkhtmltopdf
</code>```

for windows

```<code>binary:     "C:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltopdf.exe\\"
</code>```

as you can see, You can't sh (execute) a .bat file on linux.

Body:
In dev environment (windows) using xampp my pdf files are generated successfully, but in prod (linux):

string(545) "The exit status code '126' says something went wrong:

stderr: "sh: /home/trainingexperience/beta.trainingexperience.org/app/../bin/wkhtmltopdf.exe.bat: Permission denied"

stdout: ""

command: /home/trainingexperience/beta.trainingexperience.org/app/../bin/wkhtmltopdf.exe.bat --lowquality --encoding 'utf-8' '/home/trainingexperience/beta.trainingexperience.org/app/cache/prod/snappy/knp_snappy5936b3644fdf62.71499624.html' '/home/trainingexperience/beta.trainingexperience.org/app/../web/uploads/company/payments/test_cXrfA4L99zsiKi6Cfl5a.pdf'."

My config:

knp_snappy:
    pdf:
        binary: %kernel.root_dir%/../bin/wkhtmltopdf.exe.bat
    temporary_folder: %kernel.cache_dir%/snappy

Could it be because of Linux? What is the problem?

UPDATE

I tried:

knp_snappy:
    pdf:
        binary: %kernel.root_dir%/../bin/wkhtmltopdf
    temporary_folder: %kernel.cache_dir%/snappy

I got:

No such file or directory

I think could be the problem (composer.json): "wemersonjanuario/wkhtmltopdf-windows": "0.12.2.3". Is there a version to that could work on windows and linux at the same time?

Body:
You should define a shell executable for your production environement and your developement environment.

for linux

binary:     /usr/local/bin/wkhtmltopdf

for windows

binary:     "C:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltopdf.exe\\"

as you can see, You can't sh (execute) a .bat file on linux.


问:
Does this interface require a Null modem cable?
I am enclosing here the drawing of the RS-232 9 pin connection cable to link a XT2000i Blood analyser to a host PC. Is this just any serial port cable or a Null modem cable ?

Thanks. Chak.

Since @JTON said in the answer that other pins are not swapped, i am enclosing image of which pins are in use.

答:
It only has the Rx and Tx pins swapped so putting a null modem adapter in there will not match it exactly.  Usually they also have DTR/DSR and RTS/CTS swapped.  It depends if the device actually uses those pins.

To be safe about reliability, I'd probably make a cable exactly to specs.  Just get a make your own cable kit and all you have to do is pop the pins in.