问:
Python- Remove all words that contain other words in a list
I have a list populated with words from a dictionary.  I want to find a way to remove all words, only considering root words that form at the beginning of the target word.

For example, the word "rodeo" would be removed from the list because it contains the English-valid word "rode."  "Typewriter" would be removed because it contains the English-valid word "type."  However, the word "snicker" is still valid even if it contains the word "nick" because "nick" is in the middle and not at the beginning of the word.

I was thinking something like this:

```<code> for line in wordlist:
        if line.find(...) --
</code>```

but I want that "if" statement to then run through every single word in the list checking to see if its found and, if so, remove itself from the list so that only root words remain.  Do I have to create a copy of wordlist to traverse?

答:
I'm assuming that you only have one list from which you want to remove any elements that have prefixes in that same list.

```<code>#Important assumption here... wordlist is sorted

base=wordlist[0]                      #consider the first word in the list
for word in wordlist:                 #loop through the entire list checking if
    if not word.startswith(base):     # the word we're considering starts with the base
        print base                    #If not... we have a new base, print the current
        base=word                     #  one and move to this new one
    #else word starts with base
        #don't output word, and go on to the next item in the list
print base                            #finish by printing the last base
</code>```

EDIT: Added some comments to make the logic more obvious

Body:
I have a list populated with words from a dictionary.  I want to find a way to remove all words, only considering root words that form at the beginning of the target word.

For example, the word "rodeo" would be removed from the list because it contains the English-valid word "rode."  "Typewriter" would be removed because it contains the English-valid word "type."  However, the word "snicker" is still valid even if it contains the word "nick" because "nick" is in the middle and not at the beginning of the word.

I was thinking something like this:

 for line in wordlist:
        if line.find(...) --

but I want that "if" statement to then run through every single word in the list checking to see if its found and, if so, remove itself from the list so that only root words remain.  Do I have to create a copy of wordlist to traverse?

Body:
I'm assuming that you only have one list from which you want to remove any elements that have prefixes in that same list.

#Important assumption here... wordlist is sorted

base=wordlist[0]                      #consider the first word in the list
for word in wordlist:                 #loop through the entire list checking if
    if not word.startswith(base):     # the word we're considering starts with the base
        print base                    #If not... we have a new base, print the current
        base=word                     #  one and move to this new one
    #else word starts with base
        #don't output word, and go on to the next item in the list
print base                            #finish by printing the last base

EDIT: Added some comments to make the logic more obvious


来源: stackexchange

问:
Debug output in T-SQL
When debugging T-SQL, is there something like Javascript's alert(); function or console.log I can use to output values when testing and debugging SQL scripts or stored procedures?

答:
I use the instruction "RAISERROR" with the hint "WITH NOWAIT" like below:

```<code>RAISERROR('My message here', 10, 1) WITH NOWAIT
</code>```

This instruction displays the message in time.

ContentLicense: CC BY-SA 3.0

Title: Debug output in T-SQL

Body:
I use the instruction "RAISERROR" with the hint "WITH NOWAIT" like below:

RAISERROR('My message here', 10, 1) WITH NOWAIT

This instruction displays the message in time.


问:
JUnit 5: How to assert an exception is thrown?
Is there a better way to assert that a method throws an exception in JUnit 5?

Currently, I have to use an @Rule in order to verify that my test throws an exception, but this doesn't work for the cases where I expect multiple methods to throw exceptions in my test.

答:
I think this is an even simpler example

List<String> emptyList = new ArrayList<>();
Optional<String> opt2 = emptyList.stream().findFirst();
assertThrows(NoSuchElementException.class, () -> opt2.get());
```

Calling get() on an optional containing an empty ArrayList will throw a NoSuchElementException.  assertThrows declares the expected exception and provides a lambda supplier (takes no arguments and returns a value).

Thanks to @prime for his answer which I hopefully elaborated on.

Body:
I think this is an even simpler example

List<String> emptyList = new ArrayList<>();
Optional<String> opt2 = emptyList.stream().findFirst();
assertThrows(NoSuchElementException.class, () -> opt2.get());

Calling get() on an optional containing an empty ArrayList will throw a NoSuchElementException.  assertThrows declares the expected exception and provides a lambda supplier (takes no arguments and returns a value).

Thanks to @prime for his answer which I hopefully elaborated on.


问:
Injector doesn't inject dll
Wrote a simple Dll injector for "calculator.exe" process, with printing out some lines I confirmed that the injector did its job but the messagebox doesn't appear.

Context:

-void inject_dll(DWORD, char*) takes the ID of the process that I want to inject and the name of the dll it will be injecting.

-DWORD get_PId(const w_char_t*) is a function that returns the processID of the given argument (processname)

I have confirmed that the get_PId function works properly, so the error should be somewhere else.

Injector code:

```<code>#include "stdafx.h"
#include <windows.h>
#include <TlHelp32.h>
#include <iostream>
void inject_dll(DWORD PId, char* DllName)
{

HANDLE hProcess;
PVOID Alloc;
SIZE_T DllPathLen;
HMODULE Kernel32Base;
PVOID LoadLibAddress;

if (PId != 0 && DllName != NULL)
{
    DllPathLen = strlen(DllName);
    Kernel32Base = GetModuleHandleA("Kernel32.dll");
    if (Kernel32Base == NULL)
    {
        std::cout << "kernel32.dll not found" << std::endl;
        return;
    }

    LoadLibAddress = GetProcAddress(Kernel32Base, "LoadLibraryA");
    if (LoadLibAddress == NULL)
    {
        std::cout << "LoadLibraryA not found" << std::endl;
        return;
    }

    hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, PId);
    if (hProcess == NULL)
    {
        std::cout << "hProcess handle not opened" << std::endl;
        return;
    }

    Alloc = VirtualAllocEx(hProcess, NULL, DllPathLen + 1, MEM_COMMIT, PAGE_READWRITE);
    if (Alloc == NULL)
    {
        std::cout << "no memory allocated for DllPath" << std::endl;
        return;
    }

    if (!WriteProcessMemory(hProcess, Alloc, DllName, DllPathLen + 1, NULL))
    {
        std::cout << "didn't write dll to processmemory" << std::endl;
        return;
    }

    CreateRemoteThread(hProcess, NULL, 0, (LPTHREAD_START_ROUTINE)LoadLibAddress, Alloc, 0, NULL);
    std::cout << "end reached" << std::endl;
}

}

DWORD get_PId( const wchar_t* ProcessName) {

HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);

PROCESSENTRY32 pe32;
pe32.dwSize = sizeof(PROCESSENTRY32);

if (hSnapshot != NULL)
{
    if (Process32First(hSnapshot, &pe32)) {
        do
        {
            if (!wcscmp(pe32.szExeFile, ProcessName))
                return pe32.th32ProcessID;

        } while (Process32Next(hSnapshot, &pe32));
    }
}
return 0;
}

int main(int argc, char* argv[])
{
DWORD pid = get_PId(L"Calculator.exe");
std::cout << pid << std::endl;
if (pid) {
    char dllName[] = "CORRECT PATH (dont worry about this)";
    std::cout << dllName << std::endl;
    inject_dll(pid, dllName);

}

ExitPoint:
    system("Pause");
    return 0;
}
</code>```

The Dll code, when its in the memory of the injected process it should show a messagebox:

```<code>#include <windows.h>

VOID ShowMessageBox() {
MessageBoxA(NULL, "injected", "injector", MB_OK);
}

BOOL APIENTRY DllMain( HMODULE hModule, DWORD  ul_reason_for_call, LPVOID lpReserved ){

switch (ul_reason_for_call)
{
    case DLL_PROCESS_ATTACH:
        ShowMessageBox();

    case DLL_THREAD_ATTACH:
    case DLL_THREAD_DETACH:
    case DLL_PROCESS_DETACH:
        break;
}
return TRUE;
}
</code>```

答: I suspect you are running into one of the DllMain restrictions, you are not supposed to call anything in user32.dll or gdi32.dll from DllMain.</p>

Title: Injector doesn't inject dll

Body:
Wrote a simple Dll injector for "calculator.exe" process, with printing out some lines I confirmed that the injector did its job but the messagebox doesn't appear.

Context:

-void inject_dll(DWORD, char*) takes the ID of the process that I want to inject and the name of the dll it will be injecting.

-DWORD get_PId(const w_char_t*) is a function that returns the processID of the given argument (processname)

I have confirmed that the get_PId function works properly, so the error should be somewhere else.

Injector code:

#include "stdafx.h"
#include <windows.h>
#include <TlHelp32.h>
#include <iostream>
void inject_dll(DWORD PId, char* DllName)
{

HANDLE hProcess;
PVOID Alloc;
SIZE_T DllPathLen;
HMODULE Kernel32Base;
PVOID LoadLibAddress;

if (PId != 0 && DllName != NULL)
{
    DllPathLen = strlen(DllName);
    Kernel32Base = GetModuleHandleA("Kernel32.dll");
    if (Kernel32Base == NULL)
    {
        std::cout << "kernel32.dll not found" << std::endl;
        return;
    }

    LoadLibAddress = GetProcAddress(Kernel32Base, "LoadLibraryA");
    if (LoadLibAddress == NULL)
    {
        std::cout << "LoadLibraryA not found" << std::endl;
        return;
    }

    hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, PId);
    if (hProcess == NULL)
    {
        std::cout << "hProcess handle not opened" << std::endl;
        return;
    }

    Alloc = VirtualAllocEx(hProcess, NULL, DllPathLen + 1, MEM_COMMIT, PAGE_READWRITE);
    if (Alloc == NULL)
    {
        std::cout << "no memory allocated for DllPath" << std::endl;
        return;
    }

    if (!WriteProcessMemory(hProcess, Alloc, DllName, DllPathLen + 1, NULL))
    {
        std::cout << "didn't write dll to processmemory" << std::endl;
        return;
    }

    CreateRemoteThread(hProcess, NULL, 0, (LPTHREAD_START_ROUTINE)LoadLibAddress, Alloc, 0, NULL);
    std::cout << "end reached" << std::endl;
}

}

DWORD get_PId( const wchar_t* ProcessName) {

HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);

PROCESSENTRY32 pe32;
pe32.dwSize = sizeof(PROCESSENTRY32);

if (hSnapshot != NULL)
{
    if (Process32First(hSnapshot, &pe32)) {
        do
        {
            if (!wcscmp(pe32.szExeFile, ProcessName))
                return pe32.th32ProcessID;

        } while (Process32Next(hSnapshot, &pe32));
    }
}
return 0;
}

int main(int argc, char* argv[])
{
DWORD pid = get_PId(L"Calculator.exe");
std::cout << pid << std::endl;
if (pid) {
    char dllName[] = "CORRECT PATH (dont worry about this)";
    std::cout << dllName << std::endl;
    inject_dll(pid, dllName);

}

ExitPoint:
    system("Pause");
    return 0;
}

The Dll code, when its in the memory of the injected process it should show a messagebox:

#include <windows.h>

VOID ShowMessageBox() {
MessageBoxA(NULL, "injected", "injector", MB_OK);
}

BOOL APIENTRY DllMain( HMODULE hModule, DWORD  ul_reason_for_call, LPVOID lpReserved ){

switch (ul_reason_for_call)
{
    case DLL_PROCESS_ATTACH:
        ShowMessageBox();

    case DLL_THREAD_ATTACH:
    case DLL_THREAD_DETACH:
    case DLL_PROCESS_DETACH:
        break;
}
return TRUE;
}


问:
Carrot2 dcs language
I've installed Carrot2 on a web application (PHP language). Everything works perfectly. Now i want to change the language of my results. I want to change english for french. I search on carrot2 documentation, on the web but i didn't find what i want (this link was usefull but it seems like the dcs folder had change since this post http://carrot2-users-and-developers-forum.607571.n2.nabble.com/Change-Language-in-DCS-REST-PHP-td639270.html). Anyway, i pass my paramaters (algo, query, source, etc.) with a simple form (and differents variables) and send them (PHP) to carrot2's method with curl.  I tried different (strange or barbaric) ways to send french language :

```<code>$language = 'lang_fr'; // or $language = 'FRENCH'
$num = (isset($_GET["maxResult"])) ? $_GET["maxResult"] : "10";
$query = urlencode($_GET["query"]);
$source = "web";
$algorithm = "lingo";
$hierarchy = "max-hierarchy-depth";
$level_hierarchie= $_GET["deep"] ? $_GET["deep"] : "1";

