问:
Looking for light text rich editor for enterprise website ,more light then tinymce with basic buttons for comment form
I am Looking for light text rich editor for enterprise website ,more light then tinymce with basic buttons for comment form.
Its important that editor will also work in IE6.
until now I try cleditor 15KB, but he have problem with IE when 'enter' press.

cleditor have issue -  (Jquery-Rich Text Editor) How can be fixed bug in rich text editor - when press enter in firefox created 'br' tag but in IE created 'p' tag?

YUI Editor 76kb - still prefer something lighter like cleditor 15kb and use jquery and not yui 2 framework.

HtmlBox editor- only for personal use according lisence and also have some bugs in simple demo.

markitUp editor - not show result , only in other window.

tinymce/ckeditor - not light editor

jHtmlArea - not support IE6

jwysiwyg - still beta version, not tested on IE6?

Update: I alreay use jquery.

please if you have good suggestion,
Thanks,
Yosef

答:
Have you tried CKEditor? It's licensed under flexible Open Source and commercial licenses

According to their website, you'll be able to integrate and use it inside any kind of application, making it an ideal editor for developers to provide easy and powerful solutions to their users.

The cost of the license for a single website is about $400. You did say it was for an enterprise website, so maybe the cost isn't an issue.


来源: stackexchange

问:
Percentage column in DB2
How to keep the percentage in IBM DB2?
Float or Decimal? </p>

<p>// this does not work, the data is not saved:</p>

```<code>create table bms."t1"(
    "name" decimal(2,2)
);

insert into bms."t1"
    values(10.05);
</code>```

答:
decimal(2, 2) means that you have two digits, with two digits to the right of the decimal point.  So, it would contain values from 0.00 to 0.99.

You would appear to want -- at least --

```<code>create table bms."t1"(
    "name" decimal(4,2)
);

insert into bms."t1"
    values(10.05);
</code>```

ContentLicense: CC BY-SA 3.0

Title: Percentage column in DB2

Body:
How to keep the percentage in IBM DB2?
Float or Decimal?

// this does not work, the data is not saved:

create table bms."t1"(
    "name" decimal(2,2)
);

insert into bms."t1"
    values(10.05);

Body:
decimal(2, 2) means that you have two digits, with two digits to the right of the decimal point.  So, it would contain values from 0.00 to 0.99.

You would appear to want -- at least --

create table bms."t1"(
    "name" decimal(4,2)
);

insert into bms."t1"
    values(10.05);


问:
How do I copy mail into another mailbox using imap_mail_copy?
The usually comprehensive PHP manual is missing any complete examples of using the imap_mail_copy function.  Specifically I'm looking for an example of what to supply in the $msglist variable to the function.  The documentation recommends reading RFC2060 which I cannot comprehend.

I want to ultimately write a function to copy a message into the a Sent folder upon sending an email.

Can someone provide an example of using the imap_mail_copy function?

答:
If you're just copying one message, use the same msg_number you'd use in an imap_headerinfo call (etc.).

If you're copying more than one message, join the message numbers with commas (but no spaces).  E.g. "3,4,7,9".

The lousy documentation for imap_mail_copy says:

msglist is a range not just message numbers (as described in » RFC2060).

What this means is that if you want to copy a bunch of messages with consecutive message numbers (e.g. 1,2,3,4,5,6,7) you can just use a "range" and encode it as "1:7".  But, honestly, it's usually much easier to just have a comma-separated list.

It's described a lot better in the imap_fetch_overview page:

A message sequence description. You can enumerate desired messages with the X,Y syntax, or retrieve all messages within an interval with the X:Y syntax

ContentLicense: CC BY-SA 2.5


问:
Cannot load data from Excel into SQL using SSIS
I am trying to import an excel file into the SQL server using SSIS package, but every time I try to upload this file some rows from the last don't get uploaded, to be precise 55107 should be uploaded but only 54990 gets uploaded. 117 rows are creating some problem and am not able to figure out why is that so. Please help me out in understanding this error message so that I can resolve the issue. Below is the error message I'm getting:

SSIS package "C:\Users\A670814\Documents\Visual Studio 2015\Projects\Integration Services Project1\Integration Services Project1\NDCS Towers.dtsx" starting.
  Information: 0x4004300A at NDCS tower, SSIS.Pipeline: Validation phase is beginning.

Information: 0x4004300A at NDCS tower, SSIS.Pipeline: Validation phase is beginning.
  Warning: 0x80049304 at NDCS tower, SSIS.Pipeline: Warning: Could not open global shared memory to communicate with performance DLL; data flow performance counters are not available.  To resolve, run this package as an administrator, or on the system's console.
  Information: 0x40043006 at NDCS tower, SSIS.Pipeline: Prepare for Execute phase is beginning.
  Information: 0x40043007 at NDCS tower, SSIS.Pipeline: Pre-Execute phase is beginning.
  Information: 0x4004300C at NDCS tower, SSIS.Pipeline: Execute phase is beginning.
  Error: 0xC0202009 at NDCS tower, OLE DB Destination [280]: SSIS Error Code DTS_E_OLEDBERROR.  An OLE DB error has occurred. Error code: 0x80004005.
  An OLE DB record is available.

  Source: "Microsoft SQL Server Native Client 11.0"  Hresult: 0x80004005  Description: "Unspecified error".
  Error: 0xC020901C at NDCS tower, OLE DB Destination [280]: There was an error with OLE DB Destination.Inputs[OLE DB Destination Input].Columns[Copy of ID] on OLE DB Destination.Inputs[OLE DB Destination Input]. The column status returned was: "The value violated the integrity constraints for the column.".

Error: 0xC0209029 at NDCS tower, OLE DB Destination [280]: SSIS Error Code DTS_E_INDUCEDTRANSFORMFAILUREONERROR.  The "OLE DB Destination.Inputs[OLE DB Destination Input]" failed because error code 0xC020907D occurred, and the error row disposition on "OLE DB Destination.Inputs[OLE DB Destination Input]" specifies failure on error. An error occurred on the specified object of the specified component.  There may be error messages posted before this with more information about the failure.

Error: 0xC0047022 at NDCS tower, SSIS.Pipeline: SSIS Error Code DTS_E_PROCESSINPUTFAILED.  The ProcessInput method on component "OLE DB Destination" (280) failed with error code 0xC0209029 while processing input "OLE DB Destination Input" (293). The identified component returned an error from the ProcessInput method. The error is specific to the component, but the error is fatal and will cause the Data Flow task to stop running.  There may be error messages posted before this with more information about the failure.

Error: 0xC02020C4 at NDCS tower, Excel Source [156]: The attempt to add a row to the Data Flow task buffer failed with error code 0xC0047020.
  Error: 0xC0047038 at NDCS tower, SSIS.Pipeline: SSIS Error Code DTS_E_PRIMEOUTPUTFAILED.  The PrimeOutput method on Excel Source returned error code 0xC02020C4.  The component returned a failure code when the pipeline engine called PrimeOutput(). The meaning of the failure code is defined by the component, but the error is fatal and the pipeline stopped executing.  There may be error messages posted before this with more information about the failure.
  Information: 0x40043008 at NDCS tower, SSIS.Pipeline: Post Execute phase is beginning.
  Information: 0x4004300B at NDCS tower, SSIS.Pipeline: "OLE DB Destination" wrote 55107 rows.
  Information: 0x40043009 at NDCS tower, SSIS.Pipeline: Cleanup phase is beginning.
  Task failed: NDCS tower

Warning: 0x80019002 at NDCS Towers: SSIS Warning Code DTS_W_MAXIMUMERRORCOUNTREACHED.  The Execution method succeeded, but the number of errors raised (6) reached the maximum allowed (1); resulting in failure. This occurs when the number of errors reaches the number specified in MaximumErrorCount. Change the MaximumErrorCount or fix the errors.

SSIS package "C:\Users\A670814\Documents\Visual Studio 2015\Projects\Integration Services Project1\Integration Services Project1\NDCS Towers.dtsx" finished: Failure.

答:
There was an error with OLE DB Destination.Inputs[OLE DB Destination Input].Columns[Copy of ID] on OLE DB Destination.Inputs[OLE DB Destination Input]. The column status returned was: "The value violated the integrity constraints for the column.".

It looks there are many rows where [Copy of ID] column is null, or there are some constraints on the [Copy of ID] column in SQL server that are violated in some rows in the excel files.

Try deleting rows that contains no data in [Copy of ID] column, or you can filter them by adding a conditional split component and filter on the following consition

```<code>ISNULL([Copy of ID])
</code>```

Or you can access to the destination SQL table using Sql server management studio, and go to the SQL table design mode, and check the option Allow null for the column [Copy of ID]

Similar Question with many useful answers: The value violated the integrity constraints for the column

Body:
There was an error with OLE DB Destination.Inputs[OLE DB Destination Input].Columns[Copy of ID] on OLE DB Destination.Inputs[OLE DB Destination Input]. The column status returned was: "The value violated the integrity constraints for the column.".

It looks there are many rows where [Copy of ID] column is null, or there are some constraints on the [Copy of ID] column in SQL server that are violated in some rows in the excel files.

Try deleting rows that contains no data in [Copy of ID] column, or you can filter them by adding a conditional split component and filter on the following consition

ISNULL([Copy of ID])

Or you can access to the destination SQL table using Sql server management studio, and go to the SQL table design mode, and check the option Allow null for the column [Copy of ID]

Similar Question with many useful answers: The value violated the integrity constraints for the column


问:
restrict untrusted java code to a single thread
I am looking for a way to execute untrusted java code so that the code could not use multiple thread.Is it possible to use java security manager to restrict the untrusted code to create multiple thread.any resource or hints will be helpful.</p>

答:
I'm not clear on what you are asking, but I'll throw out two answers anyway.

If you are using third-party code that you don't like, and it wants to start multiple threads, then there is no way to prevent that. The big thing is that the code will fail if it blocked from starting threads.

If you want to restrict some untrusted code so that only specific classes can use it, then you would have to load it with custom classloader.

Another way to isolate this code would be to wrap it in a service and run it as a micro-service in its own JVM.

Regardless, what you are talking about sounds like a bad idea. If you don't trust it, don't use it.


问:
Button not inlined on smaller devices
I have a form that looks like this (on a big device, e.g. pc monitor)

