问:
How to upload file from a subfolder using Selenium in Python
Can somebody tell me what to modify here, so the file I'm uploading can be uploaded from a subfolder? At the moment the files are stored in the same folder as the python script.

This script helps me to automate the process of adding ads to a site. Here is the part which uploads image files from a json file (photofiles is an array in config.json). I want to store the photos in a subfolder.

```<code># Upload images
fileup = driver.find_element_by_xpath("//input[@type='file']")

for path in photofiles:
    uploaded_count = len(driver.find_elements_by_class_name("imagebox-thumbnail"))
    fileup.send_keys(os.path.abspath(path))
    total_upload_time = 0
    while uploaded_count == len(driver.find_elements_by_class_name("imagebox-thumbnail")) and \
                    total_upload_time < 30:
        time.sleep(0.5)
        total_upload_time += 0.5

    log.debug("Uploaded file in %s seconds." % total_upload_time)
</code>```

答:
The file you are uploading can be easily uploaded from a subfolder.

```<code>>>> import os
>>> print(os.getcwd())
C:\Python32
>>> os.chdir('/test')
>>> print(os.getcwd())
C:\test
</code>```

Just use os.getcwd() and os.getcwd() to enter in sub-dir.

That's it. I think now, you will yourself implement the above snippet in your script.

BTW,
I recommend you to visit Python Files.

Body:
Can somebody tell me what to modify here, so the file I'm uploading can be uploaded from a subfolder? At the moment the files are stored in the same folder as the python script.

This script helps me to automate the process of adding ads to a site. Here is the part which uploads image files from a json file (photofiles is an array in config.json). I want to store the photos in a subfolder.

# Upload images
fileup = driver.find_element_by_xpath("//input[@type='file']")

for path in photofiles:
    uploaded_count = len(driver.find_elements_by_class_name("imagebox-thumbnail"))
    fileup.send_keys(os.path.abspath(path))
    total_upload_time = 0
    while uploaded_count == len(driver.find_elements_by_class_name("imagebox-thumbnail")) and \
                    total_upload_time < 30:
        time.sleep(0.5)
        total_upload_time += 0.5

    log.debug("Uploaded file in %s seconds." % total_upload_time)

Body:
The file you are uploading can be easily uploaded from a subfolder.

>>> import os
>>> print(os.getcwd())
C:\Python32
>>> os.chdir('/test')
>>> print(os.getcwd())
C:\test

Just use os.getcwd() and os.getcwd() to enter in sub-dir.

That's it. I think now, you will yourself implement the above snippet in your script.

BTW,
I recommend you to visit Python Files.


来源: stackexchange

问:
Binary Trees vs. Linked Lists vs. Hash Tables
I'm building a symbol table for a project I'm working on. I was wondering what peoples opinions are on the advantages and disadvantages of the various methods available for storing and creating a symbol table.

I've done a fair bit of searching and the most commonly recommended are binary trees or linked lists or hash tables. What are the advantages and or disadvantages of all of the above? (working in c++)

答:
Other comments have focused on adding/retrieving elements, but this discussion isn't complete without considering what it takes to iterate over the entire collection.  The short answer here is that hash tables require less memory to iterate over, but trees require less time.

For a hash table, the memory overhead of iterating over the (key, value) pairs does not depend on the capacity of the table or the number of elements stored in the table; in fact, iterating should require just a single index variable or two.

For trees, the amount of memory required always depends on the size of the tree.  You can either maintain a queue of unvisited nodes while iterating or add additional pointers to the tree for easier iteration (making the tree, for purposes of iteration, act like a linked list), but either way, you have to allocate extra memory for iteration.

But the situation is reversed when it comes to timing.  For a hash table, the time it takes to iterate depends on the capacity of the table, not the number of stored elements.  So a table loaded at 10% of capacity will take about 10 times longer to iterate over than a linked list with the same elements!

OwnerDisplayName: Ben McRedmond

ContentLicense: CC BY-SA 3.0

LastEditorDisplayName: benofsky

OwnerDisplayName: anonymous

ContentLicense: CC BY-SA 2.5


问:
When to use each type of loop?
I'm learning the basics of programming here (C#) but I think this question is generic in its nature.

What are some simple practical situations that lend themselves closer to a particular type of loop?

The while and for loops seem pretty similar and there are several SO questions addressing the differences between the two. How about foreach? From my basic understanding, its seems I ought to be able to do everything a foreach loop does within a for loop.

答:
Which ever works best for code readability. In other words use the one that fits the situation best.

while: When you have a condition that needs to be checked at the start of each loop. e.g. while(!file.EndOfFile) { }

for: When you have an index or counter you are incrementing on each loop. for (int i = 0; i<array.Length; i++) { }. Essentially, the thing you are looping over is an indexable collection, array, list, etc.

foreach: When you are looping over a collection of objects or other Enumerable. In this event you may not know (or care) the size of the collection, or the collection is not index based (e.g. a set of objects). Generally I find foreach loops to be the most readable when I'm not interested in the index of something or any other exit conditions.

Those are my general rules of thumb anyway.

Title: When to use each type of loop?


问:
Can't update vars inside Angularjs Factory
Anyone can help with this? Can't update var ABCKey. Execute setAuthenticatedAccount and console.log return correct value. After that, run getAuthenticatedAccount, and receive undefined.

```<code>angular.module('authentication.service', [
])

.factory('Authentication', ['$state', '$cookies', '$http', 'app', 'routes', 'cfCryptoHttpInterceptor',
    function($state, $cookies, $http, app, routes, cfCryptoHttpInterceptor) {

    var ABCKey;

    var setAuthenticatedAccount = function (account, tokenAuth) {
        var accountInfo = {'email': account.email, 'username': account.username, 'token': tokenAuth}
        var abc = CryptoJS.enc.Base64.parse(account.abc);

        Authentication.setABCKey(abc);

        console.log(Authentication.showABCKey())

    }

    var getAuthenticatedAccount = function() {
        if(!$cookies.authenticatedAccount) {
            return;
        }

        console.log(Authentication.showABCKey())

    }

    var setABCKey = function(key) {
        ABCKey = key;
    };

    var showABCKey = function() {
        return ABCKey;
    };

    var Authentication = {
        setAuthenticatedAccount: setAuthenticatedAccount,
        getAuthenticatedAccount: getAuthenticatedAccount,
        setABCKey: setABCKey,
        showABCKey: showABCKey
    };

    return Authentication;
}]);
</code>```

答:
Remove Authentication while you are calling your functions because it is creating object every time. And also set var ABCKey=null at the time of decelaration like this-

```<code>angular.module('authentication.service', [
])

.factory('Authentication', ['$state', '$cookies', '$http', 'app', 'routes', 'cfCryptoHttpInterceptor',
    function($state, $cookies, $http, app, routes, cfCryptoHttpInterceptor) {

    var ABCKey=null;

    var setAuthenticatedAccount = function (account, tokenAuth) {
        var accountInfo = {'email': account.email, 'username': account.username, 'token': tokenAuth}
        var abc = CryptoJS.enc.Base64.parse(account.abc);

        setABCKey(abc);

        console.log(showABCKey())

    }

    var getAuthenticatedAccount = function() {
        if(!$cookies.authenticatedAccount) {
            return;
        }

        console.log(showABCKey())

    }

    var setABCKey = function(key) {
        ABCKey = key;
    };

    var showABCKey = function() {
        return ABCKey;
    };

    var Authentication = {
        setAuthenticatedAccount: setAuthenticatedAccount,
        getAuthenticatedAccount: getAuthenticatedAccount,
        setABCKey: setABCKey,
        showABCKey: showABCKey
    };

    return Authentication;
}]);
</code>```

Body:
Anyone can help with this? Can't update var ABCKey. Execute setAuthenticatedAccount and console.log return correct value. After that, run getAuthenticatedAccount, and receive undefined.

angular.module('authentication.service', [
])

.factory('Authentication', ['$state', '$cookies', '$http', 'app', 'routes', 'cfCryptoHttpInterceptor',
    function($state, $cookies, $http, app, routes, cfCryptoHttpInterceptor) {

    var ABCKey;

    var setAuthenticatedAccount = function (account, tokenAuth) {
        var accountInfo = {'email': account.email, 'username': account.username, 'token': tokenAuth}
        var abc = CryptoJS.enc.Base64.parse(account.abc);

        Authentication.setABCKey(abc);

        console.log(Authentication.showABCKey())

    }

    var getAuthenticatedAccount = function() {
        if(!$cookies.authenticatedAccount) {
            return;
        }

        console.log(Authentication.showABCKey())

    }

    var setABCKey = function(key) {
        ABCKey = key;
    };

    var showABCKey = function() {
        return ABCKey;
    };

    var Authentication = {
        setAuthenticatedAccount: setAuthenticatedAccount,
        getAuthenticatedAccount: getAuthenticatedAccount,
        setABCKey: setABCKey,
        showABCKey: showABCKey
    };

    return Authentication;
}]);

Body:
Remove Authentication while you are calling your functions because it is creating object every time. And also set var ABCKey=null at the time of decelaration like this-

angular.module('authentication.service', [
])

.factory('Authentication', ['$state', '$cookies', '$http', 'app', 'routes', 'cfCryptoHttpInterceptor',
    function($state, $cookies, $http, app, routes, cfCryptoHttpInterceptor) {

    var ABCKey=null;

    var setAuthenticatedAccount = function (account, tokenAuth) {
        var accountInfo = {'email': account.email, 'username': account.username, 'token': tokenAuth}
        var abc = CryptoJS.enc.Base64.parse(account.abc);

        setABCKey(abc);

        console.log(showABCKey())

    }

    var getAuthenticatedAccount = function() {
        if(!$cookies.authenticatedAccount) {
            return;
        }

        console.log(showABCKey())

    }

    var setABCKey = function(key) {
        ABCKey = key;
    };

    var showABCKey = function() {
        return ABCKey;
    };

    var Authentication = {
        setAuthenticatedAccount: setAuthenticatedAccount,
        getAuthenticatedAccount: getAuthenticatedAccount,
        setABCKey: setABCKey,
        showABCKey: showABCKey
    };

    return Authentication;
}]);


问:
SyntaxError .../project/assets/images/logo.png: Unexpected character '�' (1:0)
this looks like a loader error, but shouldn't Expo/CRNA support png by default?

Here's my code:

```<code><View style={ styles.logo }>
  <Image source={require('../assets/images/logo.png')} style={{ flex:1, width: 150, height: 150 }} />
</View>

logo: {
  flex: 1,
  flexDirection: 'column',
  justifyContent: 'center',
  alignItems: 'center',

  height: 200,
},
</code>```

My images are cached using the example code on expo.io. This is the first asset I try. How do I fix this? I can't even find any loader configuration.

答: This happens when you have 'Hot reloading' enabled. Whenever you are going to update an image on your project, disable hot reloading from the menu shaking your device.</p>

Body:
this looks like a loader error, but shouldn't Expo/CRNA support png by default?

Here's my code:

<View style={ styles.logo }>
  <Image source={require('../assets/images/logo.png')} style={{ flex:1, width: 150, height: 150 }} />
</View>

logo: {
  flex: 1,
  flexDirection: 'column',
  justifyContent: 'center',
  alignItems: 'center',

  height: 200,
},