$processor = new Carrot2Processor();
$job = new Carrot2Job();
$job->setSource($source);
$job->setQuery($query);
$job->setAlgorithm($algorithm);
$job->setAttribute("results", $num);
$job->setAttribute($hierarchy, $level_hierarchie);
</code>```

i tried to set language like this in the setAttribute() funtion and of course it doesn't work.

```<code>$job->setAttribute("language", $language);

try {
    $result = $processor->cluster($job);
} catch (Carrot2Exception $e) {
    echo 'An error occurred during processing: ' . $e->getMessage();
    exit(10);
}
</code>```

I Also tried to change the CURLOPT_HTTPHEADER(add 'Accept-langugage: fr').
I see different responses but only for developpers using java and im using php. Is it possible to pass language choice with the setAttribute() method on PHP? Someone knows a way to do that?

Thank you in advance (i use carrot2-dcs-3.16)

答:
For the eTools meta search engine, you can set the EToolsDocumentSource.language attribute directly in your calling code:

$job->setAttribute("EToolsDocumentSource.language", "FRENCH");

See the attribute documentation linked above for the list of supported languages.

Title: Carrot2 dcs language

Body:
I've installed Carrot2 on a web application (PHP language). Everything works perfectly. Now i want to change the language of my results. I want to change english for french. I search on carrot2 documentation, on the web but i didn't find what i want (this link was usefull but it seems like the dcs folder had change since this post http://carrot2-users-and-developers-forum.607571.n2.nabble.com/Change-Language-in-DCS-REST-PHP-td639270.html). Anyway, i pass my paramaters (algo, query, source, etc.) with a simple form (and differents variables) and send them (PHP) to carrot2's method with curl.  I tried different (strange or barbaric) ways to send french language :

$language = 'lang_fr'; // or $language = 'FRENCH'
$num = (isset($_GET["maxResult"])) ? $_GET["maxResult"] : "10";
$query = urlencode($_GET["query"]);
$source = "web";
$algorithm = "lingo";
$hierarchy = "max-hierarchy-depth";
$level_hierarchie= $_GET["deep"] ? $_GET["deep"] : "1";

$processor = new Carrot2Processor();
$job = new Carrot2Job();
$job->setSource($source);
$job->setQuery($query);
$job->setAlgorithm($algorithm);
$job->setAttribute("results", $num);
$job->setAttribute($hierarchy, $level_hierarchie);

i tried to set language like this in the setAttribute() funtion and of course it doesn't work.

$job->setAttribute("language", $language);

try {
    $result = $processor->cluster($job);
} catch (Carrot2Exception $e) {
    echo 'An error occurred during processing: ' . $e->getMessage();
    exit(10);
}

I Also tried to change the CURLOPT_HTTPHEADER(add 'Accept-langugage: fr').
I see different responses but only for developpers using java and im using php. Is it possible to pass language choice with the setAttribute() method on PHP? Someone knows a way to do that?

Thank you in advance (i use carrot2-dcs-3.16)


问:
Unable to cast the type 'System.DateTime' to type 'System.Object' in LINQ to Entities
I have the following code:

```<code>public static IQueryable<T> ApplyOrdering<T>(this IQueryable<T> query, IQueryObject queryObject, Dictionary<string, Expression<Func<T, Object>>> columnsMap)
    {
        if (String.IsNullOrWhiteSpace(queryObject.SortBy) || !columnsMap.ContainsKey(queryObject.SortBy))
            return query;

        if (queryObject.IsSortAscending)
            return query.OrderBy(columnsMap[queryObject.SortBy]);
        else
            return query.OrderByDescending(columnsMap[queryObject.SortBy]);
    }
</code>```

But I get the following error if object in the dictionary is a date:

Unable to cast the type 'System.DateTime' to type 'System.Object'. LINQ to Entities only supports casting EDM primitive or enumeration types.

This the code for the columnsMap that I pass through to call the above extension method:

```<code>  var columnsMap = new Dictionary<string, Expression<Func<Post, Object>>>
  {
            ["createdDate"] = p => p.CreatedDate
  };

  query = query.ApplyOrdering(queryObject, columnsMap);
</code>```

How can I fix?

答:
I think that the problem is in Expression<Func<T, Object>>> columnsMap

DateTime isn't a class, is a struct so if your signature wait for an Object and you pass a primitive type, it throws the exception.

However, I don't know how to fix it, at this moment.

Body:
I have the following code:

public static IQueryable<T> ApplyOrdering<T>(this IQueryable<T> query, IQueryObject queryObject, Dictionary<string, Expression<Func<T, Object>>> columnsMap)
    {
        if (String.IsNullOrWhiteSpace(queryObject.SortBy) || !columnsMap.ContainsKey(queryObject.SortBy))
            return query;

        if (queryObject.IsSortAscending)
            return query.OrderBy(columnsMap[queryObject.SortBy]);
        else
            return query.OrderByDescending(columnsMap[queryObject.SortBy]);
    }

But I get the following error if object in the dictionary is a date:

Unable to cast the type 'System.DateTime' to type 'System.Object'. LINQ to Entities only supports casting EDM primitive or enumeration types.

This the code for the columnsMap that I pass through to call the above extension method:

  var columnsMap = new Dictionary<string, Expression<Func<Post, Object>>>
  {
            ["createdDate"] = p => p.CreatedDate
  };

  query = query.ApplyOrdering(queryObject, columnsMap);

How can I fix?


问:
iOS Development: All I need to do is post a tweet
I've been researching the latest ways to integrate Twitter into my app and it appears the best (most painless) approach is to use the MGTwitterEngine, and the best tutorial I could find to implement this is a 3-part series.  If all I need to do is allow the user to login to their twitter account and post a single tweet that's always the same, is there an easier way to do that than following the tutorial I linked to?

Thanks so much for your wisdom.  If the alternatives aren't much easier, no problem, I'm not so lazy that I can't follow a tutorial, I was just wondering if there's a quicker way that I didn't see.

答: Create a button that opens a UIWebView when clicked. Build the URL using details here: http://twitter.com/about/resources/tweetbutton. Simple - about 10 lines of code.

ContentLicense: CC BY-SA 2.5


问:
Android Center text on canvas
I'm trying to display a text using the code below.
The problem is that the text is not centered horizontally.
When I set the coordinates for drawText, it sets the bottom of the text at this position. I would like the text to be drawn so that the text is centered also horizontally.

This is a picture to display my problem further:

```<code>@Override
protected void onDraw(Canvas canvas) {
    // TODO Auto-generated method stub
    super.onDraw(canvas);
    //canvas.drawRGB(2, 2, 200);
    Paint textPaint = new Paint();
    textPaint.setARGB(200, 254, 0, 0);
    textPaint.setTextAlign(Align.CENTER);
    textPaint.setTypeface(font);
    textPaint.setTextSize(300);
    canvas.drawText("Hello", canvas.getWidth()/2, canvas.getHeight()/2  , textPaint);
}
</code>```

答:
If we are using Static layout

```<code>mStaticLayout = new StaticLayout(mText, mTextPaint, mTextWidth,
                Layout.Alignment.ALIGN_CENTER, 1.0f, 0, true);
</code>```

Layout.Alignment.ALIGN_CENTER this  will do the trick. Static layout also has got a lot of other advantages.

Reference:Android Documentation

Title: Android Center text on canvas

Body:
I'm trying to display a text using the code below.
The problem is that the text is not centered horizontally.
When I set the coordinates for drawText, it sets the bottom of the text at this position. I would like the text to be drawn so that the text is centered also horizontally.

This is a picture to display my problem further:

@Override
protected void onDraw(Canvas canvas) {
    // TODO Auto-generated method stub
    super.onDraw(canvas);
    //canvas.drawRGB(2, 2, 200);
    Paint textPaint = new Paint();
    textPaint.setARGB(200, 254, 0, 0);
    textPaint.setTextAlign(Align.CENTER);
    textPaint.setTypeface(font);
    textPaint.setTextSize(300);
    canvas.drawText("Hello", canvas.getWidth()/2, canvas.getHeight()/2  , textPaint);
}

Body:
If we are using Static layout

mStaticLayout = new StaticLayout(mText, mTextPaint, mTextWidth,
                Layout.Alignment.ALIGN_CENTER, 1.0f, 0, true);

Layout.Alignment.ALIGN_CENTER this  will do the trick. Static layout also has got a lot of other advantages.

Reference:Android Documentation


问:
How to get access to that pointer?
I've got something like this:

```<code>template <typename T,typename K>
class Ring
{
  typedef struct Node
  {
          T data;
          K key;
          Node * next;
          Node * prev;
  };
  Node * head;
public:
   class iterator
   {
        private:
        Node * ptr;
        friend class Ring;
}
</code>```

And I want to get by iterator class to Node*ptr to return in methods like get_value(iterator x) data and key. How can I do this ommiting function friend class? I want to make that Node *ptr will not be able to being used by user.

```<code>template <typename T,typename K>
K& Ring<T,K>::get_key(iterator & iter)
{
    Node * ptr = iter.ptr;
     return ptr->key;
}
</code>```

I want to return ptr-> key of my node, but without friend class I don't have access to Node * ptr , so I totally don't know how to get acces to that values.

答:
You should have a look at the API for std:map, std::unordered_map, to see how they've overcome this issue.

as in :

```<code>std::pair<const K&, T&> std::map::iterator<K, T>::iterator::operator*();
</code>```

Dereferencing a std::map::iterator gives you references to both a key and a value, conveniently hiding the implementation details.

This approach would fit well with your container as well.

ContentLicense: CC BY-SA 4.0

Title: How to get access to that pointer?

Body:
I've got something like this:

template <typename T,typename K>
class Ring
{
  typedef struct Node
  {
          T data;
          K key;
          Node * next;
          Node * prev;
  };
  Node * head;
public:
   class iterator
   {
        private:
        Node * ptr;
        friend class Ring;
}

And I want to get by iterator class to Node*ptr to return in methods like get_value(iterator x) data and key. How can I do this ommiting function friend class? I want to make that Node *ptr will not be able to being used by user.

template <typename T,typename K>
K& Ring<T,K>::get_key(iterator & iter)
{
    Node * ptr = iter.ptr;
     return ptr->key;
}

I want to return ptr-> key of my node, but without friend class I don't have access to Node * ptr , so I totally don't know how to get acces to that values.

Body:
You should have a look at the API for std:map, std::unordered_map, to see how they've overcome this issue.

as in :

std::pair<const K&, T&> std::map::iterator<K, T>::iterator::operator*();

Dereferencing a std::map::iterator gives you references to both a key and a value, conveniently hiding the implementation details.

This approach would fit well with your container as well.


问:
Visual Studio - project shows up as "Miscellaneous Files"
This is a weird one. I have a C# Class Library project within my solution. If I open a .cs file within this project, the Project drop-down on the code editor shows that it belongs to 'Miscellaneous Files'.

Other symptoms: if I go to the properties of the project and look at Assembly Information, all values are blank, despite the values existing in the AssemblyInfo.cs file.

Both of these are annoying, but the problem is that

I don't get intellisense on any files in the project

I can't seem to step through it in the debugger (it tells me that the files do not belong to the solution and so can't be debugged).

I have tried:

Combing through the .csproj file and comparing to others in the solution (no joy)

Re-creating the .csproj file and overwriting the old one (worked until I merged the branch into trunk, then the problem re-appeared)

Banging my head on the keyboard (headache)

Google has turned up nothing. Does anyone have any ideas as to what's going on here?

答:
Here is the Solution:

Go to Tools menu > Options > (expand) Environment > Documents (If Documents does not appear in the list, select Show all settings in the Options dialog box.)

Put a tick on "Miscellaneous files in Solution Explorer" and Click OK.
(This option displays the "Miscellaneous Files" node in Solution Explorer. Miscellaneous files are files that are not associated with a project or solution but can appear in Solution Explorer for your convenience if you tick this option.)

Locate your file in the Solution Explorer under "Miscellaneous Files". Then drag and drop your file to where it should belong and voila! This will copy the file to where you drop it. You may now safely delete the older file under Miscellaneous Files folder if you wish to do so.


问:
How to generate Schema.json of swapi-graphql for Android project?
I am working on Graphql android project, my (Facebook, through the GraphQL GitHub organization, provides a sample schema and local database of Star Wars objects.)Swapi local host is up and running for request. I am also using Apollo Android. In my Android project I need Schema.json file for the variant debug. But I don't know how to generate Schema.json file.

1. So how to generate Schema.json file?
2. Do I need multiple Schema json file for each data type planet, person, vehicle etc in single android project or one schema file contains all the information?

答: Solve it already, Find the answer at https://github.com/KaustubhMemane/GraphQLProject</p>


问:
document.querySelector('a').innerHTML but how do I change the code so that it will find the 2nd or 3rd link, instead of just the first?
document.querySelector('a').innerHTML

That's an example, but how do I change the code so that it will find the 2nd or 3rd link, instead of just the first?

答:
With something similar to this.
But as pointed by @zfrisch, your post is missing vital information for people to participate in this discussion.</p>

```<code><html>
 <body>
  <a href="goingsomewhere.html">go somewhere</a><br>
  <a href="goingsomewhereelse.html">go somewhere else</a><br />
  <a href="notgoinganywhere.html">dont go anywhere</a>

