问:
Search or compare value in the textbox in certain folder or directory(location) and list the log file which have the exact value in it
[Hi All I am just new in VBA excel macro and trying to create my own macro. the vb mini-program i have will search for specific value(example. 15) in all the log files in certain directory or location. Once the value was found in the log file, the program will list it in list box. my program is functioning. My only problem is, if theres hundreds or thousands of log files in the location, the program will list all log data with value of 1 or 5 including the log data with the exact value 15. the other problem is that the log data with value of 15 will be listed below which is supposed to be on the top or listed at the first found item which have the correct value. Below are my questions.

Is it possible that if the program found out the log data with exact value, the program will list it on top or can be listed first?

It is more easy also if the output will be  limit . Because if there are thousands or hundreds of file with 1 and 5 , everything will be listed in the list box. is it possible to list only the right log data with value of 15? Kindly see below snapshot and code. I am planning to use this macro also in my work the reason why I am trying to figure it out.

Program:

```<code>Private Sub Comfind_Click()

    Dim theString As String
    Dim path As String
    Dim StrFile As String
    Dim fso As New FileSystemObject
    Dim file As TextStream
    Dim line As String
    Dim blnFound As Boolean

    ListLog.Clear
    theString = TextPlate.Text

    path = TextPath.Text
    StrFile = Dir(path & "*.pdms")

    Do While StrFile <> ""
        'Find TheString in the file
        'If found, list log and exit loop

        Set file = fso.OpenTextFile(path & StrFile)
        Do While Not file.AtEndOfLine
            line = file.ReadLine
            If InStr(1, line, theString, vbTextCompare) > 0 Then
           ListLog.AddItem StrFile

                Exit Do
            End If

        Loop
        file.Close
        Set file = Nothing
        Set fso = Nothing
        StrFile = Dir()

    Loop
     MsgBox "successfully search log data!!!"

End Sub
</code>```

Log file:

答:
You can narrow it down a bit:</p>

```<code>Dim arr
Do While Not file.AtEndOfLine
    line = file.ReadLine
    If InStr(1, line, "PLATEKEY", vbTextCompare) > 0 Then
        arr = Split(line, "PLATEKEY")
        If Trim(arr(1)) = theString Then
            ListLog.AddItem StrFile
            Exit Do
        End If
    End If
Loop
</code>```

Body:
[Hi All I am just new in VBA excel macro and trying to create my own macro. the vb mini-program i have will search for specific value(example. 15) in all the log files in certain directory or location. Once the value was found in the log file, the program will list it in list box. my program is functioning. My only problem is, if theres hundreds or thousands of log files in the location, the program will list all log data with value of 1 or 5 including the log data with the exact value 15. the other problem is that the log data with value of 15 will be listed below which is supposed to be on the top or listed at the first found item which have the correct value. Below are my questions.

Is it possible that if the program found out the log data with exact value, the program will list it on top or can be listed first?

It is more easy also if the output will be  limit . Because if there are thousands or hundreds of file with 1 and 5 , everything will be listed in the list box. is it possible to list only the right log data with value of 15? Kindly see below snapshot and code. I am planning to use this macro also in my work the reason why I am trying to figure it out.

Program:

Private Sub Comfind_Click()

    Dim theString As String
    Dim path As String
    Dim StrFile As String
    Dim fso As New FileSystemObject
    Dim file As TextStream
    Dim line As String
    Dim blnFound As Boolean

    ListLog.Clear
    theString = TextPlate.Text

    path = TextPath.Text
    StrFile = Dir(path & "*.pdms")

    Do While StrFile <> ""
        'Find TheString in the file
        'If found, list log and exit loop

        Set file = fso.OpenTextFile(path & StrFile)
        Do While Not file.AtEndOfLine
            line = file.ReadLine
            If InStr(1, line, theString, vbTextCompare) > 0 Then
           ListLog.AddItem StrFile

                Exit Do
            End If

        Loop
        file.Close
        Set file = Nothing
        Set fso = Nothing
        StrFile = Dir()

    Loop
     MsgBox "successfully search log data!!!"

End Sub

Log file:

Body:
You can narrow it down a bit:

Dim arr
Do While Not file.AtEndOfLine
    line = file.ReadLine
    If InStr(1, line, "PLATEKEY", vbTextCompare) > 0 Then
        arr = Split(line, "PLATEKEY")
        If Trim(arr(1)) = theString Then
            ListLog.AddItem StrFile
            Exit Do
        End If
    End If
Loop


来源: stackexchange

问:
How to limit the child retrieved in Firebase Android
I want to ask about how to retrieve data with limited child in Android Firebase. Here is my data structure :

```<code>"chatrooms":
    "chatroom_id_1" :
        "message":
            "message_id_1":1
            "message_id_2":1
            "message_id_3":1
            "message_id_4":1
            "message_id_5":1
            "message_id_6":1
            "message_id_7":1
            "message_id_8":1
            "message_id_9":1
            "message_id_10":1
            "message_id_11":1
    "chatroom_id_2" :
            "message":
                "message_id_12":1
                "message_id_13":1
                "message_id_14":1
                "message_id_15":1
                "message_id_16":1
                "message_id_17":1
                "message_id_18":1
                "message_id_19":1
                "message_id_20":1
                "message_id_21":1
                "message_id_22":1
</code>```

From the structure above how to do the query to retrieve a snapshot with only data limited to 5 messages?

The dataSnapshot I would like to have is like this :

```<code>DataSnapshot {
    key = chatroom_id_1,
    value = {
        messages={
            message_id_1=1,
            message_id_2=1,
            message_id_3=1,
            message_id_4=1,
            message_id_5=1
        }
    }
}
DataSnapshot {
        key = chatroom_id_2,
        value = {
            messages={
                message_id_12=1,
                message_id_13=1,
                message_id_14=1,
                message_id_15=1,
                message_id_16=1
            }
        }
    }
</code>```

is it possible to do so? Because most of the tutorial I've found can only limit the child retrieved but not the inner child. Thanks

EDIT : MY message_id is generated randomly, so to obtain the message_id I have to use an DataSnapshot with iterator . Here's my retrieve data code

```<code>public void retrieveChatRoom(final Callback callback){
        DatabaseReference ref = reference.child("chatrooms");
        ref.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                callback.onDataChanged();
                Iterator i = dataSnapshot.getChildren().iterator();
                while (i.hasNext()) {
                    DataSnapshot dataSnapshot1 = (DataSnapshot) i.next();
                    callback.dataReceived(dataSnapshot1);
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
    }
</code>```

the thing is the DataSnapshot return all of the chat_message inside my chatroom,can I limit it to only returning 5 messages?

答:
To retrieve a subset of the child nodes, you use Firebase queries. If you want to synchronize the child nodes up to a certain key, you'd use:

```<code>Query query = ref.child("chatroom_id_1/message")
    .orderByKey()
    .endAt("message_id_5");
query.addValueEventListener(new ValueEventListener() {
  @Override
  public void onDataChange(DataSnapshot dataSnapshot) {
    for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
        System.out.println(childSnapshot.getKey());
    }
  }
  ...
</code>```

If you're just looking to get 5 messages from a location:

```<code>Query query = ref.child("chatroom_id_1/message")
    .orderByKey()
    .limitToFist(5);
query.addValueEventListener(new ValueEventListener() {
  @Override
  public void onDataChange(DataSnapshot dataSnapshot) {
    for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
        System.out.println(childSnapshot.getKey());
    }
  }
  ...
</code>```

Update:

Firebase Database queries can limit the results based on a fixed property (or path) of each child node of the location where you execute them. There is no way to retrieve the last 5 messages for each chat room in one go. You can either retrieve the last 5 messages for a specific chat room. Or the last 5 chat rooms.

ContentLicense: CC BY-SA 3.0

Body:
I want to ask about how to retrieve data with limited child in Android Firebase. Here is my data structure :

"chatrooms":
    "chatroom_id_1" :
        "message":
            "message_id_1":1
            "message_id_2":1
            "message_id_3":1
            "message_id_4":1
            "message_id_5":1
            "message_id_6":1
            "message_id_7":1
            "message_id_8":1
            "message_id_9":1
            "message_id_10":1
            "message_id_11":1
    "chatroom_id_2" :
            "message":
                "message_id_12":1
                "message_id_13":1
                "message_id_14":1
                "message_id_15":1
                "message_id_16":1
                "message_id_17":1
                "message_id_18":1
                "message_id_19":1
                "message_id_20":1
                "message_id_21":1
                "message_id_22":1

From the structure above how to do the query to retrieve a snapshot with only data limited to 5 messages?

The dataSnapshot I would like to have is like this :

DataSnapshot {
    key = chatroom_id_1,
    value = {
        messages={
            message_id_1=1,
            message_id_2=1,
            message_id_3=1,
            message_id_4=1,
            message_id_5=1
        }
    }
}
DataSnapshot {
        key = chatroom_id_2,
        value = {
            messages={
                message_id_12=1,
                message_id_13=1,
                message_id_14=1,
                message_id_15=1,
                message_id_16=1
            }
        }
    }

is it possible to do so? Because most of the tutorial I've found can only limit the child retrieved but not the inner child. Thanks

EDIT : MY message_id is generated randomly, so to obtain the message_id I have to use an DataSnapshot with iterator . Here's my retrieve data code

public void retrieveChatRoom(final Callback callback){
        DatabaseReference ref = reference.child("chatrooms");
        ref.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                callback.onDataChanged();
                Iterator i = dataSnapshot.getChildren().iterator();
                while (i.hasNext()) {
                    DataSnapshot dataSnapshot1 = (DataSnapshot) i.next();
                    callback.dataReceived(dataSnapshot1);
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
    }

the thing is the DataSnapshot return all of the chat_message inside my chatroom,can I limit it to only returning 5 messages?

Body:
To retrieve a subset of the child nodes, you use Firebase queries. If you want to synchronize the child nodes up to a certain key, you'd use:

Query query = ref.child("chatroom_id_1/message")
    .orderByKey()
    .endAt("message_id_5");
query.addValueEventListener(new ValueEventListener() {
  @Override
  public void onDataChange(DataSnapshot dataSnapshot) {
    for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
        System.out.println(childSnapshot.getKey());
    }
  }
  ...

If you're just looking to get 5 messages from a location:

Query query = ref.child("chatroom_id_1/message")
    .orderByKey()
    .limitToFist(5);
query.addValueEventListener(new ValueEventListener() {
  @Override
  public void onDataChange(DataSnapshot dataSnapshot) {
    for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
        System.out.println(childSnapshot.getKey());
    }
  }
  ...

Update:

Firebase Database queries can limit the results based on a fixed property (or path) of each child node of the location where you execute them. There is no way to retrieve the last 5 messages for each chat room in one go. You can either retrieve the last 5 messages for a specific chat room. Or the last 5 chat rooms.


问:
access vba wait for code to finish (send E-Mail via CDO)
I have the following code:

```<code>Sub OutputExpences()
Dim strPath As String
Dim FileName As String
Dim TodayDate As String

TodayDate = Format(Date, "DD-MM-YYYY")
strPath = Application.CurrentProject.Path & "\Temp\"
FileName = "Report-Date_" & TodayDate & ".xlsx"

DoCmd.OutputTo acOutputForm, "frmExpences", acFormatXLSX, strPath & FileName, False
            '*** Check Network Connection ***
            If IsInternetConnected() = True Then
                ''' connected
                EmailToCashier
            Else
                ''' no connected
            End If
            '*** Check Network Connection ***
Kill strPath & FileName
End Sub

 Public Sub EmailToCashier()
 Dim mail    As Object           ' CDO.MESSAGE
 Dim config  As Object           ' CDO.Configuration
 Dim strPath As String
 Dim FileName As String
 Dim TodayDate As String

 TodayDate = Format(Date, "DD-MM-YYYY")
 strPath = Application.CurrentProject.Path & "\Temp\"
 FileName = "Report-Date_" & TodayDate & ".xlsx"

     Set mail = CreateObject("CDO.Message")
     Set config = CreateObject("CDO.Configuration")

     config.Fields(cdoSendUsingMethod).Value = cdoSendUsingPort
     config.Fields(cdoSMTPServer).Value = "smtp value"
     config.Fields(cdoSMTPServerPort).Value = 465
     config.Fields(cdoSMTPConnectionTimeout).Value = 10
     config.Fields(cdoSMTPUseSSL).Value = "true"
     config.Fields(cdoSMTPAuthenticate).Value = cdoBasic
     config.Fields(cdoSendUserName).Value = "email value"
     config.Fields(cdoSendPassword).Value = "password value"
     config.Fields.Update
     Set mail.Configuration = config

     With mail
         .To = "email"
         .From = "email"
         .Subject = "subject"
         .TextBody = "Thank you."
         .AddAttachment strPath & FileName
         .Send
     End With

     MsgBox "Email successfully sent!", vbInformation, "EMAIL STATUS"

     Set config = Nothing
     Set mail = Nothing
 End Sub
</code>```

I need to wait(user can't press anything or do anything) until all the code is finished.

EmailToCashier is sending the output file to email so it is taking time(from 2-15sec depending the network connection and file size).

Thank you.

答:
Use Application.wait</p>

```<code>Sub OutputExpences()
Dim strPath As String
Dim FileName As String
Dim TodayDate As String

TodayDate = Format(Date, "DD-MM-YYYY")
strPath = Application.CurrentProject.Path & "\Temp\"
FileName = "Report-Date_" & TodayDate & ".xlsx"

DoCmd.OutputTo acOutputForm, "frmExpences", acFormatXLSX, strPath & FileName, False
            '*** Check Network Connection ***
            If IsInternetConnected() = True Then
                ''' connected
                EmailToCashier
            Else
                ''' no connected
            End If
            '*** Check Network Connection ***
    newHour = Hour(Now())
    newMinute = Minute(Now())
    newSecond = Second(Now()) + 15
    waitTime = TimeSerial(newHour, newMinute, newSecond)
    Application.Wait waitTime
Kill strPath & FileName
End Sub
</code>```

Body:
I have the following code:

Sub OutputExpences()
Dim strPath As String
Dim FileName As String
Dim TodayDate As String

TodayDate = Format(Date, "DD-MM-YYYY")
strPath = Application.CurrentProject.Path & "\Temp\"
FileName = "Report-Date_" & TodayDate & ".xlsx"

DoCmd.OutputTo acOutputForm, "frmExpences", acFormatXLSX, strPath & FileName, False
            '*** Check Network Connection ***
            If IsInternetConnected() = True Then
                ''' connected
                EmailToCashier
            Else
                ''' no connected
            End If
            '*** Check Network Connection ***
Kill strPath & FileName
End Sub

 Public Sub EmailToCashier()
 Dim mail    As Object           ' CDO.MESSAGE
 Dim config  As Object           ' CDO.Configuration
 Dim strPath As String
 Dim FileName As String
 Dim TodayDate As String

 TodayDate = Format(Date, "DD-MM-YYYY")
 strPath = Application.CurrentProject.Path & "\Temp\"
 FileName = "Report-Date_" & TodayDate & ".xlsx"

     Set mail = CreateObject("CDO.Message")
     Set config = CreateObject("CDO.Configuration")

     config.Fields(cdoSendUsingMethod).Value = cdoSendUsingPort
     config.Fields(cdoSMTPServer).Value = "smtp value"
     config.Fields(cdoSMTPServerPort).Value = 465
     config.Fields(cdoSMTPConnectionTimeout).Value = 10
     config.Fields(cdoSMTPUseSSL).Value = "true"
     config.Fields(cdoSMTPAuthenticate).Value = cdoBasic
     config.Fields(cdoSendUserName).Value = "email value"
     config.Fields(cdoSendPassword).Value = "password value"
     config.Fields.Update
     Set mail.Configuration = config

     With mail
         .To = "email"
         .From = "email"
         .Subject = "subject"
         .TextBody = "Thank you."
         .AddAttachment strPath & FileName
         .Send
     End With

     MsgBox "Email successfully sent!", vbInformation, "EMAIL STATUS"

     Set config = Nothing
     Set mail = Nothing
 End Sub

I need to wait(user can't press anything or do anything) until all the code is finished.

EmailToCashier is sending the output file to email so it is taking time(from 2-15sec depending the network connection and file size).

Thank you.

Body:
Use Application.wait

Sub OutputExpences()
Dim strPath As String
Dim FileName As String
Dim TodayDate As String

TodayDate = Format(Date, "DD-MM-YYYY")
strPath = Application.CurrentProject.Path & "\Temp\"
FileName = "Report-Date_" & TodayDate & ".xlsx"

DoCmd.OutputTo acOutputForm, "frmExpences", acFormatXLSX, strPath & FileName, False
            '*** Check Network Connection ***
            If IsInternetConnected() = True Then
                ''' connected
                EmailToCashier
            Else
                ''' no connected
            End If
            '*** Check Network Connection ***
    newHour = Hour(Now())
    newMinute = Minute(Now())
    newSecond = Second(Now()) + 15
    waitTime = TimeSerial(newHour, newMinute, newSecond)
    Application.Wait waitTime
Kill strPath & FileName
End Sub


问:
prestashop 1.6:how to write insert query in ajax.php
I am just working prestashop in insert query.Below i have attached my ajax file.I have include all supported file but dataes is not inserted in this table.I don't know what is error?.Kindly check and help me.  </p>

```<code>include '../../config/settings.inc.php';
include '../../config/defines.inc.php';
include '../../config/config.inc.php';

    $api=$_REQUEST['api_key'];
    $install=$_REQUEST['installtion_id'];
    $percentages=$_REQUEST['dep_per'];
    $package=$_REQUEST['dep_plan'];

       $res = Db::getInstance()->insert('pay4later_setting',array(
        'api_key'       => '$api',
        'installtion_id'      => '$install',
        'deposite_percentage' =>'$percentages',
         'package_plan' =>'$package',
    ));
</code>```

答:
Where did you kept your ajax request.Ok,No problem.

For example,

In prestashop i have sent my ajax request through configure.tpl file

configure.tpl

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

        $('#submit_label').click(function(){
               var data = "welcome";
                $.ajax({
                type:"POST",
                dataType:"JSON",
                url:baseDir+'modules/anything/data.php',
                data:{
                ajax:true,
                name:data,
                },
                success: function(html){

                    if(html.added)
                    {
                         $("#success").html(html.added);

                    }

            }
                });

        });

});
</code>```

And here i have using data.php as a php file

data.php

```<code><?php
require_once(dirname(__FILE__).'../../../config/config.inc.php');
require_once(dirname(__FILE__).'../../../init.php');

if(isset($_POST['name']))
{
    $label_name = $_POST['name']; or you can use Tools::getValue("name");

    $connect_db = Db::getInstance()->insert('label', array(
    'label_name' => pSQL($label_name),
    ));

    $getin['added'] = 'Label created successfully';//here we have using JSON datatype so we need to create object and store some values.

    echo json_encode($getin);

}
</code>```

Thanks & Regards,
krishna.

Body:
I am just working prestashop in insert query.Below i have attached my ajax file.I have include all supported file but dataes is not inserted in this table.I don't know what is error?.Kindly check and help me.

include '../../config/settings.inc.php';
include '../../config/defines.inc.php';
include '../../config/config.inc.php';

    $api=$_REQUEST['api_key'];
    $install=$_REQUEST['installtion_id'];
    $percentages=$_REQUEST['dep_per'];
    $package=$_REQUEST['dep_plan'];

       $res = Db::getInstance()->insert('pay4later_setting',array(
        'api_key'       => '$api',
        'installtion_id'      => '$install',
        'deposite_percentage' =>'$percentages',
         'package_plan' =>'$package',
    ));

Body:
Where did you kept your ajax request.Ok,No problem.

For example,

In prestashop i have sent my ajax request through configure.tpl file

configure.tpl

<head>
<script>
$(document).ready(function(){

        $('#submit_label').click(function(){
               var data = "welcome";
                $.ajax({
                type:"POST",
                dataType:"JSON",
                url:baseDir+'modules/anything/data.php',
                data:{
                ajax:true,
                name:data,
                },
                success: function(html){

                    if(html.added)
                    {
                         $("#success").html(html.added);

                    }

            }
                });

        });

});

And here i have using data.php as a php file

data.php

<?php
require_once(dirname(__FILE__).'../../../config/config.inc.php');
require_once(dirname(__FILE__).'../../../init.php');

if(isset($_POST['name']))
{
    $label_name = $_POST['name']; or you can use Tools::getValue("name");

    $connect_db = Db::getInstance()->insert('label', array(
    'label_name' => pSQL($label_name),
    ));

    $getin['added'] = 'Label created successfully';//here we have using JSON datatype so we need to create object and store some values.

    echo json_encode($getin);

}

Thanks & Regards,
krishna.


问:
Or condition in PHP with str_replace
I have been looking to use or condition in PHP in str_replace when array is used.
Ex:Currently below is the some code str_replace line in one of my code snippet.

```<code>$header['model'] = str_replace(array('myexample', 'i'), '', $header['model']);
</code>```

Can I use or condition as below

```<code>$header['model'] = str_replace(array('myexample', 'i') || array('myexample1', 'i'), '', $header['model']);
</code>```

Any help/suggestions, please.

Thanks.

答:
```<code>$header['model'] = str_replace(array('myexample', 'i') || array('myexample1', 'i'), '', $header['model']);
</code>```

This OR condition will not work and str_replace only replace 1 array values.

You can merge your array and then can use str_replace for both.

Try this-

```<code>$a1 = array('myexample', 'i');
$a2 = array('myexample1', 'i');
$a3 = array_merge($a1,$a2);
echo str_replace( $a3 , '', $header['model']);
</code>```

Title: Or condition in PHP with str_replace

Body:
I have been looking to use or condition in PHP in str_replace when array is used.
Ex:Currently below is the some code str_replace line in one of my code snippet.

$header['model'] = str_replace(array('myexample', 'i'), '', $header['model']);

Can I use or condition as below

$header['model'] = str_replace(array('myexample', 'i') || array('myexample1', 'i'), '', $header['model']);

Any help/suggestions, please.

Thanks.

Body:
$header['model'] = str_replace(array('myexample', 'i') || array('myexample1', 'i'), '', $header['model']);

This OR condition will not work and str_replace only replace 1 array values.

You can merge your array and then can use str_replace for both.

Try this-

$a1 = array('myexample', 'i');
$a2 = array('myexample1', 'i');
$a3 = array_merge($a1,$a2);
echo str_replace( $a3 , '', $header['model']);


问:
How to secure .NET DLL's
What is best practice for securing DLL's for projects you are working on?  Certain DLL's I am interested in developing will have data access layer (DAL) and business logic layer (BLL) functionality.  There may be several apps that can eventually hit these DLL's to perform business specific functions.

What is the best way to secure these DLL's so they can only be used by only creator's applications?

Security for both blocking unauthorized use of the DLL's and security against possible decompilation are both desirable.

答:
Protecting your intellectual property is not really possible if you ship it in the form .NET DLL's to a client. You could host your application logic in the cloud, though that might not suit your scenario.

Even the "best" obfuscators aren't infallible. You could probably put off a casual hacker, but as dthorpe says, if someone really wants to decompile your assemblies, they will.

ContentLicense: CC BY-SA 2.5

Title: How to secure .NET DLL's


问:
How do I integrate Crashlytics with Android Instant Apps?
Does Crashlytics work with Google Play Instant and if so, how do you setup your project correctly?</p>

答:
Yes, Crashlytics does work with Android Instant Apps, in fact it is the recommended crash reporting solution at this stage as it has been tested and works fine.

For setup:

Step 1

Open the build.gradle file in your base feature module and follow the steps on the public docs site to configure Crashlytics as normal.

Step 2

At the top level of your base feature module build.gradle file, add the following Crashlytics flag:

```<code>...
android {
    ...
}
crashlytics { instantAppSupport true }
...
</code>```

Step 3 (optional but recommended)

Add the Instant App library dependency in your base library project build.gradle if not already there as per the docs:

```<code>compile 'com.google.android.instantapps:instantapps:1.1.0'
</code>```

Note: to use this dependency you will need to add the newer maven.google.com repository to your gradle files if you haven't already (see here for details).

Then in your code, after setting up Crashlytics, set a boolean value to log if the current run is an Instant App:

```<code>Crashlytics.setBool("InstantApp", InstantApps.isInstantApp(context));
</code>```

<s>
Update as of Aug 2017 - New issue that breaks support

A recent tools update seems to have caused a new issue when using Crashlytics and Instant Apps that logs the following error:

This app relies on Crashlytics. Please sign up for access at
  https://fabric.io/sign_up, install an Android build tool and ask a
  team member to invite you to this app's organization.

Until the issue is fixed, please try this as a workaround: after building, find the file com_crashlytics_build_id.xml, open it up, copy the <string> from there that contains your Fabric key and paste it into your normal strings.xml file for your feature module. Then re-build and run.</s>

Update as of Nov 15, 2017 - Issue fixed

The issue above is now fixed as of Fabric gradle plugin v1.24.5. As your gradle file should have:

```<code>classpath 'io.fabric.tools:gradle:1.+'
</code>```

You shouldn't need to do anything but sync up your build to pull down the updated plugin with fix.

ContentLicense: CC BY-SA 4.0

Body:
Yes, Crashlytics does work with Android Instant Apps, in fact it is the recommended crash reporting solution at this stage as it has been tested and works fine.

For setup:

Step 1

Open the build.gradle file in your base feature module and follow the steps on the public docs site to configure Crashlytics as normal.

Step 2

At the top level of your base feature module build.gradle file, add the following Crashlytics flag:

...
android {
    ...
}
crashlytics { instantAppSupport true }
...

Step 3 (optional but recommended)

Add the Instant App library dependency in your base library project build.gradle if not already there as per the docs:

compile 'com.google.android.instantapps:instantapps:1.1.0'

Note: to use this dependency you will need to add the newer maven.google.com repository to your gradle files if you haven't already (see here for details).

Then in your code, after setting up Crashlytics, set a boolean value to log if the current run is an Instant App:

Crashlytics.setBool("InstantApp", InstantApps.isInstantApp(context));

<s>
Update as of Aug 2017 - New issue that breaks support

A recent tools update seems to have caused a new issue when using Crashlytics and Instant Apps that logs the following error:

This app relies on Crashlytics. Please sign up for access at
  https://fabric.io/sign_up, install an Android build tool and ask a
  team member to invite you to this app's organization.

Until the issue is fixed, please try this as a workaround: after building, find the file com_crashlytics_build_id.xml, open it up, copy the <string> from there that contains your Fabric key and paste it into your normal strings.xml file for your feature module. Then re-build and run.</s>

Update as of Nov 15, 2017 - Issue fixed

The issue above is now fixed as of Fabric gradle plugin v1.24.5. As your gradle file should have:

classpath 'io.fabric.tools:gradle:1.+'

You shouldn't need to do anything but sync up your build to pull down the updated plugin with fix.


问:
unique column value per row
I find it best to use an example, so here we go:

Say I have a table with chores and a table with a weekly schedule like this:

```<code>CHORES:
|----+---------------+----------+-------|
| id |      name     |   type   | hours |
|----+---------------+----------+-------|
| 1  | clean kitchen | cleaning |   4   |
|----+---------------+----------+-------|
| 2  | clean toilet  | cleaning |   3   |
etc

SCHEDULE:
|------+---------------+---------------+-----|
| week |     monday    |    tuesday    | etc |
|------+---------------+---------------+-----|
|   1  | clean kitchen | clean toilet  | etc |
|------+---------------+---------------+-----|
|   2  | clean toilet  | clean kitchen | etc |
etc
</code>```

I want  to make sure that for one week, you can't have duplicate cells, so this wouldn't be allowed:

```<code>SCHEDULE:
|------+---------------+--------------+-----|
| week |     monday    |   tuesday    | etc |
|------+---------------+--------------+-----|
|   1  | clean toilet  | clean toilet | etc |

etc
</code>```

What would I have to do  in my models.py to get this behaviour?

Title: unique column value per row

Body:
I find it best to use an example, so here we go:

Say I have a table with chores and a table with a weekly schedule like this:

CHORES:
|----+---------------+----------+-------|
| id |      name     |   type   | hours |
|----+---------------+----------+-------|
| 1  | clean kitchen | cleaning |   4   |
|----+---------------+----------+-------|
| 2  | clean toilet  | cleaning |   3   |
etc

SCHEDULE:
|------+---------------+---------------+-----|
| week |     monday    |    tuesday    | etc |
|------+---------------+---------------+-----|
|   1  | clean kitchen | clean toilet  | etc |
|------+---------------+---------------+-----|
|   2  | clean toilet  | clean kitchen | etc |
etc

I want  to make sure that for one week, you can't have duplicate cells, so this wouldn't be allowed:

SCHEDULE:
|------+---------------+--------------+-----|
| week |     monday    |   tuesday    | etc |
|------+---------------+--------------+-----|
|   1  | clean toilet  | clean toilet | etc |

etc

What would I have to do  in my models.py to get this behaviour?

Body:
I'd better user ManyToMany through another table like that:

SCHEDULE:
 ------+------------------------+
| week |     chores             |
|------+------------------------+
|   1  | many to many to chores |
|------+------------------------+
|   2  | many to many to chores |

And trough table like that

THROUGH TABLE:
|---------+---------------+---------------+
| week_id |  day of week  |    chores_id  |
|---------+---------------+---------------+
|   1     | Monday        | clean toilet  |
|---------+---------------+---------------+
|   1     | Tuesday       | clean kitchen |

And in that table make unique together for week_id and chores_id


问:
Removing from superview with gestureRecognizer
I create a blurEffectView as such:

```<code>var blurEffectView: UIVisualEffectView{
    let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.light)
    let blurEffectView = UIVisualEffectView(effect: blurEffect)
    blurEffectView.frame = self.view.bounds
    blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
    return blurEffectView
}
</code>```

And then a tapGestureRecognizer to add to the effect view.

```<code>let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.dismissBlurView))
            self.blurEffectView.addGestureRecognizer(tapGestureRecognizer)
            self.mapView.addSubview(self.blurEffectView)
</code>```

And here is the function to dismiss it:

```<code>func dismissBlurView(){
    blurEffectView.removeFromSuperview()
}
</code>```

I am obviously missing something here, as dismissBlurView is not called when I tap on the blur view.

答:
Try this </p>

```<code>class YourViewController: UIViewController, UIGestureRecognizerDelegate{

    tapGestureRecognizer.delegate = self

    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
            return true
    }
}
</code>```

Body:
I create a blurEffectView as such:

var blurEffectView: UIVisualEffectView{
    let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.light)
    let blurEffectView = UIVisualEffectView(effect: blurEffect)
    blurEffectView.frame = self.view.bounds
    blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
    return blurEffectView
}

And then a tapGestureRecognizer to add to the effect view.

let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.dismissBlurView))
            self.blurEffectView.addGestureRecognizer(tapGestureRecognizer)
            self.mapView.addSubview(self.blurEffectView)

And here is the function to dismiss it:

func dismissBlurView(){
    blurEffectView.removeFromSuperview()
}

I am obviously missing something here, as dismissBlurView is not called when I tap on the blur view.

Body:
Try this

class YourViewController: UIViewController, UIGestureRecognizerDelegate{

    tapGestureRecognizer.delegate = self

    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
            return true
    }
}


问:
Get all push notifications received since app was last open
I'm creating an iOS 10 app using Xcode 8 and CloudKit. When the app loads, is there any way to read all push notification that have been sent since the last time the app was running?</p>

答:
You can call the following function, request contains all notifications delivered

```<code>[[UNUserNotificationCenter currentNotificationCenter]
getDeliveredNotificationsWithCompletionHandler:^(NSArray<UNNotificationRequest
 _Nonnull requests) {
           NSLog(@"");
   }];
</code>```

Body:
You can call the following function, request contains all notifications delivered

[[UNUserNotificationCenter currentNotificationCenter]
getDeliveredNotificationsWithCompletionHandler:^(NSArray<UNNotificationRequest
 _Nonnull requests) {
           NSLog(@"");
   }];


问:
MacOS: g++ cross-compiler cannot find ld from dmg image
When I compile the sources from just a directory it's OK. But if I do it from dmg image I got this:

```<code>$ make
"/Volumes/:Users:me:develop:macos_build_script:myApp:myApp_Release:myApp/myApp.app/Contents/MacOS/devkit-x86/sysroots/i386-pokysdk-darwin/usr/bin/i586-poky-linux/i586-poky-linux-g++" -std=c++11 -Wall -O2 --sysroot="/Volumes/:Users:me:develop:macos_build_script:myApp:myApp_Release:myApp/myApp.app/Contents/MacOS/devkit-x86/sysroots/core2-32-poky-linux" -c -MD main.cpp -I/Volumes/:Users:me:develop:macos_build_script:myApp:myApp_Release:myApp/myApp.app/Contents/MacOS/devkit-x86/sysroots/core2-32-poky-linux/usr/include/c++/4.9.1 -I/Volumes/:Users:me:develop:macos_build_script:myApp:myApp_Release:myApp/myApp.app/Contents/MacOS/devkit-x86/sysroots/core2-32-poky-linux/usr/include/c++/4.9.1/i586-poky-linux -o main.o
"/Volumes/:Users:me:develop:macos_build_script:myApp:myApp_Release:myApp/myApp.app/Contents/MacOS/devkit-x86/sysroots/i386-pokysdk-darwin/usr/bin/i586-poky-linux/i586-poky-linux-g++" -std=c++11 -Wall -O2 --sysroot="/Volumes/:Users:me:develop:macos_build_script:myApp:myApp_Release:myApp/myApp.app/Contents/MacOS/devkit-x86/sysroots/core2-32-poky-linux" main.o -I/Volumes/:Users:me:develop:macos_build_script:myApp:myApp_Release:myApp/myApp.app/Contents/MacOS/devkit-x86/sysroots/core2-32-poky-linux/usr/include/c++/4.9.1 -I/Volumes/:Users:me:develop:macos_build_script:myApp:myApp_Release:myApp/myApp.app/Contents/MacOS/devkit-x86/sysroots/core2-32-poky-linux/usr/include/c++/4.9.1/i586-poky-linux -lopencv_core -lopencv_highgui -lopencv_imgproc -lzmq -o aaa.bin
collect2: fatal error: cannot find 'ld'
compilation terminated.
make: *** [aaa] Error 1
</code>```

After this error I unpack contents from *.dmg then run it and compilation  completes successful.

Why and what I need to do to make it work from dmg?

My *.dmg contains an application and a cross-compiler. Source files for compilation are outside and created by this application. It is simple IDE.

答:
Finaly I find out the cause of this problem. It is two bug-or-features one in macdeployqt and one in g++.

When I wrote my building script I thought it will be good to get dmg image in same directory from which I run my script. And I added a command with absolute path:

```<code>macdeployqt /Users/me/develop/macos_build_script/myApp/myApp_Release/myApp/myApp.app -dmg
</code>```

The image was built and my app ran well. But. Silently macdeployqt made a name for dmg mount point from absolute path. The absolute path became a single directory name with colons instead slashes:
:Users:me:develop:macos_build_script:myApp:myApp_Release:myApp. The root of dmg did not contain this directory, it only appears when dmg image is mounted.

Then this directory with colons will be part of variables of makefile.

Cross-compilator i586-poky-linux-g++ builds an object files when paths with colons present. And I thought it's all ok with g++ if it using this coloned paths for object files. I thought the cause somwhere in other place. But I was wrong.

Backslashing of colons din't help.

In some moment I builded the dmg image by hands from a directory in which myApp.app bundle subdirectory placed with this short command:

```<code>macdeployqt myApp.app -dmg
</code>```

And the problem is gone. The mount point of dmg image now is just /Volumes/myApp. I do nothing except jump to dir where myApp.app is and making the relative path.

Body:
When I compile the sources from just a directory it's OK. But if I do it from dmg image I got this:

$ make
"/Volumes/:Users:me:develop:macos_build_script:myApp:myApp_Release:myApp/myApp.app/Contents/MacOS/devkit-x86/sysroots/i386-pokysdk-darwin/usr/bin/i586-poky-linux/i586-poky-linux-g++" -std=c++11 -Wall -O2 --sysroot="/Volumes/:Users:me:develop:macos_build_script:myApp:myApp_Release:myApp/myApp.app/Contents/MacOS/devkit-x86/sysroots/core2-32-poky-linux" -c -MD main.cpp -I/Volumes/:Users:me:develop:macos_build_script:myApp:myApp_Release:myApp/myApp.app/Contents/MacOS/devkit-x86/sysroots/core2-32-poky-linux/usr/include/c++/4.9.1 -I/Volumes/:Users:me:develop:macos_build_script:myApp:myApp_Release:myApp/myApp.app/Contents/MacOS/devkit-x86/sysroots/core2-32-poky-linux/usr/include/c++/4.9.1/i586-poky-linux -o main.o
"/Volumes/:Users:me:develop:macos_build_script:myApp:myApp_Release:myApp/myApp.app/Contents/MacOS/devkit-x86/sysroots/i386-pokysdk-darwin/usr/bin/i586-poky-linux/i586-poky-linux-g++" -std=c++11 -Wall -O2 --sysroot="/Volumes/:Users:me:develop:macos_build_script:myApp:myApp_Release:myApp/myApp.app/Contents/MacOS/devkit-x86/sysroots/core2-32-poky-linux" main.o -I/Volumes/:Users:me:develop:macos_build_script:myApp:myApp_Release:myApp/myApp.app/Contents/MacOS/devkit-x86/sysroots/core2-32-poky-linux/usr/include/c++/4.9.1 -I/Volumes/:Users:me:develop:macos_build_script:myApp:myApp_Release:myApp/myApp.app/Contents/MacOS/devkit-x86/sysroots/core2-32-poky-linux/usr/include/c++/4.9.1/i586-poky-linux -lopencv_core -lopencv_highgui -lopencv_imgproc -lzmq -o aaa.bin
collect2: fatal error: cannot find 'ld'
compilation terminated.
make: *** [aaa] Error 1

After this error I unpack contents from *.dmg then run it and compilation  completes successful.

Why and what I need to do to make it work from dmg?

My *.dmg contains an application and a cross-compiler. Source files for compilation are outside and created by this application. It is simple IDE.

Body:
Finaly I find out the cause of this problem. It is two bug-or-features one in macdeployqt and one in g++.

When I wrote my building script I thought it will be good to get dmg image in same directory from which I run my script. And I added a command with absolute path:

macdeployqt /Users/me/develop/macos_build_script/myApp/myApp_Release/myApp/myApp.app -dmg

The image was built and my app ran well. But. Silently macdeployqt made a name for dmg mount point from absolute path. The absolute path became a single directory name with colons instead slashes:
:Users:me:develop:macos_build_script:myApp:myApp_Release:myApp. The root of dmg did not contain this directory, it only appears when dmg image is mounted.

Then this directory with colons will be part of variables of makefile.

Cross-compilator i586-poky-linux-g++ builds an object files when paths with colons present. And I thought it's all ok with g++ if it using this coloned paths for object files. I thought the cause somwhere in other place. But I was wrong.

Backslashing of colons din't help.

In some moment I builded the dmg image by hands from a directory in which myApp.app bundle subdirectory placed with this short command:

macdeployqt myApp.app -dmg

And the problem is gone. The mount point of dmg image now is just /Volumes/myApp. I do nothing except jump to dir where myApp.app is and making the relative path.


问:
Square an array's size with the same pattern repeated
Given an array int X[x_size], I'd like to make a new array int Y[x_size * x_size] and copy the values of X in order.

For example, given X = {0, 1, 2}, I'd like array Y to be {0, 1, 2, 0, 1, 2, 0, 1, 2}.

```<code>int main(int argc, const char * argv[]) {
    int x[3] = [0,1,2];
    int * y = makeY(a,3);
}
int * makeY(int x[], int size) {
    int *y = new int[size * size];
    for(int i = 0; i < size; size+=2)
        for(int j = i; j < j + (size - 1); j++)
            for (int i = 0; i < size; i++)
                y[j+i] = x[i];
    return y;
}
</code>```

答:
Assuming you're allowed to have fun with the standard library:</p>

```<code>std::vector<int> repeat_square_vector(const std::vector<int>& original)
{
    std::vector<int> repeated(original.size() * original.size());
    std::generate(repeated.begin(), repeated.end(), [&original](){static size_t i = 0; return original[i++ % original.size()];});
    return repeated;
}

int main()
{
    std::vector<int> original = {0, 1, 2};
    std::vector<int> repeated = repeat_square_vector(original);
    //repeated == {0, 1, 2, 0, 1, 2, 0, 1, 2}
}
</code>```

Body:
Given an array int X[x_size], I'd like to make a new array int Y[x_size * x_size] and copy the values of X in order.

For example, given X = {0, 1, 2}, I'd like array Y to be {0, 1, 2, 0, 1, 2, 0, 1, 2}.

int main(int argc, const char * argv[]) {
    int x[3] = [0,1,2];
    int * y = makeY(a,3);
}
int * makeY(int x[], int size) {
    int *y = new int[size * size];
    for(int i = 0; i < size; size+=2)
        for(int j = i; j < j + (size - 1); j++)
            for (int i = 0; i < size; i++)
                y[j+i] = x[i];
    return y;
}

Body:
Assuming you're allowed to have fun with the standard library:

std::vector<int> repeat_square_vector(const std::vector<int>& original)
{
    std::vector<int> repeated(original.size() * original.size());
    std::generate(repeated.begin(), repeated.end(), [&original](){static size_t i = 0; return original[i++ % original.size()];});
    return repeated;
}

int main()
{
    std::vector<int> original = {0, 1, 2};
    std::vector<int> repeated = repeat_square_vector(original);
    //repeated == {0, 1, 2, 0, 1, 2, 0, 1, 2}
}


问:
Why doesn't Javascript Dynamic HTML5 Table Not Appear on Page
I am attempting to take quantities of products and multiplying them by the price before inserting these constantly updating values into an HTML table. I am using a forever loop to constantly take input for the sake of the example.</p>

```<code>    <!DOCTYPE html>
    <html>

    <head>
    <meta charset="utf-8">

<script>
<!--
var product1 = 0;
var product2 = 0;
var product3 = 0;
var product4 = 0;
var product5 = 0;
var productNum = 0;
var productNumInt = 0;
var quantitySold = 0;
var quantitySoldInt = 0;

document.write("<table>");
document.write("<tr><th>Product Number</th><th>Quantity Sold</th></tr>");
document.write("<tr><td>1</td><td>$" + product1 + "</td></tr>");
document.write("<tr><td>2</td><td>$" + product2 + "</td></tr>");
document.write("<tr><td>3</td><td>$" + product3 + "</td></tr>");
document.write("<tr><td>4</td><td>$" + product4 + "</td></tr>");
document.write("<tr><td>5</td><td>$" + product5 + "</td></tr>");
document.write("</table>");

while (true) {
  productNum = window.prompt("Please enter the product number");
  quantitySold = window.prompt("Please enter the quantity sold");
  productNumInt = parseInt(productNum);
  quantitySoldInt = parseInt(quantitySold);

  switch (productNumInt) {
    case 1:
      product1 += quantitySoldInt * 2.98;
      break;
    case 2:
      product2 += quantitySoldInt * 4.50;
      break;
    case 3:
      product3 += quantitySoldInt * 9.98;
      break;
    case 4:
      product4 += quantitySoldInt * 4.49;
      break;
    case 5:
      product5 += quantitySoldInt * 6.87;
      break;
  }
}
// -->
</script>
</head>

<body>
</body>

</html>
</code>```

答:
First, you don't need to document.write this part:

```<code>document.write("<table>");
document.write("<tr><th>Product Number</th><th>Quantity Sold</th></tr>");
</code>```

In fact, you don't need to use document.write at all in your situation and it can be healthier to avoid it when not necessary.

You could relieve some pain by having this markup as a base model:

HTML

```<code><table>
   <tr><th>Product Number</th><th>Quantity Sold</th></tr>
   <tr><td>1</td><td id="product1"></td></tr>
   <tr><td>2</td><td id="product2"></td></tr>
   <tr><td>3</td><td id="product3"></td></tr>
   <tr><td>4</td><td id="product4"></td></tr>
   <tr><td>5</td><td id="product5"></td></tr>
</table>
</code>```

Then, you can access your fields with something like this (the script being at the end of the body, or at least after the table markup):

JavaScript

```<code>document.getElementById("product1").innerHTML = "1.00";
document.getElementById("product2").innerHTML = "2.00";
document.getElementById("product3").innerHTML = "3.00";
document.getElementById("product4").innerHTML = "4.00";
document.getElementById("product5").innerHTML = "5.00";
</code>```

Even better, you can create a DOM (Document Object Model) text element and update it (see DOM reference):

```<code>var product1_text = document.createTextNode("1.00");
document.getElementById("product1").appendChild(product1_text);

// now you can update the value
product1_text.textContent = "1.50"; // calculated value
</code>```

I will let you think about the problem of calculating with text cells. With your current script, you will face issues with operator += on a string. Keep in mind that when you get a displayed number, you work with a string and not the base 10 number represented by it. You will need the function parseFloat(stringValue) to achieve that.

I hope this helped and good luck.

Body:
I am attempting to take quantities of products and multiplying them by the price before inserting these constantly updating values into an HTML table. I am using a forever loop to constantly take input for the sake of the example.

    <!DOCTYPE html>

    <meta charset="utf-8">

Body:
First, you don't need to document.write this part:

document.write("<table>");
document.write("<tr><th>Product Number</th><th>Quantity Sold</th></tr>");

In fact, you don't need to use document.write at all in your situation and it can be healthier to avoid it when not necessary.

You could relieve some pain by having this markup as a base model:

HTML

<table>
   <tr><th>Product Number</th><th>Quantity Sold</th></tr>
   <tr><td>1</td><td id="product1"></td></tr>
   <tr><td>2</td><td id="product2"></td></tr>
   <tr><td>3</td><td id="product3"></td></tr>
   <tr><td>4</td><td id="product4"></td></tr>
   <tr><td>5</td><td id="product5"></td></tr>
</table>

Then, you can access your fields with something like this (the script being at the end of the body, or at least after the table markup):

JavaScript

document.getElementById("product1").innerHTML = "1.00";
document.getElementById("product2").innerHTML = "2.00";
document.getElementById("product3").innerHTML = "3.00";
document.getElementById("product4").innerHTML = "4.00";
document.getElementById("product5").innerHTML = "5.00";

Even better, you can create a DOM (Document Object Model) text element and update it (see DOM reference):

var product1_text = document.createTextNode("1.00");
document.getElementById("product1").appendChild(product1_text);

// now you can update the value
product1_text.textContent = "1.50"; // calculated value

I will let you think about the problem of calculating with text cells. With your current script, you will face issues with operator += on a string. Keep in mind that when you get a displayed number, you work with a string and not the base 10 number represented by it. You will need the function parseFloat(stringValue) to achieve that.

I hope this helped and good luck.


问:
Is it normal for keys in a hashtable to sometimes collide with themselves?
This my 2nd  time on Stack Overflow so please tell me if I am missing any details and sorry if  my question  is not that properly formatted, I'm not used this site constantly.

My question is: When I run my code it's supposed to print back as an output:

the percentage of the hash-table that is filled,

the total accumulated collisions,

the total number of collisions, and

the name of keys that are being collided with when inserting keys into the hash-table.

All of which comes out fine except when printing out the names of the keys that are being collided with, sometimes it prints out the same name of the key being inserted, and I am not sure if that's supposed to happen in a hash-table or not?

```<code>/** Container class for a key-value pair */

   class KVpair<Key, E> {
   private Key k;
   private E e;

  /** Constructors */
  KVpair()
    { k = null; e = null; }
  KVpair(Key kval, E eval)
    { k = kval; e = eval; }

  /** Data member access functions */
  public Key key() { return k; }
  public E value() { return e; }
 }

public class HashTable<Key extends Comparable<? super Key>, E> {

private int M;
private KVpair<Key, E>[] HT;
private int collisionSum = 0;

private int h(Key key) {
    HashFunction hf = new HashFunction();
    return hf.sfold((String) key, M);
}

private int p(Key key, int slot) {
    return slot;
}

@SuppressWarnings("unchecked") // Generic array allocation
HashTable(int m) {
    M = m;
    HT = (KVpair<Key, E>[]) new KVpair[M];
}

/** Insert record r with key k into HT */
void hashInsert(Key k, E r) {
    int home; // Home position for r
    int pos = home = h(k); // Initial position
    int AccumulatedSum = 0;
    for (int i = 1; HT[pos] != null; i++) {
        collisionSum++;
        AccumulatedSum++;
        if (HT[pos].key().compareTo(k) != 0 )
            System.out.println("Collided with key " + HT[pos].key());
        pos = (home + p(k, i)) % M; // Next probe slot
        assert HT[pos].key().compareTo(k) != 0 : "Duplicates not allowed";
    }
    HT[pos] = new KVpair<Key, E>(k, r); // Insert R
    System.out.printf("Accumulated collisions: %d\n", AccumulatedSum);
    System.out.printf("Total number of  Collisions %d\n", collisionSum);
}

/** Search in hash table HT for the record with key k */
E hashSearch(Key k) {
    int home; // Home position for k
    int pos = home = h(k); // Initial position
    for (int i = 1; (HT[pos] != null) && (HT[pos].key().compareTo(k) != 0); i++) {
        pos = (home + p(k, i)) % M; // Next probe position
        if (i == M) {
            return null;
        }
        System.out.println(pos);
    }

    return HT[pos].value(); // Found it
}

}

import java.io.*;
import java.math.*;

  // This is the hashFunction that will be used in the hashtable
  // for linear probing of indexes when collisions happen.
   //where s is the String key being passed and M is the size of the hashTable

    public class HashFunction
{

     int sfold(String s, int M) {

     int intLength = s.length() / 4;
     int sum = 0;
     for (int j = 0; j < intLength; j++) {
       char c[] = s.substring(j*4,(j*4)+4).toCharArray();
    int mult = 1;
    for (int k = 0; k < c.length; k++) {
        sum += c[k] * mult;
        mult *= 256;
      }
  }
     char c[] = s.substring(intLength * 4).toCharArray();
     int mult = 1;
     for (int k = 0; k < c.length; k++) {
        sum += c[k] * mult;
        mult *= 256;
  }
    return(Math.abs(sum) % M);
  }
    int h(String x, int M) {
    char ch[];
    ch = x.toCharArray();
    int xlength = x.length();
    int i, sum;
    for (sum=0, i=0; i < xlength; i++)
         sum += ch[i];
    return sum % M;
}
   int h(int x) {
    return(x % 16);
  }

}

import java.util.Arrays;
import java.util.Random;

public class randHashTableDriver {

    public static void main(String[] args) {

        int htLength = 128; // HashTable Size
        HashTable<String, String> hashT = new HashTable<>(htLength);
        HashTable<String, String> hashT2= new HashTable<>(htLength);
        fillHashTable(hashT, htLength, 0.4);
        fillHashTable(hashT2, htLength, 0.6);

    }

    // Generates a String array filled with words of 8 letters in length with no
    // duplicates
    static String[] randomWordGen(int wordCount) {
        int wordLength = 8;
        String[] words = new String[wordCount];
        Arrays.fill(words, "");
        Random r = new Random();
        for (int i = 0; i < wordCount; i++) {
            String s = "";
            for (int t = 0; t < wordLength; t++) {
                char c = (char) (r.nextInt(26) + 65);
                s += c;
            }
            if (Arrays.asList(words).contains(s)) {
                i--;
                continue;
            }
            words[i] += s;
        }
        return words;
    }

    // Creates the HashTable and Fills it with indexes until it reaches the
    // Percent specified
    static void fillHashTable(HashTable<String, String> h, int size, double fillPercentage ) {
        int indexes = (int) Math.ceil( size * fillPercentage);
        String[] words = randomWordGen(indexes);
        System.out.println("\n\n------Filling HashTable------");
        for (int i = 0; i < indexes; i++) {
            h.hashInsert(words[i], words[i]);
            System.out.printf("\nInserting Word: %s , FillPercentage: %.2f\n", words[i], ((i+1d) /size) * 100);
        }

    }

}
</code>```

Example output of where the problem occurs (output is actually longer than this):

```<code>------Filling HashTable------
Accumulated collisions: 0
Total number of  Collisions 0

Inserting Word: KPUWLEYG , FillPercentage: 0.78
Accumulated collisions: 0
Total number of  Collisions 0

Inserting Word: CVJLHZTS , FillPercentage: 1.56
Accumulated collisions: 0
Total number of  Collisions 0

Inserting Word: PHTMMRDF , FillPercentage: 2.34
Collided with key PHTMMRDF
Accumulated collisions: 1
Total number of  Collisions 1

Inserting Word: LBHTQOZT , FillPercentage: 3.13
Accumulated collisions: 0
Total number of  Collisions 1

Inserting Word: JJIRZFEU , FillPercentage: 3.91
Accumulated collisions: 0
Total number of  Collisions 1

Inserting Word: ETWYECDW , FillPercentage: 4.69
Accumulated collisions: 0
Total number of  Collisions 1

Inserting Word: PEKVFYWK , FillPercentage: 5.47
Collided with key PHTMMRDF
Collided with key LBHTQOZT
Accumulated collisions: 2
Total number of  Collisions 3

Inserting Word: LSRKQZWI , FillPercentage: 6.25
Accumulated collisions: 0
Total number of  Collisions 3

Inserting Word: QVVHNKKY , FillPercentage: 7.03
Accumulated collisions: 0
Total number of  Collisions 3

Inserting Word: AWNKDWPU , FillPercentage: 7.81
Accumulated collisions: 0
Total number of  Collisions 3

Inserting Word: BCLQXGGZ , FillPercentage: 8.59
Accumulated collisions: 0
Total number of  Collisions 3

Inserting Word: NWCLTWVW , FillPercentage: 9.38
Accumulated collisions: 0
Total number of  Collisions 3

Inserting Word: EZMHLCRT , FillPercentage: 10.16
Accumulated collisions: 0
Total number of  Collisions 3

Inserting Word: AKOREOMM , FillPercentage: 10.94
Accumulated collisions: 0
Total number of  Collisions 3

Inserting Word: TFFDJHDM , FillPercentage: 11.72
Accumulated collisions: 0
Total number of  Collisions 3

Inserting Word: CVLWLOMC , FillPercentage: 12.50
Collided with key PEKVFYWK
Accumulated collisions: 1
Total number of  Collisions 4

Inserting Word: JHTDLBBU , FillPercentage: 13.28
Accumulated collisions: 0
Total number of  Collisions 4

Inserting Word: DSQRNEFA , FillPercentage: 14.06
Accumulated collisions: 0
Total number of  Collisions 4

Inserting Word: FOBTANHC , FillPercentage: 14.84
Collided with key QVVHNKKY
Collided with key TFFDJHDM
Collided with key PHTMMRDF
Collided with key LBHTQOZT
Collided with key LSRKQZWI
Collided with key BCLQXGGZ
Accumulated collisions: 6
Total number of  Collisions 10

Inserting Word: MLJVRHMQ , FillPercentage: 15.63
Collided with key MLJVRHMQ
Accumulated collisions: 1
Total number of  Collisions 11
</code>```

答:
```<code>is it normal for the key to collide with itself
</code>```

Yes, Hash collision is normal and perhaps practically not avoidable when hashing a random large set of keys. A proof could be - hashcode is of integer type with the max value of (2^32)-1. However, the hash table implementations like HashMap/Hashtable follow collision resolution strategy to handle such events. The strategy used here is called separate chaining where a bucket is created and has some sort of list of entries with the same index. If you google with "HashMap intenal implementation", you can find more details.

Basically, if we need to retrieve value object in case of collision, a call to hashCode() method will retrieve bucket and traverse thought list by comparing keys in each entries using keys.equals() until it matches. Thus there is a common saying in Java "Override hashcode when you override equals" because two unequal objects may return the same hashcode but When two objects are equal by equals(), they must have the same hashcode.

Body:
This my 2nd  time on Stack Overflow so please tell me if I am missing any details and sorry if  my question  is not that properly formatted, I'm not used this site constantly.

My question is: When I run my code it's supposed to print back as an output:

the percentage of the hash-table that is filled,

the total accumulated collisions,

the total number of collisions, and

the name of keys that are being collided with when inserting keys into the hash-table.

All of which comes out fine except when printing out the names of the keys that are being collided with, sometimes it prints out the same name of the key being inserted, and I am not sure if that's supposed to happen in a hash-table or not?

/** Container class for a key-value pair */

   class KVpair<Key, E> {
   private Key k;
   private E e;

  /** Constructors */
  KVpair()
    { k = null; e = null; }
  KVpair(Key kval, E eval)
    { k = kval; e = eval; }

  /** Data member access functions */
  public Key key() { return k; }
  public E value() { return e; }
 }

public class HashTable<Key extends Comparable<? super Key>, E> {

private int M;
private KVpair<Key, E>[] HT;
private int collisionSum = 0;

private int h(Key key) {
    HashFunction hf = new HashFunction();
    return hf.sfold((String) key, M);
}

private int p(Key key, int slot) {
    return slot;
}

@SuppressWarnings("unchecked") // Generic array allocation
HashTable(int m) {
    M = m;
    HT = (KVpair<Key, E>[]) new KVpair[M];
}

/** Insert record r with key k into HT */
void hashInsert(Key k, E r) {
    int home; // Home position for r
    int pos = home = h(k); // Initial position
    int AccumulatedSum = 0;
    for (int i = 1; HT[pos] != null; i++) {
        collisionSum++;
        AccumulatedSum++;
        if (HT[pos].key().compareTo(k) != 0 )
            System.out.println("Collided with key " + HT[pos].key());
        pos = (home + p(k, i)) % M; // Next probe slot
        assert HT[pos].key().compareTo(k) != 0 : "Duplicates not allowed";
    }
    HT[pos] = new KVpair<Key, E>(k, r); // Insert R
    System.out.printf("Accumulated collisions: %d\n", AccumulatedSum);
    System.out.printf("Total number of  Collisions %d\n", collisionSum);
}

/** Search in hash table HT for the record with key k */
E hashSearch(Key k) {
    int home; // Home position for k
    int pos = home = h(k); // Initial position
    for (int i = 1; (HT[pos] != null) && (HT[pos].key().compareTo(k) != 0); i++) {
        pos = (home + p(k, i)) % M; // Next probe position
        if (i == M) {
            return null;
        }
        System.out.println(pos);
    }

    return HT[pos].value(); // Found it
}

}

import java.io.*;
import java.math.*;

  // This is the hashFunction that will be used in the hashtable
  // for linear probing of indexes when collisions happen.
   //where s is the String key being passed and M is the size of the hashTable

    public class HashFunction
{

     int sfold(String s, int M) {

     int intLength = s.length() / 4;
     int sum = 0;
     for (int j = 0; j < intLength; j++) {
       char c[] = s.substring(j*4,(j*4)+4).toCharArray();
    int mult = 1;
    for (int k = 0; k < c.length; k++) {
        sum += c[k] * mult;
        mult *= 256;
      }
  }
     char c[] = s.substring(intLength * 4).toCharArray();
     int mult = 1;
     for (int k = 0; k < c.length; k++) {
        sum += c[k] * mult;
        mult *= 256;
  }
    return(Math.abs(sum) % M);
  }
    int h(String x, int M) {
    char ch[];
    ch = x.toCharArray();
    int xlength = x.length();
    int i, sum;
    for (sum=0, i=0; i < xlength; i++)
         sum += ch[i];
    return sum % M;
}
   int h(int x) {
    return(x % 16);
  }

}

import java.util.Arrays;
import java.util.Random;

public class randHashTableDriver {

    public static void main(String[] args) {

        int htLength = 128; // HashTable Size
        HashTable<String, String> hashT = new HashTable<>(htLength);
        HashTable<String, String> hashT2= new HashTable<>(htLength);
        fillHashTable(hashT, htLength, 0.4);
        fillHashTable(hashT2, htLength, 0.6);

    }

    // Generates a String array filled with words of 8 letters in length with no
    // duplicates
    static String[] randomWordGen(int wordCount) {
        int wordLength = 8;
        String[] words = new String[wordCount];
        Arrays.fill(words, "");
        Random r = new Random();
        for (int i = 0; i < wordCount; i++) {
            String s = "";
            for (int t = 0; t < wordLength; t++) {
                char c = (char) (r.nextInt(26) + 65);
                s += c;
            }
            if (Arrays.asList(words).contains(s)) {
                i--;
                continue;
            }
            words[i] += s;
        }
        return words;
    }

    // Creates the HashTable and Fills it with indexes until it reaches the
    // Percent specified
    static void fillHashTable(HashTable<String, String> h, int size, double fillPercentage ) {
        int indexes = (int) Math.ceil( size * fillPercentage);
        String[] words = randomWordGen(indexes);
        System.out.println("\n\n------Filling HashTable------");
        for (int i = 0; i < indexes; i++) {
            h.hashInsert(words[i], words[i]);
            System.out.printf("\nInserting Word: %s , FillPercentage: %.2f\n", words[i], ((i+1d) /size) * 100);
        }

    }

}

Example output of where the problem occurs (output is actually longer than this):

------Filling HashTable------
Accumulated collisions: 0
Total number of  Collisions 0

Inserting Word: KPUWLEYG , FillPercentage: 0.78
Accumulated collisions: 0
Total number of  Collisions 0

Inserting Word: CVJLHZTS , FillPercentage: 1.56
Accumulated collisions: 0
Total number of  Collisions 0

Inserting Word: PHTMMRDF , FillPercentage: 2.34
Collided with key PHTMMRDF
Accumulated collisions: 1
Total number of  Collisions 1

Inserting Word: LBHTQOZT , FillPercentage: 3.13
Accumulated collisions: 0
Total number of  Collisions 1

Inserting Word: JJIRZFEU , FillPercentage: 3.91
Accumulated collisions: 0
Total number of  Collisions 1

Inserting Word: ETWYECDW , FillPercentage: 4.69
Accumulated collisions: 0
Total number of  Collisions 1

Inserting Word: PEKVFYWK , FillPercentage: 5.47
Collided with key PHTMMRDF
Collided with key LBHTQOZT
Accumulated collisions: 2
Total number of  Collisions 3

Inserting Word: LSRKQZWI , FillPercentage: 6.25
Accumulated collisions: 0
Total number of  Collisions 3

Inserting Word: QVVHNKKY , FillPercentage: 7.03
Accumulated collisions: 0
Total number of  Collisions 3

Inserting Word: AWNKDWPU , FillPercentage: 7.81
Accumulated collisions: 0
Total number of  Collisions 3

Inserting Word: BCLQXGGZ , FillPercentage: 8.59
Accumulated collisions: 0
Total number of  Collisions 3

Inserting Word: NWCLTWVW , FillPercentage: 9.38
Accumulated collisions: 0
Total number of  Collisions 3

Inserting Word: EZMHLCRT , FillPercentage: 10.16
Accumulated collisions: 0
Total number of  Collisions 3

Inserting Word: AKOREOMM , FillPercentage: 10.94
Accumulated collisions: 0
Total number of  Collisions 3

Inserting Word: TFFDJHDM , FillPercentage: 11.72
Accumulated collisions: 0
Total number of  Collisions 3

Inserting Word: CVLWLOMC , FillPercentage: 12.50
Collided with key PEKVFYWK
Accumulated collisions: 1
Total number of  Collisions 4

Inserting Word: JHTDLBBU , FillPercentage: 13.28
Accumulated collisions: 0
Total number of  Collisions 4

Inserting Word: DSQRNEFA , FillPercentage: 14.06
Accumulated collisions: 0
Total number of  Collisions 4

Inserting Word: FOBTANHC , FillPercentage: 14.84
Collided with key QVVHNKKY
Collided with key TFFDJHDM
Collided with key PHTMMRDF
Collided with key LBHTQOZT
Collided with key LSRKQZWI
Collided with key BCLQXGGZ
Accumulated collisions: 6
Total number of  Collisions 10

Inserting Word: MLJVRHMQ , FillPercentage: 15.63
Collided with key MLJVRHMQ
Accumulated collisions: 1
Total number of  Collisions 11

Body:
is it normal for the key to collide with itself

Yes, Hash collision is normal and perhaps practically not avoidable when hashing a random large set of keys. A proof could be - hashcode is of integer type with the max value of (2^32)-1. However, the hash table implementations like HashMap/Hashtable follow collision resolution strategy to handle such events. The strategy used here is called separate chaining where a bucket is created and has some sort of list of entries with the same index. If you google with "HashMap intenal implementation", you can find more details.

Basically, if we need to retrieve value object in case of collision, a call to hashCode() method will retrieve bucket and traverse thought list by comparing keys in each entries using keys.equals() until it matches. Thus there is a common saying in Java "Override hashcode when you override equals" because two unequal objects may return the same hashcode but When two objects are equal by equals(), they must have the same hashcode.


问:
Inflating only a specific action bar menu
I have an action bar menu defined in my main activity. Now, one of the fragments I am using in that activity has its own action bar menu but when I click on the menu option, I get both the fragment's as well as the activity's menu items. How to ensure that only that fragment's menu item is displayed?

My java code for that fragment is:

```<code>public class ProfileD extends Fragment {

TextView tv_named, tv_genderd, tv_cfd, tv_aged, tv_biod, tv_statusd;
ImageView imageView_dp;

public ProfileD() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View rootView = inflater.inflate(R.layout.fragment_profile_d, container, false);

    tv_named = (TextView)rootView.findViewById(R.id.tv_named);
    tv_genderd = (TextView)rootView.findViewById(R.id.tv_genderd);
    tv_cfd= (TextView)rootView.findViewById(R.id.tv_cfd);
    tv_aged = (TextView)rootView.findViewById(R.id.tv_aged);
    tv_biod = (TextView)rootView.findViewById(R.id.tv_biod);

    tv_statusd = (TextView) rootView.findViewById(R.id.tv_statusd);

    imageView_dp = (ImageView)rootView.findViewById(R.id.imageView_dp);
    setHasOptionsMenu(true);

    return rootView;
}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {

    super.onCreateOptionsMenu(menu, inflater);

    getActivity().getMenuInflater().inflate(R.menu.profile_menu, menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.edit_profile) {

        Intent intent = new Intent(getContext(),PersonalDetails.class);
        intent.putExtra("Edit",1);
        startActivity(intent);

        return true;
    }

    return super.onOptionsItemSelected(item);
}

@Override
public void onResume() {
    super.onResume();

    AppCompatActivity appCompatActivity = (AppCompatActivity)getActivity();
    ActionBar actionBar = appCompatActivity.getSupportActionBar();
    actionBar.setTitle("Profile");
}
}
</code>```

The xml file for the menu is:

```<code><?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">

