问:
How to dynamically hide some options from a drop-down list using jQuery

I have two drop down list; one with states and the other with cities. I want the second list with cities to show only the cities in the selected state. Why is this not working?

$(document).ready(function($) {
  $("#state").change(function() {
    var selected_state = $("#state").val(); //get the selected state
    $("#city").children().hide(); //hide all the options
    $("#selected_state").children().show(); //only show cities in selected state
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post">
  State: <select name="state" id="state">
            <option value="state1">State1</option>
            <option value="state2">State2</option>
        </select> City:
  <select name="city" id="city">
            <div id="state1">
               <option value="0">City1a</option>
               <option value="1">City1b</option>
               <option value="2">City1c</option>
            </div>
            <div id="state2">
               <option value="3">City2a</option>
               <option value="4">City2b</option>
               <option value="5">City2c</option>
            </div>
        </select>
  <input name="submit" type="submit" value="Submit" />
</form></code>```

答:
```<code><form method="post">
State: <select name="state" id="state">
    <option value="state1">State1</option>
    <option value="state2">State2</option>
</select>
City:
    <div id="state1">
    <select name="city" id="city">
       <option value="0">City1a</option>
       <option value="1">City1b</option>
       <option value="2">City1c</option>
       </select>
    </div>
    <div id="state2">
    <select name="city" id="city">
       <option value="3">City2a</option>
       <option value="4">City2b</option>
       <option value="5">City2c</option>
    </select>
    </div>

<input name="submit" type="submit" value="Submit" />
</code>```

```<code><script type="text/javascript">
    $(document).ready(function() {
    $("#state1").hide();
    $("#state2").hide();
    $("#state").change(function() {
    var selected_state =document.getElementById("state").value;
    // $("#city").children("state1").hide(); //hide all the options
    if(selected_state === "state1"){
        alert(selected_state);
        $("#state1").show();
        $("#state2").hide();
    }else{
        $("#state1").hide();
        $("#state2").show();
    }
    //$("#selected_state").children().show(); //only show cities in selected state
    });
});
</script>
</code>```

Body:
I have two drop down list; one with states and the other with cities. I want the second list with cities to show only the cities in the selected state. Why is this not working?

$(document).ready(function($) {
  $("#state").change(function() {
    var selected_state = $("#state").val(); //get the selected state
    $("#city").children().hide(); //hide all the options
    $("#selected_state").children().show(); //only show cities in selected state
  });
});

<form method="post">
  State: <select name="state" id="state">
            <option value="state1">State1</option>
            <option value="state2">State2</option>
        </select> City:
  <select name="city" id="city">

               <option value="0">City1a</option>
               <option value="1">City1b</option>
               <option value="2">City1c</option>

               <option value="3">City2a</option>
               <option value="4">City2b</option>
               <option value="5">City2c</option>

        </select>
  <input name="submit" type="submit" value="Submit" />
</form>

Body:
<form method="post">
State: <select name="state" id="state">
    <option value="state1">State1</option>
    <option value="state2">State2</option>
</select>
City:
    <div id="state1">
    <select name="city" id="city">
       <option value="0">City1a</option>
       <option value="1">City1b</option>
       <option value="2">City1c</option>
       </select>
    </div>
    <div id="state2">
    <select name="city" id="city">
       <option value="3">City2a</option>
       <option value="4">City2b</option>
       <option value="5">City2c</option>
    </select>
    </div>

<input name="submit" type="submit" value="Submit" />

<script type="text/javascript">
    $(document).ready(function() {
    $("#state1").hide();
    $("#state2").hide();
    $("#state").change(function() {
    var selected_state =document.getElementById("state").value;
    // $("#city").children("state1").hide(); //hide all the options
    if(selected_state === "state1"){
        alert(selected_state);
        $("#state1").show();
        $("#state2").hide();
    }else{
        $("#state1").hide();
        $("#state2").show();
    }
    //$("#selected_state").children().show(); //only show cities in selected state
    });
});
</script>


来源: stackexchange

问:
spacing between UITableViewCells swift3
I am creating a IOS app in swift and want to add spacing between cells like this

I would like to give space of each table view cell same like my attach image.
How I can do that? and Right now all cells are coming without any space.
swift3

答:
From Storyboard,  your view hierarchy should be like this. View CellContent (as highlighted) will contain all the components.

Give margin to View CellContent of 10px from top, bottom, leading & trailing from its superview.

Now, select the tblCell and change the background color.

Now run your project, make sure delegate and datasource are properly binded.

OUTPUT

NOTE: I just added 1 UILabel in View CellContent for dummy purpose.

ContentLicense: CC BY-SA 3.0

Title: spacing between UITableViewCells swift3


问:
Find Whole Months from date range java
I have two dates:

```<code>Start Date: 2017-01-15
End Date: 2017-05-27
</code>```

Now I want to find the whole month between these two dates. So the result should be:

```<code>Feb-2017
Mar-2017
Apr-2017
</code>```

January is not included in the result because start date starts from the middle of the month and May is not included because end date does not cover whole May month.

How can I achieve this with Java?

I have tried doing something like:

```<code>String date1 = "2015-01-15";
String date2 = "2015-05-27";

DateFormat formater1 = new SimpleDateFormat("MMM-yyyy");
DateFormat formater = new SimpleDateFormat("yyyy-MM-dd");

Calendar startCalendar = Calendar.getInstance();
Calendar endCalendar = Calendar.getInstance();

try {
    startCalendar.setTime(formater.parse(date1));
    endCalendar.setTime(formater.parse(date2));
} catch (ParseException e) {
    e.printStackTrace();
}

System.out.println("startDate:" + startCalendar.getTime());
System.out.println("endCalendar:" + endCalendar.getTime());

while (startCalendar.before(endCalendar)) {
    // add one month to date per loop
    String date = formater1.format(startCalendar.getTime()).toUpperCase();
    System.out.println(date);
    startCalendar.add(Calendar.MONTH, 1);
}
</code>```

But I don't know how to exclude Jan and May from the result. Currently, I am getting this result:

```<code>JAN-2015
FEB-2015
MAR-2015
APR-2015
MAY-2015
</code>```

答:
I have written a program that is not using Months and Date formatter, I am handling all formatting manually.

```<code>public class cn {

    public enum Months {JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC}

    public static void main(String arg[]) {

        String s = "2015-01-15";
        String e = "2016-05-27";
        String s1[] = s.split("-");
        String e1[] = e.split("-");
        int syear = Integer.parseInt(s1[0]);
        int smonth = Integer.parseInt(s1[1]);
        int sday = Integer.parseInt(s1[2]);
        int fyear = Integer.parseInt(e1[0]);
        int fmonth = Integer.parseInt(e1[1]);
        int fday = Integer.parseInt(e1[0]);

        if (syear == fyear) {
            for (int i = smonth + 1; i < fmonth; i++) {
                System.out.println(Months.values()[i] + "-" + syear);
            }
        } else {
            int i = 0;

            while (syear <= fyear) {
                if (syear < fyear) {
                    for (i = smonth + 1; i < 12; i++) {
                        System.out.println(Months.values()[i] + "-" + syear);
                    }
                    i = 1;
                    syear++;
                } else {
                    for (; i < fmonth; i++) {
                        System.out.println(Months.values()[i] + "-" + syear);
                    }
                }
            }
        }
    }
}
</code>```

EDIT:

Above program works for different year also.

Title: Find Whole Months from date range java

Body:
I have two dates:

Start Date: 2017-01-15
End Date: 2017-05-27

Now I want to find the whole month between these two dates. So the result should be:

Feb-2017
Mar-2017
Apr-2017

January is not included in the result because start date starts from the middle of the month and May is not included because end date does not cover whole May month.

How can I achieve this with Java?

I have tried doing something like:

String date1 = "2015-01-15";
String date2 = "2015-05-27";

DateFormat formater1 = new SimpleDateFormat("MMM-yyyy");
DateFormat formater = new SimpleDateFormat("yyyy-MM-dd");

Calendar startCalendar = Calendar.getInstance();
Calendar endCalendar = Calendar.getInstance();

try {
    startCalendar.setTime(formater.parse(date1));
    endCalendar.setTime(formater.parse(date2));
} catch (ParseException e) {
    e.printStackTrace();
}

System.out.println("startDate:" + startCalendar.getTime());
System.out.println("endCalendar:" + endCalendar.getTime());

while (startCalendar.before(endCalendar)) {
    // add one month to date per loop
    String date = formater1.format(startCalendar.getTime()).toUpperCase();
    System.out.println(date);
    startCalendar.add(Calendar.MONTH, 1);
}

But I don't know how to exclude Jan and May from the result. Currently, I am getting this result:

JAN-2015
FEB-2015
MAR-2015
APR-2015
MAY-2015

Body:
I have written a program that is not using Months and Date formatter, I am handling all formatting manually.

public class cn {

    public enum Months {JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC}

    public static void main(String arg[]) {

        String s = "2015-01-15";
        String e = "2016-05-27";
        String s1[] = s.split("-");
        String e1[] = e.split("-");
        int syear = Integer.parseInt(s1[0]);
        int smonth = Integer.parseInt(s1[1]);
        int sday = Integer.parseInt(s1[2]);
        int fyear = Integer.parseInt(e1[0]);
        int fmonth = Integer.parseInt(e1[1]);
        int fday = Integer.parseInt(e1[0]);

        if (syear == fyear) {
            for (int i = smonth + 1; i < fmonth; i++) {
                System.out.println(Months.values()[i] + "-" + syear);
            }
        } else {
            int i = 0;

            while (syear <= fyear) {
                if (syear < fyear) {
                    for (i = smonth + 1; i < 12; i++) {
                        System.out.println(Months.values()[i] + "-" + syear);
                    }
                    i = 1;
                    syear++;
                } else {
                    for (; i < fmonth; i++) {
                        System.out.println(Months.values()[i] + "-" + syear);
                    }
                }
            }
        }
    }
}

EDIT:

Above program works for different year also.


问:
Django join multiple models using django ORM
I googled and read many articles but got confused in multiple table join.
My models looks like-

```<code>class ProductCategory(models.Model):
    category_name = models.CharField(max_length=200,blank=True, null=True, unique=True)
    category_image = models.ImageField(upload_to='category', null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True)
    updated_at = models.DateTimeField(auto_now=True, blank=True, null=True)
    status = models.CharField(max_length=10, default='Active', choices=status)

    def __unicode__(self):
        return '%s' % ( self.category_name)

class ProductSubCategory(models.Model):
    category = models.ForeignKey(ProductCategory)
    sub_category_name = models.CharField(max_length=200,blank=True, null=True, unique=True)
    created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True)
    updated_at = models.DateTimeField(auto_now=True, blank=True, null=True)
    sub_category_image = models.ImageField(upload_to='subcategory', null=True, blank=True)
    status = models.CharField(max_length=10, default='Active', choices=status)

    def __unicode__(self):
        return '%s' % ( self.sub_category_name)

class Product(models.Model):
    category = models.ForeignKey(ProductCategory)
    sub_category = models.ForeignKey(ProductSubCategory)
    product_name = models.CharField(max_length=200,blank=True, null=True)
    product_price = models.FloatField(default=0)
    created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True)
    updated_at = models.DateTimeField(auto_now=True, blank=True, null=True)
    # is_discountable = models.CharField(max_length=3, default='Yes', choices=option)
    status = models.CharField(max_length=10, default='Active', choices=status)

    def __unicode__(self):
        return '%s' % ( self.product_name)

class ProductColor(models.Model):
    product = models.ForeignKey(Product)
    product_color = models.ForeignKey(Color, related_name='product_color_id', blank=True, null=True)
    product_size = models.ForeignKey(Size, related_name='product_size_id', blank=True, null=True)

class ProductImages(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE, blank=True, null=True)
    product_image = models.ImageField(upload_to='images', null=True, blank=True)
</code>```

Now in views, I want to get the product filters according to category and sub-category having all the images and colors. Query is something like-

```<code>SELECT product.*, productcolor.*, productimage.* FROM product
LEFT JOIN productcolor ON productcolor.product_id = product.id
LEFT JOIN productcolor.product_id = product.id
LEFT JOIN productimage ON productimage.product_id = product.id
WHERE product.category_id=1 and product.sub_category_id=1
</code>```

Body:
I googled and read many articles but got confused in multiple table join.
My models looks like-

class ProductCategory(models.Model):
    category_name = models.CharField(max_length=200,blank=True, null=True, unique=True)
    category_image = models.ImageField(upload_to='category', null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True)
    updated_at = models.DateTimeField(auto_now=True, blank=True, null=True)
    status = models.CharField(max_length=10, default='Active', choices=status)

    def __unicode__(self):
        return '%s' % ( self.category_name)

class ProductSubCategory(models.Model):
    category = models.ForeignKey(ProductCategory)
    sub_category_name = models.CharField(max_length=200,blank=True, null=True, unique=True)
    created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True)
    updated_at = models.DateTimeField(auto_now=True, blank=True, null=True)
    sub_category_image = models.ImageField(upload_to='subcategory', null=True, blank=True)
    status = models.CharField(max_length=10, default='Active', choices=status)

    def __unicode__(self):
        return '%s' % ( self.sub_category_name)

class Product(models.Model):
    category = models.ForeignKey(ProductCategory)
    sub_category = models.ForeignKey(ProductSubCategory)
    product_name = models.CharField(max_length=200,blank=True, null=True)
    product_price = models.FloatField(default=0)
    created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True)
    updated_at = models.DateTimeField(auto_now=True, blank=True, null=True)
    # is_discountable = models.CharField(max_length=3, default='Yes', choices=option)
    status = models.CharField(max_length=10, default='Active', choices=status)

    def __unicode__(self):
        return '%s' % ( self.product_name)

class ProductColor(models.Model):
    product = models.ForeignKey(Product)
    product_color = models.ForeignKey(Color, related_name='product_color_id', blank=True, null=True)
    product_size = models.ForeignKey(Size, related_name='product_size_id', blank=True, null=True)

class ProductImages(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE, blank=True, null=True)
    product_image = models.ImageField(upload_to='images', null=True, blank=True)

Now in views, I want to get the product filters according to category and sub-category having all the images and colors. Query is something like-

SELECT product.*, productcolor.*, productimage.* FROM product
LEFT JOIN productcolor ON productcolor.product_id = product.id
LEFT JOIN productcolor.product_id = product.id
LEFT JOIN productimage ON productimage.product_id = product.id
WHERE product.category_id=1 and product.sub_category_id=1

Body: ProductCategory.productsubcategory_set.all()


问:
Regex to include white space and then verify a character
I have a pattern to search around web but im new to it and unable to verify it.

Im looking for example

[verify if any whitespace]  [any of this char ':' '|' ';']   [verify if any whitespace]   [[String a-zA-Z0-9-]+]

Suppose Test String -

" : hello129 "  or ":hello129" or ";hello129" or "|hello129" or " | hello129"

My attemps

```<code> \s[:;|]\s[a-zA-Z0-9_.+-]+

(\w+\s\w+):(\w+\s\w+)[a-zA-Z0-9_.+-]+
</code>```

Please suggest me possible solutions for this pattern in regex/regular expressions

Thank you in advance :)

答:
Whitespace is represented with \s. The other groups are easily written in brackets.
Whitespace could by one or more characters, so the + modifier will be necessary. If Whitespace was optional, the * would have been okay as well. If only one character of whitespace would be allowed, we would leave the modifier out.
The string in the end is one or more characters long and needs the + as well.

The result is a regular expression like this:

```<code>\s+[:;|]\s+[a-zA-Z0-9-]+
</code>```

Here is an example including tests on the great RegEx testing site regex101.com.

Body:
I have a pattern to search around web but im new to it and unable to verify it.

Im looking for example

[verify if any whitespace]  [any of this char ':' '|' ';']   [verify if any whitespace]   [[String a-zA-Z0-9-]+]

Suppose Test String -

" : hello129 "  or ":hello129" or ";hello129" or "|hello129" or " | hello129"

My attemps

 \s[:;|]\s[a-zA-Z0-9_.+-]+

(\w+\s\w+):(\w+\s\w+)[a-zA-Z0-9_.+-]+

Please suggest me possible solutions for this pattern in regex/regular expressions

Thank you in advance :)

Body:
Whitespace is represented with \s. The other groups are easily written in brackets.
Whitespace could by one or more characters, so the + modifier will be necessary. If Whitespace was optional, the * would have been okay as well. If only one character of whitespace would be allowed, we would leave the modifier out.
The string in the end is one or more characters long and needs the + as well.

The result is a regular expression like this:

\s+[:;|]\s+[a-zA-Z0-9-]+

Here is an example including tests on the great RegEx testing site regex101.com.


问:
Python Access Granted
I was given this program and it works.

```<code>#######################################################################
## This program simulates a login screen.
## The username and passwords are stored in an input file.
#######################################################################

f=open('usernames.txt')
usernames=[]
passwords=[]

for index in range(10):
    line = f.readline().strip()
    usernames.append(line)
    line = f.readline().strip()
    passwords.append(line)

user = input("Username: ")
found = False
for index in range(10):
     if user == usernames[index]:
         found = True
         passwrd = input("Password: ")
         if passwrd == passwords[index]:
             print("Access Granted")
         else :
             print("Username and password do not match")
         break
if (not found):
    print("Username not found")
</code>```

I need to modify this program so that it repeatedly asks for a valid username and password until access is granted. I think this is supposed to be really simple and the reason why I'm having so much trouble is the fact that I don't understand why the call of strip() needs to be there. I don't understand how the program is matching an index of the text file with the index directly after it.

答:
```<code>f = open('usernames.txt', 'r')  # you must to setup mode of opening file each time. In this case mode 'r'- read
usernames = []
granted = False

for line in f:
    # read file line by line
    usernames.append(line.strip())

if len(usernames) % 2 != 0:
    # checking that file have even numbers of lines
    print('Bad input file. Last string will be ignored')
    usernames.pop()  # removing of last string

def auth():
    user = input("Username: ")
    try:  # with try we can catch any exceptions
        index = usernames.index(user)   # check that our list have username and get index of it
        if index % 2 != 0:  # checking that it username
            print("Username not found")
            return False
    except:  # if usernames is not contained user string we catch of exception
        print("Username not found")
        return False

    passwrd = input("Password: ")
    if passwrd == usernames[index+1]:
        print("Access Granted")
        return True

    else:
        print("Username and password do not match")
        return False

while not granted:
    granted = auth()
</code>```

Title: Python Access Granted

Body:
I was given this program and it works.

#######################################################################
## This program simulates a login screen.
## The username and passwords are stored in an input file.
#######################################################################

f=open('usernames.txt')
usernames=[]
passwords=[]

for index in range(10):
    line = f.readline().strip()
    usernames.append(line)
    line = f.readline().strip()
    passwords.append(line)

user = input("Username: ")
found = False
for index in range(10):
     if user == usernames[index]:
         found = True
         passwrd = input("Password: ")
         if passwrd == passwords[index]:
             print("Access Granted")
         else :
             print("Username and password do not match")
         break
if (not found):
    print("Username not found")

I need to modify this program so that it repeatedly asks for a valid username and password until access is granted. I think this is supposed to be really simple and the reason why I'm having so much trouble is the fact that I don't understand why the call of strip() needs to be there. I don't understand how the program is matching an index of the text file with the index directly after it.


问:
Default Chinese Characters in SSRS
We use SSRS (2008 R2) to present data from several languages. We use labels with the Arial font. If the characters loaded from the database cannot be presented by Arial, SSRS converts them automatically to the relevant font that includes the special characters.
It works well with several languages. However, with Chinese the default choice of SSRS is font MingLiu. This font is quite uncommon in mainland China and the locals say that it is unusable. I would like to use the SimSun font instead.
How do I configure SSRS to force SimSun instead of MingLiu? Of course, I can create new labels with the SimSun font, but that will require recreation of all the existing reports that are already configured with Arial.

Thanks

答:
My boss found a solution to force the SimSun font:

Each one of the report's Placeholder should be configured as HTML.
This is done via the placeholder's properties / General, and then
choose "HTML - Interpret HTML tags as styles" instead of the default
"None - Plain text only"

The value to be assigned to the placeholder should
include the HTML tags to force the SimSun font. For example: 订单确认

Title: Default Chinese Characters in SSRS

Body:
My boss found a solution to force the SimSun font:

Each one of the report's Placeholder should be configured as HTML.
This is done via the placeholder's properties / General, and then
choose "HTML - Interpret HTML tags as styles" instead of the default
"None - Plain text only"

The value to be assigned to the placeholder should
include the HTML tags to force the SimSun font. For example: <font face="SimSun">订单确认</font>


问:
Concurrency problem
We got an old system here in .NET 4.0 using an Oracle DB.
At some point, some calculus are made and the system "locks" that register in the table using the following command: "SELECT [the registry that will be update by the calculus] FOR UPDATE NOWAIT". So if anyone tries to calculate or update the registry with that ID it won't work.
After calculating, the system connects to the DB again and then "releases" the registry by simply executing a Rollback command.

Theoretically, this is correct for the system(altought I don't like it).

Anyway, here is the thing: if something is being calculated(and these calculous take like 5 minutes to finish) and in the middle of the calculous I close the browser, the registry will still be "locked", only being unlocked when IIS restarts(actually I dunno if it's released first, I forced IIS restart 'cause it was taking too long).

Could anybody give me a light about how to deal with that?
Or if you guys have a better approach to deal with this tipe of concurrency, I'll be greatful.

Thanks!
Gabriel.

Adding some code.
Before starting the calculus, this method is called:

```<code>Public Shared Sub LockAndUnlock(ByVal pTable As String, ByVal pWhere As String, ByVal pConnectionString As String, ByVal pLock As Boolean)

    Dim vConnection As OleDbConnection = New OleDbConnection(pConnectionString)
    Dim vCommand As OleDbCommand = New OleDbCommand

    Try
        vCommand.Connection = vConnection
        If (pLock) Then
            vCommand.CommandText = "SELECT * " &
                                   "  FROM   " & pTable &
                                   " WHERE   " & pWhere &
                                   " FOR UPDATE NOWAIT"

            vConnection.Open()
            vCommand.ExecuteNonQuery()
        Else
            vCommand.CommandText = "ROLLBACK"

            If (vConnection.State = ConnectionState.Closed) Then
                vConnection.Open()
            End If

            vCommand.ExecuteNonQuery()
            vConnection.Close()
        End If

    Catch ex As Exception
        Throw ex
    End Try
End Sub
</code>```

If the parameter pLock is True then the method locks. Otherwise, it unlocks.

答:
It doesn't depend upon the browser because the transaction is executing in the Oracle server which is connected to by the (ASP?).NET client. Killing IIS will unlock it because it severs the connection between the DB server and the DB client which the transaction is running on.

Now, here-in lies sort of the crux of the problem :-) One could use polling from the web-client and have the server detect when not enough polls have been received. However, this has the big problem that there is (generally) no way to make sure the web-service worker that started the transaction is resumed (I think this can be done with some continuation setups, but they aren't common [yet].)

So, here I propose two methods:

1) Have an additional broker, such as a system service that can be given commands from the web-server, in addition to some kind of web-client poll. This would start any transactions, assign ids, automatically abort if polls stopped coming in, etc. This would make it possible to always "connect back" to the correct transaction to abort or pickup results or whatnot. Yuck.

2) Since the web-service worker is "busy" and can't be used by other connections until the transaction completes anyway... just have the web-server keep the web-client connection alive until the DB transaction completes (e.g. the request would be opened in a new browser window that would read: "Closing this will abort request <spinning thing>"). Of course, this depends on 1) the ability for the particular server to stream content 2) the ability (implicit/explicit) of making sure the transaction is closed when the request completes normally or when the stream is disconnected -- I have never tried in (ASP?).NET. Still yuck.

Edit: The second example could be done without streaming content -- e.g. hidden behind an AJAX call or IFRAME on a "let the user know the transaction is going on page". The key thing is that it needs to be setup so when web transaction ends, it will terminate the database transaction near-immediately. This will depend upon web-server.

For ASP.NET, see Response Stream as a way, with threading, to stream and/or detect a broken HTTP response connection.

ContentLicense: CC BY-SA 2.5

Title: Concurrency problem

Body:
We got an old system here in .NET 4.0 using an Oracle DB.
At some point, some calculus are made and the system "locks" that register in the table using the following command: "SELECT [the registry that will be update by the calculus] FOR UPDATE NOWAIT". So if anyone tries to calculate or update the registry with that ID it won't work.
After calculating, the system connects to the DB again and then "releases" the registry by simply executing a Rollback command.

Theoretically, this is correct for the system(altought I don't like it).

Anyway, here is the thing: if something is being calculated(and these calculous take like 5 minutes to finish) and in the middle of the calculous I close the browser, the registry will still be "locked", only being unlocked when IIS restarts(actually I dunno if it's released first, I forced IIS restart 'cause it was taking too long).

Could anybody give me a light about how to deal with that?
Or if you guys have a better approach to deal with this tipe of concurrency, I'll be greatful.

Thanks!
Gabriel.

Adding some code.
Before starting the calculus, this method is called:

Public Shared Sub LockAndUnlock(ByVal pTable As String, ByVal pWhere As String, ByVal pConnectionString As String, ByVal pLock As Boolean)

    Dim vConnection As OleDbConnection = New OleDbConnection(pConnectionString)
    Dim vCommand As OleDbCommand = New OleDbCommand

    Try
        vCommand.Connection = vConnection
        If (pLock) Then
            vCommand.CommandText = "SELECT * " &
                                   "  FROM   " & pTable &
                                   " WHERE   " & pWhere &
                                   " FOR UPDATE NOWAIT"

            vConnection.Open()
            vCommand.ExecuteNonQuery()
        Else
            vCommand.CommandText = "ROLLBACK"

            If (vConnection.State = ConnectionState.Closed) Then
                vConnection.Open()
            End If

            vCommand.ExecuteNonQuery()
            vConnection.Close()
        End If

    Catch ex As Exception
        Throw ex
    End Try
End Sub

If the parameter pLock is True then the method locks. Otherwise, it unlocks.


问:
Why should I use One tap sign in over Chrome's Credential Management API
Am a bit confused about the One tap sign in that was announced by google earlier this year. Our application already users Credential Management API in Chrome, which essentially provides the user with login options based on the credentials that user has saved for our site on previous visit (passwords that are saved in chrome). When I read the documentation for One tap sign in, it promises to do the same thing, but using Google's client api id. Our application has its own ID provider with our own database of user name and passwords, from the documentation it looks like One Tap sign in does not support custom ID providers. Can anyone shed more light on this, why would I use one against the other?

Thanks
Karthik

答:
I lead product development at Google for the one-tap/auto sign-in library, we designed it such that the library includes the Credential Management API and extends to provide assistance in account creation, secure passwordless, and cross-browsers support.

In particular, if you make a request for existing credentials with code like this:

```<code>googleyolo.retrieve({
  supportedAuthMethods: [
    "https://accounts.google.com",
    "googleyolo://id-and-password"
  ],
  supportedIdTokenProviders: [
    { uri: "https://accounts.google.com", clientId: "CLIENT_ID" }
  ]
});
</code>```

then any saved username/passwords from the Credential Management API will be returned (in browsers supporting the API) along with token data for Google Accounts. The one-tap/auto sign-in JavaScript library wraps the Credential Management API for credential retrieval.

Furthermore, the library provides a googleyolo.hint method to show an email selector for one-tap selection of a verified email address to assist in new account creation, or to link to an existing account, and then be auto signed-in next time with token instead of password, across all browsers, so long as the same Google Account is active.

I'd suggest using the one-tap/auto sign-in library and consuming tokens as well as passwords in order to get assisted sign-up, keep existing users signed-in automatically, and provide functionality even if the browser does not support the Credential Management API.

As for the question about using your own database of username / password, the hope with this library is you could implement the ability to create accounts and auto sign-in to these and existing accounts with an OpenID Connect ID tokens representing the user's identity. With the one-tap / auto sign-in UX, these are not only much more usable, but far more secure then passwords and mitigate creation of weak/re-used passwords. Please consider this or, even better, a hosted auth solution like Firebase Auth or Auth0 and include the one-tap UX in the frontend UI.

Body:
I lead product development at Google for the one-tap/auto sign-in library, we designed it such that the library includes the Credential Management API and extends to provide assistance in account creation, secure passwordless, and cross-browsers support.

In particular, if you make a request for existing credentials with code like this:

googleyolo.retrieve({
  supportedAuthMethods: [
    "https://accounts.google.com",
    "googleyolo://id-and-password"
  ],
  supportedIdTokenProviders: [
    { uri: "https://accounts.google.com", clientId: "CLIENT_ID" }
  ]
});

then any saved username/passwords from the Credential Management API will be returned (in browsers supporting the API) along with token data for Google Accounts. The one-tap/auto sign-in JavaScript library wraps the Credential Management API for credential retrieval.

Furthermore, the library provides a googleyolo.hint method to show an email selector for one-tap selection of a verified email address to assist in new account creation, or to link to an existing account, and then be auto signed-in next time with token instead of password, across all browsers, so long as the same Google Account is active.

I'd suggest using the one-tap/auto sign-in library and consuming tokens as well as passwords in order to get assisted sign-up, keep existing users signed-in automatically, and provide functionality even if the browser does not support the Credential Management API.

As for the question about using your own database of username / password, the hope with this library is you could implement the ability to create accounts and auto sign-in to these and existing accounts with an OpenID Connect ID tokens representing the user's identity. With the one-tap / auto sign-in UX, these are not only much more usable, but far more secure then passwords and mitigate creation of weak/re-used passwords. Please consider this or, even better, a hosted auth solution like Firebase Auth or Auth0 and include the one-tap UX in the frontend UI.


问:
Error when Generating Signed apk
This error occurs but on simple apk it generates the apk, kindly tell me solution for this issue.

this is my screen shot

Above is my manifest file i define icon find solution yet although many people mentioned same issue

答:
Use this code in your gradle file:</p>

```<code>android {
    buildTypes {
    release {
        minifyEnabled true
        shrinkResources true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}

lintOptions {
    checkReleaseBuilds false
    // Or, if you prefer, you can continue to check for errors in release builds,
    // but continue the build even when errors are found:
    abortOnError false
    }
}
</code>```

Title: Error when Generating Signed apk

Body:
Use this code in your gradle file:

android {
    buildTypes {
    release {
        minifyEnabled true
        shrinkResources true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}

lintOptions {
    checkReleaseBuilds false
    // Or, if you prefer, you can continue to check for errors in release builds,
    // but continue the build even when errors are found:
    abortOnError false
    }
}


问:
Access Sharepoint list using client Id and Client secret in asp.net C#
Currently, I'm able to access sharepoint list using user id and password as given below. But would like to understand on how can i access the list using Client Id and Client secret ?</p>

```<code>string siteUrl = "https://xyz.sharepoint.com/sites/MyList/";
ClientContext clientContext = new ClientContext(siteUrl);
string username = ConfigurationManager.AppSettings["username"];
string password = ConfigurationManager.AppSettings["password"];
System.Security.SecureString passWord = new System.Security.SecureString();
foreach (char c in password.ToCharArray())
{
    passWord.AppendChar(c);
}

clientContext.Credentials = new SharePointOnlineCredentials(username, passWord);
Web oWebsite = clientContext.Web;
ListCollection collList = oWebsite.Lists;
clientContext.Load(collList);
clientContext.ExecuteQuery();
</code>```

答:
You can use the GetAppOnlyAuthenticatedContext method of PnP CSOM core.

After that you can use the code as below:

```<code>string siteUrl = "https://xyz.sharepoint.com/sites/MyList/";
string clientId = "<client-id>";
string clientSecret = "<client-secret>";

using (var clientContext = new AuthenticationManager().GetAppOnlyAuthenticatedContext(siteUrl,clientId,clientSecret))
{
    Web oWebsite = clientContext.Web;
    ListCollection collList = oWebsite.Lists;
    clientContext.Load(collList);
    clientContext.ExecuteQuery();
}
</code>```

To add PnP CSOM core, go to your project references > manage nuget packages.

Add the SharePointPnPCoreOnline package.

References - Authenticate SharePoint using PnP Authentication Manager

Expose on public web your SharePoint Online information

Body:
Currently, I'm able to access sharepoint list using user id and password as given below. But would like to understand on how can i access the list using Client Id and Client secret ?

string siteUrl = "https://xyz.sharepoint.com/sites/MyList/";
ClientContext clientContext = new ClientContext(siteUrl);
string username = ConfigurationManager.AppSettings["username"];
string password = ConfigurationManager.AppSettings["password"];
System.Security.SecureString passWord = new System.Security.SecureString();
foreach (char c in password.ToCharArray())
{
    passWord.AppendChar(c);
}

clientContext.Credentials = new SharePointOnlineCredentials(username, passWord);
Web oWebsite = clientContext.Web;
ListCollection collList = oWebsite.Lists;
clientContext.Load(collList);
clientContext.ExecuteQuery();

Body:
You can use the GetAppOnlyAuthenticatedContext method of PnP CSOM core.

After that you can use the code as below:

string siteUrl = "https://xyz.sharepoint.com/sites/MyList/";
string clientId = "<client-id>";
string clientSecret = "<client-secret>";

using (var clientContext = new AuthenticationManager().GetAppOnlyAuthenticatedContext(siteUrl,clientId,clientSecret))
{
    Web oWebsite = clientContext.Web;
    ListCollection collList = oWebsite.Lists;
    clientContext.Load(collList);
    clientContext.ExecuteQuery();
}

To add PnP CSOM core, go to your project references > manage nuget packages.

Add the SharePointPnPCoreOnline package.

References - Authenticate SharePoint using PnP Authentication Manager

Expose on public web your SharePoint Online information


问:
How to make nested async requests in jquery?
inside main.js:

```<code>$.when(
    $.get('foo/bar.html'),
    $.get('lorem/ipsum.html')
).done(function(data1, data2){
     someCode();
});
</code>```

inside lorem/ipsum.html:

```<code>$.when(
    $.get('otherStuff.html'),
    $.get('example.html')
).done(function(data1, data2){
     moreCode();
});
</code>```

How can I make someCode() run after moreCode()?

答:
It should be,</p>

```<code>$.when( $.ajax( url ), $.ajax( otherUrl ) )
 .then( myFunc, myFailure );

function myFunc(){
   //get called on success.
}

function myFailure (){
   //get called, if either one has an error.
}
</code>```

Body:
inside main.js:

$.when(
    $.get('foo/bar.html'),
    $.get('lorem/ipsum.html')
).done(function(data1, data2){
     someCode();
});

inside lorem/ipsum.html:

$.when(
    $.get('otherStuff.html'),
    $.get('example.html')
).done(function(data1, data2){
     moreCode();
});

How can I make someCode() run after moreCode()?

Body:
It should be,

$.when( $.ajax( url ), $.ajax( otherUrl ) )
 .then( myFunc, myFailure );

function myFunc(){
   //get called on success.
}

function myFailure (){
   //get called, if either one has an error.
}


答:
You can use optgroup tag, instead divs, to wrap your options, so your HTML will look like this:

```<code><form method="post">
    State: <select name="state" id="state">
        <option value="state1">State1</option>
        <option value="state2">State2</option>
    </select>
    City:
    <select name="city" id="city">
        <optgroup label="state1" id='state1'>
           <option value="0">City1a</option>
           <option value="1">City1b</option>
           <option value="2">City1c</option>
        </optgroup>
        <optgroup label="state2" id='state2'>
           <option value="3">City2a</option>
           <option value="4">City2b</option>
           <option value="5">City2c</option>
        </optgroup>
    </select>
    <input name="submit" type="submit" value="Submit" />
</form>
</code>```

And then, few small changes in your code:

```<code>$("#state").change(function() {
    var selected_state =$("#state").val(); //get the selected state

    $("#city optgroup").not('#'+selected_state).hide();
    $("#"+selected_state).show(); //only show cities in selected state
    $('#city').val($("#"+selected_state).children().first().val());

});
</code>```

Demo:

 $("#state").change(function() {
        var selected_state =$("#state").val(); //get the selected state

        $("#city optgroup").not('#'+selected_state).hide();
        $("#"+selected_state).show(); //only show cities in selected state
        $('#city').val($("#"+selected_state).children().first().val());

    });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post">
    State: <select name="state" id="state">
        <option value="state1">State1</option>
        <option value="state2">State2</option>
    </select>
    City:
    <select name="city" id="city">
        <optgroup label="state1" id='state1'>
           <option value="0">City1a</option>
           <option value="1">City1b</option>
           <option value="2">City1c</option>
        </optgroup>
        <optgroup label="state2" id='state2'>
           <option value="3">City2a</option>
           <option value="4">City2b</option>
           <option value="5">City2c</option>
        </optgroup>
    </select>
    <input name="submit" type="submit" value="Submit" />
</form></code>```

As you can see, now code pointing to variable (id is variable), and your html is valid (no divs iniside select).

Title: How to dynamically hide some options from a drop-down list using jQuery

Body:
I have two drop down list; one with states and the other with cities. I want the second list with cities to show only the cities in the selected state. Why is this not working?

$(document).ready(function($) {
  $("#state").change(function() {
    var selected_state = $("#state").val(); //get the selected state
    $("#city").children().hide(); //hide all the options
    $("#selected_state").children().show(); //only show cities in selected state
  });
});

<form method="post">
  State: <select name="state" id="state">
            <option value="state1">State1</option>
            <option value="state2">State2</option>
        </select> City:
  <select name="city" id="city">

               <option value="0">City1a</option>
               <option value="1">City1b</option>
               <option value="2">City1c</option>

               <option value="3">City2a</option>
               <option value="4">City2b</option>
               <option value="5">City2c</option>

        </select>
  <input name="submit" type="submit" value="Submit" />
</form>

Body:
You can use optgroup tag, instead divs, to wrap your options, so your HTML will look like this:

<form method="post">
    State: <select name="state" id="state">
        <option value="state1">State1</option>
        <option value="state2">State2</option>
    </select>
    City:
    <select name="city" id="city">
        <optgroup label="state1" id='state1'>
           <option value="0">City1a</option>
           <option value="1">City1b</option>
           <option value="2">City1c</option>
        </optgroup>
        <optgroup label="state2" id='state2'>
           <option value="3">City2a</option>
           <option value="4">City2b</option>
           <option value="5">City2c</option>
        </optgroup>
    </select>
    <input name="submit" type="submit" value="Submit" />
</form>

And then, few small changes in your code:

$("#state").change(function() {
    var selected_state =$("#state").val(); //get the selected state

    $("#city optgroup").not('#'+selected_state).hide();
    $("#"+selected_state).show(); //only show cities in selected state
    $('#city').val($("#"+selected_state).children().first().val());

});

Demo:

 $("#state").change(function() {
        var selected_state =$("#state").val(); //get the selected state

        $("#city optgroup").not('#'+selected_state).hide();
        $("#"+selected_state).show(); //only show cities in selected state
        $('#city').val($("#"+selected_state).children().first().val());

    });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post">
    State: <select name="state" id="state">
        <option value="state1">State1</option>
        <option value="state2">State2</option>
    </select>
    City:
    <select name="city" id="city">
        <optgroup label="state1" id='state1'>
           <option value="0">City1a</option>
           <option value="1">City1b</option>
           <option value="2">City1c</option>
        </optgroup>
        <optgroup label="state2" id='state2'>
           <option value="3">City2a</option>
           <option value="4">City2b</option>
           <option value="5">City2c</option>
        </optgroup>
    </select>
    <input name="submit" type="submit" value="Submit" />
</form>

As you can see, now code pointing to variable (id is variable), and your html is valid (no divs iniside select).


问:
Developer2000 OPEN_FORM built-in
I am a newbie in Developer2000.
I have an Oracle pl/sql procedure (say, proc_submit_request) that fetches thousands of requests and submits them to dbms_job scheduler. The calling of dbms_job is

coded inside a loop for each request fetched.

Currently, i have a button (say, SUBMIT button) in oracle forms screen clicking which calls proc_submit_request.
The problem here is... the control does not return to my screen untill ALL of the requests fetched are submitted to the dbms_job (this takes hours to complete)
The screen grays out and just the hour-glass appears untill the completion of the procedure proc_submit_request.
proc_submit_appears returns a message to screen telling "XXXX requests submitted".

My requirement now is, once the user clicks the SUBMIT button, the screen should no longer gray out. The user should be able to navigate to other screens and not just struck with the submit screen untill the called procedure is completed.

I suggested running listeners (shell scripts and perl stuff) that can listen for any messages in pipe and run requests as back-ground process.
But the user is asking me to fix the issue in the application rather running listeners.

I've heard a little of OPEN_FORM built-in.
Suppose, I have two forms namely Form-1 and Form-2. Form-1 calls Form-2 using OPEN_FORM.
Now are the following things possible using OPEN_FORM?

On calling open_form('Form-2',OTHER-ARGUMENTS...), control must be in Form-1 (i.e. USer should not know that another form is getting opened) and Form-2 should call proc_submit_request.

User must be able to navigate to other screens in the application. But Form-2 must still be running until proc_submit_procedure is completed.

What happens if the user closes (exits) Form-1 ?  Will Form-2 be still running?

Please provide me answers or suggest a good solution.

答:
Good thought on the Form-1, Form-2 scenario - I'm not sure if that would work or not.  But here is a much easier way without having to fumble around with coordinating forms being hidden and running stuff, and coming to the forefront when the function actually returns...etc, etc.

Rewrite your function that runs the database jobs to run as an AUTONOMOUS_TRANSACTION.  Have a look at the compiler directive PRAGMA AUTONOMOUS_TRANSACTION for more details on that.  You must use this within a database function/package/procedure - it is not valid with Forms (at least forms 10, not sure about 11).

You can then store the jobs result somewhere from your function (package variable, table, etc) and then use the built-in called CREATE_TIMER in conjunction with the form level trigger WHEN-TIMER-EXPIRED to go and check your storage location every 10 seconds or so - you can then display a message to the user about the jobs, and kill the timer using DELETE_TIMER.

Title: Developer2000 OPEN_FORM built-in


问:
Displaying html div class elements repeatedly based on dropdown selection
Im having trouble using the value of of a dropdown selection to display elements within a page. Im trying to use the number given by a user in a dropdown to repeatedly display a 1 of 8 random "penguin" images. Here I can initially get the first value of the dropdown however I want the page to change once a new value is selected. I also cant seem to get my 2nd for loop here to display each image. Only my html yeti class appears.

```<code>$(document).ready( function() {

    //This code will run after the page loads
    $(function() {
        var maxPenguin = 64;
        var penguinCount = 8;

      for (var i = 2; i < maxPenguin; i++) {
        $('select').append('<option value="' + i + '">' + i + '</option>');
      }

    penguinCount = document.getElementById("penguinsSelected").value;
      alert(penguinCount);
    });

    $(function displayPenguins(penguinCount){
        for(var i = 0; i < penguinCount; i++) {
            var penguin = document.createElement("penguin" + Math.ceil(Math.random() * 8));
            document.body.appendChild(penguin);
        }
    })

    $(".yeti").mousedown(function() {
        alert("Yaaaarrrr!");
        yetiClicked();
    });

});
</code>```

It may be easier if I ran it without JQuery

答:
Pure js approach as you wanted. I hope it's self explanatory.

let imgSources = ["https://upload.wikimedia.org/wikipedia/commons/thumb/b/be/SGI-2016-South_Georgia_%28Fortuna_Bay%29%E2%80%93King_penguin_%28Aptenodytes_patagonicus%29_04.jpg/1200px-SGI-2016-South_Georgia_%28Fortuna_Bay%29%E2%80%93King_penguin_%28Aptenodytes_patagonicus%29_04.jpg","https://upload.wikimedia.org/wikipedia/commons/thumb/0/08/South_Shetland-2016-Deception_Island%E2%80%93Chinstrap_penguin_%28Pygoscelis_antarctica%29_04.jpg/1200px-South_Shetland-2016-Deception_Island%E2%80%93Chinstrap_penguin_%28Pygoscelis_antarctica%29_04.jpg","https://upload.wikimedia.org/wikipedia/commons/thumb/a/a3/Aptenodytes_forsteri_-Snow_Hill_Island%2C_Antarctica_-adults_and_juvenile-8.jpg/220px-Aptenodytes_forsteri_-Snow_Hill_Island%2C_Antarctica_-adults_and_juvenile-8.jpg"];

document.getElementById("dropdown").onchange = displayImages;

function displayImages() {
let nodes = document.getElementById("dispImage");
  removeAllChilds(nodes)
  let pengvalue = document.getElementById("dropdown").value;
  if(pengvalue != "choose") {
     for(i=0;i<pengvalue;i++) {
       var img = new Image();
        img.className = 'center';
        img.width = 300;
        img.height = 300;
        img.src = imgSources[Math.floor(Math.random()*imgSources.length)];
        document.getElementById("dispImage").appendChild(img);

     }
  }
}

function removeAllChilds(node) {
  while (node.hasChildNodes()) {
    node.removeChild(node.lastChild);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><select id="dropdown">
<option value="choose">Choose an option</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<div id="dispImage">

</div></code>```

Body:
Im having trouble using the value of of a dropdown selection to display elements within a page. Im trying to use the number given by a user in a dropdown to repeatedly display a 1 of 8 random "penguin" images. Here I can initially get the first value of the dropdown however I want the page to change once a new value is selected. I also cant seem to get my 2nd for loop here to display each image. Only my html yeti class appears.

$(document).ready( function() {

    //This code will run after the page loads
    $(function() {
        var maxPenguin = 64;
        var penguinCount = 8;

      for (var i = 2; i < maxPenguin; i++) {
        $('select').append('<option value="' + i + '">' + i + '</option>');
      }

    penguinCount = document.getElementById("penguinsSelected").value;
      alert(penguinCount);
    });

    $(function displayPenguins(penguinCount){
        for(var i = 0; i < penguinCount; i++) {
            var penguin = document.createElement("penguin" + Math.ceil(Math.random() * 8));
            document.body.appendChild(penguin);
        }
    })

    $(".yeti").mousedown(function() {
        alert("Yaaaarrrr!");
        yetiClicked();
    });

});

It may be easier if I ran it without JQuery

Body:
Pure js approach as you wanted. I hope it's self explanatory.

let imgSources = ["https://upload.wikimedia.org/wikipedia/commons/thumb/b/be/SGI-2016-South_Georgia_%28Fortuna_Bay%29%E2%80%93King_penguin_%28Aptenodytes_patagonicus%29_04.jpg/1200px-SGI-2016-South_Georgia_%28Fortuna_Bay%29%E2%80%93King_penguin_%28Aptenodytes_patagonicus%29_04.jpg","https://upload.wikimedia.org/wikipedia/commons/thumb/0/08/South_Shetland-2016-Deception_Island%E2%80%93Chinstrap_penguin_%28Pygoscelis_antarctica%29_04.jpg/1200px-South_Shetland-2016-Deception_Island%E2%80%93Chinstrap_penguin_%28Pygoscelis_antarctica%29_04.jpg","https://upload.wikimedia.org/wikipedia/commons/thumb/a/a3/Aptenodytes_forsteri_-Snow_Hill_Island%2C_Antarctica_-adults_and_juvenile-8.jpg/220px-Aptenodytes_forsteri_-Snow_Hill_Island%2C_Antarctica_-adults_and_juvenile-8.jpg"];

document.getElementById("dropdown").onchange = displayImages;

function displayImages() {
let nodes = document.getElementById("dispImage");
  removeAllChilds(nodes)
  let pengvalue = document.getElementById("dropdown").value;
  if(pengvalue != "choose") {
     for(i=0;i<pengvalue;i++) {
       var img = new Image();
        img.className = 'center';
        img.width = 300;
        img.height = 300;
        img.src = imgSources[Math.floor(Math.random()*imgSources.length)];
        document.getElementById("dispImage").appendChild(img);

     }
  }
}

function removeAllChilds(node) {
  while (node.hasChildNodes()) {
    node.removeChild(node.lastChild);
  }
}

<select id="dropdown">
<option value="choose">Choose an option</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<div id="dispImage">

</div>


问:
How to handle credit card information on my server
My company wants to start a subscription based website and I'm implementing it with a payment gateway.

The problem is, this payment gateway doesn't give me any tools to encrypt the client's credit card information before it reaches our server.

So my question is, how should I handle this very sensitive information?

I don't plan on storing it or anything, just send it straight from the server to the payment gateway for validation.

Are we even allowed to handle plain text credit card information?

I know this is a very open subject, I just want to get directed for somewhere I can read and understand more about this issue.

答:
You’ll almost certainly need pci compliance, and with the setup you’ve described, you’ll need the broadest scoped assessment. Not something you want to approach light heartedly.

If you already have industry standard security in place, then it shouldn’t be a big leap to PCI compliance, but most don’t have that. In general the approach to take is to reduce your scope, you could do this with a third party offering like an iframe or redirect, companies like Stripe offer solutions to do that. In that case you may be able to get away with SAQ A, otherwise you probably need SAQ D. This also depends on your volume, if they’re higher you’ll need a report on compliance (roc), which can be expensive and are needed annually.

You can have a chat with your merchant bank, since they are the ones generally requiring the compliance. They can be very helpful, presuming your service isn’t live.

Check out the pci council website, loads of info on there to get you started.


问:
python/django logging with decorators
I want to place a decorator on every function to log everything happening in the function. i have made a wrapper function and decorator to log the function with decorator.

views.py

```<code>def func_detail(func):
   @wraps(func)
     def func_wrapper(*args, **kwargs):
         r = func(*args, **kwargs)
         logging.getLogger(__name__)
         logging.basicConfig(filename='test.log', filemode='a',
                             format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s',
                              datefmt='%H:%M:%S',
                              level=logging.DEBUG)
         return r
     return func_wrapper

class UsersViewSet(viewsets.ViewSet):
    @func_detail
    def list(self, request):
        queryset = Mytable.objects.all()
        if request.GET.get('name'):
            queryset = queryset.filter(name=request.GET.get('name'))
        serializer = CheckSerializer(queryset, many=True)
        logging.info("GET request and returned response")
        return Response(serializer.data)
</code>```

The problem is log file is not created in this code. Also, it got created on a different project but didnot print anything in log file(empty log file). I want to print a message in log file for everything that is happening, but this doesn't seem to work. Plz help.

答:
The decorator inner function should return outer function with args and kwargs and your decorator problem will solve but another problem is Django can't able to stdr the console output of this decorated view function. </p>

```<code>def func_detail(func):
    @wraps(func)
    def func_wrapper(*args, **kwargs):
        logging.getLogger(__name__)
        ----
        return func(*args, **kwargs)
    return func_wrapper
</code>```

Title: python/django logging with decorators

Body:
I want to place a decorator on every function to log everything happening in the function. i have made a wrapper function and decorator to log the function with decorator.

views.py

def func_detail(func):
   @wraps(func)
     def func_wrapper(*args, **kwargs):
         r = func(*args, **kwargs)
         logging.getLogger(__name__)
         logging.basicConfig(filename='test.log', filemode='a',
                             format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s',
                              datefmt='%H:%M:%S',
                              level=logging.DEBUG)
         return r
     return func_wrapper

class UsersViewSet(viewsets.ViewSet):
    @func_detail
    def list(self, request):
        queryset = Mytable.objects.all()
        if request.GET.get('name'):
            queryset = queryset.filter(name=request.GET.get('name'))
        serializer = CheckSerializer(queryset, many=True)
        logging.info("GET request and returned response")
        return Response(serializer.data)

The problem is log file is not created in this code. Also, it got created on a different project but didnot print anything in log file(empty log file). I want to print a message in log file for everything that is happening, but this doesn't seem to work. Plz help.

Body:
The decorator inner function should return outer function with args and kwargs and your decorator problem will solve but another problem is Django can't able to stdr the console output of this decorated view function.

def func_detail(func):
    @wraps(func)
    def func_wrapper(*args, **kwargs):
        logging.getLogger(__name__)
        ----
        return func(*args, **kwargs)
    return func_wrapper


问:
How to use MTA API with laravel
I want to use MTA API (Metropolitan Transportation Authority ) service. But when I send a request it will return one file. How can I get data from MTA API?

http://datamine.mta.info/mta_esi.php?key=MYAPIKEY&feed_id=26

答:
first install guzzlehttp package for laravel using composer,

```<code>composer require guzzlehttp/guzzle
</code>```

use it's namespace in your controller:

```<code>use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Client;
</code>```

Then you can simply do,

```<code>$client = new Client();
$api_response = $client->get('http://datamine.mta.info/mta_esi.php?key=MYAPIKEY&feed_id=26');
$response = json_decode($api_response);

// do your stuff with the response
</code>```

Title: How to use MTA API with laravel

Body:
first install guzzlehttp package for laravel using composer,

composer require guzzlehttp/guzzle

use it's namespace in your controller:

use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Client;

Then you can simply do,

$client = new Client();
$api_response = $client->get('http://datamine.mta.info/mta_esi.php?key=MYAPIKEY&feed_id=26');
$response = json_decode($api_response);

// do your stuff with the response


问:
Ant use -source 7 or higher to enable diamond operator
I am sure this is pretty easy qoestion, but I am stuck with building Android app using Ant from commandline.
I have got this message: (use -source 7 or higher to enable diamond operator). What do I add to buildfile to make it compile using Java 1.7?

答:
Just to clarify, I changed my ant.properties as follows:

```<code>java.target=1.7
java.source=1.7
</code>```

Making changes in build.xml before the above suggested line didn't work for me for some reason.

Body:
Just to clarify, I changed my ant.properties as follows:

java.target=1.7
java.source=1.7

Making changes in build.xml before the above suggested line didn't work for me for some reason.


问:
Accessing Microsoft Graph API : Resource app ID: 00000002-0000-0000-c000-000000000000
I've been using the following code sample to test access to the Microsoft Graph API from a Java application:

https://azure.microsoft.com/en-au/resources/samples/active-directory-java-webapp-openidconnect/

In my Azure portal I've created a Registered app under Azure Active Directory.  I've gone into API Access > Required Permissions and added Microsoft Graph and checked all the Application Permissions and Delegated Permissions.

When I try to call the sample application's 'Show users in the tenant' function, I get the following error message from the Microsoft Login process:

AADSTS65005: Invalid resource. The client has requested access to a resource which is not listed in the requested permissions in the client's application registration. Client app ID: 1b350134-84b1-4ca1-a181-03e3699996a1. Resource value from request: https://graph.windows.net. Resource app ID: 00000002-0000-0000-c000-000000000000. List of valid resources from app registration: 00000003-0000-0000-c000-000000000000.

Can anyone suggest how to proceed from here?

答:
You have given permissions to wrong API.

The sample is intended to work with Azure AD Graph API. It's called Windows Azure Active Directory in the API selection.


问:
Calculating path through 3d points
How would I take a group/array of 3d points in space and calculate a path from 1 point to another, given a limit to the distance that can be jumped, so it may be necessary to jump to another point first? While also trying to minimize the total distance traveled.</p>

答: This is the shortest path problem on a graph. Your 3d points are the vertices in a graph. There is an edge between two vertices if their distance is shorter than your jump distance limit. Then just run shortest path. </p>

Title: Calculating path through 3d points


问:
jQuery: keyup for TAB-key?
So, i'm having some trouble getting my script to run IF the Tab key is pressed. After some quick googling, the charcode for Tab is 9. Also, while we're talking, is there any better ways of checking if a key is pressed without using charcodes? I'm asking because i keep getting the following Warning by firebug when using charcode:

The 'charCode' property of a keyup event should not be used. The value is meaningless.

Anyway, it still works, so that's not the problem. This is the code i use:

```<code>$('/* my inputs */').keyup(function(e) {
   console.log('keyup called');
   var code = e.keyCode || e.which;
   if (code == '9') {
     console.log('Tab pressed');
   }
});
</code>```

Using the above code the console is left blank, nothing is added (using Firebug). Of course i've tried actually doing stuff instead of logging text, but nothing  executes. So can anyone see why this isn't working? Is there a better way of checking if a key is pressed?

Thanks in advance.

答:
My hunch is that when you press the tab key, your form's input loses focus, before the keyup happens. Try changing the binding to the body, like this:

```<code> $('body').keyup(function(e) {
    console.log('keyup called');
    var code = e.keyCode || e.which;
    if (code == '9') {
    alert('Tab pressed');
    }
 });
</code>```

Then, if that works (it does for me) try changing the binding to keyDown, instead, and return false. That way you can implement your own custom behavior.

```<code>$('.yourSelector').keydown(function(e) {
   console.log('keyup called');
   var code = e.keyCode || e.which;
   if (code == '9') {
     alert('Tab pressed');

   return false;
   }

});
</code>```

One of these two should work... if it's body, you could attach a keydown handler on body, then if it's tab, find the field with focus (I think there's function .hasFocus()?), and if it's the one you want, proceed and return false. Otherwise, let the browser do its thing.

If you wanted to update the field WITH a tab character, try this in your callback:

```<code>var theVal = $(this).val();
theVal = theVal + ' ';
$(this).val(theVal);
</code>```

Haven't tested it, but it should work. You could also append 3 or 4 spaces instead of the tab character, if it's giving you trouble.

Title: jQuery: keyup for TAB-key?

Body:
So, i'm having some trouble getting my script to run IF the Tab key is pressed. After some quick googling, the charcode for Tab is 9. Also, while we're talking, is there any better ways of checking if a key is pressed without using charcodes? I'm asking because i keep getting the following Warning by firebug when using charcode:

The 'charCode' property of a keyup event should not be used. The value is meaningless.

Anyway, it still works, so that's not the problem. This is the code i use:

$('/* my inputs */').keyup(function(e) {
   console.log('keyup called');
   var code = e.keyCode || e.which;
   if (code == '9') {
     console.log('Tab pressed');
   }
});

Using the above code the console is left blank, nothing is added (using Firebug). Of course i've tried actually doing stuff instead of logging text, but nothing  executes. So can anyone see why this isn't working? Is there a better way of checking if a key is pressed?

Thanks in advance.

Body:
My hunch is that when you press the tab key, your form's input loses focus, before the keyup happens. Try changing the binding to the body, like this:

 $('body').keyup(function(e) {
    console.log('keyup called');
    var code = e.keyCode || e.which;
    if (code == '9') {
    alert('Tab pressed');
    }
 });

Then, if that works (it does for me) try changing the binding to keyDown, instead, and return false. That way you can implement your own custom behavior.

$('.yourSelector').keydown(function(e) {
   console.log('keyup called');
   var code = e.keyCode || e.which;
   if (code == '9') {
     alert('Tab pressed');

   return false;
   }

});

One of these two should work... if it's body, you could attach a keydown handler on body, then if it's tab, find the field with focus (I think there's function .hasFocus()?), and if it's the one you want, proceed and return false. Otherwise, let the browser do its thing.

If you wanted to update the field WITH a tab character, try this in your callback:

var theVal = $(this).val();
theVal = theVal + ' ';
$(this).val(theVal);

Haven't tested it, but it should work. You could also append 3 or 4 spaces instead of the tab character, if it's giving you trouble.


问:
Java Priority queue error about poll
I am having trouble with priority queue of poll. My try is this:

```<code>public int [][] MST(int i, int prim[][], int mst[][], int vertices, int counter, PriorityQueue priorityQueue){
    Table table = new Table();
    int next_row;
    for(int j=0;j<vertices;j++)
    {
        table.s = i;
        table.d = j;
        table.w = prim[i][j];

        priorityQueue.add(table);
    }
    table = priorityQueue.poll();
    mst[counter][0] = table.s;
    mst[counter][1] = table.d;
    return mst;

}
</code>```

Then I got error at priorityQueue.poll(). It says required Table, but found java.lang.Object.

How should I solve this problem?

答:
you may specify the type of items in the declaration of the priorityQueue

```<code>PriorityQueue < Integer >  prq = new PriorityQueue < Integer > ();
prq.add (new Integer (5)) ;
Integer number = prq.poll();
</code>```

but if you can't change the declaration you could use typeCasting

```<code>PriorityQueue prq = new PriorityQueue();
prq.add (new Integer (5)) ;
Integer number = (Integer) prq.poll();
</code>```

Title: Java Priority queue error about poll

Body:
I am having trouble with priority queue of poll. My try is this:

public int [][] MST(int i, int prim[][], int mst[][], int vertices, int counter, PriorityQueue priorityQueue){
    Table table = new Table();
    int next_row;
    for(int j=0;j<vertices;j++)
    {
        table.s = i;
        table.d = j;
        table.w = prim[i][j];

        priorityQueue.add(table);
    }
    table = priorityQueue.poll();
    mst[counter][0] = table.s;
    mst[counter][1] = table.d;
    return mst;

}

Then I got error at priorityQueue.poll(). It says required Table, but found java.lang.Object.

How should I solve this problem?

Body:
you may specify the type of items in the declaration of the priorityQueue

PriorityQueue < Integer >  prq = new PriorityQueue < Integer > ();
prq.add (new Integer (5)) ;
Integer number = prq.poll();

but if you can't change the declaration you could use typeCasting

PriorityQueue prq = new PriorityQueue();
prq.add (new Integer (5)) ;
Integer number = (Integer) prq.poll();


问:
How to hide groupbox by conditions in xaml
I have this piece of code:

```<code> <GroupBox Header="Varování" Grid.Column="0" VerticalAlignment="Top"  Grid.ColumnSpan="2" Height="Auto" Margin="0,75,0,-6" >

            <StackPanel Orientation="Horizontal" VerticalAlignment="Top" Height="Auto">
                <checks:UCWeighingRecordCheck x:Name="weighingRecordCheck" DataContext="{Binding EntityNotifiedTruck.WeighingRecordCheck}"  VerticalAlignment="Top" />
            </StackPanel>
        </GroupBox>
</code>```

What i want to do is: I want to hide this groupbox if UCWeighingRecordChecks is null. Any tips how to do it?

答:
You could use a binding and a converter:

in resources:

```<code><NullToVisibilityConverter x:Key="NullToVis" />
</code>```

then in your definition:

```<code><GroupBox Visibility="{Binding UCWeighingRecordChecks , Converter={StaticResource NullToVis}}" .../>
</code>```

And use this converter:

```<code>[ValueConversion(typeof(object), typeof(Visibility))]
public sealed class NullToVisibilityConverter : IValueConverter
{

    public object Convert(object value, Type targetType,
        object parameter, CultureInfo culture)
    {
        if (value != null)
            return Visibility.Visible;
        else return Visibility.Collapsed;
    }

    public object ConvertBack(object value, Type targetType,
        object parameter, CultureInfo culture)
    {
        return null;
    }
}
</code>```

Body:
I have this piece of code:

 <GroupBox Header="Varování" Grid.Column="0" VerticalAlignment="Top"  Grid.ColumnSpan="2" Height="Auto" Margin="0,75,0,-6" >

            <StackPanel Orientation="Horizontal" VerticalAlignment="Top" Height="Auto">
                <checks:UCWeighingRecordCheck x:Name="weighingRecordCheck" DataContext="{Binding EntityNotifiedTruck.WeighingRecordCheck}"  VerticalAlignment="Top" />
            </StackPanel>
        </GroupBox>

What i want to do is: I want to hide this groupbox if UCWeighingRecordChecks is null. Any tips how to do it?

Body:
You could use a binding and a converter:

in resources:

<NullToVisibilityConverter x:Key="NullToVis" />

then in your definition:

<GroupBox Visibility="{Binding UCWeighingRecordChecks , Converter={StaticResource NullToVis}}" .../>

And use this converter:

[ValueConversion(typeof(object), typeof(Visibility))]
public sealed class NullToVisibilityConverter : IValueConverter
{

    public object Convert(object value, Type targetType,
        object parameter, CultureInfo culture)
    {
        if (value != null)
            return Visibility.Visible;
        else return Visibility.Collapsed;
    }

    public object ConvertBack(object value, Type targetType,
        object parameter, CultureInfo culture)
    {
        return null;
    }
}


问:
What is the best way to split a file having large number of rows into smaller files of fixed rows?
I have several files containing around 50k lines. I need to break them into smaller files of 1k lines each. What is the best way to do this, on a windows platform?.

Any inputs would be greatly appreciated.

Thanks,
Pavan.

答:
Create a powershell file and save it with a .ps1 extension and add the following powershell code.

```<code>$Input = "LARGEFILE.txt"
$outName = "smallerfile"
$extension = "txt"
$Max = 10kb
$inputFile = [io.file]::OpenRead($Input)
$buffers = new-object byte[] $Max
$count = $lump = 0
try {
    do {
           $count = $inputFile.Read($buffers, 0, $buffers.Length)
           if ($count -gt 0) {
           $to = "{0}.{1}.{2}" -f ($outName, $lump, $extension)
           $toFile = [io.file]::OpenWrite($to)
           try {

               $tofile.Write($buffers, 0, $count)
            } finally {
                $tofile.Close()
            }
        }
        $lump ++
    } while ($count -gt 0)
}
finally {
    $inputFile.Close()
}
</code>```

You need to give the full path and name of the input file, which would be the large file. and then give a unique name of the output files you want, it will store the numbers of each for you. You can also adjust how large you want the output files. So in this instance it will create 10kb files from LARGEFILE.txt into smallerfile.1.txt, smallerfile.2.txt, smallerfile.3.txt etc.

PS!! you can run the file from cmd.exe by running as powershell .\scriptname.ps1 or by replacing .\ with the full path to the script. you can also run it directly from powershell.

Body:
Create a powershell file and save it with a .ps1 extension and add the following powershell code.

$Input = "LARGEFILE.txt"
$outName = "smallerfile"
$extension = "txt"
$Max = 10kb
$inputFile = [io.file]::OpenRead($Input)
$buffers = new-object byte[] $Max
$count = $lump = 0
try {
    do {
           $count = $inputFile.Read($buffers, 0, $buffers.Length)
           if ($count -gt 0) {
           $to = "{0}.{1}.{2}" -f ($outName, $lump, $extension)
           $toFile = [io.file]::OpenWrite($to)
           try {

               $tofile.Write($buffers, 0, $count)
            } finally {
                $tofile.Close()
            }
        }
        $lump ++
    } while ($count -gt 0)
}
finally {
    $inputFile.Close()
}

You need to give the full path and name of the input file, which would be the large file. and then give a unique name of the output files you want, it will store the numbers of each for you. You can also adjust how large you want the output files. So in this instance it will create 10kb files from LARGEFILE.txt into smallerfile.1.txt, smallerfile.2.txt, smallerfile.3.txt etc.

PS!! you can run the file from cmd.exe by running as powershell .\scriptname.ps1 or by replacing .\ with the full path to the script. you can also run it directly from powershell.


问:
GMOCK base class methods in derived class
I have a class that is inherited from another class as mentioned below:

```<code>class A
{
public:
    virtual void Show(){}
};

class B : public A
public:
    void BMethod1(){Show()}
};
</code>```

Now I am writing test cases for class B - so I have mocked class A :

```<code>class MockA : public A
{
    MOCK_METHOD0(Show, void());
};
</code>```

Below is my Google Test framework test case:

```<code>TEST(BTEST , ShowMethod)
{
    B bobj;
    MockA aobj;
    EXPECT_CALL(aobj , Show());
    bobj.BMethod1(); // updated as from bobj.METHOD0()
}
</code>```

But the test cases is calling the actual A::Show() implementation - how can call the Mocked version of MockA::Show() in such a case?

====================UPDATE=================================

Well the below implementation did the trick for me:

```<code>class A
{
public:
    virtual void Show(){}
};

class B : public A
public:
    void BMethod1(){Show()}
};

class BMock : public B
{
public:
   MOCK_METHOD0(Show, void());
};
</code>```

Now use BMock object to test you class B required methods

答:
You can use Isolator++ to create the test without the setup:</p>

```<code>class A
{
public:
    void Show() {}
};

class B : public A
{
public:
    void BMethod1() { Show(); }
};

TEST(BTEST, ShowMethod)
{
    B bobj;
    auto aobj = FAKE<A>();

    bobj.BMethod1();

    ASSERT_WAS_CALLED(aobj->Show());
}
</code>```

Body:
I have a class that is inherited from another class as mentioned below:

class A
{
public:
    virtual void Show(){}
};

class B : public A
public:
    void BMethod1(){Show()}
};

Now I am writing test cases for class B - so I have mocked class A :

class MockA : public A
{
    MOCK_METHOD0(Show, void());
};

Below is my Google Test framework test case:

TEST(BTEST , ShowMethod)
{
    B bobj;
    MockA aobj;
    EXPECT_CALL(aobj , Show());
    bobj.BMethod1(); // updated as from bobj.METHOD0()
}

But the test cases is calling the actual A::Show() implementation - how can call the Mocked version of MockA::Show() in such a case?

====================UPDATE=================================

Well the below implementation did the trick for me:

class A
{
public:
    virtual void Show(){}
};

class B : public A
public:
    void BMethod1(){Show()}
};

class BMock : public B
{
public:
   MOCK_METHOD0(Show, void());
};

Now use BMock object to test you class B required methods

Body:
You can use Isolator++ to create the test without the setup:

class A
{
public:
    void Show() {}
};

class B : public A
{
public:
    void BMethod1() { Show(); }
};

TEST(BTEST, ShowMethod)
{
    B bobj;
    auto aobj = FAKE<A>();

    bobj.BMethod1();

    ASSERT_WAS_CALLED(aobj->Show());
}


问:
How to automatically authenticate windows integrate without login popup?
I wrote an asp.net application with default.aspx. When I hit this page It is asking me windows login popup window. My application should me windows authentication required but it should "Integrated Windows authentication". If I enter login password I am able to see my page.

How can I automatically integrate this windows authentication?

I added below code in web.config. still doesn't work.

```<code><authentication mode="Windows"/>
    <identity impersonate="false"/>
    <authorization>
        <deny users="?"/>
    </authorization>
</code>```

答:
You would want to disable anonymous access and just use "Integrated Windows Authentication".

Then in Internet Explorer go to Tools -> Internet Option -> Security -> Custom Level -> Scroll the whole way to the bottom and select "Automatic Login with current user name and password” -> OK -> OK -> Close and reopen browser.

This should allow an AD authenticated user to pass straight through to your page.

Body:
I wrote an asp.net application with default.aspx. When I hit this page It is asking me windows login popup window. My application should me windows authentication required but it should "Integrated Windows authentication". If I enter login password I am able to see my page.

How can I automatically integrate this windows authentication?

I added below code in web.config. still doesn't work.

<authentication mode="Windows"/>
    <identity impersonate="false"/>
    <authorization>
        <deny users="?"/>
    </authorization>


答:
Use the then() https://api.jquery.com/jquery.when/

In the case where multiple Deferred objects are passed to
  jQuery.when(), the method returns the Promise from a new "master"
  Deferred object that tracks the aggregate state of all the Deferreds
  it has been passed. The method will resolve its master Deferred as
  soon as all the Deferreds resolve, or reject the master Deferred as
  soon as one of the Deferreds is rejected. If the master Deferred is
  resolved, the doneCallbacks for the master Deferred are executed. The
  arguments passed to the doneCallbacks provide the resolved values for
  each of the Deferreds, and matches the order the Deferreds were passed
  to jQuery.when().

```<code>$.when(
    $.get(url),
    $.get(otherUrl)
).then(function(data1){
     someCode();
});
</code>```

Title: How to make nested async requests in jquery?

Body:
inside main.js:

$.when(
    $.get('foo/bar.html'),
    $.get('lorem/ipsum.html')
).done(function(data1, data2){
     someCode();
});

inside lorem/ipsum.html:

$.when(
    $.get('otherStuff.html'),
    $.get('example.html')
).done(function(data1, data2){
     moreCode();
});

How can I make someCode() run after moreCode()?

Body:
Use the then() https://api.jquery.com/jquery.when/

In the case where multiple Deferred objects are passed to
  jQuery.when(), the method returns the Promise from a new "master"
  Deferred object that tracks the aggregate state of all the Deferreds
  it has been passed. The method will resolve its master Deferred as
  soon as all the Deferreds resolve, or reject the master Deferred as
  soon as one of the Deferreds is rejected. If the master Deferred is
  resolved, the doneCallbacks for the master Deferred are executed. The
  arguments passed to the doneCallbacks provide the resolved values for
  each of the Deferreds, and matches the order the Deferreds were passed
  to jQuery.when().

$.when(
    $.get(url),
    $.get(otherUrl)
).then(function(data1){
     someCode();
});


问:
Substring assignment
I have an assignment in school but I'm totally stuck.

My assignment:
Make a program that ask for a text and then write out the text several times. First with just one letter, then with two and so on. For example, if the user write "Thomas", your program should write out "T", "Th, "Tho, "Thom", and so on.

My hopeless attempt
I been trying to use "Substring" and a loop to make it work but I'm not sure I'm on the right path or not. Right now my code look like this:

```<code><head>
<meta charset= "UTF-8"/>
<title> assignment14 - Johan </title>

<script type="text/javascript">

var text= test.length;

for (i=0;i< test.length;i++)

function printit()
{
var str = test;
var res = str.substring (i, 2);
document.getElementById("test").innerHTML = res;
}

    </script>

</head>

<body>
<h1>Assignment 14</h1>
    <form name="f1">
    <input type="text" id="test" value="" />
    <input type="button" value="Hämta" onclick="printit(document.getElementById('test'))" />

    </form>

</body>
</code>```

Just need some kind of hint If I'm going in the right direction or not, should I use some other functions? Very thankful for help.

答:
You need to make few changes to your code:
1) use document.getElementById('test').value in printit function call at onclick as you have to send the value of the textbox instead of innerHTML.
2) Modify the printif function-

```<code>function printit(test)
{
document.getElementById('test').value='';  /*remove existing text from textbox*/
for (i=0;i< test.length;i++)   {
var res = str.substring (0, i+1);
document.getElementById("test").value += ' '+res;
}
}
</code>```

In printit function empty the text box and then append each substring to the existing text to get "T Th Tho Thom.." and so on
Hope this helps.

Title: Substring assignment

Body:
I have an assignment in school but I'm totally stuck.

My assignment:
Make a program that ask for a text and then write out the text several times. First with just one letter, then with two and so on. For example, if the user write "Thomas", your program should write out "T", "Th, "Tho, "Thom", and so on.

My hopeless attempt
I been trying to use "Substring" and a loop to make it work but I'm not sure I'm on the right path or not. Right now my code look like this:

<meta charset= "UTF-8"/>
<title> assignment14 - Johan </title>

Assignment 14

    <form name="f1">
    <input type="text" id="test" value="" />
    <input type="button" value="Hämta" onclick="printit(document.getElementById('test'))" />

    </form>

Just need some kind of hint If I'm going in the right direction or not, should I use some other functions? Very thankful for help.

Body:
You need to make few changes to your code:
1) use document.getElementById('test').value in printit function call at onclick as you have to send the value of the textbox instead of innerHTML.
2) Modify the printif function-

function printit(test)
{
document.getElementById('test').value='';  /*remove existing text from textbox*/
for (i=0;i< test.length;i++)   {
var res = str.substring (0, i+1);
document.getElementById("test").value += ' '+res;
}
}

In printit function empty the text box and then append each substring to the existing text to get "T Th Tho Thom.." and so on
Hope this helps.


问:
File Not found exception - speechclient.dll NuGet Package
I have a project using the SpeechClient.dll from NuGet. The program runs fine on the development machine. So I have a Windows Setup Project that creates the installer. I run the installer and all the files show up including the SpeechClient.dll, but as soon as the program makes the first call to the Speechclient.dll, I get a

file not found

exception. This is the output from the event viewer.

Does anyone have any troubleshooting ideas? Thanks.

答: I had this problem as well. Installing the Visual Studio C++ Redistributable 2017 x64 cleared it up.</p>


问:
NHibernate 'Where' Clause causing problems on cascading deletes
I have the following mapping file for 'Photo' objects (edited for brevity):

```<code><hibernate-mapping ... default-access="property" default-cascade="none" default-lazy="true">
<class xmlns="urn:nhibernate-mapping-2.2" name="Photo" table="Photos">
    <id name="PhotoId" unsaved-value="0">
        <column  name="PhotoId" />
        <generator class="native" />
    </id>
    ...
    <bag name="Comments" table="Comments" lazy="false" order-by="DateTimePosted desc" cascade="all-delete-orphan" inverse="true">
        <key column="PhotoId" />
        <one-to-many class="Comment" />
    </bag>
</class>
</code>```

I want to apply a Where clause against the 'Comments' bag to only retrieve Comments with the 'Approved' property = true. However, when I had this in place I came up against a problem scenario where deleted Photo objects were not then cascading deleted unapproved comments (and were leaving orphaned comment records) as it didn't meet the condition of the where clause! In essence, I wanted the where clause to be adhered to EXCEPT for cascading deletes, in which case, I ALWAYS wanted any comments associated with a photo to be deleted, when a Photo was deleted.

Here is an edited copy of my Comments mapping file:

```<code><hibernate-mapping ... default-access="property" default-cascade="none" default-lazy="true">
<class xmlns="urn:nhibernate-mapping-2.2" name="Comment" table="Comments">
    <id name="CommentId" unsaved-value="0">
        <column name="CommentId"></column>
        <generator class="native" />
    </id>
    <property name="DateTimePosted" not-null="true" />
    ...
    <property name="Approved" not-null="true" />
    <many-to-one name="Photo">
        <column name="PhotoId" />
    </many-to-one>
</class>
</code>```

How can I get around this?

答:
Since NHibernate can't guess that you "wanted the where clause to be adhered to EXCEPT for cascading deletes", you need to use filters to get the collection items instead.

An alternative is using a LINQ-to-objects projection:

```<code>public virtual IEnumerable<Comment> ApprovedComments
{
    get { return Comments.Where(c => c.Approved); }
}
</code>```

Body:
I have the following mapping file for 'Photo' objects (edited for brevity):

<hibernate-mapping ... default-access="property" default-cascade="none" default-lazy="true">
<class xmlns="urn:nhibernate-mapping-2.2" name="Photo" table="Photos">
    <id name="PhotoId" unsaved-value="0">
        <column  name="PhotoId" />
        <generator class="native" />
    </id>
    ...
    <bag name="Comments" table="Comments" lazy="false" order-by="DateTimePosted desc" cascade="all-delete-orphan" inverse="true">
        <key column="PhotoId" />
        <one-to-many class="Comment" />
    </bag>
</class>

I want to apply a Where clause against the 'Comments' bag to only retrieve Comments with the 'Approved' property = true. However, when I had this in place I came up against a problem scenario where deleted Photo objects were not then cascading deleted unapproved comments (and were leaving orphaned comment records) as it didn't meet the condition of the where clause! In essence, I wanted the where clause to be adhered to EXCEPT for cascading deletes, in which case, I ALWAYS wanted any comments associated with a photo to be deleted, when a Photo was deleted.

Here is an edited copy of my Comments mapping file:

<hibernate-mapping ... default-access="property" default-cascade="none" default-lazy="true">
<class xmlns="urn:nhibernate-mapping-2.2" name="Comment" table="Comments">
    <id name="CommentId" unsaved-value="0">
        <column name="CommentId"></column>
        <generator class="native" />
    </id>
    <property name="DateTimePosted" not-null="true" />
    ...
    <property name="Approved" not-null="true" />
    <many-to-one name="Photo">
        <column name="PhotoId" />
    </many-to-one>
</class>

How can I get around this?

Body:
Since NHibernate can't guess that you "wanted the where clause to be adhered to EXCEPT for cascading deletes", you need to use filters to get the collection items instead.

An alternative is using a LINQ-to-objects projection:

public virtual IEnumerable<Comment> ApprovedComments
{
    get { return Comments.Where(c => c.Approved); }
}


问:
deterministic stats_mode in Oracle
In Oracle, stats_mode function selects the mode of a set of data.  Unfortunately, it is non-deterministic in picking it's result in the presence of ties (e.g. stats_mode(1,2,1,2) could return 1 or 2 depending on the ordering of rows inside Oracle.  In many situations this is not acceptable.  Is there a function or nice technique for being able to supply your own deterministic ordering for stats_mode function?</p>

答:
Selecting the value among a set of values with the highest occurring frequency could also be done by counting and ordering.

```<code>select x from t group by x order by count(*) desc limit 1;
</code>```

You can also make it deterministic by ordering on the value itself.

```<code>select x from t group by x order by count(*) desc, x desc limit 1;
</code>```

I don't quite understand the complexity of Oracles query examples, the performance is really bad. Can anyone shine some light on the difference?

Title: deterministic stats_mode in Oracle

Body:
Selecting the value among a set of values with the highest occurring frequency could also be done by counting and ordering.

select x from t group by x order by count(*) desc limit 1;

You can also make it deterministic by ordering on the value itself.

select x from t group by x order by count(*) desc, x desc limit 1;

I don't quite understand the complexity of Oracles query examples, the performance is really bad. Can anyone shine some light on the difference?


问:
Hover effect not working with w3-css

a:hover
{
  text-decoration: none;
  color: #F78888;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://www.w3schools.com/w3css/4/w3.css" rel="stylesheet" />
<nav class="w3-sidebar w3-collapse w3-top w3-large" style="z-index:100;width:210px;font-weight:bold;" id="mynav">
    <div class="w3-container" style="color: white;">
        <h3 class="w3-padding-64"><b>No<br>Name</b></h3>
    </div>
    <div class="w3-bar-block  w3-padding-8" style="color: white;">
        Courses
        Exercises
        Rubric
        Students
        AnyName
        Contact
        Logout
    </div>
</nav></code>```

I am using w3-CSS for my web page. While I apply the hover effect for the 'a' elements it is applying. I can't overwrite the predefined hover effect of the w3-css.  I want to change thee text color while hovering the mouse.

答:
.w3-hover-white:hover{color:#000!important;background-color:#fff!important}

Courses```
</div>
</div>

By removing the .w3-hover-white from the <strong>a</strong> element and gave my own userdefined style.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>a:hover
{
  text-decoration: none;
  background-color: white;
  color: #F78888;
}</code>```

Title: Hover effect not working with w3-css

Body:
a:hover
{
  text-decoration: none;
  color: #F78888;
}

<link href="https://www.w3schools.com/w3css/4/w3.css" rel="stylesheet" />

No
Name

        Courses
        Exercises
        Rubric
        Students
        AnyName
        Contact
        Logout

I am using w3-CSS for my web page. While I apply the hover effect for the 'a' elements it is applying. I can't overwrite the predefined hover effect of the w3-css.  I want to change thee text color while hovering the mouse.

Body:
.w3-hover-white:hover{color:#000!important;background-color:#fff!important}

<a href="course.html" onclick="w3_close()" class="w3-bar-item w3-padding-16 myclass">Courses</a>

By removing the .w3-hover-white from the a element and gave my own userdefined style.

a:hover
{
  text-decoration: none;
  background-color: white;
  color: #F78888;
}


问:
How to remove \ character from a string in swift 3
My string is contained in a variable named str. This code isnt working :</p>

```<code>  str = str.replacingOccurrences(of: "\\", with: "")
</code>```

答:
this line remove \ from string </p>

```<code> str = str.replacingOccurrences(of: "\"", with: "")
</code>```

Body:
My string is contained in a variable named str. This code isnt working :

  str = str.replacingOccurrences(of: "\\", with: "")

Body:
this line remove \ from string

 str = str.replacingOccurrences(of: "\"", with: "")