that is as it should be. On smaller devices it however looks like this:

the button is no longer in the same line as the input. My code looks like this:

```<code><div class="form-group ">
    <label class="col-md-2 control-label">Title</label>
    <div class="col-md-10">
        <div class="row">
            <div class="col-md-10">
                <input id="title" class="form-control" placeholder="Title" autocomplete="off" name="title" type="text" value="">
            </div>
            <div class="col-md-2">
                <a id="btn-verify" class="btn btn-primary pull-right">Verify</a>
            </div>
        </div>
    </div>
</div>
</code>```

How can I ensure that it also is aligned correctly when using smaller devices?
PS: Bootstrap is being used

答:
Your columns are col-md, which means that when the screen width gets below 992px, the columns will take up the full width of the page. So if you want them to stay inline, then add col-xs classes with the column sizes that you need.

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

    Title

                <input id="title" class="form-control" placeholder="Title" autocomplete="off" name="title" type="text" value="">

                Verify

```

Title: Button not inlined on smaller devices

Body:
I have a form that looks like this (on a big device, e.g. pc monitor)

that is as it should be. On smaller devices it however looks like this:

the button is no longer in the same line as the input. My code looks like this:

    Title

                <input id="title" class="form-control" placeholder="Title" autocomplete="off" name="title" type="text" value="">

                Verify

How can I ensure that it also is aligned correctly when using smaller devices?
PS: Bootstrap is being used

Body:
Your columns are col-md, which means that when the screen width gets below 992px, the columns will take up the full width of the page. So if you want them to stay inline, then add col-xs classes with the column sizes that you need.

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="form-group ">
    <label class="col-md-2 control-label">Title</label>
    <div class="col-md-10">
        <div class="row">
            <div class="col-xs-10">
                <input id="title" class="form-control" placeholder="Title" autocomplete="off" name="title" type="text" value="">
            </div>
            <div class="col-xs-2">
                <a id="btn-verify" class="btn btn-primary pull-right">Verify</a>
            </div>
        </div>
    </div>
</div>


问:
Java ArrayIndexOutOfBoundsException MOOC Helsinki - where is the mistake in my code?
I've been searching for an answer, but without any results. I know that this exception means that I'm trying to reach nonexistent array element, but I just can't see it.

It's excercise 104 from MOOC Helsinki, you can read it here

http://mooc.cs.helsinki.fi/programming-part1/material-2013/week-6?noredirect=1

I'm supposed to create sorting algorithm by creating five methods one after another. I've created first four, but things go south with the final one. I have no idea whether it's just matter of changing a single character, or the whole construction is flawed.

I would be grateful for help, feel free to comment on my code, but if it's possible do not overwrite the whole thing, I don't want solving it for me, just some hints and help.

```<code>import java.util.Arrays;

public class Main {

    public static int smallest(int[] array) {
        int result = array[0];
        int position = 0;
        for (int i = 0; i < (array.length); i++) {
            if (result > array[i]) {
                result = array[i];
                position = i;
            }
        }
        return result;

    }

    public static int indexOfTheSmallest(int[] array) {
        int result = array[0];
        int position = 0;
        for (int i = 0; i < (array.length); i++) {
            if (result > array[i]) {
                result = array[i];
                position = i;
            }
        }
        return position;
    }

    public static int indexOfTheSmallestStartingFrom(int[] array, int index) {
        int result = array[index];
        int position = 0;
        for (int i = index; i < array.length; i++) {
            if (result > array[i]) {
                result = array[i];
                position = i;
            }
        }
        return position;
    }

    public static void swap(int[] array, int index1, int index2) {
        int a = array[index1];
        int b = array[index2];

        array[index1] = b;
        array[index2] = a;
    }

    public static void sort(int[] array) {
        int temp;
        for (int x = 0; x < array.length; x++) {
            System.out.println(Arrays.toString(array));
            temp = indexOfTheSmallestStartingFrom(array, x);
            swap(array, array[x], temp);
        }
    }

    public static void main(String[] args) {
        int[] values = {8, 3, 7, 9, 1, 2, 4};
        sort(values);
    }
}
</code>```

答:
change swap(array, array[x], temp); to
swap(array, x, temp);</p>

Body:
I've been searching for an answer, but without any results. I know that this exception means that I'm trying to reach nonexistent array element, but I just can't see it.

It's excercise 104 from MOOC Helsinki, you can read it here

http://mooc.cs.helsinki.fi/programming-part1/material-2013/week-6?noredirect=1

I'm supposed to create sorting algorithm by creating five methods one after another. I've created first four, but things go south with the final one. I have no idea whether it's just matter of changing a single character, or the whole construction is flawed.

I would be grateful for help, feel free to comment on my code, but if it's possible do not overwrite the whole thing, I don't want solving it for me, just some hints and help.

import java.util.Arrays;

public class Main {

    public static int smallest(int[] array) {
        int result = array[0];
        int position = 0;
        for (int i = 0; i < (array.length); i++) {
            if (result > array[i]) {
                result = array[i];
                position = i;
            }
        }
        return result;

    }

    public static int indexOfTheSmallest(int[] array) {
        int result = array[0];
        int position = 0;
        for (int i = 0; i < (array.length); i++) {
            if (result > array[i]) {
                result = array[i];
                position = i;
            }
        }
        return position;
    }

    public static int indexOfTheSmallestStartingFrom(int[] array, int index) {
        int result = array[index];
        int position = 0;
        for (int i = index; i < array.length; i++) {
            if (result > array[i]) {
                result = array[i];
                position = i;
            }
        }
        return position;
    }

    public static void swap(int[] array, int index1, int index2) {
        int a = array[index1];
        int b = array[index2];

        array[index1] = b;
        array[index2] = a;
    }

    public static void sort(int[] array) {
        int temp;
        for (int x = 0; x < array.length; x++) {
            System.out.println(Arrays.toString(array));
            temp = indexOfTheSmallestStartingFrom(array, x);
            swap(array, array[x], temp);
        }
    }

    public static void main(String[] args) {
        int[] values = {8, 3, 7, 9, 1, 2, 4};
        sort(values);
    }
}


问:
Why does solr add new document while updating?
```<code>curl 'http://localhost/solr/collection/update?commit=true'
-H 'Content-type:application/json'
-d
'[
  {
    "id":"11111",
    "price":{"set":1000}
  }
]'
</code>```

If id:11111 exists, price value is updated. It's ok.

If id:11111 doesn't exist, new document is created in solr index. This behavior is not desirable. I expect error with some text like: document you tried to update does not exist.
I cannot understand what is wrong.

Solr version: 4.8.0.

Part of schema.xml:

```<code><field name="id" type="string"  indexed="true" stored="true" required="true"/>
<uniqueKey>id</uniqueKey>
</code>```

答:
The /update request handler actually updates the index for new and existing documents and handles deletion as well.

During indexation:

A document is considered new if it has no identifier or if its id does not match any of the indexed documents. If no id is generated during indexing and if the uniqueKey field is required, the document is rejected.

A document that has an identifier matching an indexed document is merged with its stored version : all stored fields are loaded from the index and are overriden by field values from the request parameters, and the resulting document replace the previous one (but in the end it is the same operation).

In other word an update request - if not a delete - always ends up in the same add operation. By the way the XML schema recognized by solr.UpdateRequestHandler contains the elements <add>, <doc> and <field> regardless of the operation (add or replace).

Recent versions of Solr provide more options for updating parts of documents. (see atomic updates and in-place updates.

What you describe is the expected behavior. Since the id field is required, Solr will throw an error for document missing this field. In your situation, the document is indexed in both cases because the id is given in both cases.

With this configuration you would have to ensure that id field is empty for what you consider a new document, either client side when preparing the request or server side using an update processor or by updating the request handler implementation. Maybe it would be even simpler to prevent the indexation of any new docs ?

Body:
curl 'http://localhost/solr/collection/update?commit=true'
-H 'Content-type:application/json'
-d
'[
  {
    "id":"11111",
    "price":{"set":1000}
  }
]'

If id:11111 exists, price value is updated. It's ok.

If id:11111 doesn't exist, new document is created in solr index. This behavior is not desirable. I expect error with some text like: document you tried to update does not exist.
I cannot understand what is wrong.

Solr version: 4.8.0.

Part of schema.xml:

<field name="id" type="string"  indexed="true" stored="true" required="true"/>
<uniqueKey>id</uniqueKey>


答:
Both the input and button need to be set to display: inline, and they should be placed in the same column. Below works and should satisfy your needs:

    Title

                <input id="title" class="form-control d-inline w-70 float-left" placeholder="Title" autocomplete="off" name="title" type="text" value="">
                Verify

```

Title: Button not inlined on smaller devices

Body:
Both the input and button need to be set to display: inline, and they should be placed in the same column. Below works and should satisfy your needs:

<div class="form-group ">
    <label class="col-md-2 control-label">Title</label>
    <div class="col-md-10">
        <div class="row">
            <div class="col-md">
                <input id="title" class="form-control d-inline w-70 float-left" placeholder="Title" autocomplete="off" name="title" type="text" value="">
                <a id="btn-verify" class="btn btn-primary float-left d-inline">Verify</a>
            </div>
        </div>
    </div>
</div>


问:
Remove trailing whitespace recursively only at end of file using grep/sed?
Basically, I've got about 1,500 files and the last character of any of these files should not be any type of white space.

How do I check a bunch of files to make sure that they don't end in some form of whitespace?(newline, space, carriage return, tab, etc.)?

答:
```<code>awk '{if (flag) print line; line = $0; flag = 1} END {gsub("[[:space:]]+$","",line); printf line}'
</code>```

Edit:

New version:

The sed command removes all the trailing lines that consist of only whitespace then the awk command removes the ending newline.

```<code>sed '/^[[:space:]]*$/{:a;$d;N;/\n[[:space:]]*$/ba}' inputfile |
    awk '{if (flag) print line; line = $0; flag = 1} END {printf line}'
</code>```

The disadvantage is that it reads the file twice.

Edit 2:

Here's an all-awk solution that only reads the file once. It accumulates white-space-only lines in a manner similar to the sed command above.