<item
    android:id="@+id/edit_profile"
    android:orderInCategory="100"
    android:title="Edit"
    app:showAsAction="never" />

</menu>
</code>```

答:
I found a solution to my problem. I am posting it here so if anyone else is facing the same issue, they can benefit from this:

I created a static menu object and stored the activity's action bar menu in that object. I then called that object from my fragment and cleared it thereby clearing the activity's menu and leaving me with the fragment's menu

Here is the updated java code for the fragment

```<code>public class ProfileD extends Fragment {

TextView tv_named, tv_genderd, tv_cfd, tv_aged, tv_biod, tv_statusd;
ImageView imageView_dp;

public ProfileD() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View rootView = inflater.inflate(R.layout.fragment_profile_d, container, false);

    tv_named = (TextView)rootView.findViewById(R.id.tv_named);
    tv_genderd = (TextView)rootView.findViewById(R.id.tv_genderd);
    tv_cfd= (TextView)rootView.findViewById(R.id.tv_cfd);
    tv_aged = (TextView)rootView.findViewById(R.id.tv_aged);
    tv_biod = (TextView)rootView.findViewById(R.id.tv_biod);

    tv_statusd = (TextView) rootView.findViewById(R.id.tv_statusd);

    imageView_dp = (ImageView)rootView.findViewById(R.id.imageView_dp);
    setHasOptionsMenu(true);

    return rootView;
}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {

    super.onCreateOptionsMenu(menu, inflater);

    HomePage.menu_home.clear();

    getActivity().getMenuInflater().inflate(R.menu.profile_menu, menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.edit_profile) {

        Intent intent = new Intent(getContext(),PersonalDetails.class);
        intent.putExtra("Edit",1);
        startActivity(intent);

        return true;
    }

    return super.onOptionsItemSelected(item);
}

