text:
Q: EF pre-generate view. How to be sure that these views are using by EF I have several performance issue in my website.
I'm using asp.net mvc 2 and Entity Framework 4.0. I bought a Entity Framework Profiler to see what kind of SQL request that EF generated.
By example, some page take between 3 and 5 seconds to open. This is to much for my client.
To see if it's a performance  problem with  SQL generated by EF, I used my profiler and Copy / Paste the generated SQL in Sql Management Studio to see the execution plan and the sql statistic. The result show in less than a second.

Now that I eliminated the SQL query, I suspect EF at buidling query step.
I Follow the msdn  step by step to pre-generate my view. I didn't see any performance gain.
How to be sure that my query use these Pre-Generated Views ?
Is there anything I can do to increase performance of my website ?
thanks

A: First of all, keep in mind that the pre-compiled queries still take just as long (in fact a little longer) the first time they are run, because the queries are compiled the first time they are invoked. After the first invocation, you should see a significant performance increase on the individual queries.
However, you will find the best answer to all performance questions is: figure out what's taking the most time first, then work on improving in that area. Until you have run a profiler and know where your system is blocking, any time you spend trying to speed things up is likely to be wasted.
Once you've determined what's taking the most time, there are a lot of possible techniques to use to speed things up:

*

*Caching data that doesn't change often

*Restructuring your data accesses so you pull the data you need in fewer round trips.

*Ensuring you're not pulling more data than you need when you do your database queries.

*Buying better hardware.

*... and many others

One last note: In Entity Framework 5, they plan to implement automatic query caching, which will make precompiling queries practically useless. So I'd only recommend doing it where you know for sure that you'll get a significant improvement.


text:
Q: Create S-57 chart on ARCGIS containing only shapefiles I have a requirement where a shapefile/files needs to be converted to S-57 ENC chart for use on ECDIS system. I am not working in GIS domain so dont necessary understand all technical bits and bobs involved.
Till now I have done following steps.
I have downloaded ARCGIS + Maritime Charting and Production mapping (Desktop 10.4.1) on trial basis. Please note that I dont have any ENC data to work on.
I have created a new file Geodatabase in Acrmap, Imported XML workspace data/schema from file "Nautical_chart_template_GX.xml".
I have carried out  steps to load the shapefiles under "UserdefinedfeaturesA", create AOI (using Feature builder) under "PL_ENC_AOI" setup scale to 10000000.
Start "New Nautical Product" wizard, which works without any errors.  But when creating ENC "Export Nautical product". The I am getting "Error - Nothing found 10000000" during Export process. Export log does not give much details.
I dont have any data inside other layers. Just PL_ENC_AOI to define AOI and "UserdefinedfeaturesA" with 3 sublayers contains data.
Can anyone guide me the right way to approach this issue.

redpajama_set_name: RedPajamaStackExchange


text:
Q: SQL - Strange issue with SELECT I have a strange situation with a simple select by column pqth_scan_code from the following table:
table pqth_
Field           Type         Null   Key     Default     Extra
pqth_id         int(11)      NO     PRI     NULL        auto_increment
pqth_scan_code  varchar(250) NO             NULL
pqth_info       text         YES            NULL
pqth_opk        int(11)      NO             999

query 1
This query took 12.7221 seconds to execute
SELECT * FROM `pqth_` WHERE pqth_scan_code = "7900722!30@3#6$EN"

query 2
This query took took 0.0003 seconds to execute
SELECT * FROM `pqth` WHERE `pqth_id`=27597

Based on data from table pqth_ I have created the following table, where pqthc_id = pqth_id and pqthc_scan_code=pqth_scan_code
table pqthc
Field           Type         Null   Key     Default     Extra
pqthc_id        int(11)      NO     PRI     NULL
pqthc_scan_code tinytext     NO             NULL

The same query ,query1, on table pqthc took 0.0259 seconds to run
SELECT * FROM `pqthc` WHERE pqthc_scan_code = "7900722!30@3#6$EN"

If I run the following query will took 0.0971 seconds, very strange.
query 3
SELECT * FROM `pqth` WHERE pqth_id = (SELECT pqthc_id From pqthc where pqthc_scan_code = "7900722!30@3#6$EN")

My question is why a SELECT by pqth_scan_code is slow and SELECT by pqth_id is fastest? Both columns are indexed.
For testing please get the export from this link
The same behavior is with MySQL and MariaDB server

A: SELECT * FROM `pqth_` WHERE pqth_scan_code = "7900722!30@3#6$EN"

needs INDEX(pqth_scan_code).  Period.  End of discussion.
SELECT * FROM `pqth` WHERE `pqth_id`=27597

has a useful index, since a PRIMARY KEY is an index (and it is unique).
SELECT * FROM `pqthc` WHERE pqthc_scan_code = "7900722!30@3#6$EN"

also needs INDEX(pqthc_scan_code).  But it may have been faster because (1) the table is smaller, or (2) you ran the query before, thereby caching what was needed in RAM.
Please don't prefix column names with the table name.
Please don't have table names so close to each other that they are hard to distinguish.  (pqth and pqthc)
SELECT  *
    FROM  `pqth`
    WHERE  pqth_id =
      ( SELECT  pqthc_id
            From  pqthc
            where  pqthc_scan_code = "7900722!30@3#6$EN"
      )

The construct IN ( SELECT ... ) is not efficient.
It is rare to have two table with the same PRIMARY KEY; are you sure you meant that?
Use a JOIN instead:
SELECT  a.*
    FROM  `pqth` AS a
    JOIN  pqthc AS c ON a.id = c.id
    where  c.scan_code = "7900722!30@3#6$EN"

If that is 'correct', then I recommend this 'covering' index:
INDEX(scan_code, id)

instead of the shorter INDEX(scan_code) I previously recommended.
More on indexing.

A: you have to understand the concept of primary key and indexes and how they help in searching,
reference docs here

A: First of all pqthc_scan_code has no index/key and pqthc_id does, keys help making searches faster.
Another difference is that pqthc_id is an integer where as pqthc_scan_code is a string. comparing integers is a lot more efficient than comparing strings.
You should avoid having to search on strings in really large tables.
You could add a index/key to pqthc_scan_code but i don't know how much it will help.
You can use EXPLAIN in fronto of your query to try and figure out what takes so long More info on EXPLAIN


text:
Q: different different height for each row in UITableView how to make the first three row height should be 60 and remaining row height should be 25 in UITableView.
How can i do this?
Thanks.

A: Check out this link you can get the idea how we have to do it
different-height-for-alternative-cell-in-uitableview
or you can use the below delegate function
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
     if (indexPath.row < 3)
     {
        return 60;
     }
     else
     {
        return 25;
     }
}

HAppy Coding...


text:
Q: pandas Add html tables values where data is int I am getting html table based on day so if I search for 20 days it brings me 20 table and I want to add all 20 tables in 1 table so I can verify data within time series.
I have tried merge and add functions of pandas but it just add as string.
Table one
[['\xa0', 'All Issues', 'Investment Grade', 'High Yield', 'Convertible'],
 ['Total Issues Traded', '8039', '5456', '2386', '197'],
 ['Advances', '3834', '2671', '1075', '88'],
 ['Declines', '3668', '2580', '994', '94'],
 ['Unchanged', '163', '54', '99', '10'],
 ['52 Week High', '305', '100', '193', '12'],
 ['52 Week Low', '152', '83', '63', '6'],
 ['Dollar Volume*', '27568', '17000', '9299', '1269']]

table two
[['\xa0', 'All Issues', 'Investment Grade', 'High Yield', 'Convertible'],
 ['Total Issues Traded', '8039', '5456', '2386', '197'],
 ['Advances', '3834', '2671', '1075', '88'],
 ['Declines', '3668', '2580', '994', '94'],
 ['Unchanged', '163', '54', '99', '10'],
 ['52 Week High', '305', '100', '193', '12'],
 ['52 Week Low', '152', '83', '63', '6'],
 ['Dollar Volume*', '27568', '17000', '9299', '1269']]

code but it add as string.
tab_data = [[item.text for item in row_data.select("th,td")]
                   for row_data in tables.select("tr")]
df = pd.DataFrame(tab_data)
df2 = pd.DataFrame(tab_data)
df3 = df.add(df2,fill_value=0)
df

A: The way you are converting the data frame treats all values as text.
There are two options here.

*

*Explicitly convert the strings to the data type you want using astype

*Use read_html to create data frames from html tables, which also tries to do the data type conversion.

A: If you want to convert the numeric cells into integers, you would need to do that explicitly, as follows:
tab_data = [[int(item.text) if item.text.isdigit() else item.text
                            for item in row_data.select("th,td")]
                            for row_data in tables.select("tr")]

Hope it helps.


text:
Q: Inject dll process Подскажите каким способом еще возможно заинжектить dll .net кроме mono?
Нужно чтобы dll загрузилась и выполнила void Loader из Class Initialize.
Нужно это для того,чтобы с сервера загружать в клиент dll и далее уже инжектить в Assambly лист

A: Вручную.
Ну во-первых надо чтобы клиент тыкнул в окошко UAC, когда будет запускаться инъектор (иначе открывать чужой процесс с правами на чтение-запись-создание удаленного потока как минимум ему не дадут).
Во-вторых, ниже я привожу нужный вам код. На C# писать будет тяжеловато, придется делать dllimport для нужных системных вызовов, мучаться с типами и т.д., я бы написал код на Си, собрал в dll и подключал эту dll к проекту на шарпе.
Портянка нужного вам кода на сишке + винапи в общем тривиальна:
* Здесь и далее код с функциями винапи в скобках, описывающий ход решения *
Получить имя процесса, в который вы будете внедряться;
Получить снимок процессов скажем CreateToolHelp32Snapshot
(это функция-обертка над NtQuerySystemInformation, так что решайте, использовать её или нет. но я бы использовал);
Пробегая по полученному списку процессов (для этого есть Process32Next), найти нужный по имени;
Сделать себе SeDebugPrivilege (процессу инъектора, это необязательный пункт);
Открыть найденный процесс с правами на запись в память и создание удаленного потока (OpenProcess, нужные флаги выглядят так: PROCESS_CREATE_THREAD | PROCESS_VM_WRITE);
Далее потребуется некая предварительная подготовка.
Получите адрес kernel32.dll:LoadLibrary в инъекторе, и этот же адрес (по крайней мере для 32бит систем, в 64бит придется еще обходить/отключать ASLR) будет в чужом процессе также указывать на kernel32.dll.
Получите абсолютный путь до своей dll. В моем случае dll лежит в папке с инъектором, так что я делаю GetModuleFileName в инъекторе, получившийся путь парсю с конца до первого вхождения '\' и вставляю "\myDll.dll".
Выделите память в чужом адресном пространстве (VirtualAllocEx), вам нужна память под адрес своей dll.
Запишите туда адрес своей dll (WriteProcessMemory).
Создайте и запустите удаленный поток (CreateRemoteThread), в аргументах у него должен лежать адрес kernel32.dll:LoadLibrary, и указатель на строку с путем до dll - не в вашем процессе, а то что вернула VirtualAllocEx, она возвращает адрес в чужом адресном пространстве.
Удаленный поток вызовет в чужом процессе LoadLibrary, та загрузит вашу DLL, DLL выполнит свою точку входа. Задача решена.


text:
Q: Rally: Unable to update custom field using Java I am trying to update a custom field on test case, here's my code:
JsonObject update_story = new JsonObject();
update_story.addProperty("c_UTMSURI",url); //url is a string
UpdateRequest updateReq = new UpdateRequest(ref,update_story);
try{
        UpdateResponse response = rest.update(update);
        return (response.wasSuccessful());
    }
catch(Exception e){
        String errorMsg = "Caught exception while updating external ID for "+ref+"\n More Details "+e.getMessage();
        Logger.Log(errorMsg);
        System.out.println(errorMsg);
        return false;
    }