```<code>#!/usr/bin/awk -f

# accumulate a run of white-space-only lines so they can be printed or discarded
/^[[:space:]]*$/ {
    accumlines = accumlines nl $0
    nl = "\n"
    accum = 1
    next
}

# print the previous line and any accumulated lines, store the current line for the next pass
{
    if (flag) print line
    if (accum) { print accumlines; accum = 0 }
    accumlines = nl = ""
    line = $0
    flag = 1
}

# print the last line without a trailing newline after removing all trailing whitespace
# the resulting output could be null (nothing rather than 0x00)
# note that we're not print the accumulated lines since they're part of the
# trailing white-space we're trying to get rid of
END {
    gsub("[[:space:]]+$","",line)
    printf line
}
</code>```

Edit 3:

removed unnecessary BEGIN clause

changed lines to accumlines so it's easier to distinguish from line (singular)

added comments

Body:
awk '{if (flag) print line; line = $0; flag = 1} END {gsub("[[:space:]]+$","",line); printf line}'

Edit:

New version:

The sed command removes all the trailing lines that consist of only whitespace then the awk command removes the ending newline.

sed '/^[[:space:]]*$/{:a;$d;N;/\n[[:space:]]*$/ba}' inputfile |
    awk '{if (flag) print line; line = $0; flag = 1} END {printf line}'

The disadvantage is that it reads the file twice.

Edit 2:

Here's an all-awk solution that only reads the file once. It accumulates white-space-only lines in a manner similar to the sed command above.

#!/usr/bin/awk -f

# accumulate a run of white-space-only lines so they can be printed or discarded
/^[[:space:]]*$/ {
    accumlines = accumlines nl $0
    nl = "\n"
    accum = 1
    next
}

# print the previous line and any accumulated lines, store the current line for the next pass
{
    if (flag) print line
    if (accum) { print accumlines; accum = 0 }
    accumlines = nl = ""
    line = $0
    flag = 1
}

# print the last line without a trailing newline after removing all trailing whitespace
# the resulting output could be null (nothing rather than 0x00)
# note that we're not print the accumulated lines since they're part of the
# trailing white-space we're trying to get rid of
END {
    gsub("[[:space:]]+$","",line)
    printf line
}

Edit 3:

removed unnecessary BEGIN clause

changed lines to accumlines so it's easier to distinguish from line (singular)

added comments


问:
SQL Concatenation using case statement
I have a table which looks like this:

```<code>**ID    col1  col2  col3  col4  col5**
1       abc   NULL  NULL  NULL  NULL
2       ght   cde   NULL  NULL  NULL
3       atr   dgf   aft   NULL  NULL
4       asd   rty   tyu   xyz   NULL
5       abc   pqr   xyz   rst   rty
6       qwe   rty   ghj   rty   tyu
</code>```

I want it change in this form:

```<code>**ID    NewCol**
1   abc
2   ght/cde
3   atr/dgf/aft
4   asd/rty/tyu/xyz
5   abc/pqr/xyz/rst/rty
6   qwe/rty/ghj/rty/tyu
</code>```

The query I wrote is:

```<code>     SELECT ID,
    NewCol = CASE WHEN col1 IS NOT NULL AND col2 IS NULL THEN col1
                WHEN col1 IS NOT NULL  AND col3 IS NULL THEN col1+'/' + col2
                WHEN col1 IS NOT NULL AND col4 IS  NULL THEN col1+'/'+ col2 + '/' + col3
                WHEN col1 IS NOT NULL AND col5 IS NULL THEN col1+'/' + col2 + '/' + col3+ '/' + col4
                WHEN col1 IS NOT NULL AND col5 IS not NULL THEN col1+'/' + col2 + '/' + col3+ '/' + col4 + '/' + col5
                ELSE NULL
  END
   FROM dbo.Temp
</code>```

If we have like 10 columns then I thought may be this is not an efficient way to write this.

Can you help me find a better solution to this one?

Thanks.

答:
I think this is simpler:

```<code>select (col1 + coalesce('/' + col2, '') + coalesce('/' + col3, '') +
        coalesce('/' + col4, '') + coalesce('/' + col5, '')
       )
</code>```

This assumes that col1 always has a value.

Title: SQL Concatenation using case statement

Body:
I have a table which looks like this:

**ID    col1  col2  col3  col4  col5**
1       abc   NULL  NULL  NULL  NULL
2       ght   cde   NULL  NULL  NULL
3       atr   dgf   aft   NULL  NULL
4       asd   rty   tyu   xyz   NULL
5       abc   pqr   xyz   rst   rty
6       qwe   rty   ghj   rty   tyu

I want it change in this form:

**ID    NewCol**
1   abc
2   ght/cde
3   atr/dgf/aft
4   asd/rty/tyu/xyz
5   abc/pqr/xyz/rst/rty
6   qwe/rty/ghj/rty/tyu

The query I wrote is:

     SELECT ID,
    NewCol = CASE WHEN col1 IS NOT NULL AND col2 IS NULL THEN col1
                WHEN col1 IS NOT NULL  AND col3 IS NULL THEN col1+'/' + col2
                WHEN col1 IS NOT NULL AND col4 IS  NULL THEN col1+'/'+ col2 + '/' + col3
                WHEN col1 IS NOT NULL AND col5 IS NULL THEN col1+'/' + col2 + '/' + col3+ '/' + col4
                WHEN col1 IS NOT NULL AND col5 IS not NULL THEN col1+'/' + col2 + '/' + col3+ '/' + col4 + '/' + col5
                ELSE NULL
  END
   FROM dbo.Temp

If we have like 10 columns then I thought may be this is not an efficient way to write this.

Can you help me find a better solution to this one?

Thanks.

Body:
I think this is simpler:

select (col1 + coalesce('/' + col2, '') + coalesce('/' + col3, '') +
        coalesce('/' + col4, '') + coalesce('/' + col5, '')
       )

This assumes that col1 always has a value.


问:
Develop Turing Machine to count number of As and Bs in a String
The given Language is
L = {a^n b^n where n>= 0}
I have to develop a turing machine for it but i dont get the logic. will it go like this if an a is not followed by a b you go to halt reject state, but how we check if the count of a and b are equal?
will be very grateful for any response</p>

答:
A Turing Machine decides a language if it enters the halt-accept state when the input tape initially contains a string in the language, and enters the halt-reject state otherwise.

So, to decide your language L, you need to define states and transitions so that when the tape contains a string a^n b^n the TM ends up in halt-accept, and such that it ends up in halt-reject otherwise.

We can assume a single-tape TM and that you don't need the input tape restored to its original state after processing has finished (that is, we can do whatever we want to the tape and don't need to clean up or move the tape head anywhere in particular). What we need is a strategy for processing the tape so that we can reliably know when the string is or isn't in the language. In your case, we need a's followed by b's, with the same number of a's and b's. If you had to do this task in real life, how might you approach it?

You could first count the a's and then count the b's, and then see if the numbers are equal; however, this doesn't really simplify matters for us, since telling whether two numbers are equal is actually a somewhat harder problem than telling if two strings have the same length (the language ww | w in {a, b}* is context-sensitive, whereas a^n b^n is context-free).

Another approach is the "one for me, one for you" approach used by pirates when dividing treasure and mathematicians when establishing bijections among sets: to show that two sets have the same number of elements, you simply pair them off such that all elements are in exactly one pair. This doesn't yield the same problem that counting did, in that we don't have the same subproblem to solve: whereas the other problem yielded a harder subproblem, this one yields a subproblem of exactly the same difficulty as the original. Indeed, it's a smaller instance of the exact same problem! By erasing one a and then erasing a corresponding b, we can reduce a problem of size n to one of size n - 2. By repeating this process, we will eventually erase the whole tape and accept, or run out of symbols to pair with, and reject.

This is our design. For implementation, we will require an initial state. From the initial state, we can assume we are looking at the first non-blank tape cell, if any. If the tape cell is blank, the input is empty and we must accept since a^0 b^0 is in the language with n = 0. If the tape cell has b, we may halt-reject since we were expecting to see an a, if anything, first. If the tape cell has a, then we need to look for a corresponding b to erase.

Now, which b should we erase? Currently, we know where the input ends since we have a blank immediately after the last input symbol. If we use blanks to erase b's before that, we will have no good way of knowing whether we might have more input to the right of any currently blank cell. You could overcome this by introducing a new tape symbol E for erased cells; then, when erasing, write E instead of blank to indicate erasure. Then, it really doesn't matter which b you erase. If you prefer not to use a new tape symbol, however, you can instead erase the b immediately before the blank at the end of the input (rejecting if an a is found there instead) and achieve the same thing.

In any event, after erasing a corresponding b, we can return to the beginning of the tape (the blank cell first reached after moving left) and repeat the process over and over again until we accept or reject.

Here is a sample implementation:

```<code>Q    T    Q'    T'    D
--   -    --    --    -

// accept on empty tape
q0   B    hA    B     S

// erase an a or reject if no a
q0   a    q1    B     R
q0   b    hR    b     S

// scan to end of input
q1   B    q2    B     L
q1   a    q1    a     R
q1   b    q1    b     R

// erase last b or reject if none
q2   B    qR    B     S
q2   a    qR    a     S
q2   b    q3    B     S

// scan to beginning of input, then repeat
q3   B    q0    B     R
q3   a    q3    a     L
q3   b    q3    b     L
</code>```

Body:
A Turing Machine decides a language if it enters the halt-accept state when the input tape initially contains a string in the language, and enters the halt-reject state otherwise.

So, to decide your language L, you need to define states and transitions so that when the tape contains a string a^n b^n the TM ends up in halt-accept, and such that it ends up in halt-reject otherwise.

We can assume a single-tape TM and that you don't need the input tape restored to its original state after processing has finished (that is, we can do whatever we want to the tape and don't need to clean up or move the tape head anywhere in particular). What we need is a strategy for processing the tape so that we can reliably know when the string is or isn't in the language. In your case, we need a's followed by b's, with the same number of a's and b's. If you had to do this task in real life, how might you approach it?

You could first count the a's and then count the b's, and then see if the numbers are equal; however, this doesn't really simplify matters for us, since telling whether two numbers are equal is actually a somewhat harder problem than telling if two strings have the same length (the language ww | w in {a, b}* is context-sensitive, whereas a^n b^n is context-free).