@Override
public void onResume() {
    super.onResume();

    AppCompatActivity appCompatActivity = (AppCompatActivity)getActivity();
    ActionBar actionBar = appCompatActivity.getSupportActionBar();
    actionBar.setTitle("Profile");
}
}
</code>```

Body:
I have an action bar menu defined in my main activity. Now, one of the fragments I am using in that activity has its own action bar menu but when I click on the menu option, I get both the fragment's as well as the activity's menu items. How to ensure that only that fragment's menu item is displayed?

My java code for that fragment is:

public class ProfileD extends Fragment {

TextView tv_named, tv_genderd, tv_cfd, tv_aged, tv_biod, tv_statusd;
ImageView imageView_dp;

public ProfileD() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View rootView = inflater.inflate(R.layout.fragment_profile_d, container, false);

    tv_named = (TextView)rootView.findViewById(R.id.tv_named);
    tv_genderd = (TextView)rootView.findViewById(R.id.tv_genderd);
    tv_cfd= (TextView)rootView.findViewById(R.id.tv_cfd);
    tv_aged = (TextView)rootView.findViewById(R.id.tv_aged);
    tv_biod = (TextView)rootView.findViewById(R.id.tv_biod);

    tv_statusd = (TextView) rootView.findViewById(R.id.tv_statusd);

    imageView_dp = (ImageView)rootView.findViewById(R.id.imageView_dp);
    setHasOptionsMenu(true);

    return rootView;
}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {

    super.onCreateOptionsMenu(menu, inflater);

    getActivity().getMenuInflater().inflate(R.menu.profile_menu, menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.edit_profile) {

        Intent intent = new Intent(getContext(),PersonalDetails.class);
        intent.putExtra("Edit",1);
        startActivity(intent);

        return true;
    }

    return super.onOptionsItemSelected(item);
}

@Override
public void onResume() {
    super.onResume();

    AppCompatActivity appCompatActivity = (AppCompatActivity)getActivity();
    ActionBar actionBar = appCompatActivity.getSupportActionBar();
    actionBar.setTitle("Profile");
}
}

The xml file for the menu is:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">

<item
    android:id="@+id/edit_profile"
    android:orderInCategory="100"
    android:title="Edit"
    app:showAsAction="never" />

</menu>

Body:
I found a solution to my problem. I am posting it here so if anyone else is facing the same issue, they can benefit from this:

I created a static menu object and stored the activity's action bar menu in that object. I then called that object from my fragment and cleared it thereby clearing the activity's menu and leaving me with the fragment's menu

Here is the updated java code for the fragment

public class ProfileD extends Fragment {

TextView tv_named, tv_genderd, tv_cfd, tv_aged, tv_biod, tv_statusd;
ImageView imageView_dp;

public ProfileD() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View rootView = inflater.inflate(R.layout.fragment_profile_d, container, false);

    tv_named = (TextView)rootView.findViewById(R.id.tv_named);
    tv_genderd = (TextView)rootView.findViewById(R.id.tv_genderd);
    tv_cfd= (TextView)rootView.findViewById(R.id.tv_cfd);
    tv_aged = (TextView)rootView.findViewById(R.id.tv_aged);
    tv_biod = (TextView)rootView.findViewById(R.id.tv_biod);

    tv_statusd = (TextView) rootView.findViewById(R.id.tv_statusd);

    imageView_dp = (ImageView)rootView.findViewById(R.id.imageView_dp);
    setHasOptionsMenu(true);

    return rootView;
}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {

    super.onCreateOptionsMenu(menu, inflater);

    HomePage.menu_home.clear();

    getActivity().getMenuInflater().inflate(R.menu.profile_menu, menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.edit_profile) {

        Intent intent = new Intent(getContext(),PersonalDetails.class);
        intent.putExtra("Edit",1);
        startActivity(intent);

        return true;
    }

    return super.onOptionsItemSelected(item);
}

@Override
public void onResume() {
    super.onResume();

    AppCompatActivity appCompatActivity = (AppCompatActivity)getActivity();
    ActionBar actionBar = appCompatActivity.getSupportActionBar();
    actionBar.setTitle("Profile");
}
}


问:
Go decode json string
discovered that go json decoding is a big pain in the butt so please help.
Here's my json:

```<code> {
   "BTC_BCN":{
      "id":7,
      "last":"0.00000156",
      "lowestAsk":"0.00000156",
      "highestBid":"0.00000155",
      "percentChange":"0.01960784",
      "baseVolume":"4920.84786257",
      "quoteVolume":"3016048494.19305944",
      "isFrozen":"0",
      "high24hr":"0.00000183",
      "low24hr":"0.00000145"
   },
   "BTC_BELA":{
      "id":8,
      "last":"0.00008847",
      "lowestAsk":"0.00008848",
      "highestBid":"0.00008847",
      "percentChange":"-0.00405268",
      "baseVolume":"169.66498061",
      "quoteVolume":"1981232.44495809",
      "isFrozen":"0",
      "high24hr":"0.00008995",
      "low24hr":"0.00008120"
   }, ...
}
</code>```

So I need to put that in a type that I created

```<code>//Crypto is the currency object
type Crypto struct {
    iso           string //this is the key (ex: BTC_BCN)
    id            int
    last          float64
    lowestAsk     float64
    highestBid    float64
    percentChange float64
    baseVolume    float64
    quoteVolume   float64
    isFrozen      int
    high24hr      float64
    low24hr       float64
}
</code>```

and here is what I did so far, but I ended up with the keys in place and an empty value

```<code>func main() {
    // sendEmail("Some text")
    currencies := getCurrencies()
    if currencies == nil {
        return
    }
    fmt.Println(len(currencies))

}