I am confused because this code was working fine till a couple of days back and now the script just breaks and gets me this error:
Exception in thread "main" java.lang.NoSuchMethodError: org.apache.http.client.utils.URLEncodedUtils.parse(Ljava/lang/String;Ljava/nio/charset/Charset;)Ljava/util/List;

A: If these are the external jars that you have:
httpcore-4.2.4.jar
httpclient-4.2.5.jar
commons-logging-1.1.1.jar
commons-codec-1.6.jar
gson-2.2.4.jar
rally-rest-api-2.0.4.jar

this list matches what I have in my project.
For example in Eclipse there are Access Rules for external libraries. If your IDE has something similar are there restrictions on access? This error may indicate a wrong version of httpclient library or some conflict.
Have you tested the following?

*

*different value for the same custom field, e.g. Rally host url, as in the code below.

*other custom fields of type string

*other custom fields of any type

*any fields

I tried with the code below and a custom field of type string was updated successfully.
import com.google.gson.JsonObject;
import com.rallydev.rest.RallyRestApi;
import com.rallydev.rest.request.CreateRequest;
import com.rallydev.rest.request.UpdateRequest;
import com.rallydev.rest.response.CreateResponse;
import com.rallydev.rest.response.UpdateResponse;
import com.rallydev.rest.util.Ref;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

public class CreateUpdateTC {

    public static void main(String[] args) throws URISyntaxException, IOException {

            String url = "https://rally1.rallydev.com";
            String username = "user@co.com";
            String password = "secret";
            String projectRef = "/project/12345";
            String applicationName = "create update test case";

        RallyRestApi restApi = new RallyRestApi(
                new URI(url),
                username,
                password);
        restApi.setApplicationName(applicationName);

        try {
            for (int i=0; i<1; i++) {
                System.out.println("Creating a test case...");
                JsonObject newTC = new JsonObject();
                newTC.addProperty("Name", "some testcase");
                newTC.addProperty("Project", projectRef);

                CreateRequest createRequest = new CreateRequest("testcase", newTC);
                CreateResponse createResponse = restApi.create(createRequest);
                if (createResponse.wasSuccessful()) {

                    System.out.println(String.format("Created %s", createResponse.getObject().get("_ref").getAsString()));

                    //Read tc
                    String tcRef = Ref.getRelativeRef(createResponse.getObject().get("_ref").getAsString());
                    System.out.println(String.format("\nReading test case %s...", tcRef));
                    //Update tc
                    JsonObject tcUpdate = new JsonObject();
                    tcUpdate.addProperty("c_CustomString", url);
                    UpdateRequest updateRequest = new UpdateRequest(tcRef,tcUpdate);
                    UpdateResponse updateResponse = restApi.update(updateRequest);
                    if (updateResponse.wasSuccessful()) {
                        System.out.println("Successfully updated test case: " + newTC.get("Name") +
                                " CustomString: " + tcUpdate.get("c_CustomString"));
                    }
                    else {
                        String[] updateErrors;
                        updateErrors = createResponse.getErrors();
                        System.out.println("Error");
                        for (int j=0; i<updateErrors.length;j++) {
                            System.out.println(updateErrors[j]);
                        }
                    }

                } else {
                    String[] createErrors;
                    createErrors = createResponse.getErrors();
                    System.out.println("Error");
                    for (int j=0; i<createErrors.length;j++) {
                        System.out.println(createErrors[j]);
                    }
                }
            }

        } finally {
            //Release all resources
            restApi.close();
        }

}

}

A: Thanks @nickm . The problem was that my tool was adding another lbapi jar file on run time. This was causing the problem. The update goes through now. Thanks for your help.


text:
Q: How to prevent saved credentials to autopopulate user creation form? It happens in Django Admin, but I assume it's a browser's behavior (though it happens, at least, in Chrome and Firefox):
When a user saves his credentials in browser, it autopopulates the login form. This is ok. But it also autopopulates the user creation form, filling the username and password fields. As it happens in Django Admin, I think I can change the template field names, but then I have to change the user creation workflow and that's not what I want.
It happens too in Change Password Form, filling the Old Password Field. This situation is a security hole, since a user can change other user's password if first user left opened his session.
Is there any option to say it to the browser that I don't want to fill a form other than changing the field name?

A: You would have to edit each form element, but here's how you do it
<input name="q" type="text" autocomplete="off"/>


text:
Q: Can I do pointer arithmetic on an STL::map::iterator How to correctly use pointer arithmetics for stl::map::iterator ?
In example bellow I create stl::map and stl::map::iterator and try to access iterator second key by increasing the iterator.
#include <iostream>
#include <map>

using namespace std;

int main() {

    map <string, string> peoples;

    peoples["paul"] = "friend";
    peoples["galactus"] = "foe";

    map<string, string>::iterator my_iter = ++peoples.begin();

    cout << my_iter->first << endl;

    return 0;
}

When ++peoples.begin(); is used compilation is OK, but if  1 + peoples.begin(); is used, error is raised.
Question stands: How to use pointer arithmetics on stl::map::iterator ?
And are there any containers with similar difficulties, while I know that with stl::vector::iterator you can use pointer arithmetics?

A:
Can I do pointer arithmetic on an STL::map::iterator

No. You can't do pointer arithmetic on iterators, since iterators are (in general) not pointers.
If you take a look at the documentation, you'll find that map::iterator is a bidirectional iterator. You'll also find that bidirectional iterators do not support addition operator.
You can find n'th successor of an iterator by applying the increment operator n times. There are standard algorithms for this as well: next and advance.

I know that with stl::vector::iterator you can use pointer arithmetics?

vector::iterator is a random access iterator. Those support addition operator.

PS. The original STL wasn't in a namespace, and the standard library is in the namespace std; not stl.


text:
Q: How to SELECT DISTINCT Info with TOP 1 Info and an Order By FROM the Top 1 Info I have 2 tables, that look like:
CustomerInfo(CustomterID, CustomerName)
CustomerReviews(ReviewID, CustomerID, Review, Score)

I want to search reviews for a string and return CustomerInfo.CustomerID and CustomerInfo.CustomerName. However, I only want to show distinct CustomerID and CustomerName along with just one of their CustomerReviews.Reviews and CustomerReviews.Score. I also want to order by the CustomerReviews.Score.
I can't figure out how to do this, since a customer can leave multiple reviews, but I only want a list of customers with their highest scored review.
Any ideas?

A: This is the greatest-n-per-group problem that has come up dozens of times on Stack Overflow.
Here's a solution that works with a window function:
WITH CustomerCTE (
  SELECT i.*, r.*, ROW_NUMBER() OVER (PARTITION BY CustomerID ORDER BY Score DESC) AS RN
  FROM CustomerInfo i
  INNER JOIN CustomerReviews r ON i.CustomerID = r.CustomerID
  WHERE CONTAINS(r.Review, '"search"')
)
SELECT * FROM CustomerCTE WHERE RN = 1
ORDER BY Score;

And here's a solution that works more broadly with RDBMS brands that don't support window functions:
SELECT i.*, r1.*
FROM CustomerInfo i
INNER JOIN CustomerReviews r1 ON i.CustomerID = r1.CustomerID
  AND CONTAINS(r1.Review, '"search"')
LEFT OUTER JOIN CustomerReviews r2 ON i.CustomerID = r2.CustomerID
  AND CONTAINS(r1.Review, '"search"')
  AND (r1.Score < r2.Score OR r1.Score = r2.Score AND r1.ReviewID < r2.ReviewID)
WHERE r2.CustomerID IS NULL
ORDER BY Score;

I'm showing the CONTAINS() function because you should be using the fulltext search facility in SQL Server, not using LIKE with wildcards.

A: I voted for Bill Karwin's answer, but I thought I'd throw out another option.
It uses a correlated subquery, which can often incur performance problems with large data sets, so use with caution.  I think the only upside is that the query is easier to immediately understand.
select *
from [CustomerReviews] r
where [ReviewID] =
(
    select top 1 [ReviewID]
    from [CustomerReviews] rInner
    where rInner.CustomerID = r.CustomerID
    order by Score desc
)
order by Score desc

I didn't add the string search filter, but that can be easily added.

A: I think this should do it
select ci.CustomterID, ci.CustomerName, cr.Review, cr.Score
from CustomerInfo ci inner join
(select top 1*
from CustomerReviews
where Review like '%search%'
order by Score desc) cr on ci.CustomterID = cr.CustomterID
order by cr.Score


text:
Q: Как обойти xml дерево и сформировать новое дерево для Html? У меня есть xml код
<?xml version="1.0" encoding="UTF-8" standalone="true"?>

-<w:document mc:Ignorable="w14 w15 w16se wp14" xmlns:wps="http://schemas.microsoft.com/office/word/2010/wordprocessingShape" xmlns:wne="http://schemas.microsoft.com/office/word/2006/wordml" xmlns:wpi="http://schemas.microsoft.com/office/word/2010/wordprocessingInk" xmlns:wpg="http://schemas.microsoft.com/office/word/2010/wordprocessingGroup" xmlns:w16se="http://schemas.microsoft.com/office/word/2015/wordml/symex" xmlns:w15="http://schemas.microsoft.com/office/word/2012/wordml" xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml" xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:w10="urn:schemas-microsoft-com:office:word" xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" xmlns:wp14="http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:cx="http://schemas.microsoft.com/office/drawing/2014/chartex" xmlns:wpc="http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas">

-<w:body>

-<w:p w:rsidP="00D1536E" w:rsidRDefault="003161A0" w:rsidRPr="006C4437" w:rsidR="00113F3B">

-<w:pPr>

<w:pStyle w:val="a3"/>

-<w:numPr>

<w:ilvl w:val="0"/>

<w:numId w:val="6"/>

</w:numPr>

</w:pPr>

-<w:r>

<w:t>Первый</w:t>

</w:r>

</w:p>

-<w:p w:rsidP="00D1536E" w:rsidRDefault="003161A0" w:rsidRPr="006C4437" w:rsidR="006C4437">

-<w:pPr>

<w:pStyle w:val="a3"/>

-<w:numPr>

<w:ilvl w:val="0"/>

<w:numId w:val="6"/>

</w:numPr>

</w:pPr>

-<w:r>

<w:t>Первый</w:t>

</w:r>

</w:p>

-<w:p w:rsidP="00D1536E" w:rsidRDefault="003161A0" w:rsidRPr="006C4437" w:rsidR="006C4437">

-<w:pPr>

<w:pStyle w:val="a3"/>

-<w:numPr>

<w:ilvl w:val="1"/>

<w:numId w:val="6"/>

</w:numPr>

</w:pPr>

-<w:r>

<w:t>Второй</w:t>

</w:r>

</w:p>

-<w:p w:rsidP="00D1536E" w:rsidRDefault="003161A0" w:rsidRPr="00200659" w:rsidR="006C4437">

-<w:pPr>

<w:pStyle w:val="a3"/>

-<w:numPr>

<w:ilvl w:val="1"/>

<w:numId w:val="6"/>

</w:numPr>

</w:pPr>

-<w:r>

<w:t>Второй</w:t>

</w:r>

</w:p>

-<w:p w:rsidP="00D1536E" w:rsidRDefault="003161A0" w:rsidRPr="00200659" w:rsidR="00200659">

-<w:pPr>

<w:pStyle w:val="a3"/>

-<w:numPr>

<w:ilvl w:val="1"/>

<w:numId w:val="6"/>

</w:numPr>

</w:pPr>

-<w:r>

<w:t>Второй</w:t>

</w:r>

</w:p>

-<w:p w:rsidP="00D1536E" w:rsidRDefault="003161A0" w:rsidRPr="00200659" w:rsidR="00200659">

-<w:pPr>

<w:pStyle w:val="a3"/>

-<w:numPr>