Another approach is the "one for me, one for you" approach used by pirates when dividing treasure and mathematicians when establishing bijections among sets: to show that two sets have the same number of elements, you simply pair them off such that all elements are in exactly one pair. This doesn't yield the same problem that counting did, in that we don't have the same subproblem to solve: whereas the other problem yielded a harder subproblem, this one yields a subproblem of exactly the same difficulty as the original. Indeed, it's a smaller instance of the exact same problem! By erasing one a and then erasing a corresponding b, we can reduce a problem of size n to one of size n - 2. By repeating this process, we will eventually erase the whole tape and accept, or run out of symbols to pair with, and reject.

This is our design. For implementation, we will require an initial state. From the initial state, we can assume we are looking at the first non-blank tape cell, if any. If the tape cell is blank, the input is empty and we must accept since a^0 b^0 is in the language with n = 0. If the tape cell has b, we may halt-reject since we were expecting to see an a, if anything, first. If the tape cell has a, then we need to look for a corresponding b to erase.

Now, which b should we erase? Currently, we know where the input ends since we have a blank immediately after the last input symbol. If we use blanks to erase b's before that, we will have no good way of knowing whether we might have more input to the right of any currently blank cell. You could overcome this by introducing a new tape symbol E for erased cells; then, when erasing, write E instead of blank to indicate erasure. Then, it really doesn't matter which b you erase. If you prefer not to use a new tape symbol, however, you can instead erase the b immediately before the blank at the end of the input (rejecting if an a is found there instead) and achieve the same thing.

In any event, after erasing a corresponding b, we can return to the beginning of the tape (the blank cell first reached after moving left) and repeat the process over and over again until we accept or reject.

Here is a sample implementation:

Q    T    Q'    T'    D
--   -    --    --    -

// accept on empty tape
q0   B    hA    B     S

// erase an a or reject if no a
q0   a    q1    B     R
q0   b    hR    b     S

// scan to end of input
q1   B    q2    B     L
q1   a    q1    a     R
q1   b    q1    b     R

// erase last b or reject if none
q2   B    qR    B     S
q2   a    qR    a     S
q2   b    q3    B     S

// scan to beginning of input, then repeat
q3   B    q0    B     R
q3   a    q3    a     L
q3   b    q3    b     L


问:
Cannot store aws-glue script in an S3 Bucket that has encryption policy
Can we store the aws-glue scripts in S3 Bucket with AES encryption ?

We have bucket policies that enforce AES encryption .. cannot upload files unless they are encrypted.

When creating a simple aws-glue job,  I cannot seem to save the script in a bucket with encryption.

```<code>{
  "service": "Amazon S3",
  "statusCode": 403,
  "errorCode": "AccessDenied",
  "requestId": "2...3B",
  "errorMessage": "Access Denied",
  "type": "AwsServiceError"
}
</code>```

I confirmed access to the bucket by removing the bucket policy and the script can be saved.

Our standard is to enforce S3 Server Side Encryption.  is there a way to save have the script encrypted when saved?

Script Library server side encryption option

答: Amazon just added a feature to S3 that encrypts all objects by default. So you don't have to use the policy to force clients to specify the encryption anymore.</p>

Body:
Can we store the aws-glue scripts in S3 Bucket with AES encryption ?

We have bucket policies that enforce AES encryption .. cannot upload files unless they are encrypted.

When creating a simple aws-glue job,  I cannot seem to save the script in a bucket with encryption.

{
  "service": "Amazon S3",
  "statusCode": 403,
  "errorCode": "AccessDenied",
  "requestId": "2...3B",
  "errorMessage": "Access Denied",
  "type": "AwsServiceError"
}

I confirmed access to the bucket by removing the bucket policy and the script can be saved.

Our standard is to enforce S3 Server Side Encryption.  is there a way to save have the script encrypted when saved?

Script Library server side encryption option


问:
Center a UIView inside a TableViewCell
I've been facing an weird issue which I have never experienced before (pretty new to iOS). I am trying to develop a blog reader app and I am using a UITableView inside my main View. Within the TableView I have added 1 prototype cell and modified it's height to be somewhat bigger.

In order to create a "floating", "shadow" or "card" effect within the TableViewVell I have added another View which will contain a cover image and a summary.

The problem I am facing is related to the layout that is displayed by the Preview Assistant for Storybords.

Even though for iPhone 8 (xCode 9.1) everything looks fine based on the constraints that I have put in place, for iPhone SE and 8 Plus things look weirdly different even though during the simulation things do not really look as described.

I have watched WWDC Videos, YouTube Videos, even some great tutorials but none seem to go beyond the basics and actually cover this issue that I am facing.

Here is a screenshot:

XCode Storyboards Preview

I made a simplified demo ofthe project which can be checked out on GitHub:

https://github.com/sebastiannitu/ConstraintIssues

I would very much appreciated if seomeone would calrify this issue for me once and for all. I am sure it's just me doing something silly but I cannot really waste any more time with this. I've already invested about 2 weeks in trying to figure this out!

Thank you very much for your replies in advance!

答:
your constraints setup is fine . problem is with only assistant editor. if you run it in your simulator, View (orange View) will resize currectly.

Here is the screenshot for orange View, when running in iPhone 8s (left) and iPhone 5s.

i am not uploading project, but if you have problem then let me know.

Title: Center a UIView inside a TableViewCell


问:
What's the best practice way to convert enum to string?
I have enum like this:

```<code>public enum ObectTypes
{
    TypeOne,
    TypeTwo,
    TypeThree,
    ...
    TypeTwenty
 }
</code>```

then I need to convert this enum to string. Now Im doing this that way:

```<code>public string ConvertToCustomTypeName(ObjectTypes typeObj)
{
    string result = string.Empty;
    switch (typeObj)
    {
        case ObjectTypes.TypeOne: result = "This is type T123"; break;
        case ObjectTypes.TypeTwo: result = "Oh man! This is type T234"; break;
        ...
        case ObjectTypes.TypeTwenty: result = "This is type last"; break;
    }

    return result;
}
</code>```

Im quite sure that there is better way do do this, Im looking for some good practice solution.

EDIT: There is no one pattern in result string.

Thanks in advance.

答:
I would put these values in a database. Roles usually belong in a database for several reasons including these:

Reports may need to be run against the roles, thus a need to display the descriptions.

Role definitions can be configured without deploying new code.

Roles should be enforced with a key constraint.

If done correctly, performance should not be an issue getting the roles from the database. Additionally, because a role definition table rarely changes, it is a very good candidate for caching.

If you find yourself having to hack around an Enum to get it to work, maybe you shouldn't use an Enum. Given the proper placement, everything should flow much better in code with little or no hacks. Granted Enums have their place; for example, a rather static mutually exclusive status.

Body:
I have enum like this:

public enum ObectTypes
{
    TypeOne,
    TypeTwo,
    TypeThree,
    ...
    TypeTwenty
 }

then I need to convert this enum to string. Now Im doing this that way:

public string ConvertToCustomTypeName(ObjectTypes typeObj)
{
    string result = string.Empty;
    switch (typeObj)
    {
        case ObjectTypes.TypeOne: result = "This is type T123"; break;
        case ObjectTypes.TypeTwo: result = "Oh man! This is type T234"; break;
        ...
        case ObjectTypes.TypeTwenty: result = "This is type last"; break;
    }

    return result;
}

Im quite sure that there is better way do do this, Im looking for some good practice solution.

EDIT: There is no one pattern in result string.

Thanks in advance.


问:
Get name of abstract type
I'm trying to create a trait that would provide the name of the abstract type that is added in the sub-class:

```<code>trait T {
  type T
  def myClassOf[T:ClassTag] = implicitly[ClassTag[T]].runtimeClass
  def getType = {
    myClassOf[T].getSimpleName
  }
}

class TT extends T {
  type T = String
}
</code>```

However, this fails to compile:

```<code>Error:(7, 15) not enough arguments for method myClassOf: (implicit evidence$1: scala.reflect.ClassTag[T.this.T])Class[_].
Unspecified value parameter evidence$1.
    myClassOf[T].getSimpleName
             ^
</code>```

But it works fine if I move the getType method to the sub-class. Can someone explain why and whether there is a way to do this call from the sub-class?

答:
Note that the above answers, while good are now obsolete as of scala 2.10.
the preferred method now is to use TypeTag or ClassTag.

As described in the docs (see below) you can now use them in implicit param lists or context bounds to do this kind of thing:-

```<code>import scala.reflect.runtime.universe._

def paramInfo[T: TypeTag](x: T): Unit = {
  val targs = typeOf[T] match { case TypeRef(_, _, args) => args }
  println(s"type of $x has type arguments $targs")
}

scala> paramInfo(42)
type of 42 has type arguments List()

scala> paramInfo(List(1, 2))
type of List(1, 2) has type arguments List(Int)
</code>```

see scala docs on Typetags

see api docs

Title: Get name of abstract type

Body:
I'm trying to create a trait that would provide the name of the abstract type that is added in the sub-class:

trait T {
  type T
  def myClassOf[T:ClassTag] = implicitly[ClassTag[T]].runtimeClass
  def getType = {
    myClassOf[T].getSimpleName
  }
}

class TT extends T {
  type T = String
}

However, this fails to compile:

Error:(7, 15) not enough arguments for method myClassOf: (implicit evidence$1: scala.reflect.ClassTag[T.this.T])Class[_].
Unspecified value parameter evidence$1.
    myClassOf[T].getSimpleName
             ^

But it works fine if I move the getType method to the sub-class. Can someone explain why and whether there is a way to do this call from the sub-class?

Body:
Note that the above answers, while good are now obsolete as of scala 2.10.
the preferred method now is to use TypeTag or ClassTag.

As described in the docs (see below) you can now use them in implicit param lists or context bounds to do this kind of thing:-

import scala.reflect.runtime.universe._

def paramInfo[T: TypeTag](x: T): Unit = {
  val targs = typeOf[T] match { case TypeRef(_, _, args) => args }
  println(s"type of $x has type arguments $targs")
}

scala> paramInfo(42)
type of 42 has type arguments List()

scala> paramInfo(List(1, 2))
type of List(1, 2) has type arguments List(Int)

see scala docs on Typetags

see api docs

ContentLicense: CC BY-SA 4.0


问:
Disable save as & open in new tab on an image with css?
I know there is no point to do it, but I want to ask if it is possible to disable right click on an image with only css. </p>

<p>-What I want to do is to disallow naïve users from saving the images, from my WordPress website slider (MetaSlider)</p>