  <script>
  var thelinks = document.querySelectorAll('a');//aggregate all your links into an array
  for(var i = 0; i < thelinks.length; i++)//iterate through them
  {
      console.log(thelinks[i]);
  }
  </script>
 </body>
</html>
</code>```

Body:
With something similar to this.
But as pointed by @zfrisch, your post is missing vital information for people to participate in this discussion.

<html>
 <body>
  <a href="goingsomewhere.html">go somewhere</a><br>
  <a href="goingsomewhereelse.html">go somewhere else</a><br />
  <a href="notgoinganywhere.html">dont go anywhere</a>

  <script>
  var thelinks = document.querySelectorAll('a');//aggregate all your links into an array
  for(var i = 0; i < thelinks.length; i++)//iterate through them
  {
      console.log(thelinks[i]);
  }
  </script>
 </body>
</html>


答:
Whole Thing:

```<code>library(stringr)
library(tidyverse)

df2 <- as.data.frame(str_split_fixed(df$event_list, ",", max(length(strsplit(df$event_list, ",")))))

names(df2) <- paste0("event_", 1:ncol(df2))

df2$sequence <- paste0("seq_", 1:nrow(df2))

df3 <- df2 %>%
      gather(event, event_num, -sequence) %>%
      replace(. == "", NA) %>%
      filter(!is.na(event_num)) %>%
      select(-event) %>%
      mutate(Count = 1) %>%
      spread(event_num, Count) %>%
      replace(is.na(.), 0)
</code>```

Broken Down:

I would do a few things to clean up this dataset before tagging these. This will make it much easier to manipulate.

```<code>head(df)
                                                                   event_list completed_forms
1         211,202,214,240,104,105,106,107,114,117,118,139,140,141,142,143,146               0
2     211,202,214,240,104,105,106,107,114,117,118,121,139,140,141,142,143,146               0
3 211,202,214,240,215,104,105,106,107,114,117,118,121,139,140,141,142,143,146               0
4 211,202,214,240,215,104,105,106,107,114,117,118,121,139,140,141,142,143,146               0
5 211,202,214,240,215,104,105,106,107,114,117,118,121,139,140,141,142,143,146               0
6 211,202,214,240,215,104,105,106,107,114,117,118,121,139,140,141,142,143,146               0
</code>```

I'm going to start by using str_split_fixed from the stringr package. If you don't have it, install.packages(stringr).  This is going to turn our dataframe into a matrix so we will want to wrap it all in as.data.frame().

```<code>library(stringr)

df2 <- as.data.frame(str_split_fixed(df$event_list, ",", max(length(strsplit(df$event_list, ",")))))
</code>```

What this does is it takes a string like "134, 444, 105, 106" and splits it from one column into 4. The number of columns we'll have it split into is going to be the max(length()). That means if we have a column with 4 events, and one with 14, and another with 44 events, it will split every column into 44 columns to accommodate the largest one.

Inspect:

```<code>> head(df2)
   V1  V2  V3  V4  V5  V6  V7  V8  V9 V10 V11 V12 V13 V14 V15 V16 V17 V18 V19 V20 V21 V22 V23 V24 V25 V26 V27 V28 V29 V30
1 211 202 214 240 104 105 106 107 114 117 118 139 140 141 142 143 146
2 211 202 214 240 104 105 106 107 114 117 118 121 139 140 141 142 143 146
3 211 202 214 240 215 104 105 106 107 114 117 118 121 139 140 141 142 143 146
4 211 202 214 240 215 104 105 106 107 114 117 118 121 139 140 141 142 143 146
5 211 202 214 240 215 104 105 106 107 114 117 118 121 139 140 141 142 143 146
6 211 202 214 240 215 104 105 106 107 114 117 118 121 139 140 141 142 143 146
</code>```

Lets clean up the headers by turning them into event numbers

```<code>names(df2) <- paste0("event_", 1:ncol(df2))
</code>```

Now lets create a column to tag all of them which I'm going to call "sequence" for sequence of events.

```<code>df2$sequence <- paste0("seq_", 1:nrow(df2))
</code>```

Now we want to move it from wide format to long format to digest easier. we can do this with the gather function in tidyverse. We also want to turn the blank spaces to NA values, and then remove them from the dataframe. *We also probably don't need the event column after this. I would then add a few more steps to turn it back into a grid where the column headers are the event number, and have a 1 or 0 like you asked.

```<code>library(tidyverse)

df3 <- df2 %>%
      gather(event, event_num, -sequence) %>%
      replace(. == "", NA) %>%
      filter(!is.na(event_num)) %>%
      select(-event) %>%
      mutate(Count = 1) %>%
      spread(event_num, Count) %>%
      replace(is.na(.), 0)
</code>```

Hope this answers your question!

Title: new column value conditional on another column

Body:
I have list with many rows but one column; 107,114,142,143,146. I would like to create another column depending on whether this has certain value, lets say 114.

Looking at another post, I tried the following;

e_list$completed_forms <- rep(0, nrow(event_list))
e_list[e_list$e_list == 114, ][, "completed_forms"] <- "1"

Data list

structure(list(event_list = c("211,202,214,240,104,105,106,107,114,117,118,139,140,141,142,143,146",
"211,202,214,240,104,105,106,107,114,117,118,121,139,140,141,142,143,146",
"211,202,214,240,215,104,105,106,107,114,117,118,121,139,140,141,142,143,146",
"211,202,214,240,215,104,105,106,107,114,117,118,121,139,140,141,142,143,146",
"211,202,214,240,215,104,105,106,107,114,117,118,121,139,140,141,142,143,146",
"211,202,214,240,215,104,105,106,107,114,117,118,121,139,140,141,142,143,146",
"211,202,214,240,215,216,104,105,106,107,114,117,118,120,121,139,140,141,142,143,146",
"211,202,214,240,215,216,104,105,106,107,114,117,118,120,121,139,140,141,142,143,146",
"211,114,117,118,146", "211,104,114,117,118,121,146", "211,202,104,114,117,118,121,139,141,142,143,146",
"211,202,214,104,105,106,107,114,117,118,121,139,141,142,143,146",
"211,202,214,215,104,105,106,107,114,117,118,121,139,141,142,143,146",
"211,202,214,215,216,104,105,106,107,114,117,118,120,121,139,141,142,143,146",
"211,202,214,215,216,203,240,104,105,106,107,114,117,118,120,121,139,140,141,142,143,146",
"", "211,114,117,118,146", "211,114,117,118,146", "211,104,114,117,118,121,146",
"211,202,104,114,117,118,121,139,141,142,143,146", "211,202,214,104,105,106,107,114,117,118,121,139,141,142,143,146",
"211,202,214,215,104,105,106,107,114,117,118,121,139,141,142,143,146",
"211,202,214,215,216,104,105,106,107,114,117,118,120,121,139,141,142,143,146",
"211,202,214,215,216,217,240,104,105,106,107,114,117,118,120,121,139,140,141,142,143,146",
"211,202,214,215,216,217,240,203,104,105,106,107,114,117,118,120,121,122,139,140,141,142,143,146",
"211,202,214,215,216,217,240,203,104,105,106,107,114,117,118,120,121,122,139,140,141,142,143,146",
"211,202,214,215,216,217,240,203,104,105,106,107,114,117,118,120,121,122,139,140,141,142,143,146",
"", "211,114,117,118,146", "211,114,117,118,146"), lead_completed_new_forms = c(0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0)), .Names = c("event_list", "completed_forms"
), row.names = c(NA, 30L), class = "data.frame")

But I'm getting this error and I'm not sure why because I already added 0 to each column with the first line.

Error in [<-.data.frame(tmp, , "completed_forms", value
  = "1") :    replacement has 1 row, data has 0

Body:
Whole Thing:

library(stringr)
library(tidyverse)

df2 <- as.data.frame(str_split_fixed(df$event_list, ",", max(length(strsplit(df$event_list, ",")))))

names(df2) <- paste0("event_", 1:ncol(df2))

df2$sequence <- paste0("seq_", 1:nrow(df2))

df3 <- df2 %>%
      gather(event, event_num, -sequence) %>%
      replace(. == "", NA) %>%
      filter(!is.na(event_num)) %>%
      select(-event) %>%
      mutate(Count = 1) %>%
      spread(event_num, Count) %>%
      replace(is.na(.), 0)

Broken Down:

I would do a few things to clean up this dataset before tagging these. This will make it much easier to manipulate.

head(df)
                                                                   event_list completed_forms
1         211,202,214,240,104,105,106,107,114,117,118,139,140,141,142,143,146               0
2     211,202,214,240,104,105,106,107,114,117,118,121,139,140,141,142,143,146               0
3 211,202,214,240,215,104,105,106,107,114,117,118,121,139,140,141,142,143,146               0
4 211,202,214,240,215,104,105,106,107,114,117,118,121,139,140,141,142,143,146               0
5 211,202,214,240,215,104,105,106,107,114,117,118,121,139,140,141,142,143,146               0
6 211,202,214,240,215,104,105,106,107,114,117,118,121,139,140,141,142,143,146               0

I'm going to start by using str_split_fixed from the stringr package. If you don't have it, install.packages(stringr).  This is going to turn our dataframe into a matrix so we will want to wrap it all in as.data.frame().

library(stringr)

df2 <- as.data.frame(str_split_fixed(df$event_list, ",", max(length(strsplit(df$event_list, ",")))))

What this does is it takes a string like "134, 444, 105, 106" and splits it from one column into 4. The number of columns we'll have it split into is going to be the max(length()). That means if we have a column with 4 events, and one with 14, and another with 44 events, it will split every column into 44 columns to accommodate the largest one.

Inspect:

> head(df2)
   V1  V2  V3  V4  V5  V6  V7  V8  V9 V10 V11 V12 V13 V14 V15 V16 V17 V18 V19 V20 V21 V22 V23 V24 V25 V26 V27 V28 V29 V30
1 211 202 214 240 104 105 106 107 114 117 118 139 140 141 142 143 146
2 211 202 214 240 104 105 106 107 114 117 118 121 139 140 141 142 143 146
3 211 202 214 240 215 104 105 106 107 114 117 118 121 139 140 141 142 143 146
4 211 202 214 240 215 104 105 106 107 114 117 118 121 139 140 141 142 143 146
5 211 202 214 240 215 104 105 106 107 114 117 118 121 139 140 141 142 143 146
6 211 202 214 240 215 104 105 106 107 114 117 118 121 139 140 141 142 143 146

Lets clean up the headers by turning them into event numbers

names(df2) <- paste0("event_", 1:ncol(df2))

Now lets create a column to tag all of them which I'm going to call "sequence" for sequence of events.

df2$sequence <- paste0("seq_", 1:nrow(df2))

Now we want to move it from wide format to long format to digest easier. we can do this with the gather function in tidyverse. We also want to turn the blank spaces to NA values, and then remove them from the dataframe. *We also probably don't need the event column after this. I would then add a few more steps to turn it back into a grid where the column headers are the event number, and have a 1 or 0 like you asked.

library(tidyverse)

df3 <- df2 %>%
      gather(event, event_num, -sequence) %>%
      replace(. == "", NA) %>%
      filter(!is.na(event_num)) %>%
      select(-event) %>%
      mutate(Count = 1) %>%
      spread(event_num, Count) %>%
      replace(is.na(.), 0)

Hope this answers your question!


问:
How to force a new CNContact into a Local CNContainer?
I'm writing an app that stores contact-info fetched through REST and JSON into a container, using CNContactStore. I would like to keep these contacts separate from any other accounts, and only stored locally on the device, but a local store doesn't exist, and I can't find any way to create/activate one?

I'm able to get the default store's ID (as configured on the device, e.g. iCloud), using:

```<code>let store = CNContactStore()
let containerID = store.defaultContainerIdentifier()
</code>```

...and I can (theoretically) identify a local container like this — if one actually exists:

```<code>var allContainers = [CNContainer]()
    do {
        allContainers = try store.containersMatchingPredicate(nil)
        for container in allContainers {
            if container.type == CNContainerType.Local {
                print("Local container is: \(container.identifier)")
                break
            }
        }
    } catch {
        print("Error fetching containers")
    }
</code>```

But no local container exists. Any ideas on how to store my contacts locally, or in a new separate container?

答:
This was possible as follows with the now deprecated AB API, may still work as a workaround:</p>

```<code>ABAddressBookRef addressBook = ABAddressBookCreateWithOptions( nil, nil );

ABRecordRef source = ABAddressBookGetSourceWithRecordID( addressBook, kABSourceTypeLocal );

ABRecordRef contact = ABPersonCreateInSource( source );
</code>```

Body:
I'm writing an app that stores contact-info fetched through REST and JSON into a container, using CNContactStore. I would like to keep these contacts separate from any other accounts, and only stored locally on the device, but a local store doesn't exist, and I can't find any way to create/activate one?

I'm able to get the default store's ID (as configured on the device, e.g. iCloud), using:

let store = CNContactStore()
let containerID = store.defaultContainerIdentifier()

...and I can (theoretically) identify a local container like this — if one actually exists:

var allContainers = [CNContainer]()
    do {
        allContainers = try store.containersMatchingPredicate(nil)
        for container in allContainers {
            if container.type == CNContainerType.Local {
                print("Local container is: \(container.identifier)")
                break
            }
        }
    } catch {
        print("Error fetching containers")
    }

But no local container exists. Any ideas on how to store my contacts locally, or in a new separate container?

Body:
This was possible as follows with the now deprecated AB API, may still work as a workaround:

ABAddressBookRef addressBook = ABAddressBookCreateWithOptions( nil, nil );

ABRecordRef source = ABAddressBookGetSourceWithRecordID( addressBook, kABSourceTypeLocal );

ABRecordRef contact = ABPersonCreateInSource( source );


问:
SDWebImage - Change ActivityIndicatorView Colour?
I am currently using SDWebImage and have just started to add in the sd_setShowActivityIndicatorView feature however, is there a way I can change the colour of the progress indicator to like red?

I've tried to change the colour in UIView+WebCache.m inside the sd_addActivityIndicator function setTintColor: and setColor: but has no effect. The colour of the indicator is still grey/white.

Im coding in Objective-C.

答:
You should be able to do that using:

```<code>[imageView sd_setIndicatorStyle:UIActivityIndicatorViewStyleGray];
</code>```

For more information about the available options check the documentation of UIActivityIndicatorViewStyle.

Body:
You should be able to do that using:

[imageView sd_setIndicatorStyle:UIActivityIndicatorViewStyleGray];

For more information about the available options check the documentation of UIActivityIndicatorViewStyle.


问:
Bound service crash with "Context.startForegroundService() did not then call Service.startForeground()" error
I'm currently working on audio playback app and I'm using a started bound service to play music in background. I start and bind to the service using following code.

```<code>val intent = Intent(context, MusicService::class.java)
context.startService(intent)
context.bindService(intent, serviceConnection, 0)
</code>```

It gets promoted to foreground when playing and gets demoted when music is paused.

```<code>// onAudioPlay
service.startForeground(NOTIFY_ID, notification)

// onAudioPause
service.stopForeground(false)
</code>```

Service work fine up to now. But when the notification is swiped(removed) by the user in the paused state, the service crashes after few seconds giving this error.

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.myplayer, PID: 4380
    android.app.RemoteServiceException: Context.startForegroundService() did not then call Service.startForeground()
        android.app.ActivityThread$H.handleMessage(ActivityThread.java:1775)
        android.os.Handler.dispatchMessage(Handler.java:105)
        android.os.Looper.loop(Looper.java:164)
        android.app.ActivityThread.main(ActivityThread.java:6541)
        java.lang.reflect.Method.invoke(Native Method)
      com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
        com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
</code>```

This only happens on Oreo and I already read about the background limitations in Oreo. But following points bugs me.

This service is a bound service(which aren't affected by limitations)

I never use Context.startForegroundService() to start the service.(and don't want to use it)

The service doesn't crash when it gets demoted from foreground, it's happens when removing the notification.

Why is the service is crashing? What am I doing wrong? I'm very thankful if someone tell me whats happening here.

答:
From the docs 8.0 Behavior Changes

The system allows apps to call Context.startForegroundService() even
  while the app is in the background. However, the app must call that
  service's startForeground() method within five seconds after the
  service is created.

So, you have to call startForeground inside onCreate() for your service.

Body:
I'm currently working on audio playback app and I'm using a started bound service to play music in background. I start and bind to the service using following code.

val intent = Intent(context, MusicService::class.java)
context.startService(intent)
context.bindService(intent, serviceConnection, 0)

It gets promoted to foreground when playing and gets demoted when music is paused.

// onAudioPlay
service.startForeground(NOTIFY_ID, notification)

// onAudioPause
service.stopForeground(false)

Service work fine up to now. But when the notification is swiped(removed) by the user in the paused state, the service crashes after few seconds giving this error.

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.myplayer, PID: 4380
    android.app.RemoteServiceException: Context.startForegroundService() did not then call Service.startForeground()
        android.app.ActivityThread$H.handleMessage(ActivityThread.java:1775)
        android.os.Handler.dispatchMessage(Handler.java:105)
        android.os.Looper.loop(Looper.java:164)
        android.app.ActivityThread.main(ActivityThread.java:6541)
        java.lang.reflect.Method.invoke(Native Method)
      com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
        com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)

This only happens on Oreo and I already read about the background limitations in Oreo. But following points bugs me.

This service is a bound service(which aren't affected by limitations)

I never use Context.startForegroundService() to start the service.(and don't want to use it)

The service doesn't crash when it gets demoted from foreground, it's happens when removing the notification.

Why is the service is crashing? What am I doing wrong? I'm very thankful if someone tell me whats happening here.


问:
getting org-protocol to work on Firefox Quantum -- `No server buffers remain to edit` error
So I am trying to get org-protocol to work for the first time on Firefox Quantum. I worked through a variety of blog posts and the documentation, but still cannot get past this particular error

```<code>Greedy org-protocol handler.  Killing client.
No server buffers remain to edit.
</code>```

So I am using emacs 25.3 on Ubuntu Linux x64 16.04, and the newly released Firefox Quantum.

I tried to do this in two ways.

The traditional approach of setting up org-protocol through creating a desktop entry and then setting up bookmarklets in Firefox.

Using the org-capture add-on in Firefox.

Both are giving me the same error.

For approach 1, I followed the documentation as well as a very helpful stackexchange post:

How to make org-protocol work?

There was also this useful blog post.

Here is what I did:

A. I created a desktop entry:

```<code>[Desktop Entry]
Name=org-protocol
Exec=emacsclient -n %u
Type=Application
Terminal=false
Categories=System;
MimeType=x-scheme-handler/org-protocol;
</code>```

B. added config to .spacemacs file.

I added the lines:

```<code>(server-start)
(require 'org-protocol)
</code>```

Then I setup up the capture template in my .spacemacs file:

```<code>(setq org-capture-templates
      (quote
              ("p" "org-protocol" entry (file+headline "~/Dropbox/config/org/refile/refile.org")
                "* %^{Title}\nSource: %u, %c\n #+BEGIN_QUOTE\n%:initial\n#+END_QUOTE\n\n\n%?")
              ("l" "org-protocol link" entry (file "~/Dropbox/config/org/refile/refile.org")
                "* %? [[%:link][%:description]] \nCaptured On: %U")
... Additional templates.
))
</code>```

C. Then I created the bookmarklets with the locations:

```<code>javascript:location.href='org-protocol://store-link://l/'+encodeURIComponent(location.href)

javascript:location.href='org-protocol://capture://l/'+encodeURIComponent(location.href)+'/'+encodeURIComponent(document.title)+'/'+encodeURIComponent(window.getSelection())
</code>```

After all of this, I still get the error message referenced above.

Second, I tried the org-capture add-on in Firefox. But it did not work either.

Not sure what the cause of the error is. Any help is appreciated.

In other reading people get this Greedy error when there are problems in the org-capture template, but I did not find any errors.

答:
I had some trouble in the past too.

Now the solution I use is this firefox add-on -> You can install it directly from Firefox. That's really easy and in my case, it worked out of the box (Debian distro, Firefox 52.5.0). I do not know if it is available for Firefox Quantum though.

org-protocol is configured as usual. In my case:

```<code>cat > "${HOME}/.local/share/applications/org-protocol.desktop" << EOF
[Desktop Entry]
Name=org-protocol
Exec=emacsclient %u
Type=Application
Terminal=false
Categories=System;
MimeType=x-scheme-handler/org-protocol;
EOF
</code>```

then

```<code>update-desktop-database ~/.local/share/applications/
</code>```

In your Emacs init.el file:

```<code>(server-start)
(require 'org-protocol)

(setq org-capture-templates `(
    ("p" "Protocol" entry (file+headline ,(concat org-directory "notes.org") "Inbox")
        "* %^{Title}\nSource: %u, %c\n #+BEGIN_QUOTE\n%i\n#+END_QUOTE\n\n\n%?")
    ("L" "Protocol Link" entry (file+headline ,(concat org-directory "notes.org") "Inbox")
        "* %? [[%:link][%:description]] \nCaptured On: %U")
))
</code>```

That's all. Under my config it works, I hope this is the same for yours.

Extra: some time ago, I have suggested a small template improvement to handle ArXiv.org titles, the details are here: https://github.com/sprig/org-capture-extension/issues/37

Body:
So I am trying to get org-protocol to work for the first time on Firefox Quantum. I worked through a variety of blog posts and the documentation, but still cannot get past this particular error

Greedy org-protocol handler.  Killing client.
No server buffers remain to edit.

So I am using emacs 25.3 on Ubuntu Linux x64 16.04, and the newly released Firefox Quantum.

I tried to do this in two ways.

The traditional approach of setting up org-protocol through creating a desktop entry and then setting up bookmarklets in Firefox.

Using the org-capture add-on in Firefox.

Both are giving me the same error.

For approach 1, I followed the documentation as well as a very helpful stackexchange post:

How to make org-protocol work?

There was also this useful blog post.

Here is what I did:

A. I created a desktop entry:

[Desktop Entry]
Name=org-protocol
Exec=emacsclient -n %u
Type=Application
Terminal=false
Categories=System;
MimeType=x-scheme-handler/org-protocol;

B. added config to .spacemacs file.

I added the lines:

(server-start)
(require 'org-protocol)

Then I setup up the capture template in my .spacemacs file:

(setq org-capture-templates
      (quote
              ("p" "org-protocol" entry (file+headline "~/Dropbox/config/org/refile/refile.org")
                "* %^{Title}\nSource: %u, %c\n #+BEGIN_QUOTE\n%:initial\n#+END_QUOTE\n\n\n%?")
              ("l" "org-protocol link" entry (file "~/Dropbox/config/org/refile/refile.org")
                "* %? [[%:link][%:description]] \nCaptured On: %U")
... Additional templates.
))

C. Then I created the bookmarklets with the locations:

javascript:location.href='org-protocol://store-link://l/'+encodeURIComponent(location.href)

javascript:location.href='org-protocol://capture://l/'+encodeURIComponent(location.href)+'/'+encodeURIComponent(document.title)+'/'+encodeURIComponent(window.getSelection())

After all of this, I still get the error message referenced above.

Second, I tried the org-capture add-on in Firefox. But it did not work either.

Not sure what the cause of the error is. Any help is appreciated.

In other reading people get this Greedy error when there are problems in the org-capture template, but I did not find any errors.

Body:
I had some trouble in the past too.

Now the solution I use is this firefox add-on -> You can install it directly from Firefox. That's really easy and in my case, it worked out of the box (Debian distro, Firefox 52.5.0). I do not know if it is available for Firefox Quantum though.

org-protocol is configured as usual. In my case:

cat > "${HOME}/.local/share/applications/org-protocol.desktop" << EOF
[Desktop Entry]
Name=org-protocol
Exec=emacsclient %u
Type=Application
Terminal=false
Categories=System;
MimeType=x-scheme-handler/org-protocol;
EOF

then

update-desktop-database ~/.local/share/applications/

In your Emacs init.el file:

(server-start)
(require 'org-protocol)

(setq org-capture-templates `(
    ("p" "Protocol" entry (file+headline ,(concat org-directory "notes.org") "Inbox")
        "* %^{Title}\nSource: %u, %c\n #+BEGIN_QUOTE\n%i\n#+END_QUOTE\n\n\n%?")
    ("L" "Protocol Link" entry (file+headline ,(concat org-directory "notes.org") "Inbox")
        "* %? [[%:link][%:description]] \nCaptured On: %U")
))

That's all. Under my config it works, I hope this is the same for yours.

Extra: some time ago, I have suggested a small template improvement to handle ArXiv.org titles, the details are here: https://github.com/sprig/org-capture-extension/issues/37


问:
Errors with the align_local function in R
I am trying to compare two gene sequences:

```<code>sequence_1 <- "MPHLENVVLCRESQVSILQSLFGERHHFSFPSIFIYGHTASGKTYVTQTLLKTLELPHVFVNCVECFTLRLLLEQILNKLNHLSSSEDGCSTEITCETFNDFVRLFKQVTTAENLKDQTVYIVLDKAEYLRDMEANLLPGFLRLQELADRNVTVLFLSEIVWEKFRPNTGCFEPFVLYFPDYSIGNLQKILSHDHPPEYSADFYAAYINILLGVFYTVCRDLKELRHLAVLNFPKYCEPVVKGEASERDTRKLWRNIEPHLKKAMQTVYLREISSSQWEKLQKDDTDPGQLKGLSAHTHVELPYYSKFILIAAYLASYNPARTDKRFFLKHHGKIKKTNFLKKHEKTSNHLLGPKPFPLDRLLAILYSIVDSRVAPTANIFSQITSLVTLQLLTLVGHDDQLDGPKYKCTVSLDFIRAIARTVNFDIIKYLYDFL"

sequence_2 <- "MEEEAPRFNVLEEAFNGNGNGCANVEATQSAILKVLTRVNRFQMRVRKHIEDNYTEFLPNNTSPDIFLEESGSLNREIHDMLENLGSEGLDALDEANVKMAGNGRQLREILLGLGVSEHVLRIDELFQCVEEAKATKDYLVLLDLVGRLRAFIYGDDSVDGDAQVATPEVRRIFKALECYETIKVKYHVQAYMLQQSLQERFDRLVQLQCKSFPTSRCVTLQVSRDQTQLQDIVQALFQEPYNPARLCEFLLDNCIEPVIMRPVMADYSEEADGGTYVRLSLSYATKEPSSAHVRPNYKQVLENLRLLLHTLAGINCSVSRDQHVFGIIGDHVKDKMLKLLVDECLIPAVPESTEEYQTSTLCEDVAQLEQLLVDSFIINPEQDRALGQFVEKYETYYRNRMYRRVLETAREIIQRDLQDMVLVAPNNHSAEVANDPFLFPRCMISKSAQDFVKLMDRILRQPTDKLGDQEADPIAGVISIMLHTYINEVPKVHRKLLESIPQQAVLFHNNCMFFTHWVAQHANKGIESLAALAKTLQATGQQHFRVQVDYQSSILMGIMQEFEFESTHTLGSGPLKLVRQCLRQLELLKNVWANVLPETVYNATFCELINTFVAELIRRVFTLRDISAQMACELSDLIDVVLQRAPTLFREPNEVVQVLSWLKLQQLKAMLNASLMEITELWGDGVGPLTASYKSDEIKHLIRALFQDTDWRAKAITQIV"
</code>```

using the align_local function from the textreuse package.  My input is:

```<code>library(textreuse)
align_local(sequence_1, sequence_2)
</code>```

and I get the error:

```<code>Error in b_out[out_i] <- b_orig[row_i - 1] : replacement has length zero
In addition: Warning message:
Multiple optimal local alignments found; selecting only one of them.
</code>```

I've tried tinkering with the alignment score and the mismatch score, but to no avail.  Any advice would be appreciated.

答:
The problem here is that lsh_compare function from textreuse package is meant for analyzing text documents and detecting passages which have been re-used. Which means that it works with spaced out words in a sentence.

My suggestion would be to try to find a package that is more suitable for handling genes.

e.g. dotPlot function from seqinr gives you a visual representation of the comparison.

Body:
I am trying to compare two gene sequences:

sequence_1 <- "MPHLENVVLCRESQVSILQSLFGERHHFSFPSIFIYGHTASGKTYVTQTLLKTLELPHVFVNCVECFTLRLLLEQILNKLNHLSSSEDGCSTEITCETFNDFVRLFKQVTTAENLKDQTVYIVLDKAEYLRDMEANLLPGFLRLQELADRNVTVLFLSEIVWEKFRPNTGCFEPFVLYFPDYSIGNLQKILSHDHPPEYSADFYAAYINILLGVFYTVCRDLKELRHLAVLNFPKYCEPVVKGEASERDTRKLWRNIEPHLKKAMQTVYLREISSSQWEKLQKDDTDPGQLKGLSAHTHVELPYYSKFILIAAYLASYNPARTDKRFFLKHHGKIKKTNFLKKHEKTSNHLLGPKPFPLDRLLAILYSIVDSRVAPTANIFSQITSLVTLQLLTLVGHDDQLDGPKYKCTVSLDFIRAIARTVNFDIIKYLYDFL"

sequence_2 <- "MEEEAPRFNVLEEAFNGNGNGCANVEATQSAILKVLTRVNRFQMRVRKHIEDNYTEFLPNNTSPDIFLEESGSLNREIHDMLENLGSEGLDALDEANVKMAGNGRQLREILLGLGVSEHVLRIDELFQCVEEAKATKDYLVLLDLVGRLRAFIYGDDSVDGDAQVATPEVRRIFKALECYETIKVKYHVQAYMLQQSLQERFDRLVQLQCKSFPTSRCVTLQVSRDQTQLQDIVQALFQEPYNPARLCEFLLDNCIEPVIMRPVMADYSEEADGGTYVRLSLSYATKEPSSAHVRPNYKQVLENLRLLLHTLAGINCSVSRDQHVFGIIGDHVKDKMLKLLVDECLIPAVPESTEEYQTSTLCEDVAQLEQLLVDSFIINPEQDRALGQFVEKYETYYRNRMYRRVLETAREIIQRDLQDMVLVAPNNHSAEVANDPFLFPRCMISKSAQDFVKLMDRILRQPTDKLGDQEADPIAGVISIMLHTYINEVPKVHRKLLESIPQQAVLFHNNCMFFTHWVAQHANKGIESLAALAKTLQATGQQHFRVQVDYQSSILMGIMQEFEFESTHTLGSGPLKLVRQCLRQLELLKNVWANVLPETVYNATFCELINTFVAELIRRVFTLRDISAQMACELSDLIDVVLQRAPTLFREPNEVVQVLSWLKLQQLKAMLNASLMEITELWGDGVGPLTASYKSDEIKHLIRALFQDTDWRAKAITQIV"

using the align_local function from the textreuse package.  My input is:

library(textreuse)
align_local(sequence_1, sequence_2)

and I get the error:

Error in b_out[out_i] <- b_orig[row_i - 1] : replacement has length zero
In addition: Warning message:
Multiple optimal local alignments found; selecting only one of them.

I've tried tinkering with the alignment score and the mismatch score, but to no avail.  Any advice would be appreciated.


问:
How is the audio or image transmitted by the email client when I send them?
When I send an email with attachment of audio, image or anything other than plain ASCII bytes, how does the email client treat these various types of files? I can think of 2 options:

do nothing about the file content, just send them unchanged with the mail text, but mark them with MIME info.

re-encode these file content with Base64 and send them as text just like the mail text, and also mark them with MIME info.

So, what actuall happens?

Many thanks.

答: It's just like any other non-ascii attachment -- Base64 encoded!  Try sending or receiving an email with an audio attachment while using Wireshark, and you'll see this.</p>


问:
Use QTimer to run functions in an infinte loop
I'm new to Python and still trying to learn, but I couldn't handle this problem. I want to run some functions (which are in class) in an infinite loop. Because it is a QApplication, I've learned that I should do it with a QTimer. However, when exploring how to do it, I couldn't find a working alternative. A common solution is:

```<code>timer = QTimer()
timer.timeout.connect(function)
timer.start(60000)
</code>```

But when I insert these into my code it makes no difference. I have tried to insert it under functions, class, etc, but couldn't get a result. My functions to loop are here:

```<code>__author__ = 'pc'
import requests
from bs4 import BeautifulSoup
from PyQt5 import QtCore, QtWidgets, QtWebEngineWidgets
import sqlite3
import sys, getopt, time
from PyQt5.QtCore import QTimer

records = []
def scrape_page(url, html):
    soup = BeautifulSoup(html, 'html.parser')
    data = soup.find('div', class_='tablo_dual_board')
    try:
        datas = data.text.splitlines()
        datas1 = list(filter(None, datas))
        records.append(datas1)
    except:
        pass

def process_records():
    # add record to database ...
    print('process records:', len(records))

def generate_urls():
    onexurl = "https://1xbahis19.com/en/live/Football/"
    reply = requests.get(onexurl)
    soup = BeautifulSoup(reply.content, "html.parser")
    income = soup.find_all("ul", {"id":"games_content"})
    links = soup.find_all("a", {"class": "c-events__name"})
    urls = []
    for matchlink in links:
        urls.append("https://1xbahis19.com/en/"+(matchlink.get("href")))
    return urls

class WebPage(QtWebEngineWidgets.QWebEnginePage):
    def __init__(self):
        super(WebPage, self).__init__()
        self.loadFinished.connect(self.handleLoadFinished)

    def start(self, urls):
        self._urls = iter(urls)
        self.fetchNext()

    def fetchNext(self):
        try:
            url = next(self._urls)
        except StopIteration:
            return False
        else:
            self.load(QtCore.QUrl(url))
        return True

    def processCurrentPage(self, html):
        scrape_page(self.url().toString(), html)
        if not self.fetchNext():
            process_records()
            print(records)
            QtWidgets.qApp.quit()

    def handleLoadFinished(self):
        self.toHtml(self.processCurrentPage)

app = QtWidgets.QApplication(sys.argv)
webpage = WebPage()
webpage.start(generate_urls())
timer = QTimer()
timer.timeout.connect(WebPage)
timer.start(60000)
app.exec_()
</code>```

Can anyone help with this please?

答:
I assume you want to run the scraper at regular intervals. The script below will scrape all the urls once every 60 seconds. The signal part is there to provide a way to terminate the infinite loop - just do Ctrl+C (i.e. KeyboardInterrupt), and it will stop immediately.

```<code>import requests
from bs4 import BeautifulSoup
from PyQt5 import QtCore, QtWidgets, QtWebEngineWidgets
import sqlite3
import sys, getopt, time
from PyQt5.QtCore import QTimer

import signal
# press Ctrl+C to stop the script
signal.signal(signal.SIGINT, signal.SIG_DFL)

records = []
def scrape_page(url, html):
    print('scraping page:', url)
    soup = BeautifulSoup(html, 'html.parser')
    data = soup.find('div', class_='tablo_dual_board')
    try:
        datas = data.text.splitlines()
        datas1 = list(filter(None, datas))
        records.append(datas1)
    except:
        pass

def process_records():
    # add record to database ...
    print('processed records:', len(records))
    # clear the current records
    del records[:]
    # re-run after a timeout
    QTimer.singleShot(60000, run)

def run():
    print('running scraper...')
    webpage.start(generate_urls())

def generate_urls():
    print('generating urls...')
    onexurl = "https://1xbahis19.com/en/live/Football/"
    reply = requests.get(onexurl)
    soup = BeautifulSoup(reply.content, "html.parser")
    income = soup.find_all("ul", {"id":"games_content"})
    links = soup.find_all("a", {"class": "c-events__name"})
    urls = []
    for matchlink in links:
        urls.append("https://1xbahis19.com/en/"+(matchlink.get("href")))
    return urls

class WebPage(QtWebEngineWidgets.QWebEnginePage):
    def __init__(self):
        super(WebPage, self).__init__()
        self.loadFinished.connect(self.handleLoadFinished)

    def start(self, urls):
        self._urls = iter(urls)
        self.fetchNext()

    def fetchNext(self):
        try:
            url = next(self._urls)
        except StopIteration:
            return False
        else:
            self.load(QtCore.QUrl(url))
        return True

    def processCurrentPage(self, html):
        scrape_page(self.url().toString(), html)
        if not self.fetchNext():
            process_records()

    def handleLoadFinished(self):
        self.toHtml(self.processCurrentPage)

app = QtWidgets.QApplication(sys.argv)
webpage = WebPage()
run()
app.exec_()
</code>```

Body:
I'm new to Python and still trying to learn, but I couldn't handle this problem. I want to run some functions (which are in class) in an infinite loop. Because it is a QApplication, I've learned that I should do it with a QTimer. However, when exploring how to do it, I couldn't find a working alternative. A common solution is:

timer = QTimer()
timer.timeout.connect(function)
timer.start(60000)

But when I insert these into my code it makes no difference. I have tried to insert it under functions, class, etc, but couldn't get a result. My functions to loop are here:

__author__ = 'pc'
import requests
from bs4 import BeautifulSoup
from PyQt5 import QtCore, QtWidgets, QtWebEngineWidgets
import sqlite3
import sys, getopt, time
from PyQt5.QtCore import QTimer

records = []
def scrape_page(url, html):
    soup = BeautifulSoup(html, 'html.parser')
    data = soup.find('div', class_='tablo_dual_board')
    try:
        datas = data.text.splitlines()
        datas1 = list(filter(None, datas))
        records.append(datas1)
    except:
        pass

def process_records():
    # add record to database ...
    print('process records:', len(records))

def generate_urls():
    onexurl = "https://1xbahis19.com/en/live/Football/"
    reply = requests.get(onexurl)
    soup = BeautifulSoup(reply.content, "html.parser")
    income = soup.find_all("ul", {"id":"games_content"})
    links = soup.find_all("a", {"class": "c-events__name"})
    urls = []
    for matchlink in links:
        urls.append("https://1xbahis19.com/en/"+(matchlink.get("href")))
    return urls

class WebPage(QtWebEngineWidgets.QWebEnginePage):
    def __init__(self):
        super(WebPage, self).__init__()
        self.loadFinished.connect(self.handleLoadFinished)

    def start(self, urls):
        self._urls = iter(urls)
        self.fetchNext()

    def fetchNext(self):
        try:
            url = next(self._urls)
        except StopIteration:
            return False
        else:
            self.load(QtCore.QUrl(url))
        return True

    def processCurrentPage(self, html):
        scrape_page(self.url().toString(), html)
        if not self.fetchNext():
            process_records()
            print(records)
            QtWidgets.qApp.quit()

    def handleLoadFinished(self):
        self.toHtml(self.processCurrentPage)

app = QtWidgets.QApplication(sys.argv)
webpage = WebPage()
webpage.start(generate_urls())
timer = QTimer()
timer.timeout.connect(WebPage)
timer.start(60000)
app.exec_()

Can anyone help with this please?

Body:
I assume you want to run the scraper at regular intervals. The script below will scrape all the urls once every 60 seconds. The signal part is there to provide a way to terminate the infinite loop - just do Ctrl+C (i.e. KeyboardInterrupt), and it will stop immediately.

import requests
from bs4 import BeautifulSoup
from PyQt5 import QtCore, QtWidgets, QtWebEngineWidgets
import sqlite3
import sys, getopt, time
from PyQt5.QtCore import QTimer

import signal
# press Ctrl+C to stop the script
signal.signal(signal.SIGINT, signal.SIG_DFL)

records = []
def scrape_page(url, html):
    print('scraping page:', url)
    soup = BeautifulSoup(html, 'html.parser')
    data = soup.find('div', class_='tablo_dual_board')
    try:
        datas = data.text.splitlines()
        datas1 = list(filter(None, datas))
        records.append(datas1)
    except:
        pass

def process_records():
    # add record to database ...
    print('processed records:', len(records))
    # clear the current records
    del records[:]
    # re-run after a timeout
    QTimer.singleShot(60000, run)

def run():
    print('running scraper...')
    webpage.start(generate_urls())

def generate_urls():
    print('generating urls...')
    onexurl = "https://1xbahis19.com/en/live/Football/"
    reply = requests.get(onexurl)
    soup = BeautifulSoup(reply.content, "html.parser")
    income = soup.find_all("ul", {"id":"games_content"})
    links = soup.find_all("a", {"class": "c-events__name"})
    urls = []
    for matchlink in links:
        urls.append("https://1xbahis19.com/en/"+(matchlink.get("href")))
    return urls

class WebPage(QtWebEngineWidgets.QWebEnginePage):
    def __init__(self):
        super(WebPage, self).__init__()
        self.loadFinished.connect(self.handleLoadFinished)

    def start(self, urls):
        self._urls = iter(urls)
        self.fetchNext()

    def fetchNext(self):
        try:
            url = next(self._urls)
        except StopIteration:
            return False
        else:
            self.load(QtCore.QUrl(url))
        return True

    def processCurrentPage(self, html):
        scrape_page(self.url().toString(), html)
        if not self.fetchNext():
            process_records()

    def handleLoadFinished(self):
        self.toHtml(self.processCurrentPage)

app = QtWidgets.QApplication(sys.argv)
webpage = WebPage()
run()
app.exec_()


问:
AngularJS Two-way data binding canceled out by setTimeout
I've got this snippet of HTML using the Controller As syntax:

```<code><div ng-class="{'hide': !autoDeploy.uiVisibility.overlayLoaderVisible, 'show': autoDeploy.uiVisibility.overlayLoaderVisible}" />

<div ng-class="{'animate-top hide': !autoDeploy.uiVisibility.resultVisible, 'animate-bottom show': autoDeploy.uiVisibility.resultVisible}">

<button ng-click="autoDeploy.btn_extractFormData()">click</button>
</code>```

with this very stripped down controller:

```<code>angular.module("gms.autoDeploy").controller('AutoDeployController', ['$scope', 'AutoDeployService',
    function ($scope, AutoDeployService) {
        var model = this;

        // two-way data binding model to view
        model.uiVisibility = AutoDeployService.getUIVisibility();

        // Pull the data from our data model arrays
        function btn_extractFormData() {
            AutoDeployService.extractFormData();
        }

        model.btn_extractFormData = btn_extractFormData;
    }
]);
</code>```

and this segment from my service module:

```<code>    var uiVisibility = {
        resultVisible: false,
        overlayLoaderVisible: false
    };
    function getBuildResult() {

        $http({
            url: 'https://jenkins...com/job/...',
            method: 'GET',
            headers: {
                'Accept': "*/*",
                'Authorization': 'Basic ...'
            }
        })

            .then(function (res) {
                //stuff happens here
            })

            .catch(function (res) {
                // stuff also happens here
            });

        setTimeout(function () {
            uiVisibility.overlayLoaderVisible = false;
            uiVisibility.resultVisible = true;
        }, 1100);

    }

    // return this service (contains the objects that we want to be public)
    return {
        getUIVisibility:                getUIVisibility,
        extractFormData:                extractFormData
    };
}
</code>```

My issue here is that when the values of uiVisibility.overlayLoaderVisible and uiVisibility.resultVisible are changed in the above setTimeout(), nothing happens on the UI but I know it executes because I've tested it with console logging. If I replace the timeout with just the two lines then they will execute, but it's synchronous, so there's a second or so between each being updated in the view.

My question: Is there some mechanism here preventing the two-way data binding when the value is modified in the async setTimeout() method?

I put the two values into an associative array to account for JavaScript's pass-by-sharing, and works fine with all other objects that I use two-way binding on.

答:
Inject the $timeout service into your service, and use that instead. It will trigger a digest for you:

```<code>$timeout(function () {
    uiVisibility.overlayLoaderVisible = false;
    uiVisibility.resultVisible = true;
}, 1100);
</code>```

Body:
I've got this snippet of HTML using the Controller As syntax:

<button ng-click="autoDeploy.btn_extractFormData()">click</button>

with this very stripped down controller:

angular.module("gms.autoDeploy").controller('AutoDeployController', ['$scope', 'AutoDeployService',
    function ($scope, AutoDeployService) {
        var model = this;

        // two-way data binding model to view
        model.uiVisibility = AutoDeployService.getUIVisibility();

        // Pull the data from our data model arrays
        function btn_extractFormData() {
            AutoDeployService.extractFormData();
        }

        model.btn_extractFormData = btn_extractFormData;
    }
]);

and this segment from my service module:

    var uiVisibility = {
        resultVisible: false,
        overlayLoaderVisible: false
    };
    function getBuildResult() {

        $http({
            url: 'https://jenkins...com/job/...',
            method: 'GET',
            headers: {
                'Accept': "*/*",
                'Authorization': 'Basic ...'
            }
        })

            .then(function (res) {
                //stuff happens here
            })

            .catch(function (res) {
                // stuff also happens here
            });

        setTimeout(function () {
            uiVisibility.overlayLoaderVisible = false;
            uiVisibility.resultVisible = true;
        }, 1100);

    }

    // return this service (contains the objects that we want to be public)
    return {
        getUIVisibility:                getUIVisibility,
        extractFormData:                extractFormData
    };
}

My issue here is that when the values of uiVisibility.overlayLoaderVisible and uiVisibility.resultVisible are changed in the above setTimeout(), nothing happens on the UI but I know it executes because I've tested it with console logging. If I replace the timeout with just the two lines then they will execute, but it's synchronous, so there's a second or so between each being updated in the view.

My question: Is there some mechanism here preventing the two-way data binding when the value is modified in the async setTimeout() method?

I put the two values into an associative array to account for JavaScript's pass-by-sharing, and works fine with all other objects that I use two-way binding on.

Body:
Inject the $timeout service into your service, and use that instead. It will trigger a digest for you:

$timeout(function () {
    uiVisibility.overlayLoaderVisible = false;
    uiVisibility.resultVisible = true;
}, 1100);


问:
Objective-c NSArray with values from another class
I am trying to create a table view in my view based application but I am facing a problem

```<code>NSArray *array = [[NSArray alloc] initWithObjects:@"iPod",forecast.desc,nil];
NSLog(@"this is the forecast routeNo = %@", forecast.desc);
</code>```

As you can see this is the array that shows the values in the table, the result of this code is iPod (only), "forecast.desc" doesn't show anything knowing that forecast is an instance of another class and "desc" is a string in that class

and just to make sure forecast.desc shows the correct information in the log but in the table as if doesn't exist can anyone see where is the problem ?

Thanks

答:
Try</p>

```<code>[[NSArray alloc] initWithObjects:@"iPod", [NSString stringWithFormat:@"%@",forecast.desc], nil];
</code>```

Body:
I am trying to create a table view in my view based application but I am facing a problem

NSArray *array = [[NSArray alloc] initWithObjects:@"iPod",forecast.desc,nil];
NSLog(@"this is the forecast routeNo = %@", forecast.desc);

As you can see this is the array that shows the values in the table, the result of this code is iPod (only), "forecast.desc" doesn't show anything knowing that forecast is an instance of another class and "desc" is a string in that class

and just to make sure forecast.desc shows the correct information in the log but in the table as if doesn't exist can anyone see where is the problem ?

Thanks

Body:
Try

[[NSArray alloc] initWithObjects:@"iPod", [NSString stringWithFormat:@"%@",forecast.desc], nil];


问:
Is there a way to set the minimum viewport size for phones without causing the site to zoom in on tablets?
I've been working on making a few websites that force 1000px layouts to be more responsive. On one, it scales nicely down to ~500px and on another it scales nicely to 780px. My phone is 320px across and my tablet is around 1000x across. The problem is that:

If I don't set the viewport, both devices render the page ~1000px wide, so all of my nice scaling code gets completely ignored and the page is massive on the phone.

If I set <meta name="viewport" content="width=device-width">, the page renders perfectly, but it starts out extremely zoomed in on the phone (zoomed to show 320px of the layout).

If I set <meta name="viewport" content="width=780">, it renders and scales perfectly on the phone, but zooms in on the tablet (scaling the layout to 780px wide even though I have 1000px to work with).

I also tried a JavaScript workaround:

```<code><meta id="viewport" name="viewport" content="width=device-width, initial-scale=1.0" />
<script>
if (screen.width < 780) {
  var viewport = document.getElementById("viewport");
  viewport.setAttribute("content", "width=780");
}
</script>
</code>```

This works in Chrome but not Firefox. I even tried using CSS transforms to scale the entire page on Firefox, but that leaves a bunch of whitespace around the scaled page (and is a terrible solution).

Is there a way to make devices render and scale to their width down to 500px, and then scale and render at 500px when their screen size is below that?

答:
If your content should be at least 780px wide, set min-width on your body.

```<code>body {
  min-width: 780px;
}
</code>```

If you want it to start zoomed out (as if viewport is 780px wide), use shrink-to-fit:

```<code><meta name="viewport" content="width=device-width, shrink-to-fit=yes">
</code>```

Body:
I've been working on making a few websites that force 1000px layouts to be more responsive. On one, it scales nicely down to ~500px and on another it scales nicely to 780px. My phone is 320px across and my tablet is around 1000x across. The problem is that:

If I don't set the viewport, both devices render the page ~1000px wide, so all of my nice scaling code gets completely ignored and the page is massive on the phone.

If I set <meta name="viewport" content="width=device-width">, the page renders perfectly, but it starts out extremely zoomed in on the phone (zoomed to show 320px of the layout).

If I set <meta name="viewport" content="width=780">, it renders and scales perfectly on the phone, but zooms in on the tablet (scaling the layout to 780px wide even though I have 1000px to work with).

I also tried a JavaScript workaround:

<meta id="viewport" name="viewport" content="width=device-width, initial-scale=1.0" />

This works in Chrome but not Firefox. I even tried using CSS transforms to scale the entire page on Firefox, but that leaves a bunch of whitespace around the scaled page (and is a terrible solution).

Is there a way to make devices render and scale to their width down to 500px, and then scale and render at 500px when their screen size is below that?

Body:
If your content should be at least 780px wide, set min-width on your body.

body {
  min-width: 780px;
}

If you want it to start zoomed out (as if viewport is 780px wide), use shrink-to-fit:

<meta name="viewport" content="width=device-width, shrink-to-fit=yes">


问:
Which css style has least effect on an element?
Today I was trying to create a dummy css rule for testing and investigation.

```<code>.dummy {
  some-style : somevalue;
}
</code>```

Ideally the class should have no visible effect.  I want to be able to apply the class to elements but cause the least visible effect possible on any elements it is applied to.  For example