func getCurrencies() map[string]Crypto {
    curList := make(map[string]Crypto)
    resp, err := http.Get("https://poloniex.com/public?command=returnTicker")
    // fmt.Println(err)
    if err != nil {
        sendEmail("Error getting data from poloniex " + err.Error())
        return nil
    }
    body, readErr := ioutil.ReadAll(resp.Body)
    reader := strings.NewReader(string(body))
    jsonErr := json.NewDecoder(reader).Decode(&curList)
    // fmt.Printf("curList is : %#v\n", curList)
    // fmt.Printf("body is : %s\n", string(body))
    if readErr != nil {
        fmt.Printf("readErr: %s\n", readErr.Error())
    }
    if jsonErr != nil {
        fmt.Printf("jsonErr: %s\n", jsonErr.Error())
    }
    for k, v := range curList {
        fmt.Println("k:", k, "v:", v)
    }
    defer resp.Body.Close()
    return curList
}
</code>```

output:

```<code>k: BTC_MAID v: {0 0 0 0 0 0 0 0 0 0}
k: BTC_NOTE v: {0 0 0 0 0 0 0 0 0 0}
k: BTC_VRC v: {0 0 0 0 0 0 0 0 0 0}
k: BTC_DOGE v: {0 0 0 0 0 0 0 0 0 0}...
</code>```

Please excuse my stupid question but I've spent days on it and I think I am missing something.
Cheers.

答:
You are trying to decode in to a map containing your crypto object. This is incorrect. Create the mappings in the struct definition like so:</p>

```<code>type Crypto struct {
    iso           string  `json:"BTC_BCN"` //this is the key (ex: BTC_BCN)
    id            int     `json:"id"`
    last          float64 `json:"las"`
    ...
}