<w:ilvl w:val="2"/>

<w:numId w:val="6"/>

</w:numPr>

</w:pPr>

-<w:r>

<w:t>Третий</w:t>

</w:r>

</w:p>

-<w:p w:rsidP="00D1536E" w:rsidRDefault="003161A0" w:rsidRPr="00200659" w:rsidR="00200659">

-<w:pPr>

<w:pStyle w:val="a3"/>

-<w:numPr>

<w:ilvl w:val="2"/>

<w:numId w:val="6"/>

</w:numPr>

</w:pPr>

-<w:r>

<w:t>Третий</w:t>

</w:r>

</w:p>

-<w:p w:rsidP="003161A0" w:rsidRDefault="003161A0" w:rsidRPr="003161A0" w:rsidR="003161A0">

-<w:pPr>

<w:pStyle w:val="a3"/>

-<w:numPr>

<w:ilvl w:val="2"/>

<w:numId w:val="6"/>

</w:numPr>

</w:pPr>

-<w:r>

<w:t>Третий</w:t>

</w:r>

</w:p>

<w:p w:rsidP="003161A0" w:rsidRDefault="003161A0" w:rsidR="003161A0"/>

-<w:p w:rsidP="003161A0" w:rsidRDefault="003161A0" w:rsidR="003161A0">

-<w:r>

<w:t>Текст</w:t>

</w:r>

</w:p>

-<w:p w:rsidP="003161A0" w:rsidRDefault="003161A0" w:rsidR="003161A0">

-<w:r>

<w:t>Текст</w:t>

</w:r>

</w:p>

-<w:p w:rsidP="003161A0" w:rsidRDefault="003161A0" w:rsidR="003161A0">

-<w:r>

<w:t>Текст</w:t>

</w:r>

<w:bookmarkStart w:name="_GoBack" w:id="0"/>

<w:bookmarkEnd w:id="0"/>

</w:p>

<w:p w:rsidP="003161A0" w:rsidRDefault="003161A0" w:rsidRPr="00255B60" w:rsidR="003161A0"/>

-<w:sectPr w:rsidRPr="00255B60" w:rsidR="003161A0">

<w:pgSz w:w="11906" w:h="16838"/>

<w:pgMar w:gutter="0" w:footer="708" w:header="708" w:left="1701" w:bottom="1134" w:right="850" w:top="1134"/>

<w:cols w:space="708"/>

<w:docGrid w:linePitch="360"/>

</w:sectPr>

</w:body>

</w:document>

Как мне его обойти и сформировать дерево для формирования html текста? Использую OpenXMl


text:
Q: Spacy regex over entities How can you use in Spacy v2 the usual regex functionality but over named entities and POS?
It seems that the full syntax of the Matcher's patterns is not available.
Only scattered examples like the following are available
[{'LOWER': 'facebook'}, {'LEMMA': 'be'}, {'POS': 'ADV', 'OP': '*'}, {'POS': 'ADJ'}]

What I need is to allow for an arbitrary number of repetions of a group.
In the example below assume color as an entity and I only know Red is a color.
"Red, green and black" , "Red, white, green and black"

I need to recognize green, black, white as color entities as well since I know red is a color entity and whatever follows it by comma is also a color.
Atm i do it like this but it works only for a certain number of commas, not for an arbitrary number:
 pattern = [{'ent_type': 'Color'}, {'IS_PUNCT': True}, {'POS': 'NOUN'}, {'IS_PUNCT': True}, {'POS': 'NOUN'}, {'POS': 'CCONJ'},{'POS': 'NOUN'}]
 matcher.add('commas', add_event_skill, pattern)

In a more advanced version of my question, red would be allowed to be in any position of the sentencne, not only the first.


text:
Q: R - convert images filenames to integers I have a dataset with 3 columns. One is a column with numbered filenames. Here's a subset:
File_Name
000000079.png
000000082.png
000000083.png
000000089.png
000000090.png
...

I would like to add a new integer column that simply has the number of each filename. For example:
File_Number
79
82
83
89
90
...

A: This is possible using the extract_numeric function from TidyR or readr::parse_number().
# First, create a character vector from the column with your filenames.

File_Name <- df$File_Name

# Extract numbers

library(tidyr)
df$File_Numbers <- extract_numeric(File_Name)

Using readr::parse_number().
# First, create a character vector from the column with your filenames.

File_Name <- df$File_Name

# Extract numbers

library(readr)
df$File_Numbers <- parse_number(File_Name)


text:
Q: how to import package from github I'm trying to build a api using Go and I tried running a existing file from GitHub that I got from udemy course. I'm getting this kind of output:
C:\goworkspace\src\grpc-go-course-master\blog\blog_client>go run client.go
client.go:4:2: cannot find package "context" in any of:
        C:\go\src\context (from $GOROOT)
        C:\goworkspace\src\context (from $GOPATH)
..\..\..\golang.org\x\net\http2\not_go111.go:10:2: cannot find package "net/http/httptrace" in any of:
        C:\go\src\net\http\httptrace (from $GOROOT)
        C:\goworkspace\src\net\http\httptrace (from $GOPATH)

Could you suggest me what can cause this error?

A: In order to download the dependencies, you have to use the go get command:
go get -v -u github.com/alessiosavi/GoUtils

Change with the package that you need (in that repo you can find a bunch of 'utils' method).
If the project, instead, have the go.mod file, you have to type:
go clean
go build

By this way you are going to install the dependencies listed in the go.mod file.
For update the dependencies to the latest version:
go get -v -u all

A: go mod tidy

The above command looks for missing dependencies, adds them to go.mod, and installs them.


text:
Q: What's the commended way to organize and load svg files as part of an R package? I have an R package that generates a PDF and I'd like to include some external SVG images as part of the generated reports e.g. SVG country flags. What is the commended way to organize it i.e. where to place the external images by convention? e.g. inst\extdata\svg or? from the R package how do you access these files?
Assuming that the resource SVG image's path is accessible from my R package I would do the following (using this excellent Rlogo.html article as reference):
library(grImport2)
library(ggplot2)

myImage <- readPicture("image.svg")
myImageGrob <- gTree(children=gList(pictureGrob(myImage)))

ggplot(mtcars) + geom_point(aes(x=disp, y=mpg)) + annotation_custom(myImageGrob)


text:
Q: How Do You create a .net application with no UI How Do You create a .net application with no UI.  How would I go about doing this?  I don't want it to be a console application.  The best choice would seem to be a winform application that never calls application.run.
The goal of the app is to be run and do a simple task. say check a server for an update or copy files.  Nothing long running where a windows service would be necessary.

A: It appears you answered your own question.  Never call application.Run.  In doing so you never instantiate a form, meaning the user never see's anything.
However if you're looking for an application to run in the background, you may be looking for a Windows Service application.  Of which you can create one of these using the project template in Visual Studio

A: If Windows Service isn't an option, you can simply create an empty project (or console app) and set the compiler target to Windows Application in the project properties (/t:winexe command line option). This is essentially equivalent to your own proposal.
The whole point is, /t:winexe sets the subsystem flag in the generated binary to a Windows executable so that the command prompt is not shown when the app is executed.

A: This might work for you.
http://expsharing.blogspot.com/2008/03/hideshow-console-window-in-net-black.html

A: You are looking for a Windows Service. Windows services start when the system starts, and run in the background without any kind of UI. One caveat, they must be installed to start up, and debugging can be a little tricky. Visual Studio provides a Windows Service project template that can get you started.

A: Another fairly straightforward way of doing this is to create a winform application and Hide the form in its OnLoad method.


text:
Q: How to wait for sms send confirmation and then send next sms Android I had to send 5-10 messages using,
 SmsManager smsManager= SmsManager.getDefault();
                smsManager.sendTextMessage(phoneNo,null,messageTosend,null,null);

but condition is that i need to confirm each message send success so that i can proceed further sending rest of messages and so on till all.
I know how to listen for success using broadcast Receiver but don't know how to pause further message sending till broadcast notification.
 final BroadcastReceiver sendSMS = new BroadcastReceiver() {
                @Override
                public void onReceive(Context arg0, Intent arg1) {
                    switch (getResultCode()) {
                        case Activity.RESULT_OK:
                            break;
                        case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                            Toast.makeText(getContext(), "Generic failure",
                                    Toast.LENGTH_SHORT).show();
                            break;
                        case SmsManager.RESULT_ERROR_NO_SERVICE:
                            Toast.makeText(getContext(), "No service",
                                    Toast.LENGTH_SHORT).show();
                            break;
                        case SmsManager.RESULT_ERROR_NULL_PDU:
                            Toast.makeText(getContext(), "Null PDU",
                                    Toast.LENGTH_SHORT).show();
                            break;
                        case SmsManager.RESULT_ERROR_RADIO_OFF:
                            Toast.makeText(getContext(), "Radio off",
                                    Toast.LENGTH_SHORT).show();
                            break;
                    }
                }
            };

How to suspend execution of sendsms code till first sending of sms is a success?

A: private boolean isChecked = true;
final BroadcastReceiver sendSMS = new BroadcastReceiver() {
                @Override
                public void onReceive(Context arg0, Intent arg1) {
                    while(isChecked == true){
                    switch (getResultCode()) {
                        case Activity.RESULT_OK:
                            break;
                        case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                            Toast.makeText(getContext(), "Generic failure",
                                    Toast.LENGTH_SHORT).show();
                            isChecked = false;
                            break;
                        case SmsManager.RESULT_ERROR_NO_SERVICE:
                            Toast.makeText(getContext(), "No service",
                                    Toast.LENGTH_SHORT).show();
                            isChecked = false;
                            break;
                        case SmsManager.RESULT_ERROR_NULL_PDU:
                            Toast.makeText(getContext(), "Null PDU",
                                    Toast.LENGTH_SHORT).show();
                            isChecked = false;
                            break;
                        case SmsManager.RESULT_ERROR_RADIO_OFF:
                            Toast.makeText(getContext(), "Radio off",
                                    Toast.LENGTH_SHORT).show();
                            isChecked = false;
                            break;
                    }
                    }
                }
            };

Create a while for cheaking if the message is correct and you want to continue, or if it is false.


text:
Q: create .dll in windows for tcl/tk starkit I have a .so(for example abc.so) file created using swig in unix which i am abe to load in the tcl program using 'load abc.so'. I plan to run the tcl program in windows, therefore need to create a corresponding abc.dll file which can be loaded similarly. Kindy guide the procedure to achieve this. Thanks!

A: If you're preparing a Tcl extension in a DLL to go into a starkit, the main thing you need to do is to make sure that the extension is built in stubs enabled mode. There are several parts to this:

*

*You need to define the C symbol USE_TCL_STUBS when compiling the code. If you're also using the Tk API — less common, but might be true given your description — you also need to specify USE_TK_STUBS. These symbols are often best specified using compiler options, and specifying them causes Tcl to rewrite virtually all API function calls into stubbed calls.

*You need to call Tcl_InitStubs as the first step of your extension's init function, and if you're using the Tk API then you call Tk_InitStubs as the second step. These two calls initialise the binding of the stubbed API calls so that they point to something real. Note that these API calls are also safe to use when your extension is not built in stubbed mode.

*You need to link against the Tcl (and possibly the Tk) stubs library, which is a static library. This provides the implementation of the stubbed calls (so that they call into the implementations inside the host Tcl interpreter) and the initialisation function(s).
This is all necessary because in a starkit (just as in many other wrapping technologies) the Tcl API is not implemented by the usual Tcl DLL. Instead, the Tcl code is statically linked into an executable and the name of that executable isn't safely knowable at extension build time; using stubbed calls avoids binding the literal name of the library into your code, and that's the cause of what goes wrong when you don't use stubs.