 should look and behaves as much as possible like

I did not want the class to be empty.  Can anyone suggest a style that I could add to the class that would have the least visible impact when applied to a general html element?  I can't think of anything completely harmless.

UPDATE: I wanted to add the style to some existing html.  The reason was to use the style as a marker for diagnostic purposes.  It would help me see when and where styles and stylesheets were getting loaded/cached and where and why some styles were getting overridden, sometimes by the browser defaults which seemed odd.  At the time I didn't have exclusive use of the system I was working on so I wanted something that was going to be invisible to other users but I could see in Developer Tools.

UPDATE 2 : the html/css wasn't written by me and I didn't have my own environment in which to work. I was trying to investigate some problems in-situ in someone else's system.  I had tried using DevTools in the browser but wasn't getting anywhere with that.  I wanted to be able to make some small changes to their html/css to aid my diagnostics.  I didn't want them to have any obvious effect on the system for other people (except in DevTools, viewed by me).

It was a Wordpress site and they only had two environments, one for live and one for testing.  I was working with the test system.  There were other people testing at the time, though mainly checking content.

The real thorny problem was why was the font-size in the calendar widget much larger than everything else on the site?  Inspecting using DevTools I could see the font-size style was getting overridden by the browser default style when it seemed to me there were other css selectors that should have taken precedence.  It looked bizarre.  In the end it turned out to be a missing !DOCTYPE tag in the html.  So nothing to do with the css itself.

I didn't like this way of working, fiddling in someone's system, but there wasn't much else to do and it did help to resolve the problem for them.

Hopefully I don't have to do this again, but ever since I have been wondering what was the most harmless style that I could have used?

I thought I would ask here as there must be people who know CSS better than me.

答:
If you just need anything beeing set you could assign rules that are default anyway. For block elements like div set

```<code>.block-class { display: block; }
</code>```

And for inline elements like span

```<code>.inline-class { display: inline; }
</code>```

Of course it could be an issue doing so in some rare cases but in general it's quite harmless I guess.

Body:
Today I was trying to create a dummy css rule for testing and investigation.

.dummy {
  some-style : somevalue;
}

Ideally the class should have no visible effect.  I want to be able to apply the class to elements but cause the least visible effect possible on any elements it is applied to.  For example