答:
You can use an overlay above the image to avoid such a thing :

.img-container {
  position: relative;
}

.img-container:after {
  content: " ";
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 99;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="img-container">
  <img src="https://lorempixel.com/400/400/" />
</div></code>```

This will avoid the usual save image action but any experienced developer will always be able to get the images (source code, inspect element, screenshot, etc).

You cannot prevent any user from saving the image whatever you will do because in all the cases the image is served with the web page and it's present in the client side.

Body:
I know there is no point to do it, but I want to ask if it is possible to disable right click on an image with only css.

-What I want to do is to disallow naïve users from saving the images, from my WordPress website slider (MetaSlider)

Body:
You can use an overlay above the image to avoid such a thing :

.img-container {
  position: relative;
}

.img-container:after {
  content: " ";
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 99;
}

<div class="img-container">
  <img src="https://lorempixel.com/400/400/" />
</div>

This will avoid the usual save image action but any experienced developer will always be able to get the images (source code, inspect element, screenshot, etc).

You cannot prevent any user from saving the image whatever you will do because in all the cases the image is served with the web page and it's present in the client side.


问:
Can't add service account to new Google Analytics UI
With the old Google Analytics UI I could easily add service account email addresses, but with the new UI, I am unable to.

Every time I try to add the service account email, it says the email cannot be found.

My service account email looks like: projectName@appspot.gserviceaccount.com

答:
Ah, I needed to create a new service account user, which had the format like:

CUSTOM_NAME@PROJECT_NAME.iam.gserviceaccount.com


答:
Have you tried stacking the bootstrap col classes?

The lg / md / sm all target different screen size thresholds. Using multiples should help you define the space it should take up in a given scenario. I would say you can steal some real-estate from that input.

You could also consider putting them in the same div.

Your code modified with stacked col classes:

```<code><div class="form-group ">
    <label class="col-md-2 control-label">Title</label>
    <div class="col-md-10">
        <div class="row">
            <div class="col-md-10 col-sm-6">
                <input id="title" class="form-control" placeholder="Title" autocomplete="off" name="title" type="text" value="">
            </div>
            <div class="col-md-2 col-sm-6">
                <a id="btn-verify" class="btn btn-primary pull-right">Verify</a>
            </div>
        </div>
    </div>
</div>
</code>```

Title: Button not inlined on smaller devices

Body:
Have you tried stacking the bootstrap col classes?

The lg / md / sm all target different screen size thresholds. Using multiples should help you define the space it should take up in a given scenario. I would say you can steal some real-estate from that input.

You could also consider putting them in the same div.

Your code modified with stacked col classes:

<div class="form-group ">
    <label class="col-md-2 control-label">Title</label>
    <div class="col-md-10">
        <div class="row">
            <div class="col-md-10 col-sm-6">
                <input id="title" class="form-control" placeholder="Title" autocomplete="off" name="title" type="text" value="">
            </div>
            <div class="col-md-2 col-sm-6">
                <a id="btn-verify" class="btn btn-primary pull-right">Verify</a>
            </div>
        </div>
    </div>
</div>


问:
There is no metadata information for provider 'SqlServer-20'
I want to test the SQL database features of Quartz.NET 3.0 for .NET Core. Unfortunately, I'm unable to configure the StdSchedulerFactory properly, I always get the following exception when calling StdSchedulerFactory.GetScheduler:

```<code>System.ArgumentOutOfRangeException:
There is no metadata information for provider 'SqlServer-20'
Parameter name: providerName
   at Quartz.Impl.AdoJobStore.Common.DbProvider.GetDbMetadata(String providerName)
   at Quartz.Impl.AdoJobStore.Common.DbProvider..ctor(String dbProviderName, String connectionString)
   at Quartz.Impl.StdSchedulerFactory.<Instantiate>d__66.MoveNext()
</code>```

I've configured the factory with the following values:

var configuration = new NameValueCollection
{
    { "quartz.jobStore.type", "Quartz.Impl.AdoJobStore.JobStoreTX, Quartz" },
    { "quartz.jobStore.driverDelegateType", "Quartz.Impl.AdoJobStore.SqlServerDelegate, Quartz" },
    { "quartz.jobStore.tablePrefix", "QRTZ_" },
    { "quartz.jobStore.dataSource", "default" },
    { "quartz.dataSource.default.connectionString", "Server=(localdb)\\mssqllocaldb;Database=QuartzTest;Trusted_Connection=True;MultipleActiveResultSets=true" },
    { "quartz.dataSource.default.provider", "SqlServer-20" },
    { "quartz.jobStore.useProperties", "true" },
    { "quartz.serializer.type", "json" }
};

var schedulerFactory = new StdSchedulerFactory(configuration);
```

As you can see, I'm currently targeting LocalDB (v12.0.2000). I also checked it on SQL Server Express - same result.

How can I avoid this exception?

Did I miss any properties that I should configure?

Do I have to provide some data for the database? I only executed the tables_sqlServer.sql script.

The SqlServer-20 database driver should be installed as part of .NET 3.5, or is there a separate installation necessary?

Does Quartz.NET currently not support this functionality for .NET Core? I'm using version 3.0.0-alpha2.

Should I target other NuGet packages? I referenced Quartz and Quartz.Serialization.Json

答:
Currently according to changelog for beta1 there are no versions for providers. So correct provider configuration for SqlServer is:

```<code>["quartz.dataSource.sqlserver.provider"] = "SqlServer"
</code>```

Source: https://github.com/quartznet/quartznet/blob/e3ff6936ea1a76480b7671e2b5c468c1b67f4897/changelog.md#release-30-beta-1-oct-8-2017

Body:
I want to test the SQL database features of Quartz.NET 3.0 for .NET Core. Unfortunately, I'm unable to configure the StdSchedulerFactory properly, I always get the following exception when calling StdSchedulerFactory.GetScheduler:

System.ArgumentOutOfRangeException:
There is no metadata information for provider 'SqlServer-20'
Parameter name: providerName
   at Quartz.Impl.AdoJobStore.Common.DbProvider.GetDbMetadata(String providerName)
   at Quartz.Impl.AdoJobStore.Common.DbProvider..ctor(String dbProviderName, String connectionString)
   at Quartz.Impl.StdSchedulerFactory.<Instantiate>d__66.MoveNext()

I've configured the factory with the following values:

var configuration = new NameValueCollection
{
    { "quartz.jobStore.type", "Quartz.Impl.AdoJobStore.JobStoreTX, Quartz" },
    { "quartz.jobStore.driverDelegateType", "Quartz.Impl.AdoJobStore.SqlServerDelegate, Quartz" },
    { "quartz.jobStore.tablePrefix", "QRTZ_" },
    { "quartz.jobStore.dataSource", "default" },
    { "quartz.dataSource.default.connectionString", "Server=(localdb)\\mssqllocaldb;Database=QuartzTest;Trusted_Connection=True;MultipleActiveResultSets=true" },
    { "quartz.dataSource.default.provider", "SqlServer-20" },
    { "quartz.jobStore.useProperties", "true" },
    { "quartz.serializer.type", "json" }
};

var schedulerFactory = new StdSchedulerFactory(configuration);

As you can see, I'm currently targeting LocalDB (v12.0.2000). I also checked it on SQL Server Express - same result.

How can I avoid this exception?

Did I miss any properties that I should configure?

Do I have to provide some data for the database? I only executed the tables_sqlServer.sql script.

The SqlServer-20 database driver should be installed as part of .NET 3.5, or is there a separate installation necessary?

Does Quartz.NET currently not support this functionality for .NET Core? I'm using version 3.0.0-alpha2.

Should I target other NuGet packages? I referenced Quartz and Quartz.Serialization.Json

Body:
Currently according to changelog for beta1 there are no versions for providers. So correct provider configuration for SqlServer is:

["quartz.dataSource.sqlserver.provider"] = "SqlServer"

Source: https://github.com/quartznet/quartznet/blob/e3ff6936ea1a76480b7671e2b5c468c1b67f4897/changelog.md#release-30-beta-1-oct-8-2017


问:
How to get all existing images src in this url with PHP?
There are 6 images in this url which I want to give src images. My goal is getting all images src with PHP but only one image src coming.</p>

```<code><?php
require_once ('simple_html_dom/simple_html_dom.php');
$html = file_get_html('https://www.zara.com/tr/en/flatform-derby-shoes-with-reversible-fringe-p15318201.html?v1=5276035&v2=734142');
foreach($html->find('img') as $element){
     echo $element->src . '<br>';
}
?>
</code>```

答:
After looking at the Simple HTML DOM bug tracker. It seems like they are having some issues fetching values that aren't real URL's.

Looking at the source of the page you're trying to fetch, only one image actually does have a URL. The rest has inline images: src="data:image/png;base64,...".

I would suggest using PHP's own DOMDocument for this.

Here's a working solution (with comments):

```<code><?php
// Get the HTML from the URL
$data = file_get_contents("https://www.zara.com/tr/en/flatform-derby-shoes-with-reversible-fringe-p15318201.html?v1=5276035&v2=734142");

$doc = new DOMDocument;
// DOMDocument throws a bunch of errors since the HTML isn't 100% valid
// (and for all HTML5-tags) but it will sort them out.
// Let's just tell it to fix it in silence.
libxml_use_internal_errors(true);

$doc->loadHTML($data);

libxml_clear_errors();

// Fetch all img-tags and get the 'src' attributes.
foreach ($doc->getElementsByTagName('img') as $img) {
    echo $img->getAttribute('src') . '<br />';
}
</code>```

Demo: https://www.tehplayground.com/sh4yJ8CqIwypwkCa

Body:
There are 6 images in this url which I want to give src images. My goal is getting all images src with PHP but only one image src coming.

<?php
require_once ('simple_html_dom/simple_html_dom.php');
$html = file_get_html('https://www.zara.com/tr/en/flatform-derby-shoes-with-reversible-fringe-p15318201.html?v1=5276035&v2=734142');
foreach($html->find('img') as $element){
     echo $element->src . '
';
}
?>

Body:
After looking at the Simple HTML DOM bug tracker. It seems like they are having some issues fetching values that aren't real URL's.

Looking at the source of the page you're trying to fetch, only one image actually does have a URL. The rest has inline images: src="data:image/png;base64,...".

I would suggest using PHP's own DOMDocument for this.

Here's a working solution (with comments):

<?php
// Get the HTML from the URL
$data = file_get_contents("https://www.zara.com/tr/en/flatform-derby-shoes-with-reversible-fringe-p15318201.html?v1=5276035&v2=734142");

$doc = new DOMDocument;
// DOMDocument throws a bunch of errors since the HTML isn't 100% valid
// (and for all HTML5-tags) but it will sort them out.
// Let's just tell it to fix it in silence.
libxml_use_internal_errors(true);

$doc->loadHTML($data);

libxml_clear_errors();

// Fetch all img-tags and get the 'src' attributes.
foreach ($doc->getElementsByTagName('img') as $img) {
    echo $img->getAttribute('src') . '<br />';
}

Demo: https://www.tehplayground.com/sh4yJ8CqIwypwkCa


问:
Drupal 8 customizing view title in module
I am using the following code to change a view title to a custom title:

```<code>function MYMODULE_preprocess_page_title(&$variables) {
  if (some logic to check if this is the correct view)
    $variables['title] = 'Something Different!';
}
</code>```

This works to change the title in the content area within the
 tag, but the title of the browser tab is not changed (in <title>...</title>).

What is the correct way to change the view title to reflect both in the page body and the browser title?

答:
This page should be able to help.

tl;dr You can either set the title in the *.routing.yml file (either statically or dynamically) or you can set the title by setting #title in a markup array.

Body:
I am using the following code to change a view title to a custom title:

function MYMODULE_preprocess_page_title(&$variables) {
  if (some logic to check if this is the correct view)
    $variables['title] = 'Something Different!';
}

This works to change the title in the content area within the
 tag, but the title of the browser tab is not changed (in <title>...</title>).

What is the correct way to change the view title to reflect both in the page body and the browser title?


问:
Platform independent printf format for GLuint64?
I have a "facade" design pattern for OpenGL calls, which route the calls to their corresponding OpenGL call. I can additionally (but optionally) print out all OpenGL calls and their parameter values, which is useful for debugging. However, for methods which take a GLuint64 parameter (such as glClientWaitSync), I'm unsure which printf formatting to use. I'm specifically targeting Windows with MSVC and Linux with GCC and clang.

%lld works with MSVC, but produces warnings with GCC/clang. (warning: format ‘%lld’ expects argument of type ‘long long int’, but argument 6 has type ‘GLuint64 {aka long unsigned int})

%lu works with GCC/clang (in x64_86), but and doesn't cause warnings on MSVC. However, it doesn't print correctly (interpreted as a 32-bit integer).

Am I stuck doing an #ifdef for the compiler to make the correct format string, or is there a smarter/easier way to do this?

Note: this is not a duplicate of how to print a int64_t, because GLuint64 is defined as different concrete types at the top of the standard glext.h header.

答:
The answer here is simple: don't.

If you want to printf a GLuint64, then first cast it to a well-defined C++ type, such as unsigned long long. Since the input type is required by the OpenGL specification to be exactly 64-bits in size, and unsigned long long is required by the C specification (and thus by inclusion C++) to be at least 64-bits in size, the conversion should be lossless.


问:
Can not open project with IntelliJ IDEA
I have a project that was already working with IntelliJ IDEA but now,when I want to open it with IntelliJ IDEA, I am facing this error message:"Contains no IntelliJ IDE project".</p>

答: I faced the same issue. Deleting .project file in from the home directory and reopening solved the problem.

Title: Can not open project with IntelliJ IDEA


问:
Javascript how to get unique values from Math.random. How can i make it stop repeating?
I am trying to get some HTML dom elements remotely from some website with jquery/javascript. These elements are in the array and unique, but when I try to print them with math.random() * my array.length i see duplicates.  I want imgIdx to be unique.

So for the sake of helping me learn, can someone help me determine what am I missing here?

```<code>myarray = [
{ thumb : "http://url.com/img1.jpg", big : "http://url.com/img51.jpg" },
{ thumb : "http://url.com/img61.jpg", big : "http://url.com/img671.jpg" },
{ thumb : "http://url.com/img666.jpg", big : "http://url.com/img371.jpg" },]

function addSomeImages(limit) {
    for (var i = lastIdx; i < lastIdx + limit; i++) {
        var imgIdx = Math.floor(Math.random() * myarray.length);
        $('#endless-gallery').append('<a data-fancybox="gallery" href="' + myarray[imgIdx].big + '">' + '<img class=photo src="' + myarray[imgIdx].thumb + '' +
            '" />' +
            '</a>');
    }
</code>```

答:
What's important to note that hasn't been touched from what I've noticed is why exactly your current solution isn't working, or why shuffling your array is the ideal approach. What you need to realize is that your current code is just generating a random index for you to use to access elements in your array. Much like rolling a die, it's much more likely that you'll re-roll a number than you are to roll each of the numbers without repeating. That's the entire point of (pseudo-)random number generation, that the results are effectively non-deterministic by nature.

With that in mind, in order to retrieve elements from your array randomly without repeating, you will have to find a way to exclude repeats by design. The two most practical ways to do this are to either:

1) Shuffle the array and simply iterate through it as noted in the comments on your question, or

2) Remove the accessed elements from your array and loop until the array is empty.

