问:
How to check on multiple conditions in PHP
I want to check the security input of a form.
People should answer the security question with the words "allow", "Allow" or 'ALLOW'. These 3 answers are all accepted.

I tried code below but it doesn't pass the if loop if I type one of these 3 answers. What I am doing wrong?

```<code>if( ! isset($_POST['security']) || empty($_POST['security']) || $_POST['security'] != 'allow' || $_POST['security'] != 'Allow' || $_POST['security'] != 'ALLOW') {
      $error .= "<p class=\"message-error\">" . $messages['security_invalid'] . "</p>";
}
</code>```

答:
The problem basically comes when you try to compare string values. That's because you need to test it separetely like the following:

```<code>if (!isset($_POST['security']) || empty($_POST['security']) || ($_POST['security'] != 'allow' && $_POST['security'] != 'Allow' && $_POST['security'] != 'ALLOW'))
</code>```

In fact the string value can be one of those strings and, of course, if for example is allow then $_POST['security'] != 'Allow' will fail.

Body:
I want to check the security input of a form.
People should answer the security question with the words "allow", "Allow" or 'ALLOW'. These 3 answers are all accepted.

I tried code below but it doesn't pass the if loop if I type one of these 3 answers. What I am doing wrong?

if( ! isset($_POST['security']) || empty($_POST['security']) || $_POST['security'] != 'allow' || $_POST['security'] != 'Allow' || $_POST['security'] != 'ALLOW') {
      $error .= "
" . $messages['security_invalid'] . "
";
}

Body:
The problem basically comes when you try to compare string values. That's because you need to test it separetely like the following:

if (!isset($_POST['security']) || empty($_POST['security']) || ($_POST['security'] != 'allow' && $_POST['security'] != 'Allow' && $_POST['security'] != 'ALLOW'))

In fact the string value can be one of those strings and, of course, if for example is allow then $_POST['security'] != 'Allow' will fail.


来源: stackexchange

问:
C# transaction error in AseBulkCopy

I have a program that is performing a bulk copy into a few Sybase db tables. However, the rollback transaction isn't working. When stepping through the logic, the issue seems to be with the transaction object. I'm at a loss right now. Any advice would be great.

```<code>    public static void SqlBulkCopy()
    {
        try
        {
            conn.Open();
            using (transaction = conn.BeginTransaction())
            {
                using (bulkCopy = new AseBulkCopy(conn, AseBulkCopyOptions.Default, transaction))
                {
                    BulkCopying("DB_TABLE_1", dataTable1);
                    BulkCopying("DB_TABLE_2", dataTable2);
                    BulkCopying("DB_TABLE_3", dataTable3);
                    transaction.Commit();
                }
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            conn.Close();
        }
    }

    private static void BulkCopying(string dbTableName, DataTable dtSourceName)
    {
        try
        {
            bulkCopy.BatchSize = 1000;
            bulkCopy.BulkCopyTimeout = 720;
            bulkCopy.NotifyAfter = 1000;
            bulkCopy.DestinationTableName = dbTableName;
            bulkCopy.WriteToServer(dtSourceName);
        }
        catch (Exception ex)
        {
            transaction.Rollback();
            throw ex;
        }
    }
</code>```

This is the error I got:

Sybase.Data.AseClient.AseException: The 'CREATE TABLE' command is not allowed within a multi-statement transaction in the 'tempdb' database.

答:
Your problem is not with the rollback. The problem is as the error msg says: you cannot do a DDL statement inside a transaction. I don't know where that DDL statement comes from, but the message is pretty clear.
One possible solution is to enable the option 'ddl in tran' for the database in questions (using sp_dboption). </p>

ContentLicense: CC BY-SA 3.0

Title: C# transaction error in AseBulkCopy