crypto := &Crypto{}
err = json.NewDecoder(reader).Decode(crypto)
</code>```

Title: Go decode json string

Body:
discovered that go json decoding is a big pain in the butt so please help.
Here's my json:

 {
   "BTC_BCN":{
      "id":7,
      "last":"0.00000156",
      "lowestAsk":"0.00000156",
      "highestBid":"0.00000155",
      "percentChange":"0.01960784",
      "baseVolume":"4920.84786257",
      "quoteVolume":"3016048494.19305944",
      "isFrozen":"0",
      "high24hr":"0.00000183",
      "low24hr":"0.00000145"
   },
   "BTC_BELA":{
      "id":8,
      "last":"0.00008847",
      "lowestAsk":"0.00008848",
      "highestBid":"0.00008847",
      "percentChange":"-0.00405268",
      "baseVolume":"169.66498061",
      "quoteVolume":"1981232.44495809",
      "isFrozen":"0",
      "high24hr":"0.00008995",
      "low24hr":"0.00008120"
   }, ...
}

So I need to put that in a type that I created

//Crypto is the currency object
type Crypto struct {
    iso           string //this is the key (ex: BTC_BCN)
    id            int
    last          float64
    lowestAsk     float64
    highestBid    float64
    percentChange float64
    baseVolume    float64
    quoteVolume   float64
    isFrozen      int
    high24hr      float64
    low24hr       float64
}

and here is what I did so far, but I ended up with the keys in place and an empty value

func main() {
    // sendEmail("Some text")
    currencies := getCurrencies()
    if currencies == nil {
        return
    }
    fmt.Println(len(currencies))

}

func getCurrencies() map[string]Crypto {
    curList := make(map[string]Crypto)
    resp, err := http.Get("https://poloniex.com/public?command=returnTicker")
    // fmt.Println(err)
    if err != nil {
        sendEmail("Error getting data from poloniex " + err.Error())
        return nil
    }
    body, readErr := ioutil.ReadAll(resp.Body)
    reader := strings.NewReader(string(body))
    jsonErr := json.NewDecoder(reader).Decode(&curList)
    // fmt.Printf("curList is : %#v\n", curList)
    // fmt.Printf("body is : %s\n", string(body))
    if readErr != nil {
        fmt.Printf("readErr: %s\n", readErr.Error())
    }
    if jsonErr != nil {
        fmt.Printf("jsonErr: %s\n", jsonErr.Error())
    }
    for k, v := range curList {
        fmt.Println("k:", k, "v:", v)
    }
    defer resp.Body.Close()
    return curList
}

output:

k: BTC_MAID v: {0 0 0 0 0 0 0 0 0 0}
k: BTC_NOTE v: {0 0 0 0 0 0 0 0 0 0}
k: BTC_VRC v: {0 0 0 0 0 0 0 0 0 0}
k: BTC_DOGE v: {0 0 0 0 0 0 0 0 0 0}...

Please excuse my stupid question but I've spent days on it and I think I am missing something.
Cheers.

Body:
You are trying to decode in to a map containing your crypto object. This is incorrect. Create the mappings in the struct definition like so:

type Crypto struct {
    iso           string  `json:"BTC_BCN"` //this is the key (ex: BTC_BCN)
    id            int     `json:"id"`
    last          float64 `json:"las"`
    ...
}

crypto := &Crypto{}
err = json.NewDecoder(reader).Decode(crypto)


问:
React - Invariant Violation exception
Being new to React am stuck with something that should seemingly be pretty straightforward. Not sure what am doing wrong.

I have a component BasicReactComponent.js like this:

```<code>import React from 'react';