 should look and behaves as much as possible like

I did not want the class to be empty.  Can anyone suggest a style that I could add to the class that would have the least visible impact when applied to a general html element?  I can't think of anything completely harmless.

UPDATE: I wanted to add the style to some existing html.  The reason was to use the style as a marker for diagnostic purposes.  It would help me see when and where styles and stylesheets were getting loaded/cached and where and why some styles were getting overridden, sometimes by the browser defaults which seemed odd.  At the time I didn't have exclusive use of the system I was working on so I wanted something that was going to be invisible to other users but I could see in Developer Tools.

UPDATE 2 : the html/css wasn't written by me and I didn't have my own environment in which to work. I was trying to investigate some problems in-situ in someone else's system.  I had tried using DevTools in the browser but wasn't getting anywhere with that.  I wanted to be able to make some small changes to their html/css to aid my diagnostics.  I didn't want them to have any obvious effect on the system for other people (except in DevTools, viewed by me).

It was a Wordpress site and they only had two environments, one for live and one for testing.  I was working with the test system.  There were other people testing at the time, though mainly checking content.

The real thorny problem was why was the font-size in the calendar widget much larger than everything else on the site?  Inspecting using DevTools I could see the font-size style was getting overridden by the browser default style when it seemed to me there were other css selectors that should have taken precedence.  It looked bizarre.  In the end it turned out to be a missing !DOCTYPE tag in the html.  So nothing to do with the css itself.

I didn't like this way of working, fiddling in someone's system, but there wasn't much else to do and it did help to resolve the problem for them.

Hopefully I don't have to do this again, but ever since I have been wondering what was the most harmless style that I could have used?

I thought I would ask here as there must be people who know CSS better than me.

Body:
If you just need anything beeing set you could assign rules that are default anyway. For block elements like div set

.block-class { display: block; }

And for inline elements like span

.inline-class { display: inline; }

Of course it could be an issue doing so in some rare cases but in general it's quite harmless I guess.


问:
Delete regex matches within loop and continue with updated string version
I have a string that I want to run through four wordlists, one with four-grams, one with tri-grams, one with bigrams and one with single terms. To avoid that a word of the single term wordlist gets counted twice when it also forms part of a bigram or trigrams for example, I start with counting for four-grams, then want to update the string in terms of removing the matches to only check the remaining part of the string for matches of trigrams, bigrams and single terms, respectively. I have used the following code and illustrate it here just starting with fourgrams and then trigrams:

```<code>financial_trigrams_count=0
financial_fourgrams_count=0

strn="thank you, john, and good morning, everyone. with me today is tim, our chief financial officer."

pattern_fourgrams=["value to the business", "car and truck sales"]
pattern_trigrams=["cash flow statement", "chief financial officer"]

for i in pattern_fourgrams:
    financial_fourgrams_count=financial_fourgrams_count+strn.count(i)

new_strn=strn
def clean_text1(pattern_fourgrams, new_strn):
    for r in pattern_fourgrams:
        new_strn = re.sub(r, '', new_strn)
    return new_strn

for i in pattern_trigrams:
    financial_trigrams_count=financial_trigrams_count+new_strn.count(i)

new_strn1=new_strn
def clean_text2(pattern_trigrams, new_strn1):
    for r in pattern_trigrams:
        new_strn1 = re.sub(r, '', new_strn1)
    return new_strn1

print(financial_fourgrams_count)
print(financial_trigrams_count)
word_count_wostop=len(strn.split())
print(word_count_wostop)
</code>```

For fourgrams there is not match, so new_strn will be similar to strn. However, there is one match with trigrams ("chief financial officer"), however, I do not succees in deleteing the match from new_strn1. Instead, I again yield the full string, namely strn (or new_strn which is the same).

Could someone help me find the mistake here?

答:
you need to remove def

```<code>import re
financial_trigrams_count=0
financial_fourgrams_count=0

strn="thank you, john, and good morning, everyone. with me today is tim, our chief financial officer."

pattern_fourgrams=["value to the business", "car and truck sales"]
pattern_trigrams=["cash flow statement", "chief financial officer"]

for i in pattern_fourgrams:
    financial_fourgrams_count=financial_fourgrams_count+strn.count(i)

new_strn=strn
for r in pattern_fourgrams:
    new_strn = re.sub(r, '', new_strn)

for i in pattern_trigrams:
    financial_trigrams_count=financial_trigrams_count+new_strn.count(i)

new_strn1=new_strn
for r in pattern_trigrams:
    new_strn1 = re.sub(r, '', new_strn1)

print(new_strn1)
print(financial_fourgrams_count)
print(financial_trigrams_count)
word_count_wostop=len(strn.split())
print(word_count_wostop)
</code>```

Body:
I have a string that I want to run through four wordlists, one with four-grams, one with tri-grams, one with bigrams and one with single terms. To avoid that a word of the single term wordlist gets counted twice when it also forms part of a bigram or trigrams for example, I start with counting for four-grams, then want to update the string in terms of removing the matches to only check the remaining part of the string for matches of trigrams, bigrams and single terms, respectively. I have used the following code and illustrate it here just starting with fourgrams and then trigrams:

financial_trigrams_count=0
financial_fourgrams_count=0

strn="thank you, john, and good morning, everyone. with me today is tim, our chief financial officer."

pattern_fourgrams=["value to the business", "car and truck sales"]
pattern_trigrams=["cash flow statement", "chief financial officer"]

for i in pattern_fourgrams:
    financial_fourgrams_count=financial_fourgrams_count+strn.count(i)

new_strn=strn
def clean_text1(pattern_fourgrams, new_strn):
    for r in pattern_fourgrams:
        new_strn = re.sub(r, '', new_strn)
    return new_strn

for i in pattern_trigrams:
    financial_trigrams_count=financial_trigrams_count+new_strn.count(i)

new_strn1=new_strn
def clean_text2(pattern_trigrams, new_strn1):
    for r in pattern_trigrams:
        new_strn1 = re.sub(r, '', new_strn1)
    return new_strn1

print(financial_fourgrams_count)
print(financial_trigrams_count)
word_count_wostop=len(strn.split())
print(word_count_wostop)

For fourgrams there is not match, so new_strn will be similar to strn. However, there is one match with trigrams ("chief financial officer"), however, I do not succees in deleteing the match from new_strn1. Instead, I again yield the full string, namely strn (or new_strn which is the same).

Could someone help me find the mistake here?

Body:
you need to remove def

import re
financial_trigrams_count=0
financial_fourgrams_count=0

strn="thank you, john, and good morning, everyone. with me today is tim, our chief financial officer."

pattern_fourgrams=["value to the business", "car and truck sales"]
pattern_trigrams=["cash flow statement", "chief financial officer"]

for i in pattern_fourgrams:
    financial_fourgrams_count=financial_fourgrams_count+strn.count(i)

new_strn=strn
for r in pattern_fourgrams:
    new_strn = re.sub(r, '', new_strn)

for i in pattern_trigrams:
    financial_trigrams_count=financial_trigrams_count+new_strn.count(i)

new_strn1=new_strn
for r in pattern_trigrams:
    new_strn1 = re.sub(r, '', new_strn1)

print(new_strn1)
print(financial_fourgrams_count)
print(financial_trigrams_count)
word_count_wostop=len(strn.split())
print(word_count_wostop)


问:
Object datasource or code-behind: which is better?
I know that it's a subject that can raise a lot of debate, but I'd like to know what people think the various pros and cons of using Object Datasources are. I'm doing a project right now with another programmer who's experience and comfort level are all rooted in classic ASP, and I'm unsure of which way is going to

a) get the job done quickly
b) get the job done with a minimum of fuss