Body:
I have a program that is performing a bulk copy into a few Sybase db tables. However, the rollback transaction isn't working. When stepping through the logic, the issue seems to be with the transaction object. I'm at a loss right now. Any advice would be great.

    public static void SqlBulkCopy()
    {
        try
        {
            conn.Open();
            using (transaction = conn.BeginTransaction())
            {
                using (bulkCopy = new AseBulkCopy(conn, AseBulkCopyOptions.Default, transaction))
                {
                    BulkCopying("DB_TABLE_1", dataTable1);
                    BulkCopying("DB_TABLE_2", dataTable2);
                    BulkCopying("DB_TABLE_3", dataTable3);
                    transaction.Commit();
                }
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            conn.Close();
        }
    }

    private static void BulkCopying(string dbTableName, DataTable dtSourceName)
    {
        try
        {
            bulkCopy.BatchSize = 1000;
            bulkCopy.BulkCopyTimeout = 720;
            bulkCopy.NotifyAfter = 1000;
            bulkCopy.DestinationTableName = dbTableName;
            bulkCopy.WriteToServer(dtSourceName);
        }
        catch (Exception ex)
        {
            transaction.Rollback();
            throw ex;
        }
    }

This is the error I got:

Sybase.Data.AseClient.AseException: The 'CREATE TABLE' command is not allowed within a multi-statement transaction in the 'tempdb' database.


问:
Variable height child view controller as UITableView's tableHeaderView
I am trying to create a UITableViewController which has a UICollectionViewController as its tableHeaderView. This collection view will vary in height depending on what's (re)loaded.

Here is the basic layout.

And here it is in action:

As of now, I can get the tableHeaderView to resize by calculating the childViewController's height based on the number of cells then setting its preferredContentSize property.

```<code>- (void)reloadCollectionView {
    // Calculate size based on static cell height and layout
    _cellCount = arc4random_uniform(40) + 1;
    NSUInteger h = ceil(_cellCount / 2.0);

    // This informs the parent view controller of the size change
    self.preferredContentSize = CGSizeMake(self.collectionView.bounds.size.width, 20 * h);

    // Load the new number of cells
    [self.collectionView reloadData];
}
</code>```

Meanwhile, in the parent view controller, I override this method then update the containerView frame like so:

```<code>- (void)preferredContentSizeDidChangeForChildContentContainer:(id<UIContentContainer>)container {
    [super preferredContentSizeDidChangeForChildContentContainer:container];

    // Make new CGSize to update tableHeaderView's height and reassign tableHeaderView property (required for UI refresh)
    CGSize size = [container preferredContentSize];
    _tableHeaderContainerView.frame = CGRectMake(0, 0, self.view.bounds.size.width, size.height);
    self.tableView.tableHeaderView = _tableHeaderContainerView;
}
</code>```

This works, but this stinks. I'd like autolayout to take care of this for me but I cannot figure out how/where to get parentViewController.tableHeaderContainerView to automatically resize to fit its content view controller.

The code that I inherited and am rewriting uses a UIView/nib for the table header view but this implementation is messy as the parent view controller has too much to do already. It seems like moving this to its own view controller is the way to go, but I have to tackle this resizing problem first.

答: You could use KVO to monitor the collection view's contentSize and set the preferredContentSize to it when it changes.</p>

Body:
I am trying to create a UITableViewController which has a UICollectionViewController as its tableHeaderView. This collection view will vary in height depending on what's (re)loaded.

Here is the basic layout.

And here it is in action:

As of now, I can get the tableHeaderView to resize by calculating the childViewController's height based on the number of cells then setting its preferredContentSize property.

- (void)reloadCollectionView {
    // Calculate size based on static cell height and layout
    _cellCount = arc4random_uniform(40) + 1;
    NSUInteger h = ceil(_cellCount / 2.0);

    // This informs the parent view controller of the size change
    self.preferredContentSize = CGSizeMake(self.collectionView.bounds.size.width, 20 * h);

    // Load the new number of cells
    [self.collectionView reloadData];
}

Meanwhile, in the parent view controller, I override this method then update the containerView frame like so:

- (void)preferredContentSizeDidChangeForChildContentContainer:(id<UIContentContainer>)container {
    [super preferredContentSizeDidChangeForChildContentContainer:container];

    // Make new CGSize to update tableHeaderView's height and reassign tableHeaderView property (required for UI refresh)
    CGSize size = [container preferredContentSize];
    _tableHeaderContainerView.frame = CGRectMake(0, 0, self.view.bounds.size.width, size.height);
    self.tableView.tableHeaderView = _tableHeaderContainerView;
}

This works, but this stinks. I'd like autolayout to take care of this for me but I cannot figure out how/where to get parentViewController.tableHeaderContainerView to automatically resize to fit its content view controller.

The code that I inherited and am rewriting uses a UIView/nib for the table header view but this implementation is messy as the parent view controller has too much to do already. It seems like moving this to its own view controller is the way to go, but I have to tackle this resizing problem first.


问:
Use c++ libraries at C#
I'm working myself on a project, because performance is important i want to write some part of the code on c++ and want to call c++ codes from C#. I will write c++ library and want to write a C# wrapper, how can i do it? Have you any suggestion where i should begin to study? [any website, any link, any book]

Thanks !

答:
You need to either make C style imports for P/Invoke to use, like

```<code>void World_Hello(World* self) { self->Hello(); }
</code>```

or investigate CallingConvention.ThisCall. Thanks to name mangling, if you want to be portable to other OSes the former is a better choice.

ContentLicense: CC BY-SA 2.5

Title: Use c++ libraries at C#

Body:
You need to either make C style imports for P/Invoke to use, like

void World_Hello(World* self) { self->Hello(); }

or investigate CallingConvention.ThisCall. Thanks to name mangling, if you want to be portable to other OSes the former is a better choice.


问:
MySQL query recovery
I created a database for my class and inserted all of my data into the tables but I did not save the queries I used to create them. Is there any way that I can get back the queries I originally used to input all of the data so that I can save them to a separate query tab?</p>

答: You could possibly do a mysqldump --no-data dbname

Title: MySQL query recovery


问:
How to return the higher value of two cards?
I am creating a deck of cards and have to complete certain tasks. The third task asks me to compare two cards: card1 and card2. The function should return 1 if card1 is greater than card2, 2 if card2 is greater than card1, or 0 if both cards are equal. Suits should be ignored. The output is incorrect. For hand_1, 1 is returned when 0 should be returned. For hand_2, 2 is returned which is correct. For hand_3, 2 is returned when 1 should be returned. My question is: how do I make it so that 0, 1, and 2 are returned correctly? I have provided the entire code (Task 3 is at the bottom). Note that I cannot change the code that was provided to me, so I have to work with this code.

```<code>#Task 1
#------

import random

diamonds = ['2♦','3♦','4♦','5♦','6♦','7♦','8♦','9♦','10♦','J♦','Q♦','K♦','A♦']
clubs = ['2♣','3♣','4♣','5♣','6♣','7♣','8♣','9♣','10♣','J♣','Q♣','K♣','A♣']
hearts = ['2♥','3♥','4♥','5♥','6♥','7♥','8♥','9♥','10♥','J♥','Q♥','K♥','A♥']
spades = ['2♠','3♠','4♠','5♠','6♠','7♠','8♠','9♠','10♠','J♠','Q♠','K♠','A♠']

def shuffled_deck():
    """
    Shuffles the deck of cards and returns a shuffled deck.
    """
    deck = diamonds + clubs + hearts + spades
    random.shuffle(deck)
    return deck

deck = shuffled_deck()

if (len(deck) == 52):
    print("You might have created a random deck!")
    print(deck)
else:
    print("Your deck isn't yet complete.")
    print(deck)

#Task 2
#------

def deal_N_cards(deck, N):
    """
    Returns a list of N cards and removes them from the deck.
    """
    return [deck.pop() for k in range(N)]

deck2 = shuffled_deck()
hand1 = deal_N_cards(deck2, 5)
hand2 = deal_N_cards(deck2, 5)
hand3 = deal_N_cards(deck2, 20)

if (len(hand1) + len(hand2) + len(hand3) + len(deck2) == 52):
    print()
    print("You might have completed task 2!")
    print("hand1:")
    print(hand1)
    print("hand2:")
    print(hand2)
    print("hand3:")
    print(hand3)
    print("deck2:")
    print(deck2)
else:
    print()
    print("Your function isn't yet complete.")
    print("hand1:")
    print(hand1)
    print("hand2:")
    print(hand2)
    print("hand3:")
    print(hand3)
    print("deck2:")
    print(deck2)

#Task 3
#------

def compare_cards(card1, card2):
    """
    Returns 1 if the value of card1 is greater,
    2 if the value of card2 is greater,
    or 0 if the values of both card1 and card2 are equal.
    """
    'A' == 11
    'K' == 10
    'Q' == 10
    'J' == 10
    if card1 > card2:
        return 1
    if card1 < card2:
        return 2
    if card1 == card2:
        return 0

deck3 = shuffled_deck()
hand_1 = compare_cards('4♣', '4♠')
hand_2 = compare_cards('2♠', '6♣')
hand_3 = compare_cards('A♣', 'K♠')

print()
print("You might have completed task 3!")
print("Hand 1:")
print(hand_1)
print("Hand 2:")
print(hand_2)
print("Hand 3:")
print(hand_3)
</code>```

答:
'Strings are compared lexicographically, and dissimilar types are compared by the name of their type ("int" < "string"). 3.x fixes the second point by making them non-comparable.'Basically your comparing a string using mathematic logic which won't work. </p>

<p>As for how to fix this I think you need to restructure how your deck is made.
You could do this either by making a dictionary where the key is the suit and value is value.
Or you could have a list of lists with the suit being the name of each list. But overall the way you have structured your code needs a more object orientated approach. Such as your deck being an object with various functions attached to it instead of you creating a second deck. </p>

Body:
I am creating a deck of cards and have to complete certain tasks. The third task asks me to compare two cards: card1 and card2. The function should return 1 if card1 is greater than card2, 2 if card2 is greater than card1, or 0 if both cards are equal. Suits should be ignored. The output is incorrect. For hand_1, 1 is returned when 0 should be returned. For hand_2, 2 is returned which is correct. For hand_3, 2 is returned when 1 should be returned. My question is: how do I make it so that 0, 1, and 2 are returned correctly? I have provided the entire code (Task 3 is at the bottom). Note that I cannot change the code that was provided to me, so I have to work with this code.

#Task 1
#------

import random

diamonds = ['2♦','3♦','4♦','5♦','6♦','7♦','8♦','9♦','10♦','J♦','Q♦','K♦','A♦']
clubs = ['2♣','3♣','4♣','5♣','6♣','7♣','8♣','9♣','10♣','J♣','Q♣','K♣','A♣']
hearts = ['2♥','3♥','4♥','5♥','6♥','7♥','8♥','9♥','10♥','J♥','Q♥','K♥','A♥']
spades = ['2♠','3♠','4♠','5♠','6♠','7♠','8♠','9♠','10♠','J♠','Q♠','K♠','A♠']

def shuffled_deck():
    """
    Shuffles the deck of cards and returns a shuffled deck.
    """
    deck = diamonds + clubs + hearts + spades
    random.shuffle(deck)
    return deck

deck = shuffled_deck()

if (len(deck) == 52):
    print("You might have created a random deck!")
    print(deck)
else:
    print("Your deck isn't yet complete.")
    print(deck)

#Task 2
#------

def deal_N_cards(deck, N):
    """
    Returns a list of N cards and removes them from the deck.
    """
    return [deck.pop() for k in range(N)]

deck2 = shuffled_deck()
hand1 = deal_N_cards(deck2, 5)
hand2 = deal_N_cards(deck2, 5)
hand3 = deal_N_cards(deck2, 20)

if (len(hand1) + len(hand2) + len(hand3) + len(deck2) == 52):
    print()
    print("You might have completed task 2!")
    print("hand1:")
    print(hand1)
    print("hand2:")
    print(hand2)
    print("hand3:")
    print(hand3)
    print("deck2:")
    print(deck2)
else:
    print()
    print("Your function isn't yet complete.")
    print("hand1:")
    print(hand1)
    print("hand2:")
    print(hand2)
    print("hand3:")
    print(hand3)
    print("deck2:")
    print(deck2)

#Task 3
#------

def compare_cards(card1, card2):
    """
    Returns 1 if the value of card1 is greater,
    2 if the value of card2 is greater,
    or 0 if the values of both card1 and card2 are equal.
    """
    'A' == 11
    'K' == 10
    'Q' == 10
    'J' == 10
    if card1 > card2:
        return 1
    if card1 < card2:
        return 2
    if card1 == card2:
        return 0

deck3 = shuffled_deck()
hand_1 = compare_cards('4♣', '4♠')
hand_2 = compare_cards('2♠', '6♣')
hand_3 = compare_cards('A♣', 'K♠')

print()
print("You might have completed task 3!")
print("Hand 1:")
print(hand_1)
print("Hand 2:")
print(hand_2)
print("Hand 3:")
print(hand_3)

Body:
'Strings are compared lexicographically, and dissimilar types are compared by the name of their type ("int" < "string"). 3.x fixes the second point by making them non-comparable.'Basically your comparing a string using mathematic logic which won't work.

As for how to fix this I think you need to restructure how your deck is made.
You could do this either by making a dictionary where the key is the suit and value is value.
Or you could have a list of lists with the suit being the name of each list. But overall the way you have structured your code needs a more object orientated approach. Such as your deck being an object with various functions attached to it instead of you creating a second deck.


问:
Enable IntelliSense for Sass in .vue files in VS Code
Is there a way to enable IntelliSense for Sass in .vue files without associating them with sass for it would break off another extensions relying on .vue file association?

答:
To get sass or scss syntax highlighting you need to have the Vetur (octref.vetur) extension installed in VS Code.
I have experienced issues with Vetur that the vue-language-server fails to start, which causes alot of issues with syntax highlighting. I have not found a fix for this except a re-install. Also make sure to run the latest version of VS Code.

In a .vue file, you also need to ensure you use the correct attributes

```<code><style lang="sass">
    .my-class
        text-align: center
</style>
</code>```

Or for scss

```<code><style lang="scss">
    .my-class {
        text-align: center
    }
</style>
</code>```

Body:
To get sass or scss syntax highlighting you need to have the Vetur (octref.vetur) extension installed in VS Code.
I have experienced issues with Vetur that the vue-language-server fails to start, which causes alot of issues with syntax highlighting. I have not found a fix for this except a re-install. Also make sure to run the latest version of VS Code.

In a .vue file, you also need to ensure you use the correct attributes

<style lang="sass">
    .my-class
        text-align: center
</style>

Or for scss

<style lang="scss">
    .my-class {
        text-align: center
    }
</style>


问:
javascript - Global variable not working
I have a variable that I want saved so that multiple functions can use it. I followed w3schools's directions but it doesn't work. Am I forgetting something? Thank you in advance.

var name = document.getElementById('name').value;

function complete() {
 document.getElementById('demo').innerHTML = name;
}```

答:
There are a few things to consider:

If you have code that attempts to find an element, but that element hasn't even been read by the browser yet, the browser won't be able to find it. So, make sure that your code only runs AFTER the full DOM has been loaded
by placing the script just before the closing body tag.

Don't attempt to get the value of a form field as soon as the page
loads because the user hasn't typed anything into it yet, so the
value will be nothing. You need to set up your code so that your function gets called at the right time (after the user has had a chance to type in the form field) so only get the value when that moment has come.

Don't give any element the name name because the Global window
object has a property called name that defaults to an empty string
and when you attempt to access name, it could incorrectly attempt
to get the window.name instead of your element called name.

Only form fields have a value property. All other elements have
.textContent (used when the string does not contain any HTML or you
want the actual HTML code displayed, rather than parsed) and
.innerHTML (used when the string does contain HTML and you want
that code parsed).

Lastly, do yourself a favor and don't use W3Schools. It is well known to have outdated or flat out wrong information on it. Instead use the Mozilla Developer's Network, which is recognized as one of the best resources for client-side web development documentation.

<input type="text" id="userName">
<input type="button" value="Click Me!" id="btn">

```

Body:
There are a few things to consider:

If you have code that attempts to find an element, but that element hasn't even been read by the browser yet, the browser won't be able to find it. So, make sure that your code only runs AFTER the full DOM has been loaded
by placing the script just before the closing body tag.

Don't attempt to get the value of a form field as soon as the page
loads because the user hasn't typed anything into it yet, so the
value will be nothing. You need to set up your code so that your function gets called at the right time (after the user has had a chance to type in the form field) so only get the value when that moment has come.

Don't give any element the name name because the Global window
object has a property called name that defaults to an empty string
and when you attempt to access name, it could incorrectly attempt
to get the window.name instead of your element called name.

Only form fields have a value property. All other elements have
.textContent (used when the string does not contain any HTML or you
want the actual HTML code displayed, rather than parsed) and
.innerHTML (used when the string does contain HTML and you want
that code parsed).

Lastly, do yourself a favor and don't use W3Schools. It is well known to have outdated or flat out wrong information on it. Instead use the Mozilla Developer's Network, which is recognized as one of the best resources for client-side web development documentation.

<input type="text" id="userName">
<input type="button" value="Click Me!" id="btn">
<div id="demo"></div>

<script>
  // Set up the button's click event handling function
  document.getElementById("btn").addEventListener("click", complete);

  // Only get a reference to the element, not its value because, at this point,
  // the user hasn't had a chance to type anything into it.
  // Also, getting a reference to the element is the best approach because, if
  // you decide you want some other property of the same element later, you'd have
  // to scan the document for the same element again.
  var theName = document.getElementById('userName');

  function complete() {
   // Now, just get the current value of the textbox at this moment in time
   document.getElementById('demo').textContent = theName.value;
  }
</script>


问:
Outlook Calendar - Locations set by Add-in is cleared on save
Our Outlook add-in, as part of its process, sets the location field to a link.
This all works fine, no errors or warnings. However, recently in the web client, after setting the location in this way, once the appointment is saved and closed, the location is removed. If you're watching the item on the calendar, you can actually see it disappear within a couple seconds.

Manually typed or pasted locations do not have this problem, nor does the native Outlook client. Using the saveAsync method before save and close does not prevent the location from being deleted either.

This does not appear to be isolated to our add-in, a cursory test of the Starbucks add-in (available in the store) showed the same behaviour - location cleared on save, in the web client.

Is there a work-around for this, or is it to be expected behaviour moving forward?

答:
We apologize for any frustration or inconvenience we have caused with this issue. Please be patient as we work to fix this issue as quickly as we can.

Currently, we do not have a workaround.

[Outlook Add-ins Engineering Team]


问:
Android Studio - Scrollview moves outside the screen on keyboard open
I want to make a chat screen which has an EditText and a Button at the bottom (wrapped in a LinearLayout), and a ScrollView for the messages at the top. The problem is that when the user taps the EditText and the keyboard opens, the ScrollView will go off screen as a result of moving up. I would like to move the Layout (with the EditBox and the Button) above the keyboard and the ScrollView to be resized to fit the screen. The problem is shown on the pictures below:

As you can see, the line that writes "Chat" (left image) has disappeared in the right image.

I use this XML code:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="15sp"
    android:orientation="vertical"
    android:background="#ccdcf7"
    tools:context="com.orionz.sockettest.ChatActivity">

    <ScrollView
        android:id="@+id/scroll"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="15"
        android:isScrollContainer="false">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <TextView
                android:id="@+id/chatBox"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:padding="5dp"
                android:text="Chat\n"
                android:textColor="#000000"
                android:textIsSelectable="true"
                android:textSize="22dp" />
        </LinearLayout>
    </ScrollView>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="center|bottom"
        android:orientation="horizontal">

        <EditText
            android:id="@+id/msgInput"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="0.8"
            android:ems="10"
            android:hint="Message..."
            android:inputType="text" />

        <Button
            android:id="@+id/sendButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="0.2"
            android:background="@drawable/mybutton"
            android:padding="5sp"
            android:text="Send"
            android:textColor="#ffffff"
            android:textSize="20sp" />

    </LinearLayout>

</LinearLayout>
</code>```

I have seen many answers such as setting the android:windowSoftInputMode but none has worked. I use Android Studio. Any help would be appreciated.

答:
Finally, I found what was wrong in my case.

The theme was full screen. In the style of the activity I had this line that caused the problem:

<item name="android:windowFullscreen">true</item>

In the java code, I gave a command to open the keyboard on the start of the activity:

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

which was also part of the problem

After adding the adjustResize property to the activity in the manifest, everything worked fine:

android:windowSoftInputMode="adjustResize"

Body:
I want to make a chat screen which has an EditText and a Button at the bottom (wrapped in a LinearLayout), and a ScrollView for the messages at the top. The problem is that when the user taps the EditText and the keyboard opens, the ScrollView will go off screen as a result of moving up. I would like to move the Layout (with the EditBox and the Button) above the keyboard and the ScrollView to be resized to fit the screen. The problem is shown on the pictures below:

As you can see, the line that writes "Chat" (left image) has disappeared in the right image.

I use this XML code:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="15sp"
    android:orientation="vertical"
    android:background="#ccdcf7"
    tools:context="com.orionz.sockettest.ChatActivity">

    <ScrollView
        android:id="@+id/scroll"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="15"
        android:isScrollContainer="false">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <TextView
                android:id="@+id/chatBox"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:padding="5dp"
                android:text="Chat\n"
                android:textColor="#000000"
                android:textIsSelectable="true"
                android:textSize="22dp" />
        </LinearLayout>
    </ScrollView>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="center|bottom"
        android:orientation="horizontal">

        <EditText
            android:id="@+id/msgInput"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="0.8"
            android:ems="10"
            android:hint="Message..."
            android:inputType="text" />

        <Button
            android:id="@+id/sendButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="0.2"
            android:background="@drawable/mybutton"
            android:padding="5sp"
            android:text="Send"
            android:textColor="#ffffff"
            android:textSize="20sp" />

    </LinearLayout>

</LinearLayout>

I have seen many answers such as setting the android:windowSoftInputMode but none has worked. I use Android Studio. Any help would be appreciated.


问:
subprocess cp leaves some files empty
I'm trying to copy some files from one directory to another. I want all files in one directory to end up in the root of another directory.

This command does exactly what I want when I run it in the terminal:

```<code>cp -rv ./src/CopyPasteIntoBuildDir/* ./build-root/src/
</code>```

This line of python, however, copies most of the files just like the above command, but it leaves some of the new files empty. Specifically, files in subdirectories are left empty.

```<code>subprocess.check_call("cp -rv ./src/CopyPasteIntoBuildDir/* ./build-root/src/", shell=True)
</code>```

It creates the files if they're not there, and it truncates them if they are.

What is going on?

答:
So apparently this is a problem with sh. Using bash instead worked.

```<code>subprocess.check_call("cp -rv ./src/CopyPasteIntoBuildDir/* ./build-root/src/", shell=True, executable="/bin/bash")
</code>```

EDIT: See accepted answer!

Title: subprocess cp leaves some files empty

Body:
I'm trying to copy some files from one directory to another. I want all files in one directory to end up in the root of another directory.

This command does exactly what I want when I run it in the terminal:

cp -rv ./src/CopyPasteIntoBuildDir/* ./build-root/src/

This line of python, however, copies most of the files just like the above command, but it leaves some of the new files empty. Specifically, files in subdirectories are left empty.

subprocess.check_call("cp -rv ./src/CopyPasteIntoBuildDir/* ./build-root/src/", shell=True)

It creates the files if they're not there, and it truncates them if they are.

What is going on?

Body:
So apparently this is a problem with sh. Using bash instead worked.

subprocess.check_call("cp -rv ./src/CopyPasteIntoBuildDir/* ./build-root/src/", shell=True, executable="/bin/bash")

EDIT: See accepted answer!


问:
How to Automatically add thousand separators as number is input in EditText
Im creating a convertor application. I want to set the EditText so that when the user is inputting the number to be converted, a thousand separator (,) should be added automatically in realtime to the number once it increments by 3 figures: thousand, million, billion etc.

And when erased to below 4 figures the number goes back to normal.

Any help?

答:
I know i am very late to the party but it may be very useful for future users. My answer is an extension of Shree Krishna's answer.

Improvements:

Thousands separators and Decimal markers are locale aware i.e. they are used accordingly to the Locale of the device.

The cursor position doesn't change after deleting or adding elements in the middle also (In his answer cursor was reset to the end).

The overall quality of the code has been improved specially the getDecimalFormattedString method.

Code:

```<code>    import android.text.Editable;
    import android.text.TextWatcher;
    import android.widget.EditText;

    import java.text.DecimalFormat;

    /**
     * Created by srv_twry on 4/12/17.
     * Source: https://stackoverflow.com/a/34265406/137744
     * The custom TextWatcher that automatically adds thousand separators in EditText.
     */

    public class ThousandSeparatorTextWatcher implements TextWatcher {

        private DecimalFormat df;
        private EditText editText;
        private static String thousandSeparator;
        private static String decimalMarker;
        private int cursorPosition;

        public ThousandSeparatorTextWatcher(EditText editText) {
            this.editText = editText;
            df = new DecimalFormat("#,###.##");
            df.setDecimalSeparatorAlwaysShown(true);
            thousandSeparator = Character.toString(df.getDecimalFormatSymbols().getGroupingSeparator());
            decimalMarker = Character.toString(df.getDecimalFormatSymbols().getDecimalSeparator());
        }

        @Override
        public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) {
            cursorPosition = editText.getText().toString().length() - editText.getSelectionStart();
        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {}

        @Override
        public void afterTextChanged(Editable s) {
            try {
                editText.removeTextChangedListener(this);
                String value = editText.getText().toString();

                if (value != null && !value.equals("")) {
                    if (value.startsWith(decimalMarker)) {
                        String text = "0" + decimalMarker;
                        editText.setText(text);
                    }
                    if (value.startsWith("0") && !value.startsWith("0" + decimalMarker)) {
                        int index = 0;
                        while (index < value.length() && value.charAt(index) == '0') {
                            index++;
                        }
                        String newValue = Character.toString(value.charAt(0));
                        if (index != 0) {
                            newValue = value.charAt(0) + value.substring(index);
                        }
                        editText.setText(newValue);
                    }
                    String str = editText.getText().toString().replaceAll(thousandSeparator, "");
                    if (!value.equals("")) {
                        editText.setText(getDecimalFormattedString(str));
                    }
                    editText.setSelection(editText.getText().toString().length());
                }

                //setting the cursor back to where it was
                editText.setSelection(editText.getText().toString().length() - cursorPosition);
                editText.addTextChangedListener(this);
            } catch (Exception ex) {
                ex.printStackTrace();
                editText.addTextChangedListener(this);
            }
        }

        private static String getDecimalFormattedString(String value) {

            String[] splitValue = value.split("\\.");
            String beforeDecimal = value;
            String afterDecimal = null;
            String finalResult = "";

            if (splitValue.length == 2) {
                beforeDecimal = splitValue[0];
                afterDecimal = splitValue[1];
            }

            int count = 0;
            for (int i = beforeDecimal.length() - 1; i >= 0 ; i--) {
                finalResult = beforeDecimal.charAt(i) + finalResult;
                count++;
                if (count == 3 && i > 0) {
                    finalResult = thousandSeparator + finalResult;
                    count = 0;
                }
            }

            if (afterDecimal != null) {
                finalResult = finalResult + decimalMarker + afterDecimal;
            }

            return finalResult;
        }

        /*
        * Returns the string after removing all the thousands separators.
        * */
        public static String getOriginalString(String string) {
            return string.replace(thousandSeparator,"");
        }
    }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I know i am very late to the party but it may be very useful for future users. My answer is an extension of Shree Krishna's answer.

Improvements:

Thousands separators and Decimal markers are locale aware i.e. they are used accordingly to the Locale of the device.

The cursor position doesn't change after deleting or adding elements in the middle also (In his answer cursor was reset to the end).

The overall quality of the code has been improved specially the getDecimalFormattedString method.

Code:

    import android.text.Editable;
    import android.text.TextWatcher;
    import android.widget.EditText;

    import java.text.DecimalFormat;

    /**
     * Created by srv_twry on 4/12/17.
     * Source: https://stackoverflow.com/a/34265406/137744
     * The custom TextWatcher that automatically adds thousand separators in EditText.
     */

    public class ThousandSeparatorTextWatcher implements TextWatcher {

        private DecimalFormat df;
        private EditText editText;
        private static String thousandSeparator;
        private static String decimalMarker;
        private int cursorPosition;

        public ThousandSeparatorTextWatcher(EditText editText) {
            this.editText = editText;
            df = new DecimalFormat("#,###.##");
            df.setDecimalSeparatorAlwaysShown(true);
            thousandSeparator = Character.toString(df.getDecimalFormatSymbols().getGroupingSeparator());
            decimalMarker = Character.toString(df.getDecimalFormatSymbols().getDecimalSeparator());
        }

        @Override
        public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) {
            cursorPosition = editText.getText().toString().length() - editText.getSelectionStart();
        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {}

        @Override
        public void afterTextChanged(Editable s) {
            try {
                editText.removeTextChangedListener(this);
                String value = editText.getText().toString();

                if (value != null && !value.equals("")) {
                    if (value.startsWith(decimalMarker)) {
                        String text = "0" + decimalMarker;
                        editText.setText(text);
                    }
                    if (value.startsWith("0") && !value.startsWith("0" + decimalMarker)) {
                        int index = 0;
                        while (index < value.length() && value.charAt(index) == '0') {
                            index++;
                        }
                        String newValue = Character.toString(value.charAt(0));
                        if (index != 0) {
                            newValue = value.charAt(0) + value.substring(index);
                        }
                        editText.setText(newValue);
                    }
                    String str = editText.getText().toString().replaceAll(thousandSeparator, "");
                    if (!value.equals("")) {
                        editText.setText(getDecimalFormattedString(str));
                    }
                    editText.setSelection(editText.getText().toString().length());
                }

                //setting the cursor back to where it was
                editText.setSelection(editText.getText().toString().length() - cursorPosition);
                editText.addTextChangedListener(this);
            } catch (Exception ex) {
                ex.printStackTrace();
                editText.addTextChangedListener(this);
            }
        }

        private static String getDecimalFormattedString(String value) {

            String[] splitValue = value.split("\\.");
            String beforeDecimal = value;
            String afterDecimal = null;
            String finalResult = "";

            if (splitValue.length == 2) {
                beforeDecimal = splitValue[0];
                afterDecimal = splitValue[1];
            }

            int count = 0;
            for (int i = beforeDecimal.length() - 1; i >= 0 ; i--) {
                finalResult = beforeDecimal.charAt(i) + finalResult;
                count++;
                if (count == 3 && i > 0) {
                    finalResult = thousandSeparator + finalResult;
                    count = 0;
                }
            }

            if (afterDecimal != null) {
                finalResult = finalResult + decimalMarker + afterDecimal;
            }

            return finalResult;
        }

        /*
        * Returns the string after removing all the thousands separators.
        * */
        public static String getOriginalString(String string) {
            return string.replace(thousandSeparator,"");
        }
    }


问:
How can I get page timings for a SPA in Google Analytics using GTM?
I've been wresteling with this a few days and can't really find any good information on it. I am a novice with respect to Google Analytics and Google Tag Manager.

I have a client website which is a Single Page Application using Marionette. The client would like timings on how long it takes to load different pages in the application, specifically they want to know what pages to focus on for optimizations. They also want more analysis on user interaction in GA.

I've installed the google tag manager and setup the page view tag to show the individual page paths via the History trigger properly as described here:
https://www.pmg.com/blog/tracking-single-page-web-apps-google-tag-manager-analytics/

That is working fine, I can see the history fragments/page paths in GA.

The problem is when I go to Page Timings in the Behavior reports in GA all the timings are 0. Avg page load, server load, etc.

I've tried installing a page timing recipe from Luna Metrics:
https://www.lunametrics.com/labs/recipes/page-load-timing/

This did not work as the custom javascript in it depended on window.performance which after some research does not appear to work well for SPAs.

function() {
  var timing = window.performance.timing;
  var ms = timing.loadEventStart - timing.navigationStart;

  return Math.round(ms / 100) / 10;
}```

I've also tried setting the siteSpeedSampleRate to 100 in the PageView tag for google analytics. This appears to have had no affect either.

i've also been messing with the tags and using the GTM preview and GA Debug and I can see the custom timings being set but with the same value on every subsequent link click (Its using the same page load value on the initial page load I think) which is why I don't think window.performance is an option here.

I've not been able to find any definitive way to get google analytics to track page timings for an SPA and would love any suggestions!

答: I guess I just needed to be a little patient after the siteSpeedSampleRate change. That seems to have resolved the timing issues for me.</p>

Body:
I've been wresteling with this a few days and can't really find any good information on it. I am a novice with respect to Google Analytics and Google Tag Manager.

I have a client website which is a Single Page Application using Marionette. The client would like timings on how long it takes to load different pages in the application, specifically they want to know what pages to focus on for optimizations. They also want more analysis on user interaction in GA.

I've installed the google tag manager and setup the page view tag to show the individual page paths via the History trigger properly as described here:
https://www.pmg.com/blog/tracking-single-page-web-apps-google-tag-manager-analytics/

That is working fine, I can see the history fragments/page paths in GA.

The problem is when I go to Page Timings in the Behavior reports in GA all the timings are 0. Avg page load, server load, etc.

I've tried installing a page timing recipe from Luna Metrics:
https://www.lunametrics.com/labs/recipes/page-load-timing/

This did not work as the custom javascript in it depended on window.performance which after some research does not appear to work well for SPAs.

function() {
  var timing = window.performance.timing;
  var ms = timing.loadEventStart - timing.navigationStart;

  return Math.round(ms / 100) / 10;
}

I've also tried setting the siteSpeedSampleRate to 100 in the PageView tag for google analytics. This appears to have had no affect either.

i've also been messing with the tags and using the GTM preview and GA Debug and I can see the custom timings being set but with the same value on every subsequent link click (Its using the same page load value on the initial page load I think) which is why I don't think window.performance is an option here.

I've not been able to find any definitive way to get google analytics to track page timings for an SPA and would love any suggestions!


问:
chat web app: flex-boxes inside div position:fixed
I have a chat web app with a bottom bar consisting of: button, text entry, button:

```<code><div id="bottom-bar">
  <div class="button-left">
    <img src="https://placeholdit.co//i/40x40">
  </div>
  <div class="textentry">
    <input type="text" id="chatmsg" name="chatmsg">
  </div>
  <div class="button-right">
    <img src="https://placeholdit.co//i/40x40">
  </div>
</div>

#bottom-bar {
    position: fixed;
    bottom: 0px;
    height: 40px;
    width: 100%;
}
</code>```

What I want to achieve: (1) place the left button to the left of the bottom-bar, (2) place the right button to the right of the bottom-bar and (3) have an input field that stretches in the middle using all the space that is available.

I tried:

#bottom-bar {
   ...the css above and additionally ...
   display: flex;
   flex-direction: row;
   flex-wrap: nowrap;
   justify-content:space-between;
   align-items: center;
}

#chatmsg{
  width: auto;
}
```