const BasicReactComp = () => {
  console.log('hi');
  return (
    <div>
      I was loaded from basic react comp.
    </div>
  );
};

export default BasicReactComp;
</code>```

Am trying to call it in my main file like below:

```<code>import React from 'react';
import ReactDOM from 'react-dom';
const BasicReactComp = require('./BasicReactComp');

ReactDOM.render(
 <BasicReactComp />,
 document.getElementById('foo')
);
</code>```

I keep getting the below error

```<code>**Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.
    Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.**
</code>```

答:
When translating between ES6 modules and CommonJS modules, default exports are exported as a default property. Hence you have to access .default of the value you require:

```<code>const BasicReactComp = require('./BasicReactComp').default;
</code>```

Or use the import syntax:

```<code>import BasicReactComp from './BasicReactComp';
</code>```

Title: React - Invariant Violation exception

Body:
Being new to React am stuck with something that should seemingly be pretty straightforward. Not sure what am doing wrong.

I have a component BasicReactComponent.js like this:

import React from 'react';

const BasicReactComp = () => {
  console.log('hi');
  return (

      I was loaded from basic react comp.

  );
};

export default BasicReactComp;

Am trying to call it in my main file like below:

import React from 'react';
import ReactDOM from 'react-dom';
const BasicReactComp = require('./BasicReactComp');

ReactDOM.render(
 <BasicReactComp />,
 document.getElementById('foo')
);

I keep getting the below error

**Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.
    Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.**

Body:
When translating between ES6 modules and CommonJS modules, default exports are exported as a default property. Hence you have to access .default of the value you require:

const BasicReactComp = require('./BasicReactComp').default;

Or use the import syntax:

import BasicReactComp from './BasicReactComp';


问:
Random number guessing game throws error: > or < cannot be used between str and int
I have the following code for a random number guessing game:

```<code>import random
number = random.randint(1,100)