NB: Only Tcl/Tk extensions can be stub-enabled (unless the code to do the work is duplicated and reused) since the binding mechanism depends on having a Tcl interpreter context to convey the API descriptor structure references to the right places. Non-extension libraries require other, significantly more advanced techniques to work from a packaged environment (and the simplest way of dealing with them is often to bind them statically to a DLL that contains a Tcl extension, virtually always the DLL that contains the relevant Tcl binding layer for making an extension that uses the functionality).


text:
Q: How to implement Newton's Identities I need to produce identities related to Newton's Identities of arbitrary order. More specifically, I need the identities in the following image for an arbitrary n:

What I can't quite wrap my head around is how to work with expressions in Mathematica where I don't know how many variables are involved. Is there a way to programatically create subscripted variables on the fly? So, basically, looking for help getting started.

A: Format[p[x_] := Subscript[p, x]];
Format[e[x_] := Subscript[e, x]];
Table[p[k] == (-1)^(k - 1) e[k] k +
    Sum[(-1)^(k - 1 + i) e[k - i] p[i], {i, 1, k - 1}], {k, 1,
   10}] // Column

$$\begin{array}{l}
 p_1=e_1 \\
 p_2=e_1 p_1-2 e_2 \\
 p_3=-e_2 p_1+e_1 p_2+3 e_3 \\
 p_4=e_3 p_1-e_2 p_2+e_1 p_3-4 e_4 \\
 p_5=-e_4 p_1+e_3 p_2-e_2 p_3+e_1 p_4+5 e_5 \\
 p_6=e_5 p_1-e_4 p_2+e_3 p_3-e_2 p_4+e_1 p_5-6 e_6 \\
 p_7=-e_6 p_1+e_5 p_2-e_4 p_3+e_3 p_4-e_2 p_5+e_1 p_6+7 e_7 \\
 p_8=e_7 p_1-e_6 p_2+e_5 p_3-e_4 p_4+e_3 p_5-e_2 p_6+e_1 p_7-8 e_8 \\
 p_9=-e_8 p_1+e_7 p_2-e_6 p_3+e_5 p_4-e_4 p_5+e_3 p_6-e_2 p_7+e_1 p_8+9 e_9 \\
 p_{10}=e_9 p_1-e_8 p_2+e_7 p_3-e_6 p_4+e_5 p_5-e_4 p_6+e_3 p_7-e_2 p_8+e_1 p_9-10 e_{10} \\
\end{array}$$

A: It's not clear whether you need just a display or formal expression or an actual recursive function. I'll assume the latter.
p[1] = e[1];
p[n_] :=
  Simplify[
    Sum[e[i]*p[n - i]*(-1)^(1 + i), {i, 1, n - 1}] +
    n*e[n]*(-1)^(1 + n)]

This was just a matter of coming up with an expression for p[n] that matched the pattern provided. I didn't try to simplify it any. The Simplify just forces the terms to be combined. You should test to verify it actually matches your expectation--it looks correct to me for a small set of terms.
Now, you mentioned subscripts. Subscripts are just notation, so a formal expression like e[4] can be interpreted as equivalent to a subscripted e. However, if you really want to see subscripts you can use this:
Format[e[n_]] := Subscript[e, n]

Execute the above before evaluating any specific p, and then you should see the nicely subscripted format when you do evaluate a specific p. Understand that this will just affect the display. The actual expressions will still use things like e[5].
Since you provided the fully expanded expression on the far right hand side (the ones with just e and no p), then I'm assuming that you don't need to keep the intermediate form with p. If you do need that form, then we'd need to come up with something slightly different.


text:
Q: checking if windows update or any installer instace is running before starting my installer( java) want to make a check in my installer before starting installation if any other installation is running beforehand. Like I want to make a check if windows update or any other installer is running i'll not start my installer.
I'm planning to check if any msiexec instance is running before hand. Is there any better approach, and will that be same for checking windows update. FYI my installer is in java

A: You should know that msiexec.exe will still be running for a couple of minutes after an installation is finished. This is a default behavior in the OS, it keeps the process alive for a couple of minutes, in case the user will start another installation, to save time from starting it all over again. So checking for the process could give you incorrect data.
Also, if you have your installer written in Java can you please explain why do you need to check for msiexec.exe processes?

A: Since your installer is in Java, I see no reason to check whether other installers are running, moreover there's no robust way to do so.
Does your installer try to replace system files? It should not.
Does your installer try to update a file in use? It must do it gracefully. And ask user to close an offending application; if it's not possible or user does not want to close the application right away, your installer asks user to restart the system when it completed installation.
Too much to care about, without other installers running. That's why it's wiser to use a specialized installer tool.

A: To check the OS for installations in progress you can use the following registry entry:
HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Installer\InProgress
Please note that Windows Installer does not allow multiple InstallExecuteSequences to be executed simultaneously, however you can launch multiple installation UIs from different packages. The package enters InstallExecuteSequence usually at the moment you press "Install" and grant all the permissions for starting the system changes (creating registry, copying files, etc...).
Here you can find more information about InstallUISequence and InstallExecuteSequence:
http://msdn.microsoft.com/en-us/library/windows/desktop/aa372404(v=vs.85).aspx

A: Thank u guys for your suggestions, I final decided to go with creating a windows native dll to check the status of WindowsInstaller. The Windows Installer service is currently running if the value of the dwControlsAccepted member of the returned SERVICE_STATUS_PROCESS structure is SERVICE_ACCEPT_SHUTDOWN. Then used JNI to to call it from my java class.


text:
Q: Show that the map $F: \Bbb A^1 \to \Bbb V(y-x^2) \subset \Bbb A^2, t \longmapsto (t,t^2)$ is an isomorphism from the line to a parabola.
Show that the map $F: \Bbb A^1 \to \Bbb V(y-x^2) \subset \Bbb A^2, t \longmapsto (t,t^2)$ is an isomorphism from the line to a parabola.

I've learned about morphisms between affine varieties and the pullback and this is an example problem where I think I should use the fact that if $V$ and $W$ are affine varieties in $\Bbb A^n$, then $V \cong W \iff \Bbb C[V] \cong \Bbb C[W]$, here $\Bbb C [V]$ and $\Bbb C[W]$ are the coordinate rings of $V$ and $W$.
So if I define the pullback $F^\#: \Bbb C[x,y]/(y-x^2) \to \Bbb C[t]$ such that $x \longmapsto t, y \longmapsto t^2$ I have an surjective algebra homomorphism with kernel $\ker F^\# =\{p \in \Bbb C[x,y]/(y-x^2) \mid F^\#(p)=p(t,t^2)=0 \}$.
I think I should use the isomorphism theorem for algebras here to get something like $$\Bbb C[x,y]/(y-x^2) \Big / \ker F^\# \cong \Bbb C[t]$$ but I don't know what this kernel is and similarly I don't know how to handle this "double quotient". Any hints what to do here?