We have a nice repository layer with domain objects capable of self-validation, so the methods are in place to do either the ODS binding, or code-behind binding.

I dislike the ODS for most of the obvious reasons, but if it does save me from having to hand-code paging/sorting/selecting/inserting/updating/deleting scenarios, then can it really be that bad?

答:
ObjectDatasource like any other xxxDatasource in WebForms is the coordinator between your Business Layer on large applications (or the Data Access Layer on smaller ones) and the controls themselves.

Its just providing data and other functionality to the visual part of your application, the User Interface driven by your views in your data store.

People should see these controls as requests and responses for UI stuff and stop misuse them or discard them completely. They are not the DAL, they are not evil, they are just connections to your datasources that controls know how to speak to very efficiently.

If you have for example, a grid of data that variates it's source based on a decision, then two ObjectDatasources should be configured and that decision should reside in the page, not the ObjectDatasource. This is the preferred way to use them and avoid the problems that people try to refer at other responses.


问:
Collecting the result of an iteration on one object in to a map with values from another object
This question is an extension to this. I have provided all the needed details here.

If I have 2 collections,

```<code>List<String> domainArr;
List<Person> personArr;
</code>```

I would like to make a minor transformation on each of the elements in the String and then iterate over the personArr to

```<code>List<String> urlArr = strArr.stream()
    .map(str -> "https://" + strArr)
    .collect(Collectors.toList());
</code>```