My images are cached using the example code on expo.io. This is the first asset I try. How do I fix this? I can't even find any loader configuration.


问:
How to make a hyperlink work like a button?
For buttons, we have the onclick attribute to call a JavaScript function, but how to make a hyperlink work like a button?

In addition, how to use a hyperlink to submit a form or do anything else a button can do?

答:
```<code><a href=# onClick=alert('hi.'),false>Click</a>

a { -moz-appearance: button; } // or -webkit-
</code>```

https://jsfiddle.net/Dezain/r3g9e7a2/

Body:
<a href=# onClick=alert('hi.'),false>Click</a>

a { -moz-appearance: button; } // or -webkit-

https://jsfiddle.net/Dezain/r3g9e7a2/


问:
How to return all rows containing a certain value using excel formula
I need an excel formula that will select all rows containing a certain keyword, and then either return a pivot table of these rows, or copy them to another sheet in the workbook.  I cannot use VBA or a filter, it has to be done with excel functions.  It would also be helpful if it could search across multiple sheets.

This is what I have so far

```<code>=INDEX($A$2:$B$29,SMALL(IF($B$2:$B$29=$G$2,ROW($B$2:$B$29)),ROW(1:1))-1,1)
</code>```

But it only returns a single value from the rows that match, not entire rows, and not as a pivot table.

答:
I think I found a solution for this regarding two possibilities:

Given your data are stowed through Column A of Sheet 1.

The values seached amongst are not reduplicated, that means no two identical occurences can be found:

You should therefor create a new sheet then copy the value 0 inside the case A1, then copy this line through other rows of same column.

```<code>=IFERROR(INDIRECT("Sheet1!$A"&MATCH("*a*";INDIRECT("Sheet1!"&ADDRESS(IF(ISNUMBER(A1);A1;MATCH(A1;Sheet1!$A$1:A100;0))+1;1;1;1)):Sheet1!A100;0)+IF(ISNUMBER(A1);A1;MATCH(A1;Sheet1!$A$1:Sheet1!A100;0)));"")
</code>```

The values searched between contains duplicates:

Copy this through A2 -> A100 and 0 in A1

```<code>=IFERROR(MATCH("*a*";INDIRECT("Sheet1!"&ADDRESS(A1+1;1)):Sheet1!A100;0)+A1;"")
</code>```

then copy this throughout B2 -> B100

```<code>=IFERROR(INDIRECT("Sheet1!"&ADDRESS(A2;1));"")
</code>```

Automatically A1 and A2 should increment respectively of actual row, Also there is a way to cram (or concatenate) all results inside one whole cell because my version of EXCEL doesnt include returning pivot tables.

Body:
I need an excel formula that will select all rows containing a certain keyword, and then either return a pivot table of these rows, or copy them to another sheet in the workbook.  I cannot use VBA or a filter, it has to be done with excel functions.  It would also be helpful if it could search across multiple sheets.

This is what I have so far

=INDEX($A$2:$B$29,SMALL(IF($B$2:$B$29=$G$2,ROW($B$2:$B$29)),ROW(1:1))-1,1)

But it only returns a single value from the rows that match, not entire rows, and not as a pivot table.

Body:
I think I found a solution for this regarding two possibilities:

Given your data are stowed through Column A of Sheet 1.

The values seached amongst are not reduplicated, that means no two identical occurences can be found:

You should therefor create a new sheet then copy the value 0 inside the case A1, then copy this line through other rows of same column.

=IFERROR(INDIRECT("Sheet1!$A"&MATCH("*a*";INDIRECT("Sheet1!"&ADDRESS(IF(ISNUMBER(A1);A1;MATCH(A1;Sheet1!$A$1:A100;0))+1;1;1;1)):Sheet1!A100;0)+IF(ISNUMBER(A1);A1;MATCH(A1;Sheet1!$A$1:Sheet1!A100;0)));"")

The values searched between contains duplicates:

Copy this through A2 -> A100 and 0 in A1

=IFERROR(MATCH("*a*";INDIRECT("Sheet1!"&ADDRESS(A1+1;1)):Sheet1!A100;0)+A1;"")

then copy this throughout B2 -> B100

=IFERROR(INDIRECT("Sheet1!"&ADDRESS(A2;1));"")

Automatically A1 and A2 should increment respectively of actual row, Also there is a way to cram (or concatenate) all results inside one whole cell because my version of EXCEL doesnt include returning pivot tables.


问:
Sed remove NULL but only when the NULL means empty or no value
Exporting a table from MySQL where fields that have no value will have the keyword NULL within.

```<code>| id | name | nickname | origin | date |
| 1  | Joe  | Mini-J   | BRAZIL | NULL |
</code>```

I have written a script to automatically remove all occurrences of NULL using a one-liner sed, which will remove the NULL in date column correctly:

```<code>sed -i 's/NULL//g'
</code>```

However, how do we handle IF we have the following?

```<code>| id | name | nickname | origin | date |
| 1  | Joe  | Mini-J   | BRAZIL | NULL |
| 2  | Dees | DJ Null Bee| US| 2017-04-01 |
| 3  | NULL AND VOID | NULLZIET | NULL| 2016-05-13 |
| 4  | Pablo | ALA PUHU MINULLE | GERMANY| 2017-02-14 |
</code>```

Apparently, the global search and replace all occurrences of NULL will be removed, where even "ALA PUHU MINULLE" will become "ALA PUHU MIE", which is incorrect.

I suppose the use of regex perhaps can be useful to apply the rule? But if so, will "DJ Null Bee" be affected or will it become "DJ Bee"? The desired outcome should really be:

```<code>| id | name | nickname | origin | date |
| 1  | Joe  | Mini-J   | BRAZIL |  |
| 2  | Dees | DJ Null Bee| US| 2017-04-01 |
| 3  | NULL AND VOID | DJ Null Bee| | 2016-05-13 |
| 4  | Pablo | ALA PUHU MINULLE | GERMANY| 2017-02-14 |
</code>```

Given that NULL is a special keyword for any databases, but there is no stopping anyone from calling themselves a DJ NULL, or have the word NULL because it means differently in another language.

Any ideas on how to resolve this? Any suggestions welcomed. Thank you!

答:
```<code>awk '{sub(/BRAZIL \| NULL/,"BRAZIL \| ")sub(/NULLZIET \| NULL/,"DJ Null Bee\| ")}1' file

| id | name | nickname | origin | date |
| 1  | Joe  | Mini-J   | BRAZIL |  |
| 2  | Dees | DJ Null Bee| US| 2017-04-01 |
| 3  | NULL AND VOID | DJ Null Bee| | 2016-05-13 |
| 4  | Pablo | ALA PUHU MINULLE | GERMANY| 2017-02-14 |
</code>```

Body:
Exporting a table from MySQL where fields that have no value will have the keyword NULL within.

| id | name | nickname | origin | date |
| 1  | Joe  | Mini-J   | BRAZIL | NULL |

I have written a script to automatically remove all occurrences of NULL using a one-liner sed, which will remove the NULL in date column correctly:

sed -i 's/NULL//g'

However, how do we handle IF we have the following?

| id | name | nickname | origin | date |
| 1  | Joe  | Mini-J   | BRAZIL | NULL |
| 2  | Dees | DJ Null Bee| US| 2017-04-01 |
| 3  | NULL AND VOID | NULLZIET | NULL| 2016-05-13 |
| 4  | Pablo | ALA PUHU MINULLE | GERMANY| 2017-02-14 |

Apparently, the global search and replace all occurrences of NULL will be removed, where even "ALA PUHU MINULLE" will become "ALA PUHU MIE", which is incorrect.

I suppose the use of regex perhaps can be useful to apply the rule? But if so, will "DJ Null Bee" be affected or will it become "DJ Bee"? The desired outcome should really be:

| id | name | nickname | origin | date |
| 1  | Joe  | Mini-J   | BRAZIL |  |
| 2  | Dees | DJ Null Bee| US| 2017-04-01 |
| 3  | NULL AND VOID | DJ Null Bee| | 2016-05-13 |
| 4  | Pablo | ALA PUHU MINULLE | GERMANY| 2017-02-14 |

Given that NULL is a special keyword for any databases, but there is no stopping anyone from calling themselves a DJ NULL, or have the word NULL because it means differently in another language.

Any ideas on how to resolve this? Any suggestions welcomed. Thank you!


问:
Unit tests in Spring MVC Rest - cast issue
I am developing simple Rest API app and trying to test it using this tutorial: http://memorynotfound.com/unit-test-spring-mvc-rest-service-junit-mockito/

I have implemented entire test_get_all_success unit test using my working Rest API (written in Spring MVC). Unfortunately test cannot run because of following issue.

Here is entire test file:

```<code>import java.util.Arrays;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;

import static org.hamcrest.Matchers.*;
import org.junit.Before;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import static org.mockito.Mockito.*;
import org.mockito.MockitoAnnotations;
import org.springframework.http.MediaType;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes={MyConfigClass.class})
@WebAppConfiguration
public class ClientTest {

    private MockMvc mockMvc;

    @Mock
    private ClientManagerImpl clientManager;

    @InjectMocks
    private ClientController clientController;

    @Before
    public void init(){
        MockitoAnnotations.initMocks(this);
        mockMvc = MockMvcBuilders
                .standaloneSetup(clientController)
                .build();
    }

    @Test
    public void findAll_ClientsFound_ShouldReturnFoundClients() throws Exception {
        Client a = ...;
        Client b = ...;

        when(clientManager.getClients()).thenReturn(Arrays.asList(a, b));

        mockMvc.perform(get("/clients"))
                .andExpect(status().isOk())
        .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
                .andExpect(jsonPath("$", hasSize(2)));

        verify(clientManager, times(1)).getClients();
        verifyNoMoreInteractions(clientManager);
    }

}
</code>```

NetBeans shows error in this line:

```<code>.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))

incompatible types: RequestMatcher cannot be converted to ResultMatcher
</code>```

Test cannot run because of this error. When I delete this line everything works fine and test is passed.

What am I doing wrong?

答:
The following static import causes the conflict:

```<code>import static org.springframework.test.web.client.match.MockRestRequestMatchers.content;
</code>```

MockRestRequestMatchers class is used for client-side REST testing using MockRestServiceServer, but you are testing here MVC application controllers.

Body:
I am developing simple Rest API app and trying to test it using this tutorial: http://memorynotfound.com/unit-test-spring-mvc-rest-service-junit-mockito/

I have implemented entire test_get_all_success unit test using my working Rest API (written in Spring MVC). Unfortunately test cannot run because of following issue.

Here is entire test file:

import java.util.Arrays;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;

import static org.hamcrest.Matchers.*;
import org.junit.Before;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import static org.mockito.Mockito.*;
import org.mockito.MockitoAnnotations;
import org.springframework.http.MediaType;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes={MyConfigClass.class})
@WebAppConfiguration
public class ClientTest {

    private MockMvc mockMvc;

    @Mock
    private ClientManagerImpl clientManager;

    @InjectMocks
    private ClientController clientController;

    @Before
    public void init(){
        MockitoAnnotations.initMocks(this);
        mockMvc = MockMvcBuilders
                .standaloneSetup(clientController)
                .build();
    }