But this got me nowhere. Any help is much appreciated.

答:
Use calc(100% - 80px); as the width for .textentry (i.e. full width minus the width of the two images) and make the input 100% wide inside of that. If you do just that, the input overflows its container to the right, so use padding on .textentry to compensate that and adjust the distance between the elements as desired, as shown in my snippet.

html,
body {
  margin: 0;
}

#bottom-bar {
  position: fixed;
  bottom: 0px;
  height: 40px;
  width: 100%;
}

#bottom-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.textentry {
  width: calc(100% - 80px);
  padding: 0 10px 0 2px;
}

input#chatmsg {
  width: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="bottom-bar">
  <div class="button-left">
    <img src="https://placeholdit.co//i/40x40">
  </div>
  <div class="textentry"><input type="text" id="chatmsg" name="chatmsg"></div>
  <div class="button-right">
    <img src="https://placeholdit.co//i/40x40">
  </div>
</div></code>```

Body:
I have a chat web app with a bottom bar consisting of: button, text entry, button:

    <input type="text" id="chatmsg" name="chatmsg">

#bottom-bar {
    position: fixed;
    bottom: 0px;
    height: 40px;
    width: 100%;
}

What I want to achieve: (1) place the left button to the left of the bottom-bar, (2) place the right button to the right of the bottom-bar and (3) have an input field that stretches in the middle using all the space that is available.

I tried:

#bottom-bar {
   ...the css above and additionally ...
   display: flex;
   flex-direction: row;
   flex-wrap: nowrap;
   justify-content:space-between;
   align-items: center;
}

#chatmsg{
  width: auto;
}

But this got me nowhere. Any help is much appreciated.

Body:
Use calc(100% - 80px); as the width for .textentry (i.e. full width minus the width of the two images) and make the input 100% wide inside of that. If you do just that, the input overflows its container to the right, so use padding on .textentry to compensate that and adjust the distance between the elements as desired, as shown in my snippet.

html,
body {
  margin: 0;
}

#bottom-bar {
  position: fixed;
  bottom: 0px;
  height: 40px;
  width: 100%;
}

#bottom-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.textentry {
  width: calc(100% - 80px);
  padding: 0 10px 0 2px;
}

input#chatmsg {
  width: 100%;
}

<div id="bottom-bar">
  <div class="button-left">
    <img src="https://placeholdit.co//i/40x40">
  </div>
  <div class="textentry"><input type="text" id="chatmsg" name="chatmsg"></div>
  <div class="button-right">
    <img src="https://placeholdit.co//i/40x40">
  </div>
</div>


问:
XSLT merge multiple entries and add up numbers
ich have following XML:

```<code><item>
   <number>1</number>
   <value>2</value>