Of the above two, simply shuffling the array is far more practical and doesn't result in the destruction of your array (or require cloning the array and destroying the clone), so it's easily the ideal solution for you to use.

Why these work while your original solution doesn't:

Shuffling the array is a procedure by which your array contains the same exact elements as it originally contains, but are simply ordered randomly in the array. Much like the name implies, it's like shuffling a deck of cards; you'll always have your standard 52 unique cards, but they'll just be in a different order. As you flip through the shuffled cards, there's no risk of somehow coming across the same card that you've already passed.

Removing an element and looping until empty is like taking a perfectly-sorted deck of 52 unique cards and pulling a random one out from the deck repeatedly, discarding the ones you've already pulled out. If the card you pull out is no longer in the deck, you'll never be at risk of pulling the same card out.

What you're doing right now taking that perfectly-sorted deck of 52 cards, looking at a random one, and placing it back where it was in the deck before repeating the process. The card is still there, and because you're just looking at random cards it's possible for you to inadvertently look at it a second time.

Since shuffling the array and then iterating through the results normally is the ideal approach, consider using the Fisher-Yates shuffle function noted in the comments:

```<code>function shuffle(array) {
    var currentIndex = array.length, temporaryValue, randomIndex;

    // While there remain elements to shuffle...
    while (0 !== currentIndex) {

        // Pick a remaining element...
        randomIndex = Math.floor(Math.random() * currentIndex);
        currentIndex -= 1;

        // And swap it with the current element.
        temporaryValue = array[currentIndex];
        array[currentIndex] = array[randomIndex];
        array[randomIndex] = temporaryValue;
    }

    return array;
}
</code>```

Then you can do something like:

```<code>myarray = [ ... ];
myarray = shuffle(myarray);

function addSomeImages(limit) {
    //note: ensure that "lastIdx + limit <= myarray.length" or you could exceed the array bounds!
    for (var i = lastIdx; i < lastIdx + limit; i++) {
        $('#endless-gallery').append('<a data-fancybox="gallery" href="' + myarray[i].big + '"><img class="photo" src="' + myarray[i].thumb + '" /></a>');
    }
}
</code>```

Body:
I am trying to get some HTML dom elements remotely from some website with jquery/javascript. These elements are in the array and unique, but when I try to print them with math.random() * my array.length i see duplicates.  I want imgIdx to be unique.

So for the sake of helping me learn, can someone help me determine what am I missing here?

myarray = [
{ thumb : "http://url.com/img1.jpg", big : "http://url.com/img51.jpg" },
{ thumb : "http://url.com/img61.jpg", big : "http://url.com/img671.jpg" },
{ thumb : "http://url.com/img666.jpg", big : "http://url.com/img371.jpg" },]

function addSomeImages(limit) {
    for (var i = lastIdx; i < lastIdx + limit; i++) {
        var imgIdx = Math.floor(Math.random() * myarray.length);
        $('#endless-gallery').append('' + '' +
            '');
    }

Body:
What's important to note that hasn't been touched from what I've noticed is why exactly your current solution isn't working, or why shuffling your array is the ideal approach. What you need to realize is that your current code is just generating a random index for you to use to access elements in your array. Much like rolling a die, it's much more likely that you'll re-roll a number than you are to roll each of the numbers without repeating. That's the entire point of (pseudo-)random number generation, that the results are effectively non-deterministic by nature.

With that in mind, in order to retrieve elements from your array randomly without repeating, you will have to find a way to exclude repeats by design. The two most practical ways to do this are to either:

1) Shuffle the array and simply iterate through it as noted in the comments on your question, or

2) Remove the accessed elements from your array and loop until the array is empty.

Of the above two, simply shuffling the array is far more practical and doesn't result in the destruction of your array (or require cloning the array and destroying the clone), so it's easily the ideal solution for you to use.

Why these work while your original solution doesn't:

Shuffling the array is a procedure by which your array contains the same exact elements as it originally contains, but are simply ordered randomly in the array. Much like the name implies, it's like shuffling a deck of cards; you'll always have your standard 52 unique cards, but they'll just be in a different order. As you flip through the shuffled cards, there's no risk of somehow coming across the same card that you've already passed.

Removing an element and looping until empty is like taking a perfectly-sorted deck of 52 unique cards and pulling a random one out from the deck repeatedly, discarding the ones you've already pulled out. If the card you pull out is no longer in the deck, you'll never be at risk of pulling the same card out.

What you're doing right now taking that perfectly-sorted deck of 52 cards, looking at a random one, and placing it back where it was in the deck before repeating the process. The card is still there, and because you're just looking at random cards it's possible for you to inadvertently look at it a second time.

Since shuffling the array and then iterating through the results normally is the ideal approach, consider using the Fisher-Yates shuffle function noted in the comments:

function shuffle(array) {
    var currentIndex = array.length, temporaryValue, randomIndex;

    // While there remain elements to shuffle...
    while (0 !== currentIndex) {

        // Pick a remaining element...
        randomIndex = Math.floor(Math.random() * currentIndex);
        currentIndex -= 1;

        // And swap it with the current element.
        temporaryValue = array[currentIndex];
        array[currentIndex] = array[randomIndex];
        array[randomIndex] = temporaryValue;
    }

    return array;
}