    @Test
    public void findAll_ClientsFound_ShouldReturnFoundClients() throws Exception {
        Client a = ...;
        Client b = ...;

        when(clientManager.getClients()).thenReturn(Arrays.asList(a, b));

        mockMvc.perform(get("/clients"))
                .andExpect(status().isOk())
        .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
                .andExpect(jsonPath("$", hasSize(2)));

        verify(clientManager, times(1)).getClients();
        verifyNoMoreInteractions(clientManager);
    }

}

NetBeans shows error in this line:

.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))

incompatible types: RequestMatcher cannot be converted to ResultMatcher

Test cannot run because of this error. When I delete this line everything works fine and test is passed.

What am I doing wrong?

Body:
The following static import causes the conflict:

import static org.springframework.test.web.client.match.MockRestRequestMatchers.content;

MockRestRequestMatchers class is used for client-side REST testing using MockRestServiceServer, but you are testing here MVC application controllers.


问:
How to fill generated Pivot Elements with data [templates]
Howdy,
I would like to generate in my application several PivotItems in a pivotelement. The generation is proceeding fine, however I don't know how I can apply a template to those Pivot Elements.

I thought I would need to use:

pivotItem.ContentTemplate = (DataTemplate)Ressources["KantinenUebersicht"];

But that is only producing an empty page.

My code in the ressource file looks the following:

inserted my whole ressources File

<.ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

```<code><DataTemplate x:Key="KantinenTemplate">
    <StackPanel VerticalAlignment="Top">
            <TextBlock HorizontalAlignment="Left" TextWrapping="Wrap" Text="{Binding name}" FontSize="{StaticResource PhoneFontSizeLarge}" Margin="8,0,0,0" VerticalAlignment="Top"/>
            <TextBlock HorizontalAlignment="Left" TextWrapping="Wrap" Text="{Binding entfernung}" Margin="24,0,0,0" FontSize="{StaticResource PhoneFontSizeSmall}" VerticalAlignment="Bottom"/>
    </StackPanel>
</DataTemplate>

<DataTemplate x:Key="KantinenUebersicht">
        <Grid>
            <TextBlock x:Name="KantinenName" FontSize="{StaticResource PhoneFontSizeExtraLarge}" Text="" RenderTransformOrigin="0.566,0.407" Margin="0,0,8,0" Height="55" VerticalAlignment="Top">
                        <TextBlock.Foreground>
                            <SolidColorBrush Color="{StaticResource PhoneAccentColor}"/>
                        </TextBlock.Foreground>
            </TextBlock>
            <TextBlock x:Name="sdfsdf" HorizontalAlignment="Left" Height="40" Margin="8,59,0,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" Width="196"/>
            <TextBlock x:Name="lblGeoefsdfsdffnet" Height="40" Margin="208,59,8,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top"/>
        </Grid>
    </DataTemplate></ResourceDictionary.>
</code>```

Had to insert . in the first tags...

答:
What you're trying to do is correct.

In your question you have an extra "S" in "Resources" which could be the issue.

If I take the code from your question, I can add it to the page:

```<code><phone:PhoneApplicationPage.Resources>
    <DataTemplate x:Key="KantinenUebersicht">
        <Grid>
            <TextBlock x:Name="KantinenName" FontSize="{StaticResource PhoneFontSizeExtraLarge}" Text="" RenderTransformOrigin="0.566,0.407" Margin="0,0,8,0" Height="55" VerticalAlignment="Top">
                 <TextBlock.Foreground>
                  <SolidColorBrush Color="{StaticResource PhoneAccentColor}"/>
                 </TextBlock.Foreground>
            </TextBlock>
            <TextBlock x:Name="lblEntfernung" HorizontalAlignment="Left" Height="40" Margin="8,59,0,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" Width="196"/>
            <TextBlock x:Name="lblGeoeffnet" Height="40" Margin="208,59,8,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top"/>
        </Grid>
    </DataTemplate>
</phone:PhoneApplicationPage.Resources>
</code>```

and then use it when creating a new item:

```<code>var newItem = new PivotItem { Header = "Added" };

newItem.ContentTemplate = (DataTemplate)Resources["KantinenUebersicht"];

MyPivot.Items.Add(newItem);
</code>```

Works on my machine (emulator).

Update:

If you want to add the resource to a separate file you can do so like:

ResourceDictionary.xaml:

```<code><ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" >
    <DataTemplate x:Key="KantinenUebersicht">
        <Grid>
            <TextBlock x:Name="KantinenName" FontSize="{StaticResource PhoneFontSizeExtraLarge}" Text="" RenderTransformOrigin="0.566,0.407" Margin="0,0,8,0" Height="55" VerticalAlignment="Top">
                     <TextBlock.Foreground>
                      <SolidColorBrush Color="{StaticResource PhoneAccentColor}"/>
                     </TextBlock.Foreground>
            </TextBlock>
            <TextBlock x:Name="lblEntfernung" HorizontalAlignment="Left" Height="40" Margin="8,59,0,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" Width="196"/>
            <TextBlock x:Name="lblGeoeffnet" Height="40" Margin="208,59,8,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top"/>
        </Grid>
    </DataTemplate>
</ResourceDictionary>
</code>```

Then you must reference this external file in the page which wishes to use this file.

```<code><phone:PhoneApplicationPage.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="\ResourceDictionary.xaml"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</phone:PhoneApplicationPage.Resources>
</code>```

Body:
Howdy,
I would like to generate in my application several PivotItems in a pivotelement. The generation is proceeding fine, however I don't know how I can apply a template to those Pivot Elements.

I thought I would need to use:

pivotItem.ContentTemplate = (DataTemplate)Ressources["KantinenUebersicht"];

But that is only producing an empty page.

My code in the ressource file looks the following:

inserted my whole ressources File

<.ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

<DataTemplate x:Key="KantinenTemplate">
    <StackPanel VerticalAlignment="Top">
            <TextBlock HorizontalAlignment="Left" TextWrapping="Wrap" Text="{Binding name}" FontSize="{StaticResource PhoneFontSizeLarge}" Margin="8,0,0,0" VerticalAlignment="Top"/>
            <TextBlock HorizontalAlignment="Left" TextWrapping="Wrap" Text="{Binding entfernung}" Margin="24,0,0,0" FontSize="{StaticResource PhoneFontSizeSmall}" VerticalAlignment="Bottom"/>
    </StackPanel>
</DataTemplate>

<DataTemplate x:Key="KantinenUebersicht">
        <Grid>
            <TextBlock x:Name="KantinenName" FontSize="{StaticResource PhoneFontSizeExtraLarge}" Text="" RenderTransformOrigin="0.566,0.407" Margin="0,0,8,0" Height="55" VerticalAlignment="Top">
                        <TextBlock.Foreground>
                            <SolidColorBrush Color="{StaticResource PhoneAccentColor}"/>
                        </TextBlock.Foreground>
            </TextBlock>
            <TextBlock x:Name="sdfsdf" HorizontalAlignment="Left" Height="40" Margin="8,59,0,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" Width="196"/>
            <TextBlock x:Name="lblGeoefsdfsdffnet" Height="40" Margin="208,59,8,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top"/>
        </Grid>
    </DataTemplate></ResourceDictionary.>

Had to insert . in the first tags...

Body:
What you're trying to do is correct.

In your question you have an extra "S" in "Resources" which could be the issue.

If I take the code from your question, I can add it to the page:

<phone:PhoneApplicationPage.Resources>
    <DataTemplate x:Key="KantinenUebersicht">
        <Grid>
            <TextBlock x:Name="KantinenName" FontSize="{StaticResource PhoneFontSizeExtraLarge}" Text="" RenderTransformOrigin="0.566,0.407" Margin="0,0,8,0" Height="55" VerticalAlignment="Top">
                 <TextBlock.Foreground>
                  <SolidColorBrush Color="{StaticResource PhoneAccentColor}"/>
                 </TextBlock.Foreground>
            </TextBlock>
            <TextBlock x:Name="lblEntfernung" HorizontalAlignment="Left" Height="40" Margin="8,59,0,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" Width="196"/>
            <TextBlock x:Name="lblGeoeffnet" Height="40" Margin="208,59,8,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top"/>
        </Grid>
    </DataTemplate>
</phone:PhoneApplicationPage.Resources>

and then use it when creating a new item:

var newItem = new PivotItem { Header = "Added" };

newItem.ContentTemplate = (DataTemplate)Resources["KantinenUebersicht"];

MyPivot.Items.Add(newItem);

Works on my machine (emulator).

Update:

If you want to add the resource to a separate file you can do so like:

ResourceDictionary.xaml:

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" >
    <DataTemplate x:Key="KantinenUebersicht">
        <Grid>
            <TextBlock x:Name="KantinenName" FontSize="{StaticResource PhoneFontSizeExtraLarge}" Text="" RenderTransformOrigin="0.566,0.407" Margin="0,0,8,0" Height="55" VerticalAlignment="Top">
                     <TextBlock.Foreground>
                      <SolidColorBrush Color="{StaticResource PhoneAccentColor}"/>
                     </TextBlock.Foreground>
            </TextBlock>
            <TextBlock x:Name="lblEntfernung" HorizontalAlignment="Left" Height="40" Margin="8,59,0,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" Width="196"/>
            <TextBlock x:Name="lblGeoeffnet" Height="40" Margin="208,59,8,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top"/>
        </Grid>
    </DataTemplate>
</ResourceDictionary>

Then you must reference this external file in the page which wishes to use this file.

<phone:PhoneApplicationPage.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="\ResourceDictionary.xaml"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</phone:PhoneApplicationPage.Resources>


问:
SAPUI5: Setting Count Mode in Manifest
Is it possible to set the Count Mode in the Manifest for sap.ui.model.odata.v2.ODataModel, and what is the syntax? I see people claiming so ( oData model operation mode ), but it's not documented and my trial doesn't succeed.

Regards, Niels

答:
The default count mode (as with other settings) can be defined in

sap.ui5/models/<model name>/settings/<e.g. defaultCountMode> inside the application descriptor

```<code>"models": {
  "myOdataModel": {
    "dataSource": "...",
    "settings": {
      "defaultCountMode": "InlineRepeat"
    },
    "preload": true
  }
},
</code>```

which is also documented here.

settings: Object that is passed to the model constructor

Here is a working example using InlineRepeat --> https://embed.plnkr.co/wAlrHB/.

If we attach a requestSent-handler to the corresponding ODataModel, we can observe that requests are always sent with the URL parameter "... &$inlinecount=allpages" appended.

Title: SAPUI5: Setting Count Mode in Manifest

Body:
The default count mode (as with other settings) can be defined in

sap.ui5/models/<model name>/settings/<e.g. defaultCountMode> inside the application descriptor

"models": {
  "myOdataModel": {
    "dataSource": "...",
    "settings": {
      "defaultCountMode": "InlineRepeat"
    },
    "preload": true
  }
},

which is also documented here.

settings: Object that is passed to the model constructor

Here is a working example using InlineRepeat --> https://embed.plnkr.co/wAlrHB/.

If we attach a requestSent-handler to the corresponding ODataModel, we can observe that requests are always sent with the URL parameter "... &$inlinecount=allpages" appended.


问:
Make a div fill the height of the remaining screen space
I am working on a web application where I want the content to fill the height of the entire screen.

The page has a header, which contains a logo, and account information. This could be an arbitrary height. I want the content div to fill the rest of the page to the bottom.

I have a header div and a content div. At the moment I am using a table for the layout like so:

CSS and HTML

#page {
    height: 100%; width: 100%
}

#tdcontent {
    height: 100%;
}

#content {
    overflow: auto; /* or overflow: hidden; */
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table id="page">
    <tr>
        <td id="tdheader">
            <div id="header">...</div>
        </td>
    </tr>
    <tr>
        <td id="tdcontent">
            <div id="content">...</div>
        </td>
    </tr>
</table></code>```

The entire height of the page is filled, and no scrolling is required.

For anything inside the content div, setting top: 0; will put it right underneath the header. Sometimes the content will be a real table, with its height set to 100%. Putting header inside content will not allow this to work.

Is there a way to achieve the same effect without using the table?

Update:

Elements inside the content div will have heights set to percentages as well. So something at 100% inside the div will fill it to the bottom. As will two elements at 50%.

Update 2:

For instance, if the header takes up 20% of the screen's height, a table specified at 50% inside #content would take up 40% of the screen space. So far, wrapping the entire thing in a table is the only thing that works.

答:
CSS Grid Solution

Just defining the body with display:grid and the grid-template-rows using auto and the fr value property.

* {
  margin: 0;
  padding: 0;
}

html {
  height: 100%;
}

body {
  min-height: 100%;
  display: grid;
  grid-template-rows: auto 1fr auto;
}

header {
  padding: 1em;
  background: pink;
}

main {
  padding: 1em;
  background: lightblue;
}

footer {
  padding: 2em;
  background: lightgreen;
}

main:hover {
  height: 2000px;
  /* demos expansion of center element */
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header>HEADER</header>
<main>MAIN</main>
<footer>FOOTER</footer></code>```

A Complete Guide to Grids @ CSS-Tricks.com

OwnerDisplayName: Vincent

ContentLicense: CC BY-SA 4.0

Body:
I am working on a web application where I want the content to fill the height of the entire screen.

The page has a header, which contains a logo, and account information. This could be an arbitrary height. I want the content div to fill the rest of the page to the bottom.

I have a header div and a content div. At the moment I am using a table for the layout like so:

CSS and HTML

#page {
    height: 100%; width: 100%
}

#tdcontent {
    height: 100%;
}

#content {
    overflow: auto; /* or overflow: hidden; */
}

...

...

The entire height of the page is filled, and no scrolling is required.

For anything inside the content div, setting top: 0; will put it right underneath the header. Sometimes the content will be a real table, with its height set to 100%. Putting header inside content will not allow this to work.

Is there a way to achieve the same effect without using the table?

Update:

Elements inside the content div will have heights set to percentages as well. So something at 100% inside the div will fill it to the bottom. As will two elements at 50%.

Update 2:

For instance, if the header takes up 20% of the screen's height, a table specified at 50% inside #content would take up 40% of the screen space. So far, wrapping the entire thing in a table is the only thing that works.

LastEditorDisplayName: Vincent

Body:
CSS Grid Solution

Just defining the body with display:grid and the grid-template-rows using auto and the fr value property.

* {
  margin: 0;
  padding: 0;
}

html {
  height: 100%;
}

body {
  min-height: 100%;
  display: grid;
  grid-template-rows: auto 1fr auto;
}

header {
  padding: 1em;
  background: pink;
}

main {
  padding: 1em;
  background: lightblue;
}

footer {
  padding: 2em;
  background: lightgreen;
}

main:hover {
  height: 2000px;
  /* demos expansion of center element */
}

<header>HEADER</header>
<main>MAIN</main>
<footer>FOOTER</footer>

A Complete Guide to Grids @ CSS-Tricks.com


问:
trouble making an "if" statment with time.now on ruby on rails
I'm trying to display a message depending on the time of the day and I currently have this piece of code:

```<code><% if Time.now >= "7:00" and Time.now <= "14:00" %>
Good Morning <%= current_user.nome %>! <br>
<% else %>
Good Afternoon <%= current_user.nome %>!
<% end %>
</code>```

It's currently 14:30 and the page still displays Good Morning (username), when it should display Good Evening (username)

Is my code wrong?

How do I fix this?

答:
I would use helpers to store methods and keep views plain.

```<code>class ApplicationHelper
  def greeting
    "Good #{time_greeting} #{current_user.nome}"
  end

  def time_greeting
    return "Morning" if Time.now.hour.between?(7, 13)
    "Afternoon"
  end
end
</code>```

Then you may only use greeting method in your views:

```<code><%= greeting %>
</code>```

Body:
I'm trying to display a message depending on the time of the day and I currently have this piece of code:

<% if Time.now >= "7:00" and Time.now <= "14:00" %>
Good Morning <%= current_user.nome %>!

<% else %>
Good Afternoon <%= current_user.nome %>!
<% end %>

It's currently 14:30 and the page still displays Good Morning (username), when it should display Good Evening (username)

Is my code wrong?

How do I fix this?

Body:
I would use helpers to store methods and keep views plain.

class ApplicationHelper
  def greeting
    "Good #{time_greeting} #{current_user.nome}"
  end

  def time_greeting
    return "Morning" if Time.now.hour.between?(7, 13)
    "Afternoon"
  end
end

Then you may only use greeting method in your views:

<%= greeting %>


问:
Include or Remove decimal part in SSRS field
I have a numeric field in SSRS report. Currently, the properties of this field are set to show 2 decimal places.

I need to make a change to remove decimal points if the value is a whole number.

Ex: if the number is 12.31, the output on SSRS field should be 12.31

If the number is 12.00, the output on SSRS field should be 12

Can anyone please help how this can be done? Expressions or Field properties?

答:
You can use a SWITCH function on your data to get it into the preferred format.In the number section of the properties of your textbox (tablix cell etc)

```<code>=switch( {your field}.value mod 1 = 0 , 0,
         {your field}.value mod 1 <> 0, 0.00)
</code>```

Body:
You can use a SWITCH function on your data to get it into the preferred format.In the number section of the properties of your textbox (tablix cell etc)

=switch( {your field}.value mod 1 = 0 , 0,
         {your field}.value mod 1 <> 0, 0.00)


问:
Aggregate properties
I'm developing my own Fuseki endpoint from some DBpedia data.
I'm in doubt on how to aggregate properties related to a single resource.