I have a method like

```<code>List<Person> getPersons(String url){
 /*makes a restful call to the url and gets a List of objects for each URL.*/
}
</code>```

I know from here that I can collect the results into a flattened list like

```<code>strArr.stream()
    .map(str -> getPersons("https://" + str))
    .flatMap(persons -> persons.stream())
    .filter(Objects::nonNull)
    .map(Person::getName)
    .filter(Objects::nonNull)
    .collect(Collectors.toList());
</code>```

I was wondering how get the result in a Map with key as the domainUrl and Value as a list of names obtained by transforming the result of that particular URL?

Say a map like,

```<code>URL1 -> [name1, name2]
URL2 -> [name3, name4]
</code>```

答:
For readability, you can define a separate method that extracts the list of names for a URL:

```<code>List<String> personNames(String url) {
    return getPersons(url).stream()
            .filter(Objects::nonNull)    // why would you return null persons?
            .map(Person::getName)
            .filter(Objects::nonNull)    // why would... nevermind! :)
            .collect(Collectors.toList());
}
</code>```

Then you can write:

```<code>strArr.stream()
        .map("https://"::concat)    // Your code here says `.map(str -> "https://" + strArr)`, which I suppose should be `.map(str -> "https://" + str)`
        .collect(Collectors.toMap(Function.identity(), this::personNames));
</code>```