Then you can do something like:

myarray = [ ... ];
myarray = shuffle(myarray);

function addSomeImages(limit) {
    //note: ensure that "lastIdx + limit <= myarray.length" or you could exceed the array bounds!
    for (var i = lastIdx; i < lastIdx + limit; i++) {
        $('#endless-gallery').append('<a data-fancybox="gallery" href="' + myarray[i].big + '"><img class="photo" src="' + myarray[i].thumb + '" /></a>');
    }
}


问:
Results not being grouped when using GROUP BY on UNION ALL
I have two tables: Ambulances and Responders. The Responder table has one call_sign column and the Ambulances table has 4 columns - call_sign_1, call_sign_2, call_sign_3, call_sign_4.

I want to write a query to list every call_sign and how many times it appears in the database (i.e. how many calls each responder has attended - including the ones in ambulances). The query I've created displays some call_sign's more than once.

I'd like them to be grouped so each call_sign only appears once.

```<code>SELECT * FROM (
select call_sign as call_sign, count(call_sign) as `call_sign_count` from responders group by call_sign
UNION ALL
select call_sign_1 as call_sign, count(call_sign_1) as `call_sign_count` from ambulances group by call_sign
UNION ALL
select call_sign_2 as call_sign, count(call_sign_2) as `call_sign_count` from ambulances group by call_sign
UNION ALL
select call_sign_3 as call_sign, count(call_sign_3) as `call_sign_count` from ambulances group by call_sign
UNION ALL
select call_sign_4 as call_sign, count(call_sign_4) as `call_sign_count` from ambulances group by call_sign
)
a WHERE call_sign IS NOT NULL Group By call_sign, call_sign_count
</code>```

The databse and query can be found in this fiddle:

https://www.db-fiddle.com/f/9grxeiA277KtUqsiUbYMA8/0

答:
Yes, it displays the same call_sign multiple times because in the outer query you group by on call_sign and call_sign_count. If you want each call_sign to appear only once, then you can only group on that field and use an aggregate function on call_sign_count, let's say sum().

```<code>SELECT call_sign, sum(call_sign_count) total_call_sign_count FROM (
select call_sign as call_sign, count(call_sign) as `call_sign_count` from responders group by call_sign
UNION ALL
select call_sign_1 as call_sign, count(call_sign_1) as `call_sign_count` from ambulances group by call_sign
UNION ALL
select call_sign_2 as call_sign, count(call_sign_2) as `call_sign_count` from ambulances group by call_sign
UNION ALL
select call_sign_3 as call_sign, count(call_sign_3) as `call_sign_count` from ambulances group by call_sign
UNION ALL
select call_sign_4 as call_sign, count(call_sign_4) as `call_sign_count` from ambulances group by call_sign
)
a WHERE call_sign IS NOT NULL Group By call_sign
</code>```

Body:
I have two tables: Ambulances and Responders. The Responder table has one call_sign column and the Ambulances table has 4 columns - call_sign_1, call_sign_2, call_sign_3, call_sign_4.

I want to write a query to list every call_sign and how many times it appears in the database (i.e. how many calls each responder has attended - including the ones in ambulances). The query I've created displays some call_sign's more than once.

I'd like them to be grouped so each call_sign only appears once.

SELECT * FROM (
select call_sign as call_sign, count(call_sign) as `call_sign_count` from responders group by call_sign
UNION ALL
select call_sign_1 as call_sign, count(call_sign_1) as `call_sign_count` from ambulances group by call_sign
UNION ALL
select call_sign_2 as call_sign, count(call_sign_2) as `call_sign_count` from ambulances group by call_sign
UNION ALL
select call_sign_3 as call_sign, count(call_sign_3) as `call_sign_count` from ambulances group by call_sign
UNION ALL
select call_sign_4 as call_sign, count(call_sign_4) as `call_sign_count` from ambulances group by call_sign
)
a WHERE call_sign IS NOT NULL Group By call_sign, call_sign_count

The databse and query can be found in this fiddle:

https://www.db-fiddle.com/f/9grxeiA277KtUqsiUbYMA8/0

Body:
Yes, it displays the same call_sign multiple times because in the outer query you group by on call_sign and call_sign_count. If you want each call_sign to appear only once, then you can only group on that field and use an aggregate function on call_sign_count, let's say sum().

SELECT call_sign, sum(call_sign_count) total_call_sign_count FROM (
select call_sign as call_sign, count(call_sign) as `call_sign_count` from responders group by call_sign
UNION ALL
select call_sign_1 as call_sign, count(call_sign_1) as `call_sign_count` from ambulances group by call_sign
UNION ALL
select call_sign_2 as call_sign, count(call_sign_2) as `call_sign_count` from ambulances group by call_sign
UNION ALL
select call_sign_3 as call_sign, count(call_sign_3) as `call_sign_count` from ambulances group by call_sign
UNION ALL
select call_sign_4 as call_sign, count(call_sign_4) as `call_sign_count` from ambulances group by call_sign
)
a WHERE call_sign IS NOT NULL Group By call_sign


问:
JIRA: How to get search box to remember project code?
I use the search in JIRA about 50 times a day and every time it forgets what I just entered. Is there any way to tell it to remember the last search or the project code. (By project code I mean the first few letters of bug code such as "AAQT-").</p>

答:
That prefix is known as the project key.

(Also, what version of JIRA are you using? There are some UI differences between Cloud and most Server instances so my following advice might not make sense.)

There isn't a way to pre-define the project key in the quick search box since most JIRA instances have multiple projects, and pre-defining it for just one project doesn't make sense.

However, your browser should be able to remember previous values entered. You would have to overwrite the numerical portion that follows the key, though.


问:
How to disable dot button in android Kotlin
I am new to Android Studio - Kotlin, I am building an app with numbers and math operators with decimal point(.dot button)In my math calculator app, if press the dot button, the button should be disabled or not entered for the second time.  I want to disable or stop printing dot button(.) if pressed more than once.

Here is my code

Acitivity.kt file

```<code>package com.tripbegins.calculator
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Button
import com.tripbegins.calculator.R.id.*
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
}

var emptyText = true
fun numberEvents(view: View) {
var checkButton:Boolean = false
    if(emptyText){
        viewResult.setText("")
    }
    emptyText = false

    var button = view as Button
    var isClicked = viewResult.text.toString()
    when (button.id) {
        buttonOne.id -> isClicked += "1"
        buttonTwo.id -> isClicked += "2"
        buttonThree.id -> isClicked += "3"
        dotButton.id-> isClicked+="."
    }

    viewResult.setText(isClicked)
}

var operation ="+"
var oldValues:String? = null
fun mathOperation(view: View){
    var mathButton = view as Button
    var isClicked = viewResult.text.toString()

    when(mathButton.id){
        plusButton.id-> {
            operation = "+"
        }
        minusButton.id->{
            operation="-"
        }
        mulButton.id->{
            operation="*"
        }

    }
    oldValues = viewResult.text.toString()
    emptyText = true
}

fun Calculate(view: View){

    var newValues = viewResult.text.toString()
    var calulateButton:Double? = null
    when(operation){
        "+"-> { calulateButton = oldValues!!.toDouble() + newValues.toDouble() }
        "-"-> { calulateButton = oldValues!!.toDouble() - newValues.toDouble() }
        "*"-> { calulateButton = oldValues!!.toDouble() * newValues.toDouble() }

    }
    viewResult.setText(calulateButton.toString())
    emptyText=true
}
fun clearFunction(view: View){
    viewResult.setText("")
}
}
</code>```

activity.xml file

```<code> <?xml version="1.0" encoding="utf-8"?>
 <android.support.constraint.ConstraintLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res-auto"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 tools:context="com.tripbegins.calculator.MainActivity">

<EditText
    android:id="@+id/viewResult"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="42dp"
    android:ems="10"
    android:gravity="bottom|right"
    android:inputType="textPersonName"
    android:text="0"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<Button
    android:id="@+id/buttonTwo"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="16dp"
    android:layout_marginTop="76dp"
    android:onClick="numberEvents"
    android:text="2"
    app:layout_constraintStart_toEndOf="@+id/buttonOne"
    app:layout_constraintTop_toBottomOf="@+id/viewResult" />

<Button
    android:id="@+id/plusButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="38dp"
    android:onClick="mathOperation"
    android:text="+"
    app:layout_constraintBaseline_toBaselineOf="@+id/minusButton"
    app:layout_constraintStart_toStartOf="parent" />

<Button
    android:id="@+id/minusButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="12dp"
    android:layout_marginTop="33dp"
    android:onClick="mathOperation"
    android:text="-"
    app:layout_constraintStart_toEndOf="@+id/plusButton"
    app:layout_constraintTop_toBottomOf="@+id/buttonTwo" />

<Button
    android:id="@+id/mulButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="26dp"
    android:onClick="mathOperation"
    android:text="*"
    app:layout_constraintBaseline_toBaselineOf="@+id/minusButton"
    app:layout_constraintStart_toEndOf="@+id/minusButton" />

<Button
    android:id="@+id/calButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="44dp"
    android:onClick="Calculate"
    android:text="Calculate"
    app:layout_constraintStart_toStartOf="@+id/minusButton"
    app:layout_constraintTop_toBottomOf="@+id/minusButton" />

<Button
    android:id="@+id/buttonThree"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="26dp"
    android:onClick="numberEvents"
    android:text="3"
    app:layout_constraintBaseline_toBaselineOf="@+id/buttonTwo"
    app:layout_constraintStart_toEndOf="@+id/buttonTwo" />

<Button
    android:id="@+id/buttonOne"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="34dp"
    android:onClick="numberEvents"
    android:text="1"
    app:layout_constraintBaseline_toBaselineOf="@+id/buttonTwo"
    app:layout_constraintStart_toStartOf="parent" />

<Button
    android:id="@+id/dotButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginEnd="22dp"
    android:onClick="numberEvents"
    android:text="."
    app:layout_constraintBaseline_toBaselineOf="@+id/calButton"
    app:layout_constraintEnd_toStartOf="@+id/calButton" />

<Button
    android:id="@+id/clearButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="11dp"
    android:onClick="clearFunction"
    android:text="Clear"
    app:layout_constraintBaseline_toBaselineOf="@+id/calButton"
    app:layout_constraintStart_toEndOf="@+id/calButton" />
    </android.support.constraint.ConstraintLayout>
</code>```