</item>
<item>
   <number>2</number>
   <value>22</value>
</item>
<item>
   <number>1</number>
   <value>4</value>
</item>
</code>```

I want to transform the xml with xslt 1.0 to this:

```<code><item>
   <number>1</number>
   <value>6</value>
</item>
<item>
   <number>2</number>
   <value>22</value>
</item>
</code>```

The values from the same item number have to be added up and in the end i want to merge the elements of the same item. There can be n multible items with the same number. In this example the item with the number 1 is two times in the xml so those two will be one entry and the values(2,4) will be added up to 6.

答:
This is a very basic grouping question. In XSLT 1.0, grouping is done by using the Muenchian method.

Start with an identity transform...

```<code><xsl:template match="@*|node()">
  <xsl:copy>
    <xsl:apply-templates select="@*|node()"/>
  </xsl:copy>
</xsl:template>
</code>```

Group all of the item's by number by creating an xsl:key matching item using number...

```<code><xsl:key name="items" match="item" use="number"/>
</code>```

From the context of the parent of all item's (using doc as an example), output a copy of the element and apply templates to the first item in the group (and any attributes)...

```<code><xsl:template match="doc">
  <xsl:copy>
    <xsl:apply-templates select="@*|item[count(.|key('items',number)[1])=1]"/>
  </xsl:copy>
</xsl:template>
</code>```

Add a template that matches item and output a copy of it. Apply templates to any attributes and the number element. Then create a new value element with the sum of all item's matching that key...

```<code><xsl:template match="item">
  <xsl:copy>
    <xsl:apply-templates select="@*|number"/>
    <value><xsl:value-of select="sum(key('items',number)/value)"/></value>
  </xsl:copy>
</xsl:template>
</code>```

Full example...

XML Input (added a single root element doc to make the input well formed)

```<code><doc>
    <item>
        <number>1</number>
        <value>2</value>
    </item>
    <item>
        <number>2</number>
        <value>22</value>
    </item>
    <item>
        <number>1</number>
        <value>4</value>
    </item>
</doc>
</code>```

XSLT 1.0

```<code><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output indent="yes"/>
  <xsl:strip-space elements="*"/>

  <xsl:key name="items" match="item" use="number"/>

  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="doc">
    <xsl:copy>
      <xsl:apply-templates select="@*|item[count(.|key('items',number)[1])=1]"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="item">
    <xsl:copy>
      <xsl:apply-templates select="@*|number"/>
      <value><xsl:value-of select="sum(key('items',number)/value)"/></value>
    </xsl:copy>
  </xsl:template>

</xsl:stylesheet>
</code>```

XML Output

```<code><doc>
   <item>
      <number>1</number>
      <value>6</value>
   </item>
   <item>
      <number>2</number>
      <value>22</value>
   </item>
</doc>
</code>```

Body:
ich have following XML:

<item>
   <number>1</number>
   <value>2</value>
</item>
<item>
   <number>2</number>
   <value>22</value>
</item>
<item>
   <number>1</number>
   <value>4</value>
</item>

I want to transform the xml with xslt 1.0 to this:

<item>
   <number>1</number>
   <value>6</value>
</item>
<item>
   <number>2</number>
   <value>22</value>
</item>

The values from the same item number have to be added up and in the end i want to merge the elements of the same item. There can be n multible items with the same number. In this example the item with the number 1 is two times in the xml so those two will be one entry and the values(2,4) will be added up to 6.

Body:
This is a very basic grouping question. In XSLT 1.0, grouping is done by using the Muenchian method.

Start with an identity transform...

<xsl:template match="@*|node()">
  <xsl:copy>
    <xsl:apply-templates select="@*|node()"/>
  </xsl:copy>
</xsl:template>

Group all of the item's by number by creating an xsl:key matching item using number...

<xsl:key name="items" match="item" use="number"/>

From the context of the parent of all item's (using doc as an example), output a copy of the element and apply templates to the first item in the group (and any attributes)...

<xsl:template match="doc">
  <xsl:copy>
    <xsl:apply-templates select="@*|item[count(.|key('items',number)[1])=1]"/>
  </xsl:copy>
</xsl:template>

Add a template that matches item and output a copy of it. Apply templates to any attributes and the number element. Then create a new value element with the sum of all item's matching that key...

<xsl:template match="item">
  <xsl:copy>
    <xsl:apply-templates select="@*|number"/>
    <value><xsl:value-of select="sum(key('items',number)/value)"/></value>
  </xsl:copy>
</xsl:template>

Full example...

XML Input (added a single root element doc to make the input well formed)

<doc>
    <item>
        <number>1</number>
        <value>2</value>
    </item>
    <item>
        <number>2</number>
        <value>22</value>
    </item>
    <item>
        <number>1</number>
        <value>4</value>
    </item>
</doc>

XSLT 1.0

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output indent="yes"/>
  <xsl:strip-space elements="*"/>

  <xsl:key name="items" match="item" use="number"/>

  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="doc">
    <xsl:copy>
      <xsl:apply-templates select="@*|item[count(.|key('items',number)[1])=1]"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="item">
    <xsl:copy>
      <xsl:apply-templates select="@*|number"/>
      <value><xsl:value-of select="sum(key('items',number)/value)"/></value>
    </xsl:copy>
  </xsl:template>

</xsl:stylesheet>

XML Output

<doc>
   <item>
      <number>1</number>
      <value>6</value>
   </item>
   <item>
      <number>2</number>
      <value>22</value>
   </item>
</doc>


问:
Translator with HashMap as dictionary Java
I need to create some kind of translator. I have a HashMap with pairs of Russian and English words as keys and values respectively. When I input a phrase in Russian I need to get English translation or nulls/not found for the words which are not in the dictionary.

So I have such methods for translation:

```<code>public boolean isInDictionary(String word){
        if(dictionary.containsKey(word)){
            return true;
        }
        return false;
    }

    public String translateSentence(String sentence){
        StringBuilder result = new StringBuilder();
        String[] splittedStrings = sentence.split( "\n" );

        List<String> list = new ArrayList<>();
        for(String s : splittedStrings){
            result.append(translateCheck(s));
        }
        return result.toString();
    }

    public String getWord(String word){
        return dictionary.get(word);
    }
</code>```

Here is how I call these methods:

```<code>    Scanner scanner = new Scanner(System.in);
    Translator translator = new Translator();
    System.out.println("Input the phrase to translate:");
    String input = scanner.nextLine();
    System.out.println(translator.translateSentence(input));
</code>```

When I input distinct word in Russian I get a translation for that, while when I input a phrase consisting of different words I get null.
So what am I doing wrong? I would be grateful for some help!

答:
Something like this:</p>

```<code>    public boolean isInDictionary(String word) {
        return dictionary.containsKey(word); //note the removal of the if as it already returns a boolean
    }

    public String translateSentence(String sentence) {
        StringBuilder result = new StringBuilder();
        String[] splittedStrings = sentence.trim().split(" "); // the actual change

        List<String> list = new ArrayList<>();
        for (String s : splittedStrings) {
            result.append(translateCheck(s));
        }
        return result.toString();
    }

    public String getWord(String word) {
        return dictionary.get(word);
    }
</code>```

Body:
I need to create some kind of translator. I have a HashMap with pairs of Russian and English words as keys and values respectively. When I input a phrase in Russian I need to get English translation or nulls/not found for the words which are not in the dictionary.

So I have such methods for translation:

public boolean isInDictionary(String word){
        if(dictionary.containsKey(word)){
            return true;
        }
        return false;
    }

    public String translateSentence(String sentence){
        StringBuilder result = new StringBuilder();
        String[] splittedStrings = sentence.split( "\n" );

        List<String> list = new ArrayList<>();
        for(String s : splittedStrings){
            result.append(translateCheck(s));
        }
        return result.toString();
    }

    public String getWord(String word){
        return dictionary.get(word);
    }

Here is how I call these methods:

    Scanner scanner = new Scanner(System.in);
    Translator translator = new Translator();
    System.out.println("Input the phrase to translate:");
    String input = scanner.nextLine();
    System.out.println(translator.translateSentence(input));

When I input distinct word in Russian I get a translation for that, while when I input a phrase consisting of different words I get null.
So what am I doing wrong? I would be grateful for some help!

Body:
Something like this:

    public boolean isInDictionary(String word) {
        return dictionary.containsKey(word); //note the removal of the if as it already returns a boolean
    }

    public String translateSentence(String sentence) {
        StringBuilder result = new StringBuilder();
        String[] splittedStrings = sentence.trim().split(" "); // the actual change

        List<String> list = new ArrayList<>();
        for (String s : splittedStrings) {
            result.append(translateCheck(s));
        }
        return result.toString();
    }

    public String getWord(String word) {
        return dictionary.get(word);
    }


问:
Fixed table header on window scroll
I have a simple Bootstrap table with a lot of rows.
Is there a way to make the table header be fixed when scrolling the window, but have the width of each column header to equal the width of the row with the most text.
Because when setting table header position to fixed, then the header doesn't change its width based off the content.
In other words set width of each column dependent on widest value (be that title in the header or value in a cell) in the column.
Is there a way to put such calculations on the header column width ?
I cant think of any other way to do this.
I am using angular.

Here's a jsfiddle of what I've tried when setting position of header row to fixed : JsFiddle
As you can see now the columns don't align with the appropriate columns in the body.
I need them to be aligned, but without setting a fixed width for every column, since I do not know how long the data I'm getting will be.

HTML code:

```<code><div class="col-md-12 tableDiv"  >
 <table class="table table-striped" >
  <thead class="table-bordered">
    <tr>
      <th>Column1</th>
      <th>Column2</th>
      <th>Column3</th>
      <th>Column4</th>
      <th>Column5</th>
      <th>Column6</th>

    </tr>
  </thead>
  <tbody >
    <tr>
      <td > FIRST</td>
      <td >asdasdfasf</td>
      <td >fsdf</td>
      <td>sdfsfd</td>
      <td>sdfs</td>
      <td>fsdfsdf</td>
    </tr>
        <tr>
      <td > asdf</td>
      <td >asdfa</td>
      <td >fsdf</td>
      <td>sdfsfd</td>
      <td>sdfs</td>
      <td>fsdfsdf</td>
    </tr>
        <tr>
      <td > asdf</td>
      <td >asdfa</td>
      <td >fsdf</td>
      <td>sdfsfd</td>
      <td>sdfs</td>
      <td>fsdfsdf</td>
    </tr>
  </tbody>
</table>
  </div>
<div>
</div>
</code>```

Css:

```<code>.table-bordered tr {
  position: fixed;
   z-index:1;
  top: 50px;
  background: #fff;
 }
</code>```

答:
If you don't care about the performance and you can live without borders in the header (because the borders will not get the CSS transform), there is a solution using CSS3 transforms. The technique is to take the scroll of the window and apply a transform to the header with the same value. In this way, the header is not fixed and it maintains its original widths:

```<code>let header = document.querySelector(".table-bordered");
let body = document.body;

function setTranslate (element, value) {
    let style = `translateY(${value}px)`;
    element.style.oTransform = style;
    element.style.MozTransform = style;
    element.style.WebkitTransform = style;
    element.style.transform = style;
}

window.onscroll = () => {
    setTranslate(header, window.scrollY);
};
</code>```

jsFiddle working example

The bad part about this solution is that you need to update the styles of the header in every scroll event, so, the performance will not be well enough. Another solution is to build two different tables, one for the header and another for the body and a generic function that set the widths of the header taking into account the widths of the body. In this way, you can set the position property of the table in fixed and you could call this function in every resize of the window or in every moment that you need to refresh the sizes of the table. Take a look at the next snippet:

let header = document.querySelector(".table-header");
let body = document.querySelector(".table-body");
let htds = header.querySelectorAll("th");
let btds = body.querySelectorAll("tbody tr:first-child td");

function fixHeaderWidths() {
  header.style.width = `${body.offsetWidth}px`;
  Array.prototype.forEach.call(htds, (td, index) => {
    td.style.width = `${btds[index].offsetWidth}px`;
  });
  body.style.top = "";
  let top = (header.getBoundingClientRect()).bottom - (btds[0].getBoundingClientRect()).top;
  body.style.top = `${top}px`;
}

fixHeaderWidths();

window.onresize = fixHeaderWidths;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.table-header {
  background: white;
  position: fixed;
  table-layout: fixed;
  z-index: 1;
}

.table-body {
  position: relative;
}

.table-body thead {
  visibility: hidden;
}

.tableDiv {
  margin-top: 40px
}</code>```

<link href="https://maxcdn.bootstrapcdn.com/bootswatch/3.3.7/flatly/bootstrap.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.2/css/bootstrap.min.css" rel="stylesheet" />

        Column1
        Column2
        Column3
        Column4
        Column5
        Column6

        Column1
        Column2
        Column3
        Column4
        Column5
        Column6

        FIRST
        asda sdfasf
        fsdf
        sdfsfd
        sdfs
        fsdfsdf

        asdf
        asdfa
        fsdf
        sdfsfd
        sdfs
        fsdfsdf

        asdf
        asdfa
        fsdf
        sdfsfd
        sdfs
        fsdfsdf

        asdf
        asdfa
        fsdf
        sdfsfd
        sdfs
        fsdfsdf

        asdf
        asdfa
        fsdf
        sdfsfd
        sdfs
        fsdfsdf

        asdf
        asdfa
        fsdf
        sdfsfd
        sdfs
        fsdfsdf

        asdf
        asdfa
        fsdf
        sdfsfd
        sdfs
        fsdfsdf

        asdf
        asdfa
        fsdf
        sdfsfd
        sdfs
        fsdfsdf

        asdf
        asdfa
        fsdf
        sdfsfd
        sdfs
        fsdfsdf

        asdf
        asdfa
        fsdf
        sdfsfd
        sdfs
        fsdfsdf

        asdf
        asdfa
        fsdf
        sdfsfd
        sdfs
        fsdfsdf

        asdf
        asdfa
        fsdf
        sdfsfd
        sdfs
        fsdfsdf

        asdf
        asdfa
        fsdf
        sdfsfd
        sdfs
        fsdfsdf

        asdf
        asdfa
        fsdf
        sdfsfd
        sdfs
        fsdfsdf

        asdf
        asdfa
        fsdf
        sdfsfd
        sdfs
        fsdfsdf

        asdf
        asdfa
        fsdf
        sdfsfd
        sdfs
        fsdfsdf

        asdf
        asdfa
        fsdf
        sdfsfd
        sdfs
        fsdfsdf

        asdf
        asdfa
        fsdf
        sdfsfd
        sdfs
        fsdfsdf

        asdf
        asdfa
        fsdf
        sdfsfd
        sdfs
        fsdfsdf

        asdf
        asdfa
        fsdf
        sdfsfd
        sdfs
        fsdfsdf

        asdf
        asdfa
        fsdf
        sdfsfd
        sdfs
        fsdfsdf

        asdf
        asdfa
        fsdf
        sdfsfd
        sdfs
        fsdfsdf

        asdf
        asdfa
        fsdf
        sdfsfd
        sdfs
        fsdfsdf

        asdf
        asdfa
        fsdf
        sdfsfd
        sdfs
        fsdfsdf

        asdf
        asdfa
        fsdf
        sdfsfd
        sdfs
        fsdfsdf

        asdf
        asdfa
        fsdf
        sdfsfd
        sdfs
        fsdfsdf

        asdf
        asdfa
        fsdf
        sdfsfd
        sdfs
        fsdfsdf

        asdf
        asdfa
        fsdf
        sdfsfd
        sdfs
        fsdfsdf

        asdf
        asdfa
        fsdf
        sdfsfd
        sdfs
        fsdfsdf

        asdf
        asdfa
        fsdf
        sdfsfd
        sdfs
        fsdfsdf

        asdf
        asdfa
        fsdf
        sdfsfd
        sdfs
        fsdfsdf

        asdf
        asdfa
        fsdf
        sdfsfd
        sdfs
        fsdfsdf

```

If you don't want to use jQuery, don't use the Bootstrap script file (I've seen that you have included it in your jsFiddle) because it requires jQuery to work. But you can use to replace it something like this.

Title: Fixed table header on window scroll

Body:
I have a simple Bootstrap table with a lot of rows.
Is there a way to make the table header be fixed when scrolling the window, but have the width of each column header to equal the width of the row with the most text.
Because when setting table header position to fixed, then the header doesn't change its width based off the content.
In other words set width of each column dependent on widest value (be that title in the header or value in a cell) in the column.
Is there a way to put such calculations on the header column width ?
I cant think of any other way to do this.
I am using angular.

Here's a jsfiddle of what I've tried when setting position of header row to fixed : JsFiddle
As you can see now the columns don't align with the appropriate columns in the body.
I need them to be aligned, but without setting a fixed width for every column, since I do not know how long the data I'm getting will be.

HTML code:

      Column1
      Column2
      Column3
      Column4
      Column5
      Column6

       FIRST
      asdasdfasf
      fsdf
      sdfsfd
      sdfs
      fsdfsdf

       asdf
      asdfa
      fsdf
      sdfsfd
      sdfs
      fsdfsdf

       asdf
      asdfa
      fsdf
      sdfsfd
      sdfs
      fsdfsdf

Css:

.table-bordered tr {
  position: fixed;
   z-index:1;
  top: 50px;
  background: #fff;
 }

Body:
If you don't care about the performance and you can live without borders in the header (because the borders will not get the CSS transform), there is a solution using CSS3 transforms. The technique is to take the scroll of the window and apply a transform to the header with the same value. In this way, the header is not fixed and it maintains its original widths:

let header = document.querySelector(".table-bordered");
let body = document.body;

function setTranslate (element, value) {
    let style = `translateY(${value}px)`;
    element.style.oTransform = style;
    element.style.MozTransform = style;
    element.style.WebkitTransform = style;
    element.style.transform = style;
}

window.onscroll = () => {
    setTranslate(header, window.scrollY);
};

jsFiddle working example

The bad part about this solution is that you need to update the styles of the header in every scroll event, so, the performance will not be well enough. Another solution is to build two different tables, one for the header and another for the body and a generic function that set the widths of the header taking into account the widths of the body. In this way, you can set the position property of the table in fixed and you could call this function in every resize of the window or in every moment that you need to refresh the sizes of the table. Take a look at the next snippet:

let header = document.querySelector(".table-header");
let body = document.querySelector(".table-body");
let htds = header.querySelectorAll("th");
let btds = body.querySelectorAll("tbody tr:first-child td");

function fixHeaderWidths() {
  header.style.width = `${body.offsetWidth}px`;
  Array.prototype.forEach.call(htds, (td, index) => {
    td.style.width = `${btds[index].offsetWidth}px`;
  });
  body.style.top = "";
  let top = (header.getBoundingClientRect()).bottom - (btds[0].getBoundingClientRect()).top;
  body.style.top = `${top}px`;
}

fixHeaderWidths();

window.onresize = fixHeaderWidths;

.table-header {
  background: white;
  position: fixed;
  table-layout: fixed;
  z-index: 1;
}

.table-body {
  position: relative;
}

.table-body thead {
  visibility: hidden;
}

.tableDiv {
  margin-top: 40px
}

<link href="https://maxcdn.bootstrapcdn.com/bootswatch/3.3.7/flatly/bootstrap.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.2/css/bootstrap.min.css" rel="stylesheet" />
<div class="col-md-12 tableDiv">
  <table class="table-header table table-stripedcf table-bordered">
    <thead>
      <tr>
        <th>Column1</th>
        <th>Column2</th>
        <th>Column3</th>
        <th>Column4</th>
        <th>Column5</th>
        <th>Column6</th>
      </tr>
    </thead>
  </table>
  <table class="table-body table table-stripedcf table-bordered">
    <thead>
      <tr>
        <th>Column1</th>
        <th>Column2</th>
        <th>Column3</th>
        <th>Column4</th>
        <th>Column5</th>
        <th>Column6</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>FIRST</td>
        <td>asda sdfasf</td>
        <td>fsdf</td>
        <td>sdfsfd</td>
        <td>sdfs</td>
        <td>fsdfsdf</td>
      </tr>
      <tr>
        <td>asdf</td>
        <td>asdfa</td>
        <td>fsdf</td>
        <td>sdfsfd</td>
        <td>sdfs</td>
        <td>fsdfsdf</td>
      </tr>
      <tr>
        <td>asdf</td>
        <td>asdfa</td>
        <td>fsdf</td>
        <td>sdfsfd</td>
        <td>sdfs</td>
        <td>fsdfsdf</td>
      </tr>
      <tr>
        <td>asdf</td>
        <td>asdfa</td>
        <td>fsdf</td>
        <td>sdfsfd</td>
        <td>sdfs</td>
        <td>fsdfsdf</td>
      </tr>
      <tr>
        <td>asdf</td>
        <td>asdfa</td>
        <td>fsdf</td>
        <td>sdfsfd</td>
        <td>sdfs</td>
        <td>fsdfsdf</td>
      </tr>
      <tr>
        <td>asdf</td>
        <td>asdfa</td>
        <td>fsdf</td>
        <td>sdfsfd</td>
        <td>sdfs</td>
        <td>fsdfsdf</td>
      </tr>
      <tr>
        <td>asdf</td>
        <td>asdfa</td>
        <td>fsdf</td>
        <td>sdfsfd</td>
        <td>sdfs</td>
        <td>fsdfsdf</td>
      </tr>
      <tr>
        <td>asdf</td>
        <td>asdfa</td>
        <td>fsdf</td>
        <td>sdfsfd</td>
        <td>sdfs</td>
        <td>fsdfsdf</td>
      </tr>
      <tr>
        <td>asdf</td>
        <td>asdfa</td>
        <td>fsdf</td>
        <td>sdfsfd</td>
        <td>sdfs</td>
        <td>fsdfsdf</td>
      </tr>
      <tr>
        <td>asdf</td>
        <td>asdfa</td>
        <td>fsdf</td>
        <td>sdfsfd</td>
        <td>sdfs</td>
        <td>fsdfsdf</td>
      </tr>
      <tr>
        <td>asdf</td>
        <td>asdfa</td>
        <td>fsdf</td>
        <td>sdfsfd</td>
        <td>sdfs</td>
        <td>fsdfsdf</td>
      </tr>
      <tr>
        <td>asdf</td>
        <td>asdfa</td>
        <td>fsdf</td>
        <td>sdfsfd</td>
        <td>sdfs</td>
        <td>fsdfsdf</td>
      </tr>
      <tr>
        <td>asdf</td>
        <td>asdfa</td>
        <td>fsdf</td>
        <td>sdfsfd</td>
        <td>sdfs</td>
        <td>fsdfsdf</td>
      </tr>
      <tr>
        <td>asdf</td>
        <td>asdfa</td>
        <td>fsdf</td>
        <td>sdfsfd</td>
        <td>sdfs</td>
        <td>fsdfsdf</td>
      </tr>
      <tr>
        <td>asdf</td>
        <td>asdfa</td>
        <td>fsdf</td>
        <td>sdfsfd</td>
        <td>sdfs</td>
        <td>fsdfsdf</td>
      </tr>
      <tr>
        <td>asdf</td>
        <td>asdfa</td>
        <td>fsdf</td>
        <td>sdfsfd</td>
        <td>sdfs</td>
        <td>fsdfsdf</td>
      </tr>
      <tr>
        <td>asdf</td>
        <td>asdfa</td>
        <td>fsdf</td>
        <td>sdfsfd</td>
        <td>sdfs</td>
        <td>fsdfsdf</td>
      </tr>
      <tr>
        <td>asdf</td>
        <td>asdfa</td>
        <td>fsdf</td>
        <td>sdfsfd</td>
        <td>sdfs</td>
        <td>fsdfsdf</td>
      </tr>
      <tr>
        <td>asdf</td>
        <td>asdfa</td>
        <td>fsdf</td>
        <td>sdfsfd</td>
        <td>sdfs</td>
        <td>fsdfsdf</td>
      </tr>
      <tr>
        <td>asdf</td>
        <td>asdfa</td>
        <td>fsdf</td>
        <td>sdfsfd</td>
        <td>sdfs</td>
        <td>fsdfsdf</td>
      </tr>
      <tr>
        <td>asdf</td>
        <td>asdfa</td>
        <td>fsdf</td>
        <td>sdfsfd</td>
        <td>sdfs</td>
        <td>fsdfsdf</td>
      </tr>
      <tr>
        <td>asdf</td>
        <td>asdfa</td>
        <td>fsdf</td>
        <td>sdfsfd</td>
        <td>sdfs</td>
        <td>fsdfsdf</td>
      </tr>
      <tr>
        <td>asdf</td>
        <td>asdfa</td>
        <td>fsdf</td>
        <td>sdfsfd</td>
        <td>sdfs</td>
        <td>fsdfsdf</td>
      </tr>
      <tr>
        <td>asdf</td>
        <td>asdfa</td>
        <td>fsdf</td>
        <td>sdfsfd</td>
        <td>sdfs</td>
        <td>fsdfsdf</td>
      </tr>
      <tr>
        <td>asdf</td>
        <td>asdfa</td>
        <td>fsdf</td>
        <td>sdfsfd</td>
        <td>sdfs</td>
        <td>fsdfsdf</td>
      </tr>
      <tr>
        <td>asdf</td>
        <td>asdfa</td>
        <td>fsdf</td>
        <td>sdfsfd</td>
        <td>sdfs</td>
        <td>fsdfsdf</td>
      </tr>
      <tr>
        <td>asdf</td>
        <td>asdfa</td>
        <td>fsdf</td>
        <td>sdfsfd</td>
        <td>sdfs</td>
        <td>fsdfsdf</td>
      </tr>
      <tr>
        <td>asdf</td>
        <td>asdfa</td>
        <td>fsdf</td>
        <td>sdfsfd</td>
        <td>sdfs</td>
        <td>fsdfsdf</td>
      </tr>
      <tr>
        <td>asdf</td>
        <td>asdfa</td>
        <td>fsdf</td>
        <td>sdfsfd</td>
        <td>sdfs</td>
        <td>fsdfsdf</td>
      </tr>
      <tr>
        <td>asdf</td>
        <td>asdfa</td>
        <td>fsdf</td>
        <td>sdfsfd</td>
        <td>sdfs</td>
        <td>fsdfsdf</td>
      </tr>
      <tr>
        <td>asdf</td>
        <td>asdfa</td>
        <td>fsdf</td>
        <td>sdfsfd</td>
        <td>sdfs</td>
        <td>fsdfsdf</td>
      </tr>
      <tr>
        <td>asdf</td>
        <td>asdfa</td>
        <td>fsdf</td>
        <td>sdfsfd</td>
        <td>sdfs</td>
        <td>fsdfsdf</td>
      </tr>
    </tbody>
  </table>
</div>

If you don't want to use jQuery, don't use the Bootstrap script file (I've seen that you have included it in your jsFiddle) because it requires jQuery to work. But you can use to replace it something like this.


问:
Android SDK tools and SDK manager
I want to download the Android SDK tools, without the IDE. but the sdkmanager command couldn't load the repositories.cfg file.  How can this be accomplished?

答:
I suggest you reinstall the sdk but before doing so try to do this:

```<code>touch ~/.android/repositories.cfg
</code>```

if you are using Linux if windows then put your directory.

Title: Android SDK tools and SDK manager

Body:
I suggest you reinstall the sdk but before doing so try to do this:

touch ~/.android/repositories.cfg

if you are using Linux if windows then put your directory.


问:
How to use LLVM-C to JIT-compile the floating-point identity function
So far I have written the following code:

```<code>#include <stdlib.h>
#include <stdio.h>
#include <llvm-c/Core.h>
#include <llvm-c/Analysis.h>
#include <llvm-c/ExecutionEngine.h>
#include <llvm-c/Target.h>
#include <llvm-c/Transforms/Scalar.h>

int main (int argc, char const *argv[])
{
  char *error = NULL;
  LLVMLinkInMCJIT();
  LLVMInitializeNativeTarget();
  LLVMInitializeNativeAsmPrinter();
  LLVMInitializeNativeAsmParser();

  LLVMModuleRef mod = LLVMModuleCreateWithName("minimal_module");
  LLVMTypeRef identity_args[] = { LLVMDoubleType(), NULL };
  LLVMValueRef identity = LLVMAddFunction(mod, "identity", LLVMFunctionType(LLVMDoubleType(), identity_args, 1, 0));
  LLVMSetFunctionCallConv(identity, LLVMCCallConv);
  LLVMValueRef n = LLVMGetParam(identity, 0);

  LLVMBasicBlockRef entry = LLVMAppendBasicBlock(identity, "entry");
  LLVMBuilderRef builder = LLVMCreateBuilder();
  LLVMPositionBuilderAtEnd(builder, entry);
  LLVMBuildRet(builder, n);

  LLVMVerifyModule(mod, LLVMAbortProcessAction, &error);
  LLVMDisposeMessage(error);

  LLVMExecutionEngineRef engine;
  error = NULL;
  if(LLVMCreateJITCompilerForModule(&engine, mod, 2, &error) != 0) {
    fprintf(stderr, "%s\n", error);
    LLVMDisposeMessage(error);
    abort();
  }

  LLVMDumpModule(mod);

  LLVMGenericValueRef exec_args[] = {LLVMCreateGenericValueOfFloat(LLVMDoubleType(), 1.25)};
  LLVMGenericValueRef exec_res = LLVMRunFunction(engine, identity, 1, exec_args);
  fprintf(stderr, "\n");
  fprintf(stderr, "; Running identity(%f) with JIT...\n", 1.25);
  fprintf(stderr, "; Result: %f\n", LLVMGenericValueToFloat(LLVMDoubleType(), exec_res));

  LLVMRemoveModule(engine, mod, &mod, &error);
  LLVMDisposeModule(mod);
  LLVMDisposeExecutionEngine(engine);
  LLVMDisposeBuilder(builder);
  return 0;
}
</code>```

The corresponding implementation using 32-bit integers works, i.e. identity(42) will return 42. However the floating-point version above returns 0.0. Above program generates the following output:

```<code>; ModuleID = 'minimal_module'
source_filename = "minimal_module"
target datalayout = "e-m:e-i64:64-f80:128-n8:16:32:64-S128"

define double @identity(double) {
entry:
  ret double %0
}

; Running identity(1.250000) with JIT...
; Result: 0.000000
</code>```

I am using LLVM-3.9 under Debian Jessie on an AMD computer. My question is: What am I doing wrong?

答:
I found a solution to the problem.
Instead of using LLVMRunFunction one can use LLVMGetFunctionAddress to get the address of the function and call it directly using C (or using an FFI library).

```<code>#include <stdlib.h>
#include <stdio.h>
#include <llvm-c/Core.h>
#include <llvm-c/Analysis.h>
#include <llvm-c/ExecutionEngine.h>
#include <llvm-c/Target.h>
#include <llvm-c/Transforms/Scalar.h>

int main (int argc, char const *argv[])
{
  char *error = NULL;
  LLVMLinkInMCJIT();
  LLVMInitializeNativeTarget();
  LLVMInitializeNativeAsmPrinter();
  LLVMInitializeNativeAsmParser();

  LLVMModuleRef mod = LLVMModuleCreateWithName("minimal_module");
  LLVMTypeRef identity_args[] = { LLVMInt32Type() };
  LLVMValueRef identity = LLVMAddFunction(mod, "identity", LLVMFunctionType(LLVMInt32Type(), identity_args, 1, 0));
  LLVMSetFunctionCallConv(identity, LLVMCCallConv);
  LLVMValueRef n = LLVMGetParam(identity, 0);

  LLVMBasicBlockRef entry = LLVMAppendBasicBlock(identity, "entry");
  LLVMBuilderRef builder = LLVMCreateBuilder();
  LLVMPositionBuilderAtEnd(builder, entry);
  LLVMBuildRet(builder, n);

  LLVMVerifyModule(mod, LLVMAbortProcessAction, &error);
  LLVMDisposeMessage(error);

  LLVMExecutionEngineRef engine;
  error = NULL;
  if(LLVMCreateJITCompilerForModule(&engine, mod, 2, &error) != 0) {
    fprintf(stderr, "%s\n", error);
    LLVMDisposeMessage(error);
    abort();
  }
  int (*fun)(int) = (int (*)(int))LLVMGetFunctionAddress(engine, "identity");

  LLVMDumpModule(mod);

  fprintf(stderr, "\n");
  fprintf(stderr, "; Running identity(42) with JIT...\n");
  fprintf(stderr, "; Result: %d\n", (*fun)(42));

  LLVMRemoveModule(engine, mod, &mod, &error);
  LLVMDisposeModule(mod);
  LLVMDisposeExecutionEngine(engine);
  LLVMDisposeBuilder(builder);
  return 0;
}
</code>```

Body:
So far I have written the following code:

#include <stdlib.h>
#include <stdio.h>
#include <llvm-c/Core.h>
#include <llvm-c/Analysis.h>
#include <llvm-c/ExecutionEngine.h>
#include <llvm-c/Target.h>
#include <llvm-c/Transforms/Scalar.h>

int main (int argc, char const *argv[])
{
  char *error = NULL;
  LLVMLinkInMCJIT();
  LLVMInitializeNativeTarget();
  LLVMInitializeNativeAsmPrinter();
  LLVMInitializeNativeAsmParser();

  LLVMModuleRef mod = LLVMModuleCreateWithName("minimal_module");
  LLVMTypeRef identity_args[] = { LLVMDoubleType(), NULL };
  LLVMValueRef identity = LLVMAddFunction(mod, "identity", LLVMFunctionType(LLVMDoubleType(), identity_args, 1, 0));
  LLVMSetFunctionCallConv(identity, LLVMCCallConv);
  LLVMValueRef n = LLVMGetParam(identity, 0);

  LLVMBasicBlockRef entry = LLVMAppendBasicBlock(identity, "entry");
  LLVMBuilderRef builder = LLVMCreateBuilder();
  LLVMPositionBuilderAtEnd(builder, entry);
  LLVMBuildRet(builder, n);

  LLVMVerifyModule(mod, LLVMAbortProcessAction, &error);
  LLVMDisposeMessage(error);

  LLVMExecutionEngineRef engine;
  error = NULL;
  if(LLVMCreateJITCompilerForModule(&engine, mod, 2, &error) != 0) {
    fprintf(stderr, "%s\n", error);
    LLVMDisposeMessage(error);
    abort();
  }

  LLVMDumpModule(mod);

  LLVMGenericValueRef exec_args[] = {LLVMCreateGenericValueOfFloat(LLVMDoubleType(), 1.25)};
  LLVMGenericValueRef exec_res = LLVMRunFunction(engine, identity, 1, exec_args);
  fprintf(stderr, "\n");
  fprintf(stderr, "; Running identity(%f) with JIT...\n", 1.25);
  fprintf(stderr, "; Result: %f\n", LLVMGenericValueToFloat(LLVMDoubleType(), exec_res));

  LLVMRemoveModule(engine, mod, &mod, &error);
  LLVMDisposeModule(mod);
  LLVMDisposeExecutionEngine(engine);
  LLVMDisposeBuilder(builder);
  return 0;
}

The corresponding implementation using 32-bit integers works, i.e. identity(42) will return 42. However the floating-point version above returns 0.0. Above program generates the following output:

; ModuleID = 'minimal_module'
source_filename = "minimal_module"
target datalayout = "e-m:e-i64:64-f80:128-n8:16:32:64-S128"

define double @identity(double) {
entry:
  ret double %0
}

; Running identity(1.250000) with JIT...
; Result: 0.000000

I am using LLVM-3.9 under Debian Jessie on an AMD computer. My question is: What am I doing wrong?

Body:
I found a solution to the problem.
Instead of using LLVMRunFunction one can use LLVMGetFunctionAddress to get the address of the function and call it directly using C (or using an FFI library).

#include <stdlib.h>
#include <stdio.h>
#include <llvm-c/Core.h>
#include <llvm-c/Analysis.h>
#include <llvm-c/ExecutionEngine.h>
#include <llvm-c/Target.h>
#include <llvm-c/Transforms/Scalar.h>

int main (int argc, char const *argv[])
{
  char *error = NULL;
  LLVMLinkInMCJIT();
  LLVMInitializeNativeTarget();
  LLVMInitializeNativeAsmPrinter();
  LLVMInitializeNativeAsmParser();

  LLVMModuleRef mod = LLVMModuleCreateWithName("minimal_module");
  LLVMTypeRef identity_args[] = { LLVMInt32Type() };
  LLVMValueRef identity = LLVMAddFunction(mod, "identity", LLVMFunctionType(LLVMInt32Type(), identity_args, 1, 0));
  LLVMSetFunctionCallConv(identity, LLVMCCallConv);
  LLVMValueRef n = LLVMGetParam(identity, 0);

  LLVMBasicBlockRef entry = LLVMAppendBasicBlock(identity, "entry");
  LLVMBuilderRef builder = LLVMCreateBuilder();
  LLVMPositionBuilderAtEnd(builder, entry);
  LLVMBuildRet(builder, n);

  LLVMVerifyModule(mod, LLVMAbortProcessAction, &error);
  LLVMDisposeMessage(error);

  LLVMExecutionEngineRef engine;
  error = NULL;
  if(LLVMCreateJITCompilerForModule(&engine, mod, 2, &error) != 0) {
    fprintf(stderr, "%s\n", error);
    LLVMDisposeMessage(error);
    abort();
  }
  int (*fun)(int) = (int (*)(int))LLVMGetFunctionAddress(engine, "identity");

  LLVMDumpModule(mod);

  fprintf(stderr, "\n");
  fprintf(stderr, "; Running identity(42) with JIT...\n");
  fprintf(stderr, "; Result: %d\n", (*fun)(42));

  LLVMRemoveModule(engine, mod, &mod, &error);
  LLVMDisposeModule(mod);
  LLVMDisposeExecutionEngine(engine);
  LLVMDisposeBuilder(builder);
  return 0;
}


问:
Mongoose: Match UserIDs with Embedded Document
What i'm trying to achieve is matching people with each other.
To achieve this behavior, i'm embedding Match document to user's matches array.

Heres my User Model

```<code>const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const Match = new Schema({
    with: {type: Schema.Types.ObjectId, ref: 'User'},
    near: {type:String},
    createdAt: {type:Date, default: Date.now}
 });

const UserSchema = new Schema({
    name: { type: String, default: '' },
    surname: { type: String, default: '' },
    email: { type: String, default: '', },
    salt: { type: String, default: '' },
    hashed_password: { type: String, default: '' },
    interested: { type: [String] },
    about: { type: String },
    createdAt: {type:Date, default:Date.now},
    devices: {type: [String]},
    matches: [Match]
 });
</code>```

But for a reliable application logic,
The users must not be matched twice. My plan is inserting matched people inside their matches array together,

for example;

```<code>User A
_id: 123
matches: [{with: 456,near:California,createdAt:someDateTime}]

User B
_id: 456
matches: [{with: 123,near:California,createdAt:someDateTime}]
</code>```

Before a match occurs, i need to control whether any of the users matched before or not and it must be atomic.

Thanks.

答:
Maybe this works:

```<code>const Match = new Schema({
    matchedIds: [ {type:string} ]
    near: {type:String},
    createdAt: {type:Date, default: Date.now}
 });
</code>```

So matchedIds just contains the two userIDs. You can find the match then with:

```<code>db.match.find( { matchedIds: { $all: ["UserID 1", "UserID 2"] } } )
</code>```

Body:
What i'm trying to achieve is matching people with each other.
To achieve this behavior, i'm embedding Match document to user's matches array.

Heres my User Model

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const Match = new Schema({
    with: {type: Schema.Types.ObjectId, ref: 'User'},
    near: {type:String},
    createdAt: {type:Date, default: Date.now}
 });

const UserSchema = new Schema({
    name: { type: String, default: '' },
    surname: { type: String, default: '' },
    email: { type: String, default: '', },
    salt: { type: String, default: '' },
    hashed_password: { type: String, default: '' },
    interested: { type: [String] },
    about: { type: String },
    createdAt: {type:Date, default:Date.now},
    devices: {type: [String]},
    matches: [Match]
 });

But for a reliable application logic,
The users must not be matched twice. My plan is inserting matched people inside their matches array together,

for example;

User A
_id: 123
matches: [{with: 456,near:California,createdAt:someDateTime}]

User B
_id: 456
matches: [{with: 123,near:California,createdAt:someDateTime}]

Before a match occurs, i need to control whether any of the users matched before or not and it must be atomic.

Thanks.

Body:
Maybe this works:

const Match = new Schema({
    matchedIds: [ {type:string} ]
    near: {type:String},
    createdAt: {type:Date, default: Date.now}
 });

So matchedIds just contains the two userIDs. You can find the match then with:

db.match.find( { matchedIds: { $all: ["UserID 1", "UserID 2"] } } )


问:
Algorithm for Least Edge Intersections
(Before anyone asks, it's not homework.)

Say you have 2 Arrays y0 and y1 where

y0 = [1,2,3,4,5,6] and
y1 = [2,1,6,3,4,5]

Notice y0[0] = y1[1] = 1, it essentially means y0[0] is connected to y1[1]. Similarly, y0[2] = y1[3] = 3 so they are "connected" as well.

(Image courtesy : belisarius)

Each element in one array has a corresponding entry in the second array. Imagine each element in the array as a vertex, and these connections as Edges being drawn from one array to the other.

I need to find a set of edges (of maximum size) such that none of the "edges" (or lines) will intersect.

In the above example, notice,

Edge 1 and Edge 2 will intersect.

Edge 6  will intersect with  Edge 3, Edge 4, Edge 5.

Therefore, the solution can be be 1,3,4,5 or 2,3,4,5 (size = 4) since none of those lines will intersect each other. There can be multiple solutions, but I need just one.

My Question, Is there any known CS Problem that resembles this? What algorithm should i be using?

I've tried to explain my problem with an example, however, incase it's still not clear i'll clarify any queries.
Thanks in advance.

答:
What you are describing is known as the  matching problem for bipartite graphs.  I suspect there is something (as yet unstated) about the problem which makes it difficult to solve.  So far you really haven't placed any restriction on what edges can be used.  Supposing that there are certain edges (not all) available, those "possible" edges form a graph, and the ones you decide to use form a maximum matching.  Finding a maximum matching in a graph is a polynomial time algorithm, and it is particularly easy to code for the bipartite case.

The title makes it sound as though circumstances might impose some circumstance so that "disjoint" edges might not be feasible ("least edge intersections").  Perhaps you want edge covering (or 1-cover), i.e. that every vertex belongs to at least one edge.  Then, if the two "vertex" arrays are of different length, there will not be a "perfect matching", i.e. a matching that is also a cover.  A classic result  Hall's Marriage Theorem characterizes when there are perfect matchings in a bipartite graph.  If the graph is regular (all vertices have equal degree), then  König's Theorem tells us there is perfect matching (and more).

Added:

It may be worth stating what the picture seems to say about the restrictions on choosing edges.  Two sets of vertices have coordinates {(i,0) | i=1,..,N} and {(j,1) | j=1,..,N}.  There are N available edges, line segments that connect (i,0) and (j,1) whenever y0[i] = y1[j].  Although the subject line says "least edge intersections", a solution is a maximum subset of these edges that admits no intersections, a largest  planar straight-line graph contained in a given  permutation graph.

It is related to the 2-level crossing minimization problem considered here:

An Alternative Method to Crossing Minimization on Hierarchical Graphs -- P. Mutzel

"We suggest... removing the minimal number of edges such that the resulting graph is k-level planar...  In this paper we address the case k = 2... [W]e address the problem of extracting a 2-level planar subgraph of maximum weight in a given 2-level graph.  This problem is NP-hard."

The present problem imposes an equal number of points in the two vertex sets, the base graph is regular of degree 1, and no choice is allowed in the numbering or positioning of points.  So it is not possible to conclude it is as hard as the one described in the above paper.  However it does direct us to so-called "branch and bound" methods for the exact solution of such problems.

Let's consider the "edges" of the original problem as "nodes" of a new graph where two nodes are adjacent iff the original edges intersect.  [This is an example of an intersection graph.]  The problem as restated is now to find  a maximum independent set of the new graph.  The problems of that kind are in general NP-hard, but again we suspect the extent of the present problems may not be so general.

One reason to suspect a polynomial time algorithm could exist is the availability of polynomial time approximation algorithms for maximum independent subsets of intersection graphs for finite collections of planar convex sets:

Independent Set of Intersection Graphs of Convex Objects in 2D -- P. Agarwal and M Mustafa

"In this paper, we present approximation algorithms for the independent-set problem on intersection graphs of line segments and convex objects in the plane."

There is one further observation about the specialness of the present problem that seems to make it solvable in polynomial time.  A  circle graph is the intersection graph of line segments that can be drawn as chords of a circle.  By a pertubation argument the straight-line edges of a permutation graph can be so drawn, without loss or introduction of intersections.

Now the maximum independent set problem for circle graphs can be solved in polynomial time.  The Wikipedia article linked above gives this reference:

Nash, Nicholas; Gregg, David (2010), "An output sensitive algorithm for computing a maximum independent set of a circle graph", Information Processing Letters 116 (16): 630–634

I also found this reference in Google Books:

Valiente, Gabriel (2003), "A New Simple Algorithm for the Maximum-Weight Independent Set Problem on Circle Graphs", Algorithms and computation: 14th Symposium, ISAAC 2003 Kyoto

Title: Algorithm for Least Edge Intersections


答: You are splitting the sentence by lines instead of words, probably you wanted to use sentence.split(" ") instead of sentence.split("\n").

Title: Translator with HashMap as dictionary Java


问:
Is it possible to use emoji on A-Frame a-text?
I find it useful to use an emoji instead of an image in an a-text
But I tried this:

```<code><a-text value="&#1F601"></a-text>
</code>```

And this:

```<code><a-text value=""></a-text>
</code>```

And it doesn't seem to work (text is omitted).

And yes, it's included in head:

```<code><head>
  <meta charset="utf-8" />
</head>
</code>```

Is it possible or is there a limitation with WebGL/ThreeJS/A-Frame?

答:
The optimal way would be to have a bunch of emojis in a spritesheet and then use something like https://github.com/ngokevin/kframe/tree/master/components/atlas-uvs to represent them individually.</p>

```<code>  <a-scene>
    <a-mixin id="emojis" atlas-uvs="totalRows: 4; totalColumns: 4" material="src: emojis.png" geometry="primitive: plane; buffer: false; skipCache: true"></a-mixin>

    <a-entity mixin="emojis" atlas-uvs="column: 1; row: 1"></a-entity>
    <a-entity mixin="emojis" atlas-uvs="column: 3; row: 2"></a-entity>
    <a-entity mixin="emojis" atlas-uvs="column: 2; row: 4"></a-entity>
  </a-scene>
</code>```

Body:
I find it useful to use an emoji instead of an image in an a-text
But I tried this:

And this:

And it doesn't seem to work (text is omitted).

And yes, it's included in head:

  <meta charset="utf-8" />

Is it possible or is there a limitation with WebGL/ThreeJS/A-Frame?

Body:
The optimal way would be to have a bunch of emojis in a spritesheet and then use something like https://github.com/ngokevin/kframe/tree/master/components/atlas-uvs to represent them individually.

  <a-scene>
    <a-mixin id="emojis" atlas-uvs="totalRows: 4; totalColumns: 4" material="src: emojis.png" geometry="primitive: plane; buffer: false; skipCache: true"></a-mixin>

    <a-entity mixin="emojis" atlas-uvs="column: 1; row: 1"></a-entity>
    <a-entity mixin="emojis" atlas-uvs="column: 3; row: 2"></a-entity>
    <a-entity mixin="emojis" atlas-uvs="column: 2; row: 4"></a-entity>
  </a-scene>