name = input('Hi, Whats your name?')
print ("Well", name, "i am thinking of a number between 1 and 100, take a guess")

guess1 = input()
if guess1 == number:
    print ("Good job, you got it!")
while guess1 != number:
    if guess1 > number:
        print ('your guess is too high')
    if guess1 < number:
        print ('your guess is too low')
</code>```

which throws the error that > or < cannot be used between str and int.

What should I do so it doesn't trigger that error?

答:
You can conditions within the while loop to check if its right. It can be done the following way.</p>

```<code>import random

print('Hello! What is your name?')
myName = input()

number = random.randint(1, 100)
print('Well, ' + myName + ', I am thinking of a number between 1 and 100.')
inputNumber = int(raw_input('Enter the number')
while inputNumber != number:
      print "Sorry wrong number , try again"
      inputNumber = int(raw_input('Enter the number')
print "Congrats!"
</code>```

Body:
I have the following code for a random number guessing game:

import random
number = random.randint(1,100)

name = input('Hi, Whats your name?')
print ("Well", name, "i am thinking of a number between 1 and 100, take a guess")

guess1 = input()
if guess1 == number:
    print ("Good job, you got it!")
while guess1 != number:
    if guess1 > number:
        print ('your guess is too high')
    if guess1 < number:
        print ('your guess is too low')

which throws the error that > or < cannot be used between str and int.

What should I do so it doesn't trigger that error?

Body:
You can conditions within the while loop to check if its right. It can be done the following way.

import random

print('Hello! What is your name?')
myName = input()

number = random.randint(1, 100)
print('Well, ' + myName + ', I am thinking of a number between 1 and 100.')
inputNumber = int(raw_input('Enter the number')
while inputNumber != number:
      print "Sorry wrong number , try again"
      inputNumber = int(raw_input('Enter the number')
print "Congrats!"


问:
PHP - Validity of appending string to new variable
```<code>$var .= "hello";
echo $var;
</code>```

Is the above block of code valid or will it generate notices / errors under some circumstances?

If no should $var = "" or just $var be added before the block of code?

答:
Above block of code will generate notice the following notice:

Undefined variable: var

Variables should be defined before they are used in code, see example below:

```<code><?php
    $var = '';
    $var .= "hello";
    echo $var;
?>
</code>```

Body:
$var .= "hello";
echo $var;

Is the above block of code valid or will it generate notices / errors under some circumstances?

If no should $var = "" or just $var be added before the block of code?

Body:
Above block of code will generate notice the following notice:

Undefined variable: var

Variables should be defined before they are used in code, see example below:

<?php
    $var = '';
    $var .= "hello";
    echo $var;
?>


问:
React Native update style of Component
I'm trying to update the style of my TouchableOpacity Component when props change. I call a function, which is responsible for returning the style. Within that function I log the value of area.included. It returns the correct value, however the styles do not update appropriately.</p>

```<code><TouchableOpacity style={this.getRowStyle(area)} onPress={() => this.navToArea(area)}>
  <Text>Some Random Text</Text>
</TouchableOpacity>

getRowStyle(area) {
  console.log('area included', area.included)
  if (area.included) {
    return styles.swipeContainer
  } else {
    return styles.swipeContainerOpacity
  }
}

const styles = StyleSheet.create({
  swipeContainer: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    padding: 15,
  },
  swipeContainerOpacity: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    padding: 15,
    opacity: 0.2,
  },
})
</code>```

答:
if you just want to switch beetween two different style classes you can also add them into a condition like this:

```<code><TouchableOpacity style={this.state.areaIncluded ? [styles.swipeContainer] : [styles.swipeContainerOpacity]} onPress={() => this.navToArea(area)}>
  <Text>Some Random Text</Text>