My expectation of the result

Valid entry -> 3. (.dot button should not be entered for the second time)

Invalid entry -> 3... (currently i can able to enter multiple .dot buttons)

Dot button should not pressed twice. It should be active only once.

Thanks
Mohammed

答:
so you want to disable the button that has the name dotButton after the user clicks it for the first time :

to disable a button, use:

```<code>dotButton.isClickable=false
</code>```

if you want the button to become clickable again(like when the user deletes the dot that he already pressed) you can use:

```<code>dotButton.isClickable=true
</code>```

Edit:
modify your activity code like that :

```<code>when (button.id) {
        buttonOne.id -> isClicked += "1"
        buttonTwo.id -> isClicked += "2"
        buttonThree.id -> isClicked += "3"
        dotButton.id-> {
        isClicked+="."
        dotButton.isClickable=false//**add this line here**

                       }
    }

fun clearFunction(view: View){
    viewResult.setText("")
    dotButton.isClickable=true//**add this line here**
}
</code>```

Body:
I am new to Android Studio - Kotlin, I am building an app with numbers and math operators with decimal point(.dot button)In my math calculator app, if press the dot button, the button should be disabled or not entered for the second time.  I want to disable or stop printing dot button(.) if pressed more than once.

Here is my code

Acitivity.kt file

package com.tripbegins.calculator
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Button
import com.tripbegins.calculator.R.id.*
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
}

var emptyText = true
fun numberEvents(view: View) {
var checkButton:Boolean = false
    if(emptyText){
        viewResult.setText("")
    }
    emptyText = false

    var button = view as Button
    var isClicked = viewResult.text.toString()
    when (button.id) {
        buttonOne.id -> isClicked += "1"
        buttonTwo.id -> isClicked += "2"
        buttonThree.id -> isClicked += "3"
        dotButton.id-> isClicked+="."
    }

    viewResult.setText(isClicked)
}

var operation ="+"
var oldValues:String? = null
fun mathOperation(view: View){
    var mathButton = view as Button
    var isClicked = viewResult.text.toString()

    when(mathButton.id){
        plusButton.id-> {
            operation = "+"
        }
        minusButton.id->{
            operation="-"
        }
        mulButton.id->{
            operation="*"
        }

    }
    oldValues = viewResult.text.toString()
    emptyText = true
}

fun Calculate(view: View){

    var newValues = viewResult.text.toString()
    var calulateButton:Double? = null
    when(operation){
        "+"-> { calulateButton = oldValues!!.toDouble() + newValues.toDouble() }
        "-"-> { calulateButton = oldValues!!.toDouble() - newValues.toDouble() }
        "*"-> { calulateButton = oldValues!!.toDouble() * newValues.toDouble() }

    }
    viewResult.setText(calulateButton.toString())
    emptyText=true
}
fun clearFunction(view: View){
    viewResult.setText("")
}
}

activity.xml file

 <?xml version="1.0" encoding="utf-8"?>
 <android.support.constraint.ConstraintLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res-auto"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 tools:context="com.tripbegins.calculator.MainActivity">

<EditText
    android:id="@+id/viewResult"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="42dp"
    android:ems="10"
    android:gravity="bottom|right"
    android:inputType="textPersonName"
    android:text="0"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<Button
    android:id="@+id/buttonTwo"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="16dp"
    android:layout_marginTop="76dp"
    android:onClick="numberEvents"
    android:text="2"
    app:layout_constraintStart_toEndOf="@+id/buttonOne"
    app:layout_constraintTop_toBottomOf="@+id/viewResult" />

<Button
    android:id="@+id/plusButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="38dp"
    android:onClick="mathOperation"
    android:text="+"
    app:layout_constraintBaseline_toBaselineOf="@+id/minusButton"
    app:layout_constraintStart_toStartOf="parent" />

<Button
    android:id="@+id/minusButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="12dp"
    android:layout_marginTop="33dp"
    android:onClick="mathOperation"
    android:text="-"
    app:layout_constraintStart_toEndOf="@+id/plusButton"
    app:layout_constraintTop_toBottomOf="@+id/buttonTwo" />

<Button
    android:id="@+id/mulButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="26dp"
    android:onClick="mathOperation"
    android:text="*"
    app:layout_constraintBaseline_toBaselineOf="@+id/minusButton"
    app:layout_constraintStart_toEndOf="@+id/minusButton" />

<Button
    android:id="@+id/calButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="44dp"
    android:onClick="Calculate"
    android:text="Calculate"
    app:layout_constraintStart_toStartOf="@+id/minusButton"
    app:layout_constraintTop_toBottomOf="@+id/minusButton" />

<Button
    android:id="@+id/buttonThree"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="26dp"
    android:onClick="numberEvents"
    android:text="3"
    app:layout_constraintBaseline_toBaselineOf="@+id/buttonTwo"
    app:layout_constraintStart_toEndOf="@+id/buttonTwo" />

<Button
    android:id="@+id/buttonOne"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="34dp"
    android:onClick="numberEvents"
    android:text="1"
    app:layout_constraintBaseline_toBaselineOf="@+id/buttonTwo"
    app:layout_constraintStart_toStartOf="parent" />

<Button
    android:id="@+id/dotButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginEnd="22dp"
    android:onClick="numberEvents"
    android:text="."
    app:layout_constraintBaseline_toBaselineOf="@+id/calButton"
    app:layout_constraintEnd_toStartOf="@+id/calButton" />

<Button
    android:id="@+id/clearButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="11dp"
    android:onClick="clearFunction"
    android:text="Clear"
    app:layout_constraintBaseline_toBaselineOf="@+id/calButton"
    app:layout_constraintStart_toEndOf="@+id/calButton" />
    </android.support.constraint.ConstraintLayout>

My expectation of the result

Valid entry -> 3. (.dot button should not be entered for the second time)

Invalid entry -> 3... (currently i can able to enter multiple .dot buttons)

Dot button should not pressed twice. It should be active only once.

Thanks
Mohammed

Body:
so you want to disable the button that has the name dotButton after the user clicks it for the first time :

to disable a button, use:

dotButton.isClickable=false

if you want the button to become clickable again(like when the user deletes the dot that he already pressed) you can use:

dotButton.isClickable=true

Edit:
modify your activity code like that :

when (button.id) {
        buttonOne.id -> isClicked += "1"
        buttonTwo.id -> isClicked += "2"
        buttonThree.id -> isClicked += "3"
        dotButton.id-> {
        isClicked+="."
        dotButton.isClickable=false//**add this line here**

                       }
    }

fun clearFunction(view: View){
    viewResult.setText("")
    dotButton.isClickable=true//**add this line here**
}


问:
Windows 10 quick access links docfile corrupted
In Windows 10, my quick access links have been broken for a while. I upgraded to the Pro Insider build 17025 and now get a new error "The docfile has been corrupted"</p>

答:
Thanks to Alexander_ALX on Microsoft dev forums.

Type cmd in search bar, right click on Command Prompt and Run as Administrator

Run this:
del %appdata%\microsoft\windows\recent\automaticdestinations*

Close all File Explorers. When you re-open a fresh one, Quick Access will be alive again with the default settings and you can now pin folders to it


问:
Can not resolve snackbar_layout while adding firebase invitation
I'm trying to add firebase app invitation but getting this error (in the second last line of the code mentioned below):

can not resolve snackbar_layout

I've already add the dependency: compile 'com.google.firebase:firebase-invites:11.6.0' . Couldn't find the solution anywhere on the internet. Please help! Thanks in advance.

Here is the part of the code, where I'm getting this error:

```<code>// [START on_activity_result]
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    Log.d(TAG, "onActivityResult: requestCode=" + requestCode + ", resultCode=" + resultCode);

    if (requestCode == REQUEST_INVITE) {
        if (resultCode == RESULT_OK) {
            // Get the invitation IDs of all sent messages
            String[] ids = AppInviteInvitation.getInvitationIds(resultCode, data);
            for (String id : ids) {
                Log.d(TAG, "onActivityResult: sent invitation " + id);
            }
        } else {
            // Sending failed or it was canceled, show failure message to the user
            // [START_EXCLUDE]
            showMessage(getString(R.string.send_failed));
            // [END_EXCLUDE]
        }
    }
}
// [END on_activity_result]

private void showMessage(String msg) {
    ViewGroup container = findViewById(R.id.snackbar_layout);
    Snackbar.make(container, msg, Snackbar.LENGTH_SHORT).show();
}
</code>```

答:
What does the layout of your activity look like?

you need to have an actual element in your view with an ID of snackbar_layout.

you are saying, find this view, and then anchor a snackbar into it. but if that view does not exist in your layout, it has nothing to anchor to.

```<code>    <View android:id="@+id/snackbar_layout"/>
</code>```

Body:
I'm trying to add firebase app invitation but getting this error (in the second last line of the code mentioned below):

can not resolve snackbar_layout

I've already add the dependency: compile 'com.google.firebase:firebase-invites:11.6.0' . Couldn't find the solution anywhere on the internet. Please help! Thanks in advance.

Here is the part of the code, where I'm getting this error:

// [START on_activity_result]
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    Log.d(TAG, "onActivityResult: requestCode=" + requestCode + ", resultCode=" + resultCode);

    if (requestCode == REQUEST_INVITE) {
        if (resultCode == RESULT_OK) {
            // Get the invitation IDs of all sent messages
            String[] ids = AppInviteInvitation.getInvitationIds(resultCode, data);
            for (String id : ids) {
                Log.d(TAG, "onActivityResult: sent invitation " + id);
            }
        } else {
            // Sending failed or it was canceled, show failure message to the user
            // [START_EXCLUDE]
            showMessage(getString(R.string.send_failed));
            // [END_EXCLUDE]
        }
    }
}
// [END on_activity_result]

private void showMessage(String msg) {
    ViewGroup container = findViewById(R.id.snackbar_layout);
    Snackbar.make(container, msg, Snackbar.LENGTH_SHORT).show();
}

Body:
What does the layout of your activity look like?

you need to have an actual element in your view with an ID of snackbar_layout.

you are saying, find this view, and then anchor a snackbar into it. but if that view does not exist in your layout, it has nothing to anchor to.

    <View android:id="@+id/snackbar_layout"/>