A: First, here's what I'd call the "right" way to do this problem. Define
\begin{align*}
G: \mathbb{V}(y-x^2) &\to \mathbb{A}^1\\
(x,y) &\mapsto x \, .
\end{align*}
$G \newcommand{\Ft}{\tilde{F}}$ is a polynomial map, hence is a morphism, and one can easily check that $F$ and $G$ are mutually inverse, using the fact that a point on the parabola is of the form $(x, x^2)$. Thus $F$ (and $G$) is an isomorphism.
If you'd prefer to work with coordinate algebras, we can similarly define the map
\begin{align*}
G^\#: \mathbb{C}[t] &\to \mathbb{C}[x,y]/(y-x^2)\\
t &\mapsto x
\end{align*}
and show that $F^\#$ and $G^\#$ are mutually inverse.
To pursue your desired approach and show that $\ker(F^\#) = 0$: consider the composition
\begin{align*}
\Ft : \mathbb{C}[x,y] \overset{\pi}{\to} \mathbb{C}[x,y]/(y-x^2) \overset{F^\#}{\to} \mathbb{C}[t]
\end{align*}
with the quotient map $\pi$. So $\Ft$ is just the evaluation map $x \mapsto t, y \mapsto t^2$. We now apply the following lemma. (See here for a proof.)
Lemma.
Let $R$ be a unital commutative ring and $R[x]$ be the one-variable polynomial ring over $R$.  For $\alpha \in R$, let
\begin{align*}
\varphi = \text{eval}_\alpha: R[x] &\to R\\
x &\mapsto \alpha
\end{align*}
be the evaluation homomorphism.  Then $\ker(\varphi) = (x-\alpha)$.  Moreover, the induced map $\overline{\varphi}: R[x]/(x-\alpha) \to R$ is an isomorphism.
Considering $\mathbb{C}[x,y]$ as $(\mathbb{C}[x])[y]$, we get that
\begin{align*}
\frac{\mathbb{C}[x,y]}{(y-x^2)} &\overset{\sim}{\to} \mathbb{C}[x]\\
y &\mapsto x^2
\end{align*}
is an isomorphism, which, after changing $x$ to $t$, is exactly the map $F^\#$.
One can also show that the kernel is $(y-x^2)$ more directly, as done in this answer.


text:
Q: using array_rand rather than shuffle in PHP I am using the code from this grade.php. I would like to use array_Rand than using shuffle. Can anyone please help?
The code works fine but I would like to show maybe like 10 out of 20 questions instead hence using shuffle() isn't really what I wanted. Would appreciate any help I could get, thank you in advance!
Edit: I added the Array_slice and now is showing error :

Undefined index: Questions @ line 77

A: You can pick Ids and then intersect the original array.  Here is an example picking two at random:
<?php
$questions = array(
    1 => array(
        'Question' => '1. CSS stands for',
        'Answers' => array(
            'A' => 'Computer Styled Sections',
            'B' => 'Cascading Style Sheets',
            'C' => 'Crazy Solid Shapes'
        ),
        'CorrectAnswer' => 'B'
    ),
    2 => array(
        'Question' => '2. What is the Capital of the Philippines',
        'Answers' => array(
            'A' => 'Cebu City',
            'B' => 'Davao City',
            'C' => 'Manila City'
        ),
        'CorrectAnswer' => 'C'
    ),
    3 => array(
        'Question' => '3. What is black and white',
        'Answers' => array(
            'A' => 'A Zebra',
            'B' => 'A Sycamore Tree',
            'C' => 'Law'
        ),
        'CorrectAnswer' => 'A'
    )
);

$rand_ids       = array_rand($questions, 2);
$rand_questions = array_intersect_key($questions, array_flip($rand_ids));


text:
Q: Decide whether the following is a smooth (1-dimensional manifold). If not, what are the trouble points? - Solution Verification Decide whether the following is a smooth (1-dimensional manifold)
$x^2 + y ^2 + z^2 - 1 = z^2 - xy = 0$
I'm asking this question because I want to know if I'm performing the analysis correctly with regards to determining whether a set is a manifold or not. I've only begun to learn about the concept so my understanding is still rudimentary.
Given this set of equations I perform the following analysis:
define $$F\left( \begin{array} \
x \\
y \\
z
\end{array} \right) = \left[ \begin{array} \
x^2 + y ^2 + z^2 - 1 \\
z^{2} - xy
\end{array} \right] = \left[ \begin{array} \
0 \\
0
\end{array} \right]$$
which yields the following derivative:
$$DF(\mathbf{x}) = \left[ \begin{array} \
2x & 2y & 2z \\
-y & -x & 2z \\
\end{array} \right]$$
In order for me to be able to obtain a 1 dimensional manifold it will be required that my derivative matrix is of $rank = 2$. So now I have to determine when that condition does not occur:

*

*if $(x,y,z) = (0,0,0)$ then the first expression of $F(\mathbf{x})$ would be undefined, so we can state that the point$(0,0,0$ does not occur in my subspace.

*if $x = y = 0$, then I would end up with $z = \pm 1$ in the first equation of $F(\mathbf{x})$ and $z = 0$ in the second equation. Again creating an impossible situation. So this scenario cannot occur.

*if $x = z = 0$ then $y = \pm 1$. This would give me a linearly dependent set of rows which would result in me only being able to write this curve as a 2-dimensional manifold. i.e as a function of $x,z$ for example: $ y =\phi(x,z)$ which also means $(x, \phi_{y}(x,z), z)$. (I think, not sure about this conclusion)

*with some fiddling around and row reduction I got the following matrix from $DF$:
$$DF(\mathbf{x}) = \left[ \begin{array} \
2x & 2y & 2z \\
-2x-y & -x-2y & 0 \\
\end{array} \right]$$
Which only yielded that if only one of $x,y,z$ are $0$ at one time I would get a matrix of $rank = 2$.
To conclude, trouble points would occur if$(x,y,z) = (0,0,0)$, if $x = y = 0$, and if $x = z = 0$, besides these situations we would be able to obtain a 1 - dimensional manifold.
Is this the proper approach to thinking about such a scenario. Any feedback would be appreciated.


text:
Q: Tiers tree print all suffixed provied wrong output I need to print all suffixes of a tires tree. I am using following traverse method to print all suffixes.
struct TrieNode {
    struct TrieNode *children[ALPHABET_SIZE];
    char label;
    bool isLeaf;
};

void traverse(char prefix[], struct TrieNode *root) {
    concatenate_string(prefix, &(root->label));
    if (root->isLeaf) {
        printf("%s\n", prefix);
    }

    for (int i = 0; i < 26; i++) {
        if (root->children[i]) {
            traverse(prefix, root->children[i]);
        }
    }
}

Consider following Trie tree
    Root
 |     |    |
 L     M    N
|  |
a  b

So my expected output is
La
Lb
M
N

But my code prints
  La
  Lab
  LabM
  LabMN

As per my understanding root cause for the issue is not updating prefix variable correctly. How to fix this issue?

A: That is because you keep concatenating. It is better to have char prefix[] as a local variable, e.g:
void traverse(char prefix[], struct TrieNode *root)
{
    char newprefix[30];
    strcpy(newprefix, prefix);
    concatenate_string(newprefix, &(root->label));
    if (root->isLeaf) {
        printf("%s\n",newprefix);
    }

    for(int i=0 ; i< 26 ; i++){
        if(root->children[i]){
            traverse(newprefix, root->children[i]);
        }
    }
}

and call like:
traverse("", root);


text:
Q: Close XPages ExtLib dialog from inside iframe I have db1.nsf/doc1 open in an XPage. On the XPage is a view of of related documents (db2.nsf/doc2) on the same server. I am using a repeat control with a link wrapped around each entry to open doc2 in an ExtLib dialog.
Note: Because doc2 has fileUpload and fileDownload controls on it, I have to open doc2 in an iframe in the dialog (v8.5.3). I have all the file upload/download stuff working thanks to Toohey's article File Upload XPage Forms via OpenNTF.org Extension Library Dialogs.
The problem is that I am unable to close the dialog with a button in the iframe in the dialog. The difference between my scenario and Toohey's is that I am working with 2 different documents in 2 different databases. The parent opener is an XPage with datasource doc1 in db1 while the dialog child is doc2 in db2. I don't seem to be able to get a handle on the parent document from within the child document in the iframe so i can close the dialog. It looks something like this:

<form action="db1.nsf/mainDoc.xsp?doc1&action=openDocument"></form>

    <form action="db1.nsf/mainDoc.xsp?doc1&action=openDocument">

                <form action="db1.nsf/showDialog.xsp?databaseName=db2.nsf&doc2&action=editDocument">
                    <button id="okBtn" type="submit">OK</button>
                </form>

    </form>

*Note: showDialog.xsp is an XPage in db1 with it's datasource being db2.nsf/doc2. (I'm using xp:panel with tagName="iframe".)
I want the OK button to save the document (which it does) and close the dialog (which it doesn't). I have tried several different methods of "parent. ..." to get a handle on  and close it - with no success at all.
How do I get a handle on the dialog element from within the iframe so I can close it?
*Added server version.

A: The way the XPages Extension Library dialog works is that it runs SSJS, then calls view.postScript() to pass CSJS back to the browser to close the dialog. You need to reproduce that. (I'm not sure what server version you're using but view.postScript() was only added in 8.5.3, probably for the dialog use case.)
I'm not familiar with the functionality you're using, but 9.0.1 provided the ability to upload attachments within a partial refresh, which resolves workarounds for Ext Lib dialogs.
The databaseName property of a datasource can be computed (format is serverName!!filePath), so data being in a separate database should not be an issue. Indeed most applications I build now separate XPages into one NSF and data / forms / views / agents in another. That application architecture is required anyway for XPages on Bluemix, and standard for other web application development.


text:
Q: Automatic shutdown after startup I played a little with the shutdown command typing:
sudo shutdown +20

and then:
sudo shutdown -c

I then manually hibernate my pc because I had to go out. Now I'm back and I found that I could no longer turn on the pc because once Linux is started, I can see the desktop for 1 second, and then my pc shutdown.
How can I solve this?

A: you could try adding noacpi to kernel-/linux-line via grub on boot.

*

*Start PC

*Select First Entry in Grub

*Press e

*Append noacpi to kernel-/linux-line

*Press F10 if you have grub2 (for grub i don't know...maybe just press enter)

This way you should get back in your system and be able check out whats going wrong.


text:
Q: How to highlight text spanning multiple lines that includes macros? I am currently proofreading a document and want to highlight some sentences. Unfortunately, I haven't found a highlighting package that can both

*

*Preserve linebreaks

*Highlight text produced by macros, especially \cite and the macros from siunitx such as \SI

Using the changes package, linebreaks do not work (changes uses internally a colorbox). However, with soul, the macros do not work.
In the end, I would like to use highlight from changes, since it combines nicely with a comment function. By replacing the colorbox using
\renewcommand{\colorbox}[2]{\colorlet{tmpcolor}{#1}\sethlcolor{tmpcolor}\hl{#2}}

I am able to "patch" the highlight command to use soul. For using \cite with soul I can use soulregister as pointed out in How to make \hl (highlighting) to automatically place incompatible commands in \mbox?. However, this approach does not work for \SI. The \SI command, however, works, if it is surrounded by braces. But this is not an option for me, since I am not responsible for writing the original text. Including a preamble, however, is fine.
How can I do highlighting without having to change the text (aside from preambles and the surrounding command)? Ideally I would not need to include a separate entry for each macro, but it would be acceptable for me to do so. To some extent, crude hacks (such as redefining \SI) would be ok as well.
MWE using changes
\documentclass[11pt]{scrartcl}

\usepackage[utf8]{inputenc}
\usepackage{siunitx}
\usepackage{changes}

\begin{document}
After the introduction, \highlight{this part of the sentence is quite long and contains a unit (\SI{5}{\ns}) and a citation~\cite{myref}.} How do I highlight it?
\end{document}

MWE using soul (with braces around SI)
\documentclass[11pt]{scrartcl}

\usepackage[utf8]{inputenc}
\usepackage{siunitx}
\usepackage{color}
\usepackage{soul}

\soulregister\cite7
%\soulregister\SI7 %Does not work

\begin{document}
After the introduction, \highlight{this part of the sentence is quite long and contains a unit ({\SI{5}{\ns}}) and a citation~\cite{myref}.} How do I highlight it?
\end{document}

A: Place macro in their own group and use \hl from the soul package.
\documentclass[11pt]{scrartcl}

\usepackage[utf8]{inputenc}
\usepackage{siunitx}
\usepackage{changes}
\usepackage{soul}
\begin{document}
After the introduction, \hl{this part of the sentence is quite
long and contains a unit ({\SI{5}{\ns}}) and a citation~{\cite{myref}}.}
How do I highlight it?
\end{document}


text:
Q: Fields with the property $\Bbb{F}^\times / \{1, -1\}$ is isomorphic to a subgroup of $\Bbb{F}^\times$. The field of real numbers has the property that $\Bbb{R}^\times/\{1, -1\}$ is isomorphic to a subgroup of $\Bbb{R}^\times$, namely the positive reals. This is because there is a homomorphism $f:\ \Bbb{R}^\times \to \Bbb{R}^\times$ given by $f(x) = |x|$.
I believe there evidence to believe that $\Bbb{F}_p$ has this property as well, since $\Bbb{F}_p^\times$ is a product of cyclic groups.
Not surprisingly, I find it hard to show that the complex numbers have this property.
How do I characterize all fields with this property?

A: In fact $\Bbb{F}_p^{\times}$ is cyclic of order $p-1$, and hence any quotient of it is cyclic as well and its order divides $p-1$. Of course a cyclic group of order $p-1$ has a subgroup of any order dividing $p-1$, so every prime field $\Bbb{F}_p$ has this property. In fact the same argument shows that every finite field has this property.

In general, for any field $k$ the map
$$k^{\times}\ \longrightarrow\ k^{\times}:\ x\ \longmapsto\ x^2,$$
is a group homomorphism with kernel $\{1,-1\}$, so the quotient $k/\{1,-1\}$ is isomorphic to its image by the first isomorphism theorem, which is a subgroup of $k^{\times}$. This is the subgroup $k^{\times2}$ of squares in $k^{\times}$. In the particular case of $k=\Bbb{C}$ we see that $\Bbb{C}/\{1,-1\}\cong\Bbb{C}$.


text:
Q: Prolog | findall with result list of another findall How can i get values by an specific condition, and next with these selected elements get values from other facts serie?
I've this code
%code, date, amount
values1('AAA', date(02, 03, 2020), 1000).
values1('AAA', date(31, 03, 2020), 2000).
values1('BBB', date(02, 04, 2020), 1350).
values1('BBB', date(15, 04, 2020), 1500).
values1('CCC', date(23, 05, 2020), 5500).
values1('CCC', date(01, 05, 2020), 750).
values1('DDD', date(06, 05, 2020), 3560).
values1('AAA', date(18, 06, 2020), 4600).
values1('CCC', date(27, 07, 2020), 1200).

%code, percent
values2('AAA', '0.2').
values2('BBB', '0.25').
values2('CCC', '0.55').
values2('DDD', '0.98').

predicate1(Code, Percent) :-
    findall(Code, (values1(Code, _, Value), Value > 1000), Code),
    findall(Percent, values2(Code, Percent), Percent).

For example in this case the idea it's get Code which amount is bigger than 1000, and when there are selected get the percent from value2, but the Percent list it's return empty. Why it happening that?
This is the return
predicate1(Code, Percent).
Code = ['AAA', 'BBB', 'BBB', 'CCC', 'DDD', 'AAA', 'CCC'],
Percent = []

it may be by the difference between number of elements in list of Code and number of fact of values2 maybe?

A: You have a typo and a (few) logic errors.
The value of Code goes into a list of Code: CodeList. You have variable Code on first and third position. Use this:
findall(Code, (values1(Code, _, Value), Value > 1000), CodeList).

Run it:
?- findall(Code, (values1(Code, _, Value), Value > 1000), CodeList).
CodeList = ['AAA', 'BBB', 'BBB', 'CCC', 'DDD', 'AAA', 'CCC'].

Duplicate elements are removed by using the predicate setof/3 instead.
However, setof/3 demands that you indicate ("existentially quantify" with the caret notation: Value^Date^) the variables that shall be invisible outside the inner goal, otherwise backtracking over possible values of Value and Date will occur outside of setof/3:
?- setof(Code, Value^Date^(values1(Code, Date, Value), Value > 1000), CodeList).
CodeList = ['AAA', 'BBB', 'CCC', 'DDD'].

Now you just need to "join" any "code" with the "percentage" ... inside of setof/3:
?- setof([Code,Percent],
         Value^Date^(values1(Code, Date, Value),
                     Value > 1000,
                     values2(Code,Percent)),
         Set).

Set = [['AAA', '0.2'], ['BBB', '0.25'], ['CCC', '0.55'], ['DDD', '0.98']].

You can pack this into a predicate which backtracks over the setof/3 result:
gimme(Code, Percent) :-
   setof([Code,Percent],
            Value^Date^(values1(Code, Date, Value),
                        Value > 1000,
                        values2(Code,Percent)),
            Set),
   member([Code,Percent],Set).

Note that the reuse of variables of Code and Percent inside setof/3 and in the call to member/2 s well is actually ok: These are not the same variables.
And so:
?- gimme(Code,Percent).
Code = 'AAA',
Percent = '0.2' ;
Code = 'BBB',
Percent = '0.25' ;
Code = 'CCC',
Percent = '0.55' ;
Code = 'DDD',
Percent = '0.98'.

A: predicate1(Code,Percent)
:-
values1(Code,_,Amount) ,
Amount > 1000 ,
values2(Code,Percent)
.

example usage from toplevel :
?- predicate1(Code,Percent).
Code = 'AAA',
Percent = '0.2' ;
Code = 'BBB',
Percent = '0.25' ;
Code = 'BBB',
Percent = '0.25' ;
Code = 'CCC',
Percent = '0.55' ;
Code = 'DDD',
Percent = '0.98' ;
Code = 'AAA',
Percent = '0.2' ;
Code = 'CCC',
Percent = '0.55'.

A: The other answers give you solutions with backtracking. If you really want lists (see note below), you need a predicate that can relate "a list of A elements" and "a list of B elements" such that each A-B pair is in some relation.
SWI-Prolog has maplist/N for this:
predicate1(Codes, Percents) :-
    findall(Code, (values1(Code, _, Value), Value > 1000), Codes),
    maplist(values2, Codes, Percents).

This gives you your codes and an equal length list of the corresponding percentages:
?- predicate1(Codes, Percents).
Codes = ['AAA', 'BBB', 'BBB', 'CCC', 'DDD', 'AAA', 'CCC'],
Percents = ['0.2', '0.25', '0.25', '0.55', '0.98', '0.2', '0.55'].

Note: Prolog beginners love collecting solutions into lists. This is often not the best way to solve a problem in Prolog. Backtracking can be more natural, simpler, and more efficient. I recommend that you try to resist the urge to collect everything into lists unless really needed.
Edit: As a note on style, if I do use findall/3, setof/3, or bagof/3, I prefer to write an auxiliary predicate that hides all variables that are not relevant to the data I want to collect:
code_above(Code, Limit) :-
    values1(Code, _, Value),
    Value > Limit.

This way the findall and setof calls look the same, which makes it easy to switch between them. They are also (in my opinion) a lot more readable than the Value^Date^ gymnastics that setof otherwise requires, as illustrated in David Tonhofer's answer:
predicate1(Codes, Percents) :-
    findall(Code, code_above(Code, 1000), Codes),
    maplist(values2, Codes, Percents).

predicate2(Codes, Percents) :-
    setof(Code, code_above(Code, 1000), Codes),
    maplist(values2, Codes, Percents).

With this you get rid of duplicates for free:
?- predicate1(Codes, Percents).
Codes = ['AAA', 'BBB', 'BBB', 'CCC', 'DDD', 'AAA', 'CCC'],
Percents = ['0.2', '0.25', '0.25', '0.55', '0.98', '0.2', '0.55'].

?- predicate2(Codes, Percents).
Codes = ['AAA', 'BBB', 'CCC', 'DDD'],
Percents = ['0.2', '0.25', '0.55', '0.98'].


text:
Q: Question about what is causing endogeneity I have the following model:
$r_t=\beta_1+\beta_2\ div_t + \beta_3 \ result_t + u_t$
$r$ is the return of a stock index, $div$ are the dividend gains in percentage of the market price, $result$ are the results of the companies included in the stock index. Also:
$r_t=\frac{p_t+ \ d_t-p_{t-1}}{p_{t-1}}=\frac{p_t+ \ d_t}{p_{t-1}}-1$
$div_t=\frac{d_t}{p_{t-1}}$
$p$ is the market price of the index, $d$ are the dividends.
I am told that it is reasonable to consider that $div$ is endogenous. Is it because of the presence of $p_{t-1}$ in both $div$ and $r$? Is it a problem of simultaneity that causes endogeneity?

A: Both $r_t$ and $div_t$ are functions of $p_{t-1}$, hence the two variables will be correlated with the past price. However, $p_{t-1}$ does not occur in your regression and therefore is left in the error, meaning that you will have a correlation between $div_t$ and $u_t = \epsilon_t + p_{t-1}$. So if instead of running
$$r_t = \beta_1 + \beta_2 div_t + \beta_3 result_t + \beta_4 p_{t-1} + \epsilon_t$$
you choose to run the short regression
$$r_t = \beta_1 + \beta_2 div_t + \beta_3 result_t + u_t$$
the bias for your estimated coefficient on $div_t$ is going to be
$$\widehat{\beta}_2 = \beta_2 + \beta_4 \frac{Cov(div_t, p_{t-1})}{Var(div_t)}$$
and this bias is not going to be zero. From the expressions provided for $r_t$ and $div_t$, both are decreasing in $p_{t-1}$ meaning that it is likely that $\beta_4 < 0$ and $Cov(div_t,p_{t-1})<0$, in which case $\widehat{\beta_2}$ will be biased upward, i.e. it is going to be too large.
However, even if you include $p_{t-1}$ in your regression, there might be other issues such as simultaneity or reverse causality. Right now the model posits that an increase in the dividend increases the return of a stock. Perhaps it could also be though that an increase in the return of a stock increases the dividend, e.g. more successful stocks pay out higher dividends (I'm only speculating here because this isn't my field of expertise but it might be worth thinking about it).


text:
Q: Calling np.array on a list of RandomForestRegressors returns an array of DecisionTreeRegressors When I try to convert a list of RandomForestRegressors to a numpy array, I get an array of Decision Trees.  How do I get an array of RandomForestRegressors instead?
e.g.
clf0=RandomForestRegressor()
clf1=RandomForestRegressor()

X = np.random.randn(10,1)
y = np.random.randn(10,1)

clf0.fit(X,y)
clf1.fit(X,y)

m = np.array( [clf0, clf1 ] )

m.shape

Out[1]: (2, 10)

I want m.shape to be (2,), not (2,10).  And it should contrain RandomForestRegressors, not DecisionTreeRegressors.

A: This was recently answered on the scikit-learn mailing list: a random forest behaves as sequence of decision trees:
>>> len(clf0)
10
>>> clf0[:2]
[DecisionTreeRegressor(compute_importances=None, criterion='mse',
           max_depth=None, max_features='auto', max_leaf_nodes=None,
           min_density=None, min_samples_leaf=1, min_samples_split=2,
           random_state=1087328618, splitter='best'),
 DecisionTreeRegressor(compute_importances=None, criterion='mse',
           max_depth=None, max_features='auto', max_leaf_nodes=None,
           min_density=None, min_samples_leaf=1, min_samples_split=2,
           random_state=357905606, splitter='best')]

NumPy picks this up and converts the RFs themselves to arrays. The workaround is easy:
>>> m = np.empty(2, object)
>>> m[:] = clf0, clf1
>>> m
array([ RandomForestRegressor(bootstrap=True, compute_importances=None,
           criterion='mse', max_depth=None, max_features='auto',
           max_leaf_nodes=None, min_density=None, min_samples_leaf=1,
           min_samples_split=2, n_estimators=10, n_jobs=1, oob_score=False,
           random_state=None, verbose=0),
       RandomForestRegressor(bootstrap=True, compute_importances=None,
           criterion='mse', max_depth=None, max_features='auto',
           max_leaf_nodes=None, min_density=None, min_samples_leaf=1,
           min_samples_split=2, n_estimators=10, n_jobs=1, oob_score=False,
           random_state=None, verbose=0)], dtype=object)

(Mind you, your y has the wrong shape. It should be (10,), not (10, 1).)


text:
Q: React dev tools shows components as  Anyone have any clue why my react component dev tools looks like this? Prior to the most recent react dev tools major update, I could see the names of all my components, but now it just looks like this.
Dev Tools View

A: You're using production/ minified version of the code. When such code is viewed in Devtool, you can only see single letter representation.
Make sure to run app in development mode and see if Devtool is picking up the right component name.


text:
Q: how to loop through the elements in Behat and Mink I'm using Behat and Mink framework for BDD (using PHP)
I was looping through td elements to verify the values and text. Since all the elements returned are span elements, I could use getText() on the elements and it was all good.
$page = $this->getSession()->getPage();
$expected_values = ["Tuesday", 22, 22, 22, 22];
$actual_rows = $page->findAll('css', 'table.admin-table tbody tr td');
$actual_Values = array();
foreach($actual_rows as $row) {
$actual_Values[] = $row->getText();
}
assertEquals($expected_values, $actual_Values);

But recently, the design of the page has changed. And some of the span elements have been replaced by input elements. And getText() returns null so I replaced it with getValue(). But since the first td element is a span it returns null if we use getText().
Is there anyway I can skip the first td within the loop from the code snippet above.
Update:
Here is what I put in comments which hasn't rendered properly:
$actual_Values[] = $row->find('css', 'input')->getValue();

A: I misread and thought you want to get text independently whether there is an input or span. To skip the first value you can just:
foreach($actual_rows as $row) {
    if ($row !== reset($actual_rows) {
        $actual_Values[] = $row->getText();
    }
}

Or a better approach would be to array_shift($actual_rows) to remove the first value and do the normal loop then.
Or another approach would be to change your selector to $page->findAll('css', 'table.admin-table tbody tr td:not(:first-child)'); to select everything but the first td child.


text:
Q: Immutable beans in Java I am very curious about the possibility of providing immutability for java beans (by beans here I mean classes with an empty constructor providing getters and setters for members).    Clearly these classes are not immutable and where they are used to transport values from the data layer this seems like a real problem.
One approach to this problem has been mentioned here in StackOverflow called "Immutable object pattern in C#" where the object is frozen once fully built.  I have an alternative approach and would really like to hear people's opinions on it.
The pattern involves two classes Immutable and Mutable where Mutable and Immutable both implement an interface which provides non-mutating bean methods.
For example
public interface DateBean {
    public Date getDate();
    public DateBean getImmutableInstance();
    public DateBean getMutableInstance();
}

public class ImmutableDate implements DateBean {
    private Date date;

ImmutableDate(Date date) {
    this.date = new Date(date.getTime());
}

public Date getDate() {
    return new Date(date.getTime());
}

    public DateBean getImmutableInstance() {
        return this;
    }

    public DateBean getMutableInstance() {
        MutableDate dateBean = new MutableDate();
        dateBean.setDate(getDate());
        return dateBean;
    }
}

public class MutableDate implements DateBean {
    private Date date;

public Date getDate() {
    return date;
}

public void setDate(Date date) {
    this.date = date;
}

public DateBean getImmutableInstance() {
    return new ImmutableDate(this.date);
}

    public DateBean getMutableInstance() {
        MutableDate dateBean = new MutableDate();
        dateBean.setDate(getDate());
        return dateBean;
    }
}

This approach allows the bean to be constructed using reflection (by the usual conventions) and also allows us to convert to an immutable variant at the nearest opportunity.  Unfortunately there is clearly a large amount of boilerplate per bean.
I am very interested to hear other people's approach to this issue.  (My apologies for not providing a good question, which can be answered rather than discussed :)

A: Some comments (not necessarily problems):

*

*The Date class is itself mutable so you are correctly copying it to protect immutability, but personally I prefer to convert to long in the constructor and return a new Date(longValue) in the getter.

*Both your getWhateverInstance() methods return DateBean which will necessitate casting, it might be an idea to change the interface to return the specific type instead.

*Having said all that I would be inclined to just have two classes one mutable and one immutable, sharing a common (i.e. get only) interface if appropriate. If you think there will be a lot of conversion back and forth then add a copy constructor to both classes.

*I prefer immutable classes to declare fields as final to make the compiler enforce immutability as well.

e.g.
public interface DateBean {
    public Date getDate();
}

public class ImmutableDate implements DateBean {
    private final long date;

    ImmutableDate(long date) {
       this.date = date;
    }

    ImmutableDate(Date date) {
       this(date.getTime());
    }

    ImmutableDate(DateBean bean) {
       this(bean.getDate());
    }

    public Date getDate() {
         return new Date(date);
    }
}

public class MutableDate implements DateBean {
    private long date;

    MutableDate() {}

    MutableDate(long date) {
       this.date = date;
    }

    MutableDate(Date date) {
       this(date.getTime());
    }

    MutableDate(DateBean bean) {
       this(bean.getDate());
    }

    public Date getDate() {
        return new Date(date);
    }

    public void setDate(Date date) {
        this.date = date.getTime();
    }

}

A: I think I'd use the delegation pattern - make an ImmutableDate class with a single DateBean member that must be specified in the constructor:
public class ImmutableDate implements DateBean
{
   private DateBean delegate;

   public ImmutableDate(DateBean d)
   {
      this.delegate = d;
   }

   public Date getDate()
   {
      return delegate.getDate();
   }
}

If ever I need to force immutability on a DateBean d, I just new ImmutableDate(d) on it. I could have been smart and made sure I didn't delegate the delegate, but you get the idea. That avoids the issue of a client trying to cast it into something mutable. This is much like the JDK does with Collections.unmodifiableMap() etc. (in those cases, however, the mutation functions still have to be implemented, and are coded to throw a runtime exception. Much easier if you have a base interface without the mutators).
Yet again it is tedious boilerplate code but it is the sort of thing that a good IDE like Eclipse can auto-generate for you  with just a few mouse clicks.
If it's the sort of thing you end up doing to a lot of domain objects, you might want to consider using dynamic proxies or maybe even AOP. It would be relatively easy then to build a proxy for any object, delegating all the get methods, and trapping or ignoring the set methods as appropriate.

A: I use interfaces and casting to control the mutability of beans. I don't see a good reason to complicate my domain objects with methods like getImmutableInstance() and getMutableInstance().
Why not just make use of inheritance and abstraction? e.g.
public interface User{

  long getId();

  String getName();

  int getAge();

}

public interface MutableUser extends User{

  void setName(String name);

  void setAge(int age);

}

Here's what the client of the code will be doing:
public void validateUser(User user){
  if(user.getName() == null) ...
}

public void updateUserAge(MutableUser user, int age){
  user.setAge(age);
}

Does it answer your question?
yc


text:
Q: Fix an error to getting city info from a list of ip through an ip checker website (html+table) to a data frame I have a list of ip's that I need to plot on a map and I would like to use this website Ip Checker to extract the info about the city and make a data frame.
the structure of the table that the website generates is the following

the ROW #7 contains the information about the City if present, if not it contains the latitude and longitude, but that is a problem for later
The final result that I'm trying to achieve

IP
CITY
Number of Occurrences

64.4.99.114
Covington
2

201.105.211.222
Xalapa
2

73.6.19.32
Texas City
1

and so on
So far this is the result that I have obtained with the manual insertion
    url_ip <- "https://ipleak.net/?q=64.4.99.114"

      page <- read_html(url_ip)

      tbls <- html_nodes(page, "table")

      tbls2 <- html_table(tbls)

      table2 <- table2[c(1,7),2]

      table2 <- t(table2)

city_table <-  as.data.frame(table2)

The final result of the manual insertion

V1
V2

64.4.99.114
Covington

this is what I have produced so far
if (!require("pacman"))
  install.packages("pacman")
pacman::p_load(
  dplyr,
  readr,
  ggplot2,
  hrbrthemes,
  RColorBrewer,
  lubridate,
  countrycode,
  stringi,
  tidyverse,
  rvest,
  purrr,
  tidyr,
  openxlsx,
)

ip_range <- threedsecure_authentication_report_tidy %>% pull(shopper_ip) #this is from our payment's system report generator

ip_range <- unique(ip_range)

ip_range <- trimws(ip_range)

purrr::map_df(ip_range, ~ {

  url_reviews <- paste0("https://ipleak.net/?q,.x)

  page <- read_html(url_reviews)

  # Review Question
  tbls <- html_nodes(page, "table")

  tbls2 <- html_table(tbls)

  table2 <- table2[c(1,7),2]

  table2 <- t(table2)

  table2 <- as.data.frame(table2) -> q #I'm not sure about this part

  data.frame(q) }) -> ip_geo

but I get this: Error in open.connection(x, "rb") : HTTP error 504
This is the traceback
12.
open.connection(x, "rb")
11.
open(x, "rb")
10.
read_xml.connection(con, encoding = encoding, ..., as_html = as_html,
    base_url = x, options = options)
9.
read_xml.character(x, encoding = encoding, ..., as_html = TRUE,
    options = options)
8.
read_xml(x, encoding = encoding, ..., as_html = TRUE, options = options)
7.
withCallingHandlers(expr, warning = function(w) if (inherits(w,
    classes)) tryInvokeRestart("muffleWarning"))
6.
suppressWarnings(read_xml(x, encoding = encoding, ..., as_html = TRUE,
    options = options))
5.
read_html.default(url_reviews)
4.
read_html(url_reviews)
3.
.f(.x[[i]], ...)
2.
map(.x, .f, ...)
1.
purrr::map_df(ip_range, ~{
    url_reviews <- paste0("https://ipleak.net/?q=", .x)
    page <- read_html(url_reviews)
    tbls <- html_nodes(page, "table") ...

I have also saw R packages that do this but they do not seem to work: ip2location


text:
Q: Frequency of driven damped oscillation and the driven force For a driven damped oscillation, if the driven force $F = F_0 \cos(\omega t)$, then the solution to the motion is
$$x = A \cos(\omega t+\varphi ) \, .$$

*

*Why must the the oscillation and the driven force have the same frequency but can be out of phase?

The solution to $\varphi$ is $\tan(\varphi )=\omega \gamma / (\omega_0^2 - \omega^2)$. ($\gamma$ is the damping coefficient divided by mass for a spring system)

*

*Why would $\varphi$ goes to zero (meaning $F$ and $x$ are in phase) if $\omega$ goes to zero?

A: I'll start with the second part of your question:
If the frequency of the force, $\omega$, goes to zero then it is just a constant force - there won't be any oscillation! Since there is no oscillation the force and the motion will be in phase (by default).
To answer why the force and motion can HAVE separate phases in the first place we look at the differential equation that describes the motion. Let $x$ be the displacement of the object about the central (rest) point. For the system you describe we will have:

*

*A restoring force, $F_R$, with equation $$F_R=-kx$$ where $k$ is a positive constant (often called spring constant).

*A damping force, $F_D$ proportional to the objects velocity, which takes the form $$F_D=-c\frac{dx}{dt}$$
where $c$ is also a positive constant.

*and a driving force, which in your question takes the form
$$F(t)=F_0\cos(\omega t) \, .$$
Applying Newton's second law ($F=ma$):
$$\Sigma F=m\frac{d^2x}{dt^2}\\
\implies F_0\cos(\omega t)-c\frac{dx}{dt}-kx=m\frac{d^2x}{dt^2} \, .$$
Solving this differential equation isn't too hard, and I encourage you to look up the details on solving it. The result is:
$$x(t)=x_0\cos(\omega t+\phi)$$
where $x_0$ and $\phi$ depend on the other parameters given.


text:
Q: android stock inventory system I have an inventory system that reads from a file and you should be able to enter stock items in manually as well, the program reads from the file ok but wont add a new item in, as soon as you click the add button the program crashes
below is the log cat:
12-02 15:07:03.171: E/AndroidRuntime(2803): FATAL EXCEPTION: main
12-02 15:07:03.171: E/AndroidRuntime(2803): java.lang.IllegalStateException: Could not execute method of the activity
12-02 15:07:03.171: E/AndroidRuntime(2803):     at android.view.View$1.onClick(View.java:3597)
12-02 15:07:03.171: E/AndroidRuntime(2803):     at android.view.View.performClick(View.java:4202)
12-02 15:07:03.171: E/AndroidRuntime(2803):     at android.view.View$PerformClick.run(View.java:17340)
12-02 15:07:03.171: E/AndroidRuntime(2803):     at android.os.Handler.handleCallback(Handler.java:725)
12-02 15:07:03.171: E/AndroidRuntime(2803):     at android.os.Handler.dispatchMessage(Handler.java:92)
12-02 15:07:03.171: E/AndroidRuntime(2803):     at android.os.Looper.loop(Looper.java:137)
12-02 15:07:03.171: E/AndroidRuntime(2803):     at android.app.ActivityThread.main(ActivityThread.java:5039)
12-02 15:07:03.171: E/AndroidRuntime(2803):     at java.lang.reflect.Method.invokeNative(Native Method)
12-02 15:07:03.171: E/AndroidRuntime(2803):     at java.lang.reflect.Method.invoke(Method.java:511)
12-02 15:07:03.171: E/AndroidRuntime(2803):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
12-02 15:07:03.171: E/AndroidRuntime(2803):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
12-02 15:07:03.171: E/AndroidRuntime(2803):     at dalvik.system.NativeStart.main(Native Method)
12-02 15:07:03.171: E/AndroidRuntime(2803): Caused by: java.lang.reflect.InvocationTargetException
12-02 15:07:03.171: E/AndroidRuntime(2803):     at java.lang.reflect.Method.invokeNative(Native Method)
12-02 15:07:03.171: E/AndroidRuntime(2803):     at java.lang.reflect.Method.invoke(Method.java:511)
12-02 15:07:03.171: E/AndroidRuntime(2803):     at android.view.View$1.onClick(View.java:3592)
12-02 15:07:03.171: E/AndroidRuntime(2803):     ... 11 more
12-02 15:07:03.171: E/AndroidRuntime(2803): Caused by: java.lang.NullPointerException
12-02 15:07:03.171: E/AndroidRuntime(2803):     at com.example.assignmentfinal.EnterItemActivity.onClick(EnterItemActivity.java:141)
12-02 15:07:03.171: E/AndroidRuntime(2803):     ... 14 more

and below is the item class and the enter item class:
public class EnterItemActivity extends Activity implements OnEditorActionListener, OnItemSelectedListener, OnClickListener, android.content.DialogInterface.OnClickListener
{
private EditText et;
private EditText etP;
private EditText etS;
private EditText etN;
private EditText etSU;
private EditText etA;
private DatePicker dp;
private CheckBox cb;
private TextView tvSC;
private RadioButton rbE;
private RadioButton rbS;
private RadioButton rbU;
private Item item;
private TextView tv;
private TimePicker tp;
private Spinner spin;
String[] idItems = {"1253", "3965" , "3234", "9912", "3423"};
private boolean isNew = true;

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_enter_item);

    etP = (EditText)this.findViewById(R.id.edit_plant);
    etP.setOnEditorActionListener(this);

    dp = (DatePicker)this.findViewById(R.id.dp_inspection_date);

    etS= (EditText)this.findViewById(R.id.edit_stock_id);
    etS.setOnEditorActionListener(this);

    etN = (EditText)this.findViewById(R.id.edit_name_of_item);
    etN.setOnEditorActionListener(this);

    tp = (TimePicker)this.findViewById(R.id.tp_time_inspection);

    tv = (TextView)this.findViewById(R.id.tv_inspector_id);
    tv = (TextView)this.findViewById(R.id.tv_inspector_id_value);

    spin = (Spinner)this.findViewById(R.id.sp_spinner_in_id);
    spin.setOnItemSelectedListener(this);
    ArrayAdapter inspectorSpinner = new ArrayAdapter(this, android.R.layout.simple_spinner_item, idItems);
    inspectorSpinner.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spin.setAdapter(inspectorSpinner);

    etSU = (EditText)this.findViewById(R.id.edit_stock_units);
    etSU.setOnEditorActionListener(this);

    rbE = (RadioButton)this.findViewById(R.id.rb_condition_excellent);
    rbS = (RadioButton)this.findViewById(R.id.rb_condition_statisfactory);
    rbU = (RadioButton)this.findViewById(R.id.rb_condition_unacceptable);
    tvSC = (TextView)this.findViewById(R.id.tv_conditon_selected);

    etA = (EditText)this.findViewById(R.id.edit_additional);
    etA.setOnEditorActionListener(this);

    cb = (CheckBox)this.findViewById(R.id.cb_follow_up);

    //initialise the data if this is not a new student
    //get the student object to be updated
    Bundle extras = this.getIntent().getExtras();
    if (extras != null)
    {
        isNew = false;
        int position = extras.getInt("position");
        item = ((ItemApplication)getApplication()).getItem(position);

        etP.setText(item.getPlant());
        etP.setFocusable(false); //can't update the name
        dp.updateDate(item.getYear(), item.getMonth(), item.getDay());
        tp.setCurrentHour(item.getHour());
        tp.setCurrentMinute(item.getMinute());
        etS.setText((String.valueOf(item.getStockId())));
        etS.setFocusable(false);
        etN.setText(item.getNameOfItem());
        tv.setText(item.getInspectorId());
        etSU.setText(item.getStockUnits());
        tvSC.setText(item.getCondition());
        etA.setText(item.getAdditional());
        cb.setChecked(item.isFollowUp());

    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu)
{
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.itemmenu, menu);

    return true;
}

@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event)
{
    InputMethodManager mgr = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
    mgr.hideSoftInputFromWindow(et.getWindowToken(), 0);

    return true;
}

public void onClick(View v)
{
    //get the values for displaying in the list
    String plant = etP.getText().toString();
    int day = dp.getDayOfMonth();
    int month = dp.getMonth();
    int year = dp.getYear();
    int stockId = item.getStockId();
    String nameOfItem = etN.getText().toString();
    int hour = tp.getCurrentHour();
    int minute = tp.getCurrentMinute();
    String inspectorId = tv.getText().toString();
    String stockUnits = etSU.getText().toString();
    String condition = tvSC.getText().toString();
    String additional = etA.getText().toString();
    boolean isFollowUp= cb.isChecked();

        if (isNew)
        {
            item = new Item(plant, day, month, year, stockId, nameOfItem,  hour, minute, inspectorId, stockUnits, condition, additional, false);
            ((ItemApplication)getApplication()).addItem(item);
        }
        else
        {
            //update the student already in the list
            item.setPlant(plant);
            item.setDay(day);
            item.setMonth(month);
            item.setStockId(stockId);
            item.setNameOfItem(nameOfItem);
            item.setYear(year);
            item.setHour(hour);
            item.setMinute(minute);
            item.setInspectorId(inspectorId);
            item.setStockUnits(stockUnits);
            item.setCondition(condition);
            item.setAdditional(additional);
            item.setFollowUp(isFollowUp);
        }

        showItem(item);
    }

    public void showItem(Item i)
    {
        new AlertDialog.Builder(this).setTitle("Item Details").setMessage(i.toString()).setNeutralButton("OK", this).show();
    }

    @Override
    public void onClick(DialogInterface dialog, int which)
    {

    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View v, int position, long id)
    {
        tv.setText(idItems [position]);
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent)
    {
        tv.setText("");
    }

    public void onRadioButtonClickCondition(View view)
    {
        if(rbE.isChecked())
        {
            tvSC.setText("Excellent");
        }
        else if(rbS.isChecked())
        {
            tvSC.setText("Satisfactory");
        }
        else if(rbU.isChecked())
        {
            tvSC.setText("Unacceptable");
        }
    }

}

public class Item
{
private String plant;
private int day, month, year;
private int hour, minute;
private int stockId;
private String nameOfItem;
private String inspectorId;
private String stockUnits;
private String condition;
private String additional;
private boolean isFollowUp;

public Item(String plant, int day, int month, int year,  int stockId, String nameOfItem, int hour, int minute, String inspectorId, String stockUnits, String condition, String additional, boolean isFollowUp)
{
    this.plant = plant;
    this.day = day;
    this.month = month;
    this.year = year;
    this.stockId = stockId;
    this.nameOfItem = nameOfItem;
    this.inspectorId = getInspectorId();
    this.stockUnits = getStockUnits();
    this.condition = getCondition();
    this.additional = getAdditional();
    this.isFollowUp = isFollowUp();
}

public String getPlant()
{
    return plant;
}

public boolean isFollowUp()
{
    return isFollowUp;
}

@Override
public String toString()
{
    return "Plant: " + plant + "\n" + "Inspection Date: " + day + ", " + (month +1) + ", " + year +
            "\n" + "Inspection Time: " + hour + ":" + minute + "\n" + "Stock ID: " + stockId + "\n" + "Name of Item: " + nameOfItem + "\n" + "Inspector ID: "
            + inspectorId + "\n" + "Stock Units: " + stockUnits + "\n" + "Condition: " + condition + "\n"
            + "Additional Info: " + additional +"\n" + "Follow-up? " + isFollowUp;
}

public Item(String plant, int day, int month, int year,  int stockId, String nameOfItem, int hour, int minute, String inspectorId, String stockUnits, String condition, String additional)
{
    this(plant, day, month, year, stockId, nameOfItem, hour, minute, inspectorId, stockUnits, condition, additional, true);
}

public int getDay()
{
    return day;
}

public int getMonth()
{
    return month;
}

public int getYear()
{
    return year;
}

public void setPlant(String plant)
{
    this.plant = plant;
}

public void setDay(int day)
{
    this.day = day;
}

public void setMonth(int month)
{
    this.month = month;
}

public void setYear(int year)
{
    this.year = year;
}

public void setFollowUp(boolean isFollowUp)
{
    this.isFollowUp = isFollowUp;
}

public int getStockId()
{
    return stockId;
}

public void setStockId(int stockId)
{
    this.stockId = stockId;
}

public String getNameOfItem()

{
    return nameOfItem;
}

public void setNameOfItem(String nameOfItem)
{
    this.nameOfItem = nameOfItem;
}

public String getInspectorId()
{
    return inspectorId;
}

public void setInspectorId(String inspectorId)
{
    this.inspectorId = inspectorId;
}

public String getStockUnits()
{
    return stockUnits;
}

public void setStockUnits(String stockUnits)
{
    this.stockUnits = stockUnits;
}

public String getCondition()
{
    return condition;
}

public void setCondition(String condition)
{
    this.condition = condition;
}

public String getAdditional()
{
    return additional;
}

public void setAdditional(String additional)
{
    this.additional = additional;
}

public int getHour()
{
    return hour;
}

public void setHour(int hour)
{
    this.hour = hour;
}

public int getMinute()
{
    return minute;
}

public void setMinute(int minute)
{
    this.minute = minute;
}
}


text:
Q: Java io.FileNotFoundException; suspect port at issue Context: I'm a very experienced programmer, but not a very experienced Java programmer.
I've inherited a small body of code that generates JNLP to wrap a JAR in order to gather some information about a client computer. This has always worked fine in contexts where no port was explicitly specified in a URL, but is failing in a test environment where I need to specify port explicitly.
The relevant Java code is:
URL RegURL = new URL(System.getProperty("jnlp.reg"));
...

try {
  //Create connection
  connection = (HttpURLConnection)RegURL.openConnection();
  connection.setRequestMethod("POST");
  connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
  connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
  connection.setRequestProperty("Content-Language", "en-US");
  connection.setUseCaches(false);
  connection.setDoInput(true);
  connection.setDoOutput(true);

  //Send request
  DataOutputStream wr = new DataOutputStream (connection.getOutputStream ());
  wr.writeBytes (urlParameters);
  wr.flush ();
  wr.close ();

  //Get Response
  InputStream is = connection.getInputStream();
  ...
} catch (Exception e) {
  ...
} finally {
  ...
}

RegURL has a value of the form "http://arthur.OURCOMPANY.com:81/fb/register.php", and I've confirmed that is the case. But I get a client-side error:
java.io.FileNotFoundException: http://arthur.OURCOMPANY.com/fb/register.php
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
    at main.main(main.java:253)
    ...

This means the error is fired by the line InputStream is = connection.getInputStream();
I assume this means that somewhere along the way the port number got lost and it is using a URL which I would, indeed, expect to be invalid. However, I have no idea why the port number would get lost.
Any insights would be welcome.

A: As mentioned in this answer you might want to set User-Agent and Accept properties. My guess is that if you use non-standard port, the URLConnection cannot properly guess the content type you're expecting to receive.

A: It has nothing whatsoever to do with the port number. The URL you mention  was not found at the server. HTTP status 404. You can't get that from a a wrong port number: you would get a ConnectException.


text:
Q: Query where ALL associated records have attribute value X I have a query that counts associated records AND associated status
SELECT
  orders.id,
  SUM(CASE WHEN s.shipment_status='CLOSED' THEN 1 ELSE 0 END) as closed,
  COUNT(*) as shipment_count
FROM orders as po
JOIN shipments as s ON s.order_id = po.id
GROUP BY po.id

I am attempting to query all orders, where all the shipments are CLOSED.
Essentially looking at the above, just returning when closed = shipment_count .
If I add an AND clause to the join then it will simply limit the number of shipments.

A: I figured this out with a HAVING clause, which doesn't use the select attrs.
SELECT
  orders.id
FROM orders as po
JOIN shipments as s ON s.order_id = po.id
GROUP BY po.id
HAVING SUM(CASE WHEN s.shipment_status='CLOSED' THEN 1 ELSE 0 END) = COUNT(*)

Leaving my answer up in case it helps others. Maybe better answers available to come from the community.


text:
Q: Multiselect element identifying after multiple clicks I've select element box with multiple options.
A
B
C
D

It also has "multiple" attribute, allowing user to choose multiple options at once (ctrl + click).
Currently I'm using
var example= document.getElementById('selectedboxid');

which returns selected element id (what is what I need!).
Problem I am facing is - if user wants to choose multiple elements, getElementById will return same id (the one, who was clicked first!). I need to return newly clicked element id on every click (choosing more than one element at once). How can this be accomplished?
Code looks like:
    var example = document.getElementById('select_example');

    select_example.addEventListener('change', function() {
        var elementID = select_example.value;     // Element ID stays the same...
          ...
        }
    });

A: Yout can do it like this:
var selectedOptions = document.querySelectorAll('#select_example option:checked')

This will return NodeList of all selected option elements
var selectedValues = Array.prototype.map.call(selectedOptions, function(el){return el.value})

This will map array of selected option elements to array of selected values.

A: Use selectedOptions property. Example:
<select id="myselect" multiple="multiple">
<option value="0">0-0-0-0-0-0</option>
<option value="1">1-1-1-1-1-1</option>
<option value="2">2-2-2-2-2-2</option>
<option value="3">3-3-3-3-3-3</option>
<option value="4">4-4-4-4-4-4</option>
</select>

var select = document.getElementById('myselect');

function processChange(event) {
    var selectElement = event.target;
    console.log(selectElement.selectedOptions);
}

select.addEventListener('change', processChange);

Working example: https://jsfiddle.net/a8nbj7rw/

A: This should work for getting the last one clicked and also grabbing the full list.

var sel = document.getElementById('sel');

// GEt all selected
sel.addEventListener('change',function() {

  console.log(this.selectedOptions);

});

// Get the one clicked
sel.addEventListener('click', function(evt) {
  console.log(evt.target);
});
select {
  width: 200px;
  height: 200px;
  }
<select id="sel" multiple>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
</select>