</TouchableOpacity>
</code>```

Hope this can help you to start!!!

Title: React Native update style of Component

Body:
I'm trying to update the style of my TouchableOpacity Component when props change. I call a function, which is responsible for returning the style. Within that function I log the value of area.included. It returns the correct value, however the styles do not update appropriately.

<TouchableOpacity style={this.getRowStyle(area)} onPress={() => this.navToArea(area)}>
  <Text>Some Random Text</Text>
</TouchableOpacity>

getRowStyle(area) {
  console.log('area included', area.included)
  if (area.included) {
    return styles.swipeContainer
  } else {
    return styles.swipeContainerOpacity
  }
}

const styles = StyleSheet.create({
  swipeContainer: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    padding: 15,
  },
  swipeContainerOpacity: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    padding: 15,
    opacity: 0.2,
  },
})

Body:
if you just want to switch beetween two different style classes you can also add them into a condition like this:

<TouchableOpacity style={this.state.areaIncluded ? [styles.swipeContainer] : [styles.swipeContainerOpacity]} onPress={() => this.navToArea(area)}>
  <Text>Some Random Text</Text>
</TouchableOpacity>

Hope this can help you to start!!!


问:
Select all posts that user hasn't responded to?
I have a website that shows posts, and a user can vote on it. After they vote once I don't want it to show to that user again. So I need to have a query that polls all posts and returns the ones the user has not yet responded to.

I was thinking it would be simplest to have a posts table, responses table, and user table. The response table could include a postId, and userId. This could allow me to see all the posts that a user has responded to, but I couldn't figure out how to flip it to show the negation. Also it seems like it would be pretty slow to do it that way.

答:
To find all posts which have not yet been seen by a given user, you could try the following query:

```<code>SELECT p.*
FROM posts p
WHERE NOT EXISTS (SELECT 1 FROM responses r
                  WHERE r.postId = p.postId AND r.userId = <some value>)
</code>```

As an alternative to using NOT EXISTS, you could also phrase this using a LEFT JOIN:

```<code>SELECT p.*
FROM posts p
LEFT JOIN responses r
    ON p.postId = r.postId AND
       r.userId = <some value>
WHERE r.postId IS NULL
</code>```

Body:
To find all posts which have not yet been seen by a given user, you could try the following query:

SELECT p.*
FROM posts p
WHERE NOT EXISTS (SELECT 1 FROM responses r
                  WHERE r.postId = p.postId AND r.userId = <some value>)

As an alternative to using NOT EXISTS, you could also phrase this using a LEFT JOIN:

SELECT p.*
FROM posts p
LEFT JOIN responses r
    ON p.postId = r.postId AND
       r.userId = <some value>
WHERE r.postId IS NULL