Body:
This question is an extension to this. I have provided all the needed details here.

If I have 2 collections,

List<String> domainArr;
List<Person> personArr;

I would like to make a minor transformation on each of the elements in the String and then iterate over the personArr to

List<String> urlArr = strArr.stream()
    .map(str -> "https://" + strArr)
    .collect(Collectors.toList());

I have a method like

List<Person> getPersons(String url){
 /*makes a restful call to the url and gets a List of objects for each URL.*/
}

I know from here that I can collect the results into a flattened list like

strArr.stream()
    .map(str -> getPersons("https://" + str))
    .flatMap(persons -> persons.stream())
    .filter(Objects::nonNull)
    .map(Person::getName)
    .filter(Objects::nonNull)
    .collect(Collectors.toList());

I was wondering how get the result in a Map with key as the domainUrl and Value as a list of names obtained by transforming the result of that particular URL?

Say a map like,

URL1 -> [name1, name2]
URL2 -> [name3, name4]

Body:
For readability, you can define a separate method that extracts the list of names for a URL:

List<String> personNames(String url) {
    return getPersons(url).stream()
            .filter(Objects::nonNull)    // why would you return null persons?
            .map(Person::getName)
            .filter(Objects::nonNull)    // why would... nevermind! :)
            .collect(Collectors.toList());
}

Then you can write:

strArr.stream()
        .map("https://"::concat)    // Your code here says `.map(str -> "https://" + strArr)`, which I suppose should be `.map(str -> "https://" + str)`
        .collect(Collectors.toMap(Function.identity(), this::personNames));


问:
Please give some approach to achieve the data set for the following data set
In my table there is 5 distinct event 1,2,3,4,5. In attendee column there are attendees who attained these events. and in isThisuserHost column there is 0 and 1 flag. 1 for host who host the event and 1 for attendee who attain the event.I need to show the event where host is 2 and attendee is 4. In this table we can see that event 1,2,and 4 is those rows where host is 2 and attendee is 4. How to extract the result using a single query?

答:
You need a selfjoin here:

```<code>select h.eventId
from myTable h
join myTable a using(eventId)
where h.isTheuserHost = 1
  and a.isTheuserHost = 0
  and h.attendee = 2
  and a.attendee = 4
</code>```

h and a are different aliases for the same table. h stands for hoster and a for anttendee with the corresponding condition for the isTheuserHost column. Then you can use that table as if it were two.

Body:
You need a selfjoin here:

select h.eventId
from myTable h
join myTable a using(eventId)
where h.isTheuserHost = 1
  and a.isTheuserHost = 0
  and h.attendee = 2
  and a.attendee = 4

h and a are different aliases for the same table. h stands for hoster and a for anttendee with the corresponding condition for the isTheuserHost column. Then you can use that table as if it were two.


问:
Vue.js vue-video-player renders 100px wide
I have begun integrating vue-video-player. The player renders at only 100px wide. I don't know why or how to change it.

I have not been able to find anything in the documentation. In fact, the inclusion of css files was a little confusing and I'm uncertain if my import (versus the require in the docs) is correct.

How can I set the width of the player?

```<code><template>
    <div>
        <video-player
                ref="videoPlayer"
                :options="playerOptions"
                :playsinline="true"
        >
        </video-player>
    </div>
</template>

<script>
    import { videoPlayer } from 'vue-video-player'
    import 'video.js/dist/video-js.css'
    import 'vue-video-player/src/custom-theme.css'

    export default {
        name: 'foo',

        components: {
            videoPlayer,
        },

        data () {
            return {
                playerOptions: {
                    muted: true,
                    language: 'en',

                    playbackRates: [1.0],

                    sources: [{
                        type: "video/mp4",
                        src: "https://cdn.theguardian.tv/webM/2015/07/20/150716YesMen_synd_768k_vp8.webm"
                    }],

                    poster: "/static/images/defaults/image.png",
                }
            }
        },
    }
</script>
</code>```

答:
in the playerOptions set the width and height</p>

```<code> playerOptions: {
    // videojs options
    muted: true,
    language: 'en',
    techOrder: ['html5', 'flvjs'],
    playbackRates: [0.7, 1.0, 1.5, 2.0],
    width: '800px',
    height: '800px',
    plugins: {

    },
    flash: {
      swf: './#/assets/video-js.swf'
    },
    poster: './#/assets/logo.png',
    sources: [
    ]
  }
}
</code>```

Body:
I have begun integrating vue-video-player. The player renders at only 100px wide. I don't know why or how to change it.

I have not been able to find anything in the documentation. In fact, the inclusion of css files was a little confusing and I'm uncertain if my import (versus the require in the docs) is correct.

How can I set the width of the player?

<template>

        <video-player
                ref="videoPlayer"
                :options="playerOptions"
                :playsinline="true"
        >
        </video-player>

</template>

Body:
in the playerOptions set the width and height

 playerOptions: {
    // videojs options
    muted: true,
    language: 'en',
    techOrder: ['html5', 'flvjs'],
    playbackRates: [0.7, 1.0, 1.5, 2.0],
    width: '800px',
    height: '800px',
    plugins: {

    },
    flash: {
      swf: './#/assets/video-js.swf'
    },
    poster: './#/assets/logo.png',
    sources: [
    ]
  }
}