SELECT ?name ?website ?abstract ?genre ?image
WHERE{
VALUES ?s {<http://dbpedia.org/resource/Attack_Attack!>}
  ?s  foaf:name ?name ;
      dbo:abstract ?abstract .
  OPTIONAL { ?s dbo:genre ?genre } .
  OPTIONAL { ?s dbp:website ?website } .
  OPTIONAL { ?s dbo:image ?image } .
  FILTER LANGMATCHES(LANG(?abstract ), "en")
}
```

SPARQL endpoint: http://dbpedia.org/sparql/

This query returns 2 matching results. They are different just for the dbo:genre value. There is a way I can query the knowledge base and retrieving a single result with a list of genres?

答:
Yes, the GROUP_CONCAT() function is what you want.</p>

```<code>SELECT ?name ?website ?abstract (GROUP_CONCAT(?genre,',') AS ?genres) ?image
WHERE{
  <http://dbpedia.org/resource/Attack_Attack!> a dbo:Band ;
       foaf:name ?name;
      dbo:abstract ?abstract .
  OPTIONAL{   <http://dbpedia.org/resource/Attack_Attack!> dbo:genre ?genre } .
  OPTIONAL{   <http://dbpedia.org/resource/Attack_Attack!> dbp:website ?website} .
  OPTIONAL{   <http://dbpedia.org/resource/Attack_Attack!> dbo:image ?image} .
FILTER LANGMATCHES(LANG(?abstract ), "en")

}
</code>```

Title: Aggregate properties

Body:
I'm developing my own Fuseki endpoint from some DBpedia data.
I'm in doubt on how to aggregate properties related to a single resource.

SELECT ?name ?website ?abstract ?genre ?image
WHERE{
VALUES ?s {<http://dbpedia.org/resource/Attack_Attack!>}
  ?s  foaf:name ?name ;
      dbo:abstract ?abstract .
  OPTIONAL { ?s dbo:genre ?genre } .
  OPTIONAL { ?s dbp:website ?website } .
  OPTIONAL { ?s dbo:image ?image } .
  FILTER LANGMATCHES(LANG(?abstract ), "en")
}

SPARQL endpoint: http://dbpedia.org/sparql/

This query returns 2 matching results. They are different just for the dbo:genre value. There is a way I can query the knowledge base and retrieving a single result with a list of genres?

Body:
Yes, the GROUP_CONCAT() function is what you want.

SELECT ?name ?website ?abstract (GROUP_CONCAT(?genre,',') AS ?genres) ?image
WHERE{
  <http://dbpedia.org/resource/Attack_Attack!> a dbo:Band ;
       foaf:name ?name;
      dbo:abstract ?abstract .
  OPTIONAL{   <http://dbpedia.org/resource/Attack_Attack!> dbo:genre ?genre } .
  OPTIONAL{   <http://dbpedia.org/resource/Attack_Attack!> dbp:website ?website} .
  OPTIONAL{   <http://dbpedia.org/resource/Attack_Attack!> dbo:image ?image} .
FILTER LANGMATCHES(LANG(?abstract ), "en")

}


问:
call data-id on ajax success response
Originally I have a "like button" that is working very smoothly, and it looked like this:

```<code><a href="javascript:void();" class="like" id="<?php echo $row['id']; ?>">Like <span><?php echo likes($row['id']); ?></span></a>
</code>```

Here is the Ajax code:

```<code><script>
    $(function(){
        $(".like").click(function(){

            var postid = $(this).attr("id");
              $.ajax({
                type:'POST',
                url:'addlike.php',
                data:'id='+postid,
                success:function(data){
                   if(data=="you already liked this post"){
                       alert(data);
                     }
                   else{
                      $('a#'+postid).html(data);
                      }
                }
            });

        });
    });

</script>
</code>```

If AJAX is successful, addlike.php will have two kinds of response, either alert "you already liked the post" if the user already liked it, or the updated number of likes. For example, if there are currently 10 likes, when the user clicked the button, $('a#'+postid).html(data) will change 10 to 11, because in this case the data will be the updated number of likes, and $('a#'+postid) selects the "like button" that is just being clicked.

For some reason, I have to use data-id instead of id for the html id of the button. For more detailed explanation, see here:Disable boostrap toggle collapse for one class and enable it for another

Now I have to call the element which has a data-id instead of id on ajax success response, how can I do it? I tried the following:

```<code>     $('a#data-id'+postid).html(data);
     $('.[data-id="postid"]').html(data);
     $('a[data-id='+postid']').html(data);
     $('a#'+"[data-id=postid"]).text(data);
</code>```

but none of them works. Thanks in advance.

答: Create a property data-id='' in your anchor tag like your id property. Then, it will work.</p>

Title: call data-id on ajax success response

Body:
Originally I have a "like button" that is working very smoothly, and it looked like this:

<a href="javascript:void();" class="like" id="<?php echo $row['id']; ?>">Like <?php echo likes($row['id']); ?>

Here is the Ajax code:

If AJAX is successful, addlike.php will have two kinds of response, either alert "you already liked the post" if the user already liked it, or the updated number of likes. For example, if there are currently 10 likes, when the user clicked the button, $('a#'+postid).html(data) will change 10 to 11, because in this case the data will be the updated number of likes, and $('a#'+postid) selects the "like button" that is just being clicked.

For some reason, I have to use data-id instead of id for the html id of the button. For more detailed explanation, see here:Disable boostrap toggle collapse for one class and enable it for another

Now I have to call the element which has a data-id instead of id on ajax success response, how can I do it? I tried the following:

     $('a#data-id'+postid).html(data);
     $('.[data-id="postid"]').html(data);
     $('a[data-id='+postid']').html(data);
     $('a#'+"[data-id=postid"]).text(data);

but none of them works. Thanks in advance.


问:
How to import a large SQL file in the server?
Unfortunately I have a SQL file more than 350 MB. I have to import this file on the server to connect the database with one of my clients website. How I can do this? If it was my PC, then I can easily do it by editing the php.ini file. But it's in the live server and the sql file upload limit is only 50 MB. What can I do? I have the cPanel and also the server access. Can anyone help me? Thanks in advance.</p>

答:
Assuming you have FTP access but don't have SSH command-line access, which is often the case with shared servers:

Upload the file via FTP

Write a PHP program to read through the file line by line and import it. If the file is CSV or similar data, you will need to parse and turn into SQL statements. If the file is SQL statements then you just process each one as a direct SQL command.

PHP is often set to a relatively short timeout to avoid runaway scripts. So you may want to add a set_time_limit() call inside your main loop so that it won't be aborted in the middle.

I also recommend using a counter in the loop to track lines processed. If you get a SQL error then report it (mysqli_error() or similar function) along with the line count. That way you can edit your file locally, find/fix the problem and upload only the unprocessed data to try again.


问:
mapbox ForEach function
When pulling in data from a geojson file that is stored online. The forEach function can not read the features I have set in the geojson file. Below is part of the code. </p>

```<code>map.on('load', function() {
            // Add a GeoJSON source containing place coordinates and information.
            map.addSource('orders', {
                type: 'geojson',
                data: ordersjson,
            });

            map.addLayer({
                        id: "layerID",
                        type: "symbol",
                        source: 'orders',
                        layout: {
                            "icon-image": "circle" + "-15",
                            "icon-allow-overlap": true,
                        },
                    });

            map.getLayer('layerID').features.forEach(function(feature) {
                var earthquakeID = feature.properties['primary ID']

            });
</code>```

答:
The layer itself does not have any data at all. What you need is to get the source that holds the data. The layer is just for style definitions.

What you want is something like this:

map.getSource('orders')._data.features.forEach(function(feature) {
  // do something
});```

Title: mapbox ForEach function

Body:
When pulling in data from a geojson file that is stored online. The forEach function can not read the features I have set in the geojson file. Below is part of the code.

map.on('load', function() {
            // Add a GeoJSON source containing place coordinates and information.
            map.addSource('orders', {
                type: 'geojson',
                data: ordersjson,
            });

            map.addLayer({
                        id: "layerID",
                        type: "symbol",
                        source: 'orders',
                        layout: {
                            "icon-image": "circle" + "-15",
                            "icon-allow-overlap": true,
                        },
                    });

            map.getLayer('layerID').features.forEach(function(feature) {
                var earthquakeID = feature.properties['primary ID']

            });


问:
How can I display a box by using the hover method in jQuery?
How can I display a box by using the hover method in jQuery?
I want to open my box by hovering the button like this one
example</p>

答:
If you really wanna use jQuery's hover function, there's a simple example below on how to show an element when hovering another. The idea is to add a class to the "box" when hovering the button, and then style that class in CSS. In this case, the box is hidden by default (visibility: hidden;), and when the class visible is added, the box will instead get the style visibility: visible;.

This however can be done with CSS only.

$("#button1").hover(function(){
    $('#box1').addClass('visible');
},function(){
    $('#box1').removeClass('visible');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#box1{
  margin-top: 20px;
  visibility: hidden;
  opacity:0;
  position:relative;
  top: -10px;
  background-color: #eee;
  padding: 5px;
  transition: visibility 0s, opacity 0.2s, top 0.2s;
}
#box1.visible{
  visibility: visible;
  opacity: 1;
  top:0;
}</code>```

Hover me

I'm a box
```

Body:
If you really wanna use jQuery's hover function, there's a simple example below on how to show an element when hovering another. The idea is to add a class to the "box" when hovering the button, and then style that class in CSS. In this case, the box is hidden by default (visibility: hidden;), and when the class visible is added, the box will instead get the style visibility: visible;.

This however can be done with CSS only.

$("#button1").hover(function(){
    $('#box1').addClass('visible');
},function(){
    $('#box1').removeClass('visible');
});

#box1{
  margin-top: 20px;
  visibility: hidden;
  opacity:0;
  position:relative;
  top: -10px;
  background-color: #eee;
  padding: 5px;
  transition: visibility 0s, opacity 0.2s, top 0.2s;
}
#box1.visible{
  visibility: visible;
  opacity: 1;
  top:0;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<a href="" id="button1">Hover me</a>
<div id="box1">I'm a box</div>


问:
Test for OpenSSL enabled fails
I am testing if openssl is enabled and returns keys. Though openssl is enabled it is not returing keys. When tried to install the TYPO3 the error message is appearing.

```<code>if (extension_loaded('openssl')) {
   $testKey = @openssl_pkey_new();
   if (is_resource($testKey)) {
   } else {
      echo ' Please check the integration of the PHP OpenSSL extension and if it is installed correctly.';
   }
}
</code>```

Please help to continue installation. Thanks

答: Most likely the openssl.cnf file is not correctly configured or cannot be found. Please also check the openssl manual.

Title: Test for OpenSSL enabled fails

Body:
I am testing if openssl is enabled and returns keys. Though openssl is enabled it is not returing keys. When tried to install the TYPO3 the error message is appearing.

if (extension_loaded('openssl')) {
   $testKey = @openssl_pkey_new();
   if (is_resource($testKey)) {
   } else {
      echo ' Please check the integration of the PHP OpenSSL extension and if it is installed correctly.';
   }
}

Please help to continue installation. Thanks


问:
superagent post vs put in react
```<code>var request = require('superagent');
var url = 'api/server';
request.put(url)
    .set('Content-Type', 'application/json')
    .send('{"name":"tj","pet":"tobi"}')
    .end(function(err, res){
        if (err) throw err;
        console.log(res.text);
    });
</code>```

above is the code that i use for upload data. If I change put into post, it's not working. I don't know why is that, can anyone help?

Also, actually I want to upload a file. But I cannot use put with .attach('theFile', file) . I've search a lot of example but none of them work for me.

答: Probably your server expects PUT and not POST methods on api/server url, check the server source or documentation.</p>

Title: superagent post vs put in react

Body:
var request = require('superagent');
var url = 'api/server';
request.put(url)
    .set('Content-Type', 'application/json')
    .send('{"name":"tj","pet":"tobi"}')
    .end(function(err, res){
        if (err) throw err;
        console.log(res.text);
    });

above is the code that i use for upload data. If I change put into post, it's not working. I don't know why is that, can anyone help?

Also, actually I want to upload a file. But I cannot use put with .attach('theFile', file) . I've search a lot of example but none of them work for me.


问:
Working with Maps in Facebook Flow
In the current React application that I'm building, I'm using Facebook Flow to check the JavaScript code I'm writing.

However, I'm a bit confused about the Objects as maps as described here.

I'm having the following dataset:

```<code>var dataSet : data = {
    translations: {
        TITLE: [
            "sdmk",
            "sdmflk",
            "sdmflk"
        ]
    }
}
</code>```

And the following 2 types:

```<code>type languageResource = {
    [key: string]: Array<string>;
};

type data = {
    +translations?: Array<languageResource>;
};
</code>```

When I try to access the translations dynamically using this code:

```<code>var t = dataSet.translations["TITLE"];
</code>```

Flow yields an error:

20: var t = dataSet.translations["TITLE"];
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ access of computed property/element. Element cannot be accessed with
   20: var t = dataSet.translations["TITLE"];
                                    ^^^^^^^ string

Any advice on what's wrong with this piece of code?

答:
You defined translations as Array, therefore the implementation of your object should reflect it

```<code>var dataSet : data = {
    translations: [
      {
         TITLE: [
            "sdmk",
            "sdmflk",
            "sdmflk"
         ]
      }
   ]
}
</code>```

Title: Working with Maps in Facebook Flow

Body:
In the current React application that I'm building, I'm using Facebook Flow to check the JavaScript code I'm writing.

However, I'm a bit confused about the Objects as maps as described here.

I'm having the following dataset:

var dataSet : data = {
    translations: {
        TITLE: [
            "sdmk",
            "sdmflk",
            "sdmflk"
        ]
    }
}

And the following 2 types:

type languageResource = {
    [key: string]: Array<string>;
};

type data = {
    +translations?: Array<languageResource>;
};

When I try to access the translations dynamically using this code:

var t = dataSet.translations["TITLE"];

Flow yields an error:

20: var t = dataSet.translations["TITLE"];
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ access of computed property/element. Element cannot be accessed with
   20: var t = dataSet.translations["TITLE"];
                                    ^^^^^^^ string

Any advice on what's wrong with this piece of code?

Body:
You defined translations as Array, therefore the implementation of your object should reflect it

var dataSet : data = {
    translations: [
      {
         TITLE: [
            "sdmk",
            "sdmflk",
            "sdmflk"
         ]
      }
   ]
}


问:
Type casting in bitwise operations confuses me in C
I'm trying to make a part of a ciphering encryption. I'm trying to cipher the data with the keystream I got.

The data is in form uint8_t and the keystream KS is uint32_t.

variable n is the length of the data (in 32 bit chunks obviously)

I have this code:

```<code>for (i=0; i<n; i++)
{
  wo_data[4*i+0] ^= (uint8_t)(KS[i] >> 24) & 0xff;
  wo_data[4*i+1] ^= (uint8_t)(KS[i] >> 16) & 0xff;
  wo_data[4*i+2] ^= (uint8_t)(KS[i] >>  8) & 0xff;
  wo_data[4*i+3] ^= (uint8_t)(KS[i]      ) & 0xff;
}
</code>```

But it doesn't work even close to expected.

Now if I type cast the data to 32-bit length:

```<code>uint32_t* data2 = (uint32_t *)wo_data;
for(i=0; i < n; i++)
{
  data2[i] ^= KS[i];
}
</code>```

It starts to work. Can someone explain me why? I would prefer to use the 8-bit length as it is easier to align the ending if the input data is not byte-aligned.

Data is initialized with following:

```<code>7EC61272 743BF161 4726446A 6C38CED1
66F6CA76 EB543004 4286346C EF130F92
</code>```

KS is initialized with following:

```<code>F22DB45B 37E71C5B 4EB6F404 CD886C15
9DCA27B1 F062AF46 F8E2F587 8976E8B8
</code>```

I'm expecting following (obviously):

```<code>8CEBA629 43DCED3A 0990B06E A1B0A2C4
FB3CEDC7 1B369F42 BA64C1EB 6665E72A
</code>```

答:
As @Arkku stated in the comments, it is an endianness issue.

For instance, if you are in a little-endian machine, K[0]=0xF22DB45B is stored in the following way:

```<code>@K+0: 5B
@K+1: B4
@K+2: 2D
@K+3: F2
</code>```

Hence, the least significant byte (LSB) of each KS word has to be XORed with wo_data[4*i+0], and so on.

This code gives the expected values:

```<code>for (int i=0; i < N; i++)
{
    wo_data[4*i+0] ^= ((KS[i]      ) & 0xff);
    wo_data[4*i+1] ^= ((KS[i] >>  8) & 0xff);
    wo_data[4*i+2] ^= ((KS[i] >> 16) & 0xff);
    wo_data[4*i+3] ^= ((KS[i] >> 24) & 0xff);
}
</code>```

The 32-bit version is probably faster since it processes more bytes per instruction. Moreover, it can be vectorized and executed in a more efficient way. See the generated assembly for the 8- and 32-bit versions. The 8-bit version can be used to process the remaining bytes, if any.

Body:
I'm trying to make a part of a ciphering encryption. I'm trying to cipher the data with the keystream I got.

The data is in form uint8_t and the keystream KS is uint32_t.

variable n is the length of the data (in 32 bit chunks obviously)

I have this code:

for (i=0; i<n; i++)
{
  wo_data[4*i+0] ^= (uint8_t)(KS[i] >> 24) & 0xff;
  wo_data[4*i+1] ^= (uint8_t)(KS[i] >> 16) & 0xff;
  wo_data[4*i+2] ^= (uint8_t)(KS[i] >>  8) & 0xff;
  wo_data[4*i+3] ^= (uint8_t)(KS[i]      ) & 0xff;
}

But it doesn't work even close to expected.

Now if I type cast the data to 32-bit length:

uint32_t* data2 = (uint32_t *)wo_data;
for(i=0; i < n; i++)
{
  data2[i] ^= KS[i];
}

It starts to work. Can someone explain me why? I would prefer to use the 8-bit length as it is easier to align the ending if the input data is not byte-aligned.

Data is initialized with following:

7EC61272 743BF161 4726446A 6C38CED1
66F6CA76 EB543004 4286346C EF130F92

KS is initialized with following:

F22DB45B 37E71C5B 4EB6F404 CD886C15
9DCA27B1 F062AF46 F8E2F587 8976E8B8

I'm expecting following (obviously):

8CEBA629 43DCED3A 0990B06E A1B0A2C4
FB3CEDC7 1B369F42 BA64C1EB 6665E72A

Body:
As @Arkku stated in the comments, it is an endianness issue.

For instance, if you are in a little-endian machine, K[0]=0xF22DB45B is stored in the following way:

@K+0: 5B
@K+1: B4
@K+2: 2D
@K+3: F2

Hence, the least significant byte (LSB) of each KS word has to be XORed with wo_data[4*i+0], and so on.

This code gives the expected values:

for (int i=0; i < N; i++)
{
    wo_data[4*i+0] ^= ((KS[i]      ) & 0xff);
    wo_data[4*i+1] ^= ((KS[i] >>  8) & 0xff);
    wo_data[4*i+2] ^= ((KS[i] >> 16) & 0xff);
    wo_data[4*i+3] ^= ((KS[i] >> 24) & 0xff);
}

The 32-bit version is probably faster since it processes more bytes per instruction. Moreover, it can be vectorized and executed in a more efficient way. See the generated assembly for the 8- and 32-bit versions. The 8-bit version can be used to process the remaining bytes, if any.


答:
Since post-id is a variable and can contain any characters, it's necessary to place it between quotes ("") or simple quotes (''). This requirement applies for every other attribute other than ID and CLASS, as stated in the docs

```<code>$("a[data-id='" + postid + "']").html(data);
</code>```

Title: call data-id on ajax success response

Body:
Since post-id is a variable and can contain any characters, it's necessary to place it between quotes ("") or simple quotes (''). This requirement applies for every other attribute other than ID and CLASS, as stated in the docs

$("a[data-id='" + postid + "']").html(data);


问:
Eclipse IDE for JavaScript Web Developers + Subclipse + JavaHL on Mac OS X 10.6
I want to use the Eclipse plugin Subclipse on Snow Leopard.
I installed Eclipse IDE for JavaScript Web Developers (Helios Service Release 1).

I should mention that the subversion server ist SSL protected, I have to use a personal certificate (p12 file).

I tell the system where to find the certificate file in

```<code>/Users/<USERNAME>/.subversion/servers
</code>```

with this lines:

```<code>[groups]
servername = 999.999.99.99
...
[servername]
ssl-client-cert-file = /Users/<USERNAME>/Desktop/<CERTIFICATE>
</code>```

Using SVN in the command line this works.

So my first try was to use the Subclipse plugin offered by subclipse.tigris.org within Eclipse's "Install new software" dialogue. This offers me the Subclipse 1.0.0.
It ended with this error in Eclipse's console view when trying to connect to the SVN repository:

```<code>svn: PROPFIND request failed on '/blahblahblahrepositorydirectory'
svn: Received fatal alert: handshake_failure
</code>```

I thought it might be a good idea to use a newer SVN version + JavaHL (Snow Leopard's preinstalled SVN is 1.0) but according to http://subclipse.tigris.org/wiki/JavaHL#head-5ccce53a67ca6c3965de863ae91e2642eab537de one needs at least SVN/JavaHL Version 1.4.x from openCollabNet. But 1.4.x is not available there for Mac OS X 10.6. You get only 1.6 there.
So I took the 1.6 and expected Ecipse's "Install new software" dialogue to offer me a newer version of Subclipse but it still offers the 1.0.0. And actually this combination doesn't work, still getting errors when trying to connect with SVN...

What can I do now?

答:
How did you get Subclipse to begin with that you would have the 1.0 version?  Current Subclipse is 1.6.x and has been out for nearly 2 years.

Just specify the update site URL for Subclipse 1.6.x and install it.  Or use the Eclipse Marketplace client to do so.

Body:
I want to use the Eclipse plugin Subclipse on Snow Leopard.
I installed Eclipse IDE for JavaScript Web Developers (Helios Service Release 1).

I should mention that the subversion server ist SSL protected, I have to use a personal certificate (p12 file).

I tell the system where to find the certificate file in

/Users/<USERNAME>/.subversion/servers

with this lines:

[groups]
servername = 999.999.99.99
...
[servername]
ssl-client-cert-file = /Users/<USERNAME>/Desktop/<CERTIFICATE>

Using SVN in the command line this works.

So my first try was to use the Subclipse plugin offered by subclipse.tigris.org within Eclipse's "Install new software" dialogue. This offers me the Subclipse 1.0.0.
It ended with this error in Eclipse's console view when trying to connect to the SVN repository:

svn: PROPFIND request failed on '/blahblahblahrepositorydirectory'
svn: Received fatal alert: handshake_failure

I thought it might be a good idea to use a newer SVN version + JavaHL (Snow Leopard's preinstalled SVN is 1.0) but according to http://subclipse.tigris.org/wiki/JavaHL#head-5ccce53a67ca6c3965de863ae91e2642eab537de one needs at least SVN/JavaHL Version 1.4.x from openCollabNet. But 1.4.x is not available there for Mac OS X 10.6. You get only 1.6 there.
So I took the 1.6 and expected Ecipse's "Install new software" dialogue to offer me a newer version of Subclipse but it still offers the 1.0.0. And actually this combination doesn't work, still getting errors when trying to connect with SVN...

What can I do now?


问:
Slack backend: is it possible to detect an edit?
Our errbot is providing links to JIRA tickets when it sees the right ticket patterns. Unfortunately, in slack it is common for users to edit their posts, and if both edits contain the JIRA ticket pattern, errbot provides the link twice, it is annoying.

Can I detect when a message is an edit as opposed to the original message?

答: Now you can because from the .extra argument on the messages you can get the message ID from slack.</p>


问:
What's a legit use case for a function call to be on left-hand side of assignment?
There's a compile error in VBA that reads as follows:

Compile error:

Function call on left-hand side of assignment must return Variant or Object.

To produce this compile error, you just need a function:

```<code>Public Function Foo(ByVal x As Integer) As Integer
    Foo = x
End Function
</code>```

..And then a function call on the left-hand side of an assignment - for example:

```<code>Public Sub Test()
    Foo(42) = 12
End Sub
</code>```

If I remove the As Integer return type from the function's signature, I get a function that returns an implicit Variant, and the compiler is satisfied - but now there's a run-time error 424 / "Object Required".

So I make the function return an actual object:

```<code>Public Function Foo(ByVal x As Integer) As Object
    Dim result As Collection
    Set result = New Collection
    result.Add x
    Set Foo = result
End Function

Public Sub Test()
    Foo(42) = 12
End Sub
</code>```

Now at run-time the error is 438 / "Object doesn't support this property or method" - obviously, that Test method makes no sense whatsoever.

I cannot for the life of me think of anything that would be a valid, legitimate (and warranted?) use of a function call on the LHS of an assignment.

That compile error exists for a reason, so there must be a valid use case. What is it?

答:
If the function were to return a Variant, and that Variant contains an Object (i.e. the Variant type is VT_DISPATCH), and that object has a default "property put", then the assignment is valid, and the assignment is set to that default property.

In all other cases, it isn't.

Body:
There's a compile error in VBA that reads as follows:

Compile error:

Function call on left-hand side of assignment must return Variant or Object.

To produce this compile error, you just need a function:

Public Function Foo(ByVal x As Integer) As Integer
    Foo = x
End Function

..And then a function call on the left-hand side of an assignment - for example:

Public Sub Test()
    Foo(42) = 12
End Sub

If I remove the As Integer return type from the function's signature, I get a function that returns an implicit Variant, and the compiler is satisfied - but now there's a run-time error 424 / "Object Required".

So I make the function return an actual object:

Public Function Foo(ByVal x As Integer) As Object
    Dim result As Collection
    Set result = New Collection
    result.Add x
    Set Foo = result
End Function

Public Sub Test()
    Foo(42) = 12
End Sub

Now at run-time the error is 438 / "Object doesn't support this property or method" - obviously, that Test method makes no sense whatsoever.

I cannot for the life of me think of anything that would be a valid, legitimate (and warranted?) use of a function call on the LHS of an assignment.

That compile error exists for a reason, so there must be a valid use case. What is it?


问:
how to get current location in google map android
Actually my problem is I am not getting current location latitude and longitude I tried so many ways.I know that this question already asked in SO I tried that answers also still I didn't get answer.Please help me
Code:</p>

```<code>    if (googleMap == null) {
        googleMap = ((MapFragment) getFragmentManager().findFragmentById(
                R.id.map)).getMap();

        // check if map is created successfully or not
        if (googleMap == null) {
            Toast.makeText(getApplicationContext(),
                    "Sorry! unable to create maps", Toast.LENGTH_SHORT)
                    .show();
        }
    }
    googleMap.setMyLocationEnabled(true);
    Location myLocation = googleMap.getMyLocation();  //Nullpointer exception.........
    LatLng myLatLng = new LatLng(myLocation.getLatitude(),
            myLocation.getLongitude());

    CameraPosition myPosition = new CameraPosition.Builder()
            .target(myLatLng).zoom(17).bearing(90).tilt(30).build();
    googleMap.animateCamera(
        CameraUpdateFactory.newCameraPosition(myPosition));
</code>```

答:
Why not to use FusedLocationApi instead of OnMyLocationChangeListener? You need to initialize GoogleApiClient object and use LocationServices.FusedLocationApi.requestLocationUpdates() method to register location change listener. It is important to note, that don't forget to remove the registered listener and disconnect GoogleApiClient.

```<code>private LocationRequest  mLocationRequest;
private GoogleApiClient  mGoogleApiClient;
private LocationListener mLocationListener;

private void initGoogleApiClient(Context context)
{
    mGoogleApiClient = new GoogleApiClient.Builder(context).addApi(LocationServices.API).addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks()
    {
        @Override
        public void onConnected(Bundle bundle)
        {
            mLocationRequest = LocationRequest.create();
            mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
            mLocationRequest.setInterval(1000);

            setLocationListener();
        }

        @Override
        public void onConnectionSuspended(int i)
        {
            Log.i("LOG_TAG", "onConnectionSuspended");
        }
    }).build();

    if (mGoogleApiClient != null)
        mGoogleApiClient.connect();

}

private void setLocationListener()
{
    mLocationListener = new LocationListener()
    {
        @Override
        public void onLocationChanged(Location location)
        {
            String lat = String.valueOf(location.getLatitude());
            String lon = String.valueOf(location.getLongitude());
            Log.i("LOG_TAG", "Latitude = " + lat + " Longitude = " + lon);
        }
    };

    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, mLocationListener);
}

private void removeLocationListener()
{
    LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, mLocationListener);
}
</code>```

Body:
Actually my problem is I am not getting current location latitude and longitude I tried so many ways.I know that this question already asked in SO I tried that answers also still I didn't get answer.Please help me
Code:

    if (googleMap == null) {
        googleMap = ((MapFragment) getFragmentManager().findFragmentById(
                R.id.map)).getMap();

        // check if map is created successfully or not
        if (googleMap == null) {
            Toast.makeText(getApplicationContext(),
                    "Sorry! unable to create maps", Toast.LENGTH_SHORT)
                    .show();
        }
    }
    googleMap.setMyLocationEnabled(true);
    Location myLocation = googleMap.getMyLocation();  //Nullpointer exception.........
    LatLng myLatLng = new LatLng(myLocation.getLatitude(),
            myLocation.getLongitude());

    CameraPosition myPosition = new CameraPosition.Builder()
            .target(myLatLng).zoom(17).bearing(90).tilt(30).build();
    googleMap.animateCamera(
        CameraUpdateFactory.newCameraPosition(myPosition));

Body:
Why not to use FusedLocationApi instead of OnMyLocationChangeListener? You need to initialize GoogleApiClient object and use LocationServices.FusedLocationApi.requestLocationUpdates() method to register location change listener. It is important to note, that don't forget to remove the registered listener and disconnect GoogleApiClient.

private LocationRequest  mLocationRequest;
private GoogleApiClient  mGoogleApiClient;
private LocationListener mLocationListener;

private void initGoogleApiClient(Context context)
{
    mGoogleApiClient = new GoogleApiClient.Builder(context).addApi(LocationServices.API).addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks()
    {
        @Override
        public void onConnected(Bundle bundle)
        {
            mLocationRequest = LocationRequest.create();
            mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
            mLocationRequest.setInterval(1000);

            setLocationListener();
        }

        @Override
        public void onConnectionSuspended(int i)
        {
            Log.i("LOG_TAG", "onConnectionSuspended");
        }
    }).build();

    if (mGoogleApiClient != null)
        mGoogleApiClient.connect();

}

private void setLocationListener()
{
    mLocationListener = new LocationListener()
    {
        @Override
        public void onLocationChanged(Location location)
        {
            String lat = String.valueOf(location.getLatitude());
            String lon = String.valueOf(location.getLongitude());
            Log.i("LOG_TAG", "Latitude = " + lat + " Longitude = " + lon);
        }
    };

    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, mLocationListener);
}

private void removeLocationListener()
{
    LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, mLocationListener);
}


问:
Custom seeder in laravel 5.4
how can we make custom seeder in Laravel which can read the folder name and put into a specific column in database and the sub folder's name in the next column and finally the file name in the last?

答: check the documentation here https://laravel.com/docs/5.4/seeding#writing-seeders.</p>

Title: Custom seeder in laravel 5.4


问:
Cannot instantiate class: org.apache.qpid.jndi.PropertiesFileInitialContextFactory
I am writing a Qpid client that sends a message. The example code that I am using is :

```<code>private void runTest() throws Exception {
  Properties properties = new Properties();
  properties.load(this.getClass().getResourceAsStream("helloworld.properties"));
  Context context = new InitialContext(properties);

  ConnectionFactory connectionFactory = (ConnectionFactory) context.lookup("qpidConnectionFactory");
  Connection connection = connectionFactory.createConnection();
  connection.start();

  Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
  Queue queue = (Queue) context.lookup("myqueue");

  MessageConsumer messageConsumer = session.createConsumer(queue);
  MessageProducer messageProducer = session.createProducer(queue);

  TextMessage message = session.createTextMessage("Hello world!");
  messageProducer.send(message);
  session.commit();

  message = (TextMessage)messageConsumer.receive();
  session.commit();
  System.out.println(message.getText());

  connection.close();
  context.close();
}
</code>```

The accompanying config is :

```<code>java.naming.factory.initial = org.apache.qpid.jndi.PropertiesFileInitialContextFactory
connectionfactory.qpidConnectionFactory = amqp://guest:guest@clientid/?brokerlist='tcp://localhost:61111'
queue.myqueue = queue1
</code>```

The ERROR that I am getting is :

```<code>Exception in thread "main" javax.naming.NoInitialContextException: Cannot instantiate class: org.apache.qpid.jndi.PropertiesFileInitialContextFactory [Root exception is java.lang.ClassNotFoundException: org.apache.qpid.jndi.PropertiesFileInitialContextFactory]
    at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:674)
    at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:313)
    at javax.naming.InitialContext.init(InitialContext.java:244)
    at javax.naming.InitialContext.<init>(InitialContext.java:216)
    at Hello.runTest(Hello.java:19)
    at Hello.main(Hello.java:13)
Caused by: java.lang.ClassNotFoundException: org.apache.qpid.jndi.PropertiesFileInitialContextFactory
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:348)
    at com.sun.naming.internal.VersionHelper12.loadClass(VersionHelper12.java:72)
    at com.sun.naming.internal.VersionHelper12.loadClass(VersionHelper12.java:61)
    at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:672)
    ... 5 more
</code>```

Looks like it is unable to initialize the context for the Properties file.

I have an ActiveMQ instance running locally on port 61111. The Properties file is indeed in my CLASSPATH. What else could I be missing here ?

答: Try java.naming.factory.initial = org.apache.qpid.jms.jndi.JmsInitialContextFactory

Body:
I am writing a Qpid client that sends a message. The example code that I am using is :

private void runTest() throws Exception {
  Properties properties = new Properties();
  properties.load(this.getClass().getResourceAsStream("helloworld.properties"));
  Context context = new InitialContext(properties);

  ConnectionFactory connectionFactory = (ConnectionFactory) context.lookup("qpidConnectionFactory");
  Connection connection = connectionFactory.createConnection();
  connection.start();

  Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
  Queue queue = (Queue) context.lookup("myqueue");

  MessageConsumer messageConsumer = session.createConsumer(queue);
  MessageProducer messageProducer = session.createProducer(queue);

  TextMessage message = session.createTextMessage("Hello world!");
  messageProducer.send(message);
  session.commit();

  message = (TextMessage)messageConsumer.receive();
  session.commit();
  System.out.println(message.getText());

  connection.close();
  context.close();
}

The accompanying config is :

java.naming.factory.initial = org.apache.qpid.jndi.PropertiesFileInitialContextFactory
connectionfactory.qpidConnectionFactory = amqp://guest:guest@clientid/?brokerlist='tcp://localhost:61111'
queue.myqueue = queue1

The ERROR that I am getting is :

Exception in thread "main" javax.naming.NoInitialContextException: Cannot instantiate class: org.apache.qpid.jndi.PropertiesFileInitialContextFactory [Root exception is java.lang.ClassNotFoundException: org.apache.qpid.jndi.PropertiesFileInitialContextFactory]
    at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:674)
    at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:313)
    at javax.naming.InitialContext.init(InitialContext.java:244)
    at javax.naming.InitialContext.<init>(InitialContext.java:216)
    at Hello.runTest(Hello.java:19)
    at Hello.main(Hello.java:13)
Caused by: java.lang.ClassNotFoundException: org.apache.qpid.jndi.PropertiesFileInitialContextFactory
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:348)
    at com.sun.naming.internal.VersionHelper12.loadClass(VersionHelper12.java:72)
    at com.sun.naming.internal.VersionHelper12.loadClass(VersionHelper12.java:61)
    at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:672)
    ... 5 more

Looks like it is unable to initialize the context for the Properties file.

I have an ActiveMQ instance running locally on port 61111. The Properties file is indeed in my CLASSPATH. What else could I be missing here ?


问:
Spring Integration - How to implement an asynchronous TCP Socket requests/responses over the same connection?
I have a Python TCP Socket server service which:

Allows only one client connection at time;

Its inputstream/outputstream operates independently.

On the other side, I have a Java Spring Boot client application using Spring Integration. My actual TCP Socket configurator
implementation uses:

```<code>@MessagingGateway(defaultRequestChannel = REQUEST_CHANNEL, errorChannel = ERROR_CHANNEL)
public interface ClientGtw {
    Future<Response> send(Request request);
}

@Bean
@ServiceActivator(inputChannel = REQUEST_CHANNEL)
public MessageHandler outboundGateway(TcpNioClientConnectionFactory connectionFactory) {
    TcpOutboundGateway gateway = new TcpOutboundGateway();
    gateway.setConnectionFactory(connectionFactory);
    gateway.setRequestTimeout(TimeUnit.SECONDS.toMillis(timeout));
    gateway.setRemoteTimeout(TimeUnit.SECONDS.toMillis(timeout));
    return gateway;
}

@Bean
public TcpNioClientConnectionFactory clientConnectionFactory(AppConfig config) {
    Host host = getHost(config);

    TcpNioClientConnectionFactory factory = new TcpNioClientConnectionFactory(host.name, host.port);
    factory.setSingleUse(false);
    factory.setSoTimeout((int) TimeUnit.SECONDS.toMillis(timeout));

    SerializerDeserializer sd = new SerializerDeserializer();
    factory.setDeserializer(sd);
    factory.setSerializer(sd);
    return factory;
}
</code>```

This actual approach works fine, however, when a request is sent it hangs the connection until a response is received. This is a problem due the fact that some times a request can get too much time to receive a response and the system has other requests incomming whose response can be achieved faster. I would like to send and receive as much as possible requests and responses independetly (decoupled between them). The object transported (serialized and deserialized) contains a key pair that can do the correct correlation.

TL;DR: How to implement an Asynchronous requests/responses over the same connection?

The Spring TcpOutboundGateway javadoc mentions: Use a pair of outbound/inbound adapters for that use case.

So, in addition to the declaration above:

1st Attempt

```<code>@Bean
public TcpInboundGateway inboundGateway(AbstractServerConnectionFactory connectionFactory) {
    TcpInboundGateway gateway = new TcpInboundGateway();
    gateway.setConnectionFactory(connectionFactory);
    gateway.setRequestTimeout(TimeUnit.SECONDS.toMillis(timeout));
    return gateway;
}

@Bean
public AbstractServerConnectionFactory serverFactory(AppConfig config) {
    Host host = getHost(config);
    AbstractServerConnectionFactory connectionFactory = new TcpNetServerConnectionFactory(host.port);
    connectionFactory.setSingleUse(true);
    connectionFactory.setSoTimeout(timeout);
    return connectionFactory;
}
</code>```

The requests are blocked until a response is delivered as before.

2nd Attempt

```<code>@Bean
public TcpInboundGateway inboundGateway(TcpNioClientConnectionFactory connectionFactory) {
    TcpInboundGateway gateway = new TcpInboundGateway();
    gateway.setConnectionFactory(connectionFactory);
    gateway.setRequestTimeout(TimeUnit.SECONDS.toMillis(timeout));
    gateway.setClientMode(true);
    return gateway;
}
</code>```

org.springframework.integration.ip.tcp.connection.TcpNioClientConnectionFactory may only be used by one inbound adapter

Any clue?

答:
Gary, thanks for your guidance.

To solve this issue is important to first understand Messaging Channel types.

So, in the configurer class:

```<code>@Bean(name = REQUEST_CHANNEL)
public DirectChannel sender() {
    return new DirectChannel();
}

@Bean(name = RESPONSE_CHANNEL)
public PollableChannel receiver() {
    return new QueueChannel();
}

@Bean
@ServiceActivator(inputChannel = REQUEST_CHANNEL)
public TcpSendingMessageHandler outboundClient(TcpNioClientConnectionFactory connectionFactory) {
    TcpSendingMessageHandler outbound = new TcpSendingMessageHandler();
    outbound.setConnectionFactory(connectionFactory);
    outbound.setRetryInterval(TimeUnit.SECONDS.toMillis(timeout));
    outbound.setClientMode(true);
    return outbound;
}

@Bean
public TcpReceivingChannelAdapter inboundClient(TcpNioClientConnectionFactory connectionFactory) {
    TcpReceivingChannelAdapter inbound = new TcpReceivingChannelAdapter();
    inbound.setConnectionFactory(connectionFactory);
    inbound.setRetryInterval(TimeUnit.SECONDS.toMillis(timeout));
    inbound.setOutputChannel(receiver());
    inbound.setClientMode(true);
    return inbound;
}
</code>```

This scratch @Singleton class illustrates how to operate the requests and responses (considering that requests and responses contains a UID to correlate them):

```<code>@Autowired
private DirectChannel sender;

@Autowired
private PollableChannel receiver;

private BlockingQueue<Request> requestPool = new LinkedBlockingQueue<>();

private Map<String, Response> responsePool = Collections.synchronizedMap(new HashMap<>());

@PostConstruct
private void init() {
    new Receiver().start();
    new Sender().start();
}

/*
 * It can be called as many as necessary without hanging for a response
 */
public void send(Request req) {
    requestPool.add(req);
}

/*
 * Check for a response until a socket timout
 */
public Response receive(String key) {
    Response res = responsePool.get(key);
    if (res != null) {
        responsePool.remove(key);
    }
    return res;
}

private class Receiver extends Thread {
    @Override
    public void run() {
        while (true) {
            try {
                tcpReceive();
                Thread.sleep(250);
            } catch (InterruptedException e) { }
        }
    }
    private void tcpReceive() {
        Response res = (Message<Response>) receiver.receive();
        if (res != null) {
            responsePool.put(res.getUID(), res);
        }
    }
}

private class Sender extends Thread {
    @Override
    public void run() {
        while (true) {
            try {
                tcpSend();
                Thread.sleep(250);
            } catch (InterruptedException e) { }
        }
    }
    private void tcpSend() {
        Request req = requestPool.poll(125, TimeUnit.MILLISECONDS);
        if (req != null) {
            sender.send(MessageBuilder.withPayload(req).build());
        }
    }
}
</code>```

UPDATED

I forgot to mention this:

```<code>@Bean
public TcpNioClientConnectionFactory clientConnectionFactory(Config config) {
    // Get host properties
    Host host = getHost(config);
    // Create socket factory
    TcpNioClientConnectionFactory factory = new TcpNioClientConnectionFactory(host.name, host.port);
    factory.setSingleUse(false); // IMPORTANT FOR SINGLE CHANNEL
    factory.setSoTimeout((int) TimeUnit.SECONDS.toMillis(timeout));
    return factory;
}
</code>```

Feel free to make any considerations.

Body:
I have a Python TCP Socket server service which:

Allows only one client connection at time;

Its inputstream/outputstream operates independently.

On the other side, I have a Java Spring Boot client application using Spring Integration. My actual TCP Socket configurator
implementation uses:

@MessagingGateway(defaultRequestChannel = REQUEST_CHANNEL, errorChannel = ERROR_CHANNEL)
public interface ClientGtw {
    Future<Response> send(Request request);
}

@Bean
@ServiceActivator(inputChannel = REQUEST_CHANNEL)
public MessageHandler outboundGateway(TcpNioClientConnectionFactory connectionFactory) {
    TcpOutboundGateway gateway = new TcpOutboundGateway();
    gateway.setConnectionFactory(connectionFactory);
    gateway.setRequestTimeout(TimeUnit.SECONDS.toMillis(timeout));
    gateway.setRemoteTimeout(TimeUnit.SECONDS.toMillis(timeout));
    return gateway;
}

@Bean
public TcpNioClientConnectionFactory clientConnectionFactory(AppConfig config) {
    Host host = getHost(config);

    TcpNioClientConnectionFactory factory = new TcpNioClientConnectionFactory(host.name, host.port);
    factory.setSingleUse(false);
    factory.setSoTimeout((int) TimeUnit.SECONDS.toMillis(timeout));

    SerializerDeserializer sd = new SerializerDeserializer();
    factory.setDeserializer(sd);
    factory.setSerializer(sd);
    return factory;
}

This actual approach works fine, however, when a request is sent it hangs the connection until a response is received. This is a problem due the fact that some times a request can get too much time to receive a response and the system has other requests incomming whose response can be achieved faster. I would like to send and receive as much as possible requests and responses independetly (decoupled between them). The object transported (serialized and deserialized) contains a key pair that can do the correct correlation.

TL;DR: How to implement an Asynchronous requests/responses over the same connection?

The Spring TcpOutboundGateway javadoc mentions: Use a pair of outbound/inbound adapters for that use case.

So, in addition to the declaration above:

1st Attempt

@Bean
public TcpInboundGateway inboundGateway(AbstractServerConnectionFactory connectionFactory) {
    TcpInboundGateway gateway = new TcpInboundGateway();
    gateway.setConnectionFactory(connectionFactory);
    gateway.setRequestTimeout(TimeUnit.SECONDS.toMillis(timeout));
    return gateway;
}

@Bean
public AbstractServerConnectionFactory serverFactory(AppConfig config) {
    Host host = getHost(config);
    AbstractServerConnectionFactory connectionFactory = new TcpNetServerConnectionFactory(host.port);
    connectionFactory.setSingleUse(true);
    connectionFactory.setSoTimeout(timeout);
    return connectionFactory;
}

The requests are blocked until a response is delivered as before.

2nd Attempt

@Bean
public TcpInboundGateway inboundGateway(TcpNioClientConnectionFactory connectionFactory) {
    TcpInboundGateway gateway = new TcpInboundGateway();
    gateway.setConnectionFactory(connectionFactory);
    gateway.setRequestTimeout(TimeUnit.SECONDS.toMillis(timeout));
    gateway.setClientMode(true);
    return gateway;
}

org.springframework.integration.ip.tcp.connection.TcpNioClientConnectionFactory may only be used by one inbound adapter

Any clue?

Body:
Gary, thanks for your guidance.

To solve this issue is important to first understand Messaging Channel types.

So, in the configurer class:

@Bean(name = REQUEST_CHANNEL)
public DirectChannel sender() {
    return new DirectChannel();
}

@Bean(name = RESPONSE_CHANNEL)
public PollableChannel receiver() {
    return new QueueChannel();
}

@Bean
@ServiceActivator(inputChannel = REQUEST_CHANNEL)
public TcpSendingMessageHandler outboundClient(TcpNioClientConnectionFactory connectionFactory) {
    TcpSendingMessageHandler outbound = new TcpSendingMessageHandler();
    outbound.setConnectionFactory(connectionFactory);
    outbound.setRetryInterval(TimeUnit.SECONDS.toMillis(timeout));
    outbound.setClientMode(true);
    return outbound;
}

@Bean
public TcpReceivingChannelAdapter inboundClient(TcpNioClientConnectionFactory connectionFactory) {
    TcpReceivingChannelAdapter inbound = new TcpReceivingChannelAdapter();
    inbound.setConnectionFactory(connectionFactory);
    inbound.setRetryInterval(TimeUnit.SECONDS.toMillis(timeout));
    inbound.setOutputChannel(receiver());
    inbound.setClientMode(true);
    return inbound;
}

This scratch @Singleton class illustrates how to operate the requests and responses (considering that requests and responses contains a UID to correlate them):

@Autowired
private DirectChannel sender;

@Autowired
private PollableChannel receiver;

private BlockingQueue<Request> requestPool = new LinkedBlockingQueue<>();

private Map<String, Response> responsePool = Collections.synchronizedMap(new HashMap<>());

@PostConstruct
private void init() {
    new Receiver().start();
    new Sender().start();
}

/*
 * It can be called as many as necessary without hanging for a response
 */
public void send(Request req) {
    requestPool.add(req);
}

/*
 * Check for a response until a socket timout
 */
public Response receive(String key) {
    Response res = responsePool.get(key);
    if (res != null) {
        responsePool.remove(key);
    }
    return res;
}

private class Receiver extends Thread {
    @Override
    public void run() {
        while (true) {
            try {
                tcpReceive();
                Thread.sleep(250);
            } catch (InterruptedException e) { }
        }
    }
    private void tcpReceive() {
        Response res = (Message<Response>) receiver.receive();
        if (res != null) {
            responsePool.put(res.getUID(), res);
        }
    }
}

private class Sender extends Thread {
    @Override
    public void run() {
        while (true) {
            try {
                tcpSend();
                Thread.sleep(250);
            } catch (InterruptedException e) { }
        }
    }
    private void tcpSend() {
        Request req = requestPool.poll(125, TimeUnit.MILLISECONDS);
        if (req != null) {
            sender.send(MessageBuilder.withPayload(req).build());
        }
    }
}

UPDATED

I forgot to mention this:

@Bean
public TcpNioClientConnectionFactory clientConnectionFactory(Config config) {
    // Get host properties
    Host host = getHost(config);
    // Create socket factory
    TcpNioClientConnectionFactory factory = new TcpNioClientConnectionFactory(host.name, host.port);
    factory.setSingleUse(false); // IMPORTANT FOR SINGLE CHANNEL
    factory.setSoTimeout((int) TimeUnit.SECONDS.toMillis(timeout));
    return factory;
}

Feel free to make any considerations.


问:
Remove Bottom border for tabed view react native
How to remove the border from tabed view for react native

答:
Try setting the borderBottomWidth property to 0</p>

```<code>indicatorStyle: { backgroundColor: '#fff', borderBottomWidth: 0 }
</code>```

Body:
Try setting the borderBottomWidth property to 0

indicatorStyle: { backgroundColor: '#fff', borderBottomWidth: 0 }