text:
Q: Spring JPA - Reading data along with relations - performance improvement I am reading data from a table using Spring JPA.
This Entity object has one-to-many relationship to other six tables.
All tables together has 20,000 records in them.
I am using below query to fetch data from DB.
SELECT * FROM A WHER ID IN (SELECT ID FROM B WHERE COL1 = '?')

A table has relationship to other 6 tables.
Spring JPA is taking around 30 seconds of time to read this data from DB.
Any idea to improve the data fetch time here.
I am using native Queries here and i am looking for query rewriting that will optimize the data fetch time.
Please suggest thanks.

A: You might need consider below to identify the root cause:

*

*Check if you are ending up with n+1 query issue. Your query might end up calling n queries for each join table, where n is no. of associations with the join table. You can check this by setting spring.jpa.show-sql=true

*If you see the issue as n+1 then you need set appropriate FetchMode, refer https://www.baeldung.com/hibernate-fetchmode for detailed explanation of using different FetchModes.

*If it is not n+1 query issue you might need to check the performance of the genarated queries using EXPLAIN command. Usually IN clause on a non indexed columns have performance impact.

So set spring.jpa.show-sql=true and check queries generated and run to debug and optimize your code or query.


text:
Q: How to include php code in .tpl file I have a small school project which I've almost finished. But now I have to change my working code and use template instead. I chose Smarty.
Table displays data from a form. Data is stored in the text file and each element is on new line. Everything worked before but now that I can't figure out how to how to display my table. With my current code, my page turns white.
I debugged it and got an error "is deprecated, use SmartyBC class to enable". I tried setting new smarty, I also tried using template function (plugin) but I still get white page. Any suggestions would be appreciated!
My table.php code: ($items function reads from the file)
<?php
$count = 0;
if (isset($Items)){
    foreach ($Items as $item) {
        if($count == 0){
            print "
$item	";
            $count += 1;
        } else if($count == 1) {
            print "$item	";
            $count +=1;
        } else if($count == 2) {
            print"$item
";
            $count = 0;
        }

    }
}

tpl file

        Name
        Lastname
        Phone

    {include_php file='table.php'}

Edit:
I used $smarty = new SmartyBC(); and changed to {php} tags. It no longer shows white screen but the table.php code doesn't work -the table doesn't show.
Is there a smarter way to do this? Other than including php file?
Edit: I got it working by using foreach loop inside the tpl but I wonder if it's the right way to do this?

A: You should not inject php code in any kind of template (not only Smarty). Load your data and perform your logic in php and render in the templating. engine. There is no need for template functions or to include php in your case.
PHP file
// Initiate smarty
$smarty = new Smarty ...;
...

// Somehow load your data from file
$itemsFromFile = somehow_load_data_from_file( ... );
...

// PAss your data to Smarty
$smarty->assign('items', $itemsFromFile);
...

// Render your template
$smarty->display( ... );

TPL file

        Name
        Lastname
        Phone

    {foreach $items as $key => $item}
        {if $key % 3 == 0}

        {/if}
                $item
        {if $key % 3 == 2}

        {/if}
    {/foreach}

Use the advantages of the templating engine. You can use modulus of three instead of counting to two and then reseting to zero.
Sources:

*

*https://www.smarty.net/docsv2/en/language.function.if.tpl

*https://www.smarty.net/docsv2/en/language.function.foreach.tpl

*Passing variable from PHP to Smarty

A: Use {php} tag then include the php file path inside it
{php}
  include('table.php');
{/php}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Copy Table from file on SD card to App database table I have created database with one table.I uploaded and downloaded that database file to and from  "SD card/Dropbox" successfully.I am storing that file upon downloading in app internal storage.Now when i am trying to copy table from that file to app database table its not inserting record.
        File data = Environment.getDataDirectory();
        db= new DatabaseHandler(getActivity().getApplicationContext());
        String currentDBPath = "//data//"+ "loginscreen.example.com.girviapp" +"//databases//"+DATABASE_NAME;
        Context context = getActivity().getApplicationContext();
        String con=context.getDatabasePath(currentDBPath).getAbsolutePath();
        File currentDB = new File(data, currentDBPath);
        ContextWrapper contextWrapper = new ContextWrapper(getActivity().getApplicationContext());
        File directory = contextWrapper.getDir("GirviDrop", Context.MODE_PRIVATE);
        File myInternalFile = new File(directory ,"GirviDrop.db");
        if (myInternalFile.exists())
        {
            db.delete_allsource_table();
            db.create_allsource_table();
            db.copy_to_allsource_table(currentDB.getAbsolutePath(),myInternalFile.getAbsolutePath());
        }

Function for Copy:
 public int copy_to_allsource_table(String dbpath,String backpath)
    {
        SQLiteDatabase db1 = this.getWritableDatabase();
        db1.openDatabase(dbpath, null, SQLiteDatabase.OPEN_READWRITE);
        String attachquery="ATTACH '"+ dbpath +"' AS AAA";
        db1.execSQL(attachquery);

        SQLiteDatabase db2 = this.getWritableDatabase();
        db1.openDatabase(backpath, null, SQLiteDatabase.OPEN_READWRITE);
        String attachquery2="ATTACH '"+ backpath +"' AS YYY";
        db1.execSQL(attachquery2);
        String countQuery1 ="INSERT INTO 'AAA'.'"+ TABLE_CONTACTSDUMMY +"' SELECT * FROM 'YYY'.'"+ TABLE_CONTACTS +"'";

        Cursor cursor1 = db1.rawQuery(countQuery1, null);
       // String countQuery11 =" SELECT * FROM 'YYY'.'"+ TABLE_CONTACTS +"'";
       // Cursor cursor11 = db1.rawQuery(countQuery11, null);

        return cursor1.getCount();
    }

Result : No Record Inserted
But there are records present in 'YYY.TABLE_CONTACTS' While i run the code by uncommenting the commented line its returning no. of records.


text:
Q: Store api responce without get method in pyspark We have deployed API in azure function API having only "post" method there is no "get" method, so here am getting below error to store the data:
Am able to see required data in print command but am unable to save, so please help me how can i save the api response in this code it self.
Code:
a = 0
while a<len(Loan_number):
    Loan = [Loan_number[a]]
    loanid = ' '.join(map(str,Loan))
    loan_id = loan_detail_df.filter(col("Loan_Number").isin(loanid))
    loan = loan_id.toPandas()
    loan_df = loan.to_dict(orient='records')
    if __name__ == '__main__':
        print("Application Started")

        rest_api_url ="<API Path>"
        input_data = loan_df

        headers = {'content-type' : 'application/json'}
        rest_api_responce_data = requests.post(url=rest_api_url, data = json.dumps(input_data), headers = headers)

        response = requests.get(rest_api_url)
        response_df = response

        print(rest_api_responce_data)
        print(rest_api_responce_data.content)

   a+=1

Thank you


text:
Q: Display Custom Properties in the Identity Management Grid and Edit views I have added a couple of Custom Properties to AppUser.  All is fine with regards to database update.
Custom Properties Added:
public static void ConfigureCustomUserProperties<TUser>(this EntityTypeBuilder<TUser> b) where TUser: class, IUser
{
    b.Property<string>(nameof(AppUser.SiteCode));
    b.Property<string>(nameof(AppUser.SiteName));
}

Question:
Now I'm look for a way to display my 2 new custom properties in the Identity Management Grid and Edit views.
Is this possible at the moment?

A: After some research into the packages used for this feature I can see the columns are hard coded so I don't expect to get any ability to see custom properties in the near future.


text:
Q: Variable levels of recursive self join - ORACLE I have the following table:
+----+---------+----------------+
| ID | COMPANY | PARENT_COMPANY |
+----+---------+----------------+
|  1 | A       | X              |
|  2 | B       | Y              |
|  3 | C       | Z              |
|  4 | D       | A              |
|  5 | E       | D              |
+----+---------+----------------+
I need to retrieve the a certain company and all descendants regardless how many they are and how many levels they expand.
For example, the company A has the child D which in turn has the child E and so forth. I want to show all these companies in one column.
I tired self-join, but I think it the number of levels is fixed. I checked the ORACLE related questions here, and I found this but the number of levels is restricted.

A: Using WITH clause:
WITH rt (
    COMPANY,
    CHILD_COMPANY
) AS (
    SELECT
        t.COMPANY,
        t.COMPANY AS CHILD_COMPANY
    FROM
        Test t
    WHERE
        t.COMPANY = 'A' /* selected company */
UNION ALL
    SELECT
        rt.COMPANY,
        t.COMPANY AS CHILD_COMPANY
    FROM
        rt
    JOIN
        Test t
    ON
        rt.CHILD_COMPANY = t.PARENT_COMPANY
)
SELECT
    rt.COMPANY,
    LISTAGG(rt.CHILD_COMPANY, ', ') WITHIN GROUP (ORDER BY rt.CHILD_COMPANY) AS DESCENDANTS
FROM
    rt
WHERE
    rt.COMPANY <> rt.CHILD_COMPANY  /* exclude self-match */
GROUP BY
    rt.COMPANY;


text:
Q: How to sequence row based on another row? I am trying to convert a formula from excel to pandas.
The DataFrame looks like this:
Column A    Column B
H
H
H
J
J
J
J
K
K

I want to fill column B to increment while the value in column A remains the same. In the example above, this would be:
Column A     Column B
H            1
H            2
H            3
J            1
J            2
J            3
J            4
K            1
K            2

In excel, the formula would be =IF(A2<>A1,1,B1+1)
How can I apply this formula in pandas?

A: This can be done using the following vectorised method:
Code:
>>> df = pd.DataFrame({'A':['H', 'H', 'H', 'J', 'J', 'J', 'J', 'K', 'K']})
>>> df['B'] = df.groupby((df['A'].shift(1) != df['A']).cumsum()).cumcount() + 1

Output:
>>> df
   A  B
0  H  1
1  H  2
2  H  3
3  J  1
4  J  2
5  J  3
6  J  4
7  K  1
8  K  2

Explanation:
First, we use df['A'].shift(1) != df['A'] to compare column A with column A shifted by 1. This yields:
>>> df['A'] != df['A'].shift(1)
0     True
1    False
2    False
3     True
4    False
5    False
6    False
7     True
8    False
Name: A, dtype: bool

Next, we use cumsum() to return the cumulative sum over that column. This gives us:
>>> (df['A'] != df['A'].shift(1)).cumsum()
0    1
1    1
2    1
3    2
4    2
5    2
6    2
7    3
8    3
Name: A, dtype: int32

Now, we can use GroupBy.cumcount() as usual to enumerate each item in ascending order, adding 1 to start the index at 1. Note that we can't just use
df.groupby('A').cumcount()

Because if, for example, we had:
>>> df
   A
0  H
1  H
2  H
3  J
4  J
5  J
6  J
7  K
8  K
9  H

This would give us:
>>> df.groupby('A').cumcount() + 1
0    1
1    2
2    3
3    1
4    2
5    3
6    4
7    1
8    2
9    4
dtype: int64

Note that the final row is 4 and not 1 as expected.


text:
Q: How do i get voicemail message programmatically in android? i want to retrive a voicemail message in my android application.is there any way to do this?
or an API??

A: voicemail is accessed by dialing a number, to do this you have to all steps programatically.
May be you want to look at Google voice mail, i heart that they have their own service which provide voicemail service.
http://support.google.com/voice/bin/answer.py?hl=en&answer=115073


text:
Q: Usage of for range in Vectors in order to add elements A lot of questions related to for range has been asked around here, but I cannot find the version I need.
So, I was reading this book called C Primer 5th edition, and while reading about Vectors I read a line which stated,
we cannot use a range for if the body of the loop adds elements to the vector.
But just before this line there was a code part written to add elements in the vectors during the run time, i.e.,
vector<int> v2; // empty vector
for (int i = 0; i != 100; ++i)
v2.push_back(i); // append sequential integers to v2
// at end of loop v2 has 100 elements, values 0 . . . 99

All I want to ask is that how can they both contradict to one another? Or are they completely different and not related to one another? If the second one is the condition can you explain me how this works?
And if the former is correct can you please explain me why do the code part and the statement contradicted to one another?

A: The reason that (amongst other things) a range-based for loop shouldn't append elements is because behind the curtains, a range-based for loop is just a loop that iterates over the container's iterators from begin to end. And std::vector::push_back will invalidate all iterators:

If the new size() is greater than capacity() then all iterators and
references (including the past-the-end iterator) are invalidated.
Otherwise only the past-the-end iterator is invalidated.

Contrary to using iterators, however, the same cannot be said when indexing the vector, because even if push_back invalidats iterators, vec[3] will always refer to the element at position 3 (assuming size() > 3).
Furthermore, the loop you show does not even iterate over the vector's elements. It just adds more elements to an existing vector, and it is not a range-based for loop.
To be clear, a construct that would be a problem would be the following:
std::vector<int> vec(10); // 10 times a zero
vec[0] = 1;
for (int k: vec)
  if (k == 1)
    vec.push_back(2); // invalidates iterators!

While this, equivalent looking code, is legal:
std::vector<int> vec(10); // 10 times a zero
vec[0] = 1;
for (std::size_t i = 0; i < std::size(vec); ++i)
  if (vec[i] == 1)
    vec.push_back(2);


text:
Q: Google App Engine Efficient Data store Read/Write Operation to Save Quota I've created an Google App Engine Apps using Python.The application deals with lot of user names.
It has got a database to 50K usernames. Each user name has a unique hash value. Which is also stored in the data store.
When any app user submit any user name. The application first checks if the username exist in DB.
If its a new user name, the application calculate a new hash for the new name and store the name and hash in DataStore.
If user name already exist in Datastore, it retrieve the old hash from data store.
Sample Code:
class Names(db.Model):
    name = db.StringProperty(required=True)
    hash = db.StringProperty(required=True)

username = "debasish"
user_db = db.GqlQuery("SELECT * FROM Names WHERE name=:1", username)
user = user_db.get()
if user == None:
    #doesn't exist in DB..so calculate new hash for that name and store it in DB
    e = Names(name=username,hash="badasdbashdbhasbdasbdbjasbdjbasjdbasbdbasjdbjasbd")
    e.put()
else:
    #retrieve the old hash.
    self.response.out.write('{"name":"'+user.name+'","hash":"'+user.hash+'"}')

The problem I'm facing is GAE's free data store read operation quota.Its exceeding too quickly and My application stop working.
I've also tried to implement memcache,like this , adding entire db in memcache. But it was also a failure,result more bad.
def get_fresh_all(self):
    all_names = db.GqlQuery("SELECT * FROM Names")
    memcache.add('full_db', all_names, 3600)
    return all_names

So,guys could you please suggest , Am I doing something wrong??
How I can make data store read operations more efficiently??
Thanks in Adv.

A: you can:

*

*switch to NDB where caching is automatic

*query the keys instead of entities SELECT __key__ FROM...

*reduce the related indexes (surely decreases the write ops, perhaps even read ops)

*rewrite all your entities with username as key_name and use the method get_or_insert()

user = Names.get_or_insert("debasish", hash="badasdbashdbhasbd")

A: You should cache only the username = hash instead of all. Plus add a in memory cache (this works per instance only cache. Should help more, just create a dict on global  module level). This could grow really quickly depending on your unique hits but you can add a logic to only hold certain numbers. Here is a sample:
cache = {}

def get_user_hash(username):
    if username in cache:
         return cache[username]
    hash = memcache.get(username)
    if not hash:
        hash = # retrieve from db
        if not hash:
            # put to db & assign hash=new_hash

        cache[username] = hash
        memcache.set(username, hash)
    return hash

A: @Faisal's method should work well, it adds two levels of caching to the query.
Another option is to store the username and hash in the session.  Only check the database once per session, and then retrieve the values from the session variables.


text:
Q: How to deal with multi-REST client running on one server Here is my situation:
I wrote two REST clients in Java which are running on my server. And these clients are packaged into Runnable Jar files. I set a schedule for running it. Every time data has been synced around 3MB.
Recently, I needed to write two more clients to sync from other resources. Before that, I didn't have software architecture experience to build an efficient client System.
My problem is my server is not good for running Microsoft windows server 2003 R2. The hardware info is following:

*

*CPU: Intel Xeon E5649 2.53GHZ

*RAM: 2GB

I use MySQL database, basically the sql writes per second around 20. It is very slow. From now, doing one synchronization takes 2 hours. I could not imagine 4 REST clients running on Monday.
I need help with how to deal with four clients running on a low capacity server. However, please don't convince me to change a new powerful server :)
I have been thinking for a long time, could I only build a client which sync data from different resource? Or build four clients which running on a different schedule? The other problem is in the future more resources will be added. I don't know how to build a system with strong scalability because of my lack of knowledge.
If you could give me some advice to push my learning a little bit, it will be very appreciated. Thank you.
Further information:
The goal is to grasp data from different RESTful servers with different API and GET query rules and insert these data into Database. Thus, basically the application's job is to put data into MySQL via RESTful call.
In addition, I only focus on it. I do not need to consider about how to deal with inserted data. The structure is simply:

*

*Get Restful call and get JSON format result

*parsing JSON

*insert into DB

I used (JAX-RS) Jersey api to implement RESTful call, and use JDBC to manage the database, but I am working on the next version which will use Hibernate to implement insert, delete, update, and search functions.
This application implementation does not use any application server. I package the program to runnable jar file, and set schedule to run it on windows server 2003.
Being a recently graduated student, that is my first REST client, but with my deep research and studying, I know more about it. However, I don't have experience on it. I just want to make it work better. Any suggestion, I appreciate it.

A: Use a profiler to gain insight into the actual memory and CPU usage of your application. You can then decide how to improve it using the appropriate means. (F.e. multithreading, caching, compression, ...)


text:
Q: Why FULL OUTER JOIN 2 Tables not returning all rows of those tables I have 2 tables like below
Table Demographics2
CREATE TABLE Demographics2
(Date date,
 FirstID int,
 SecondID int,
 FirstName varchar(50),
 LastName varchar(50),
 DCode int
 )
 ;

Insert into Demographics2 VALUES
('20200402', 342, 812, 'John', 'Smith', 823),
('20200414', 263, 812, 'Jane', 'Austen', 676),
('20200414', 263, 812, 'Jane', 'Austen', 556)
;

Table Item2
CREATE TABLE Item2
(Date date,
 FirstID int,
 SecondID int,
 ItemName varchar(50),
 ItemForm varchar(50),
 ICode int
 )
;

Insert into Item2 VALUES
('20200318', 754, 812, 'Perindo', 'Blue', 169),
('20200318', 754, 812, 'Perindo', 'Blue', 156),
('20200318', 754, 812, 'Lipitor', 'Blue', 295),
('20200318', 754, 812, 'Perindo', 'Blue', 627),
('20200318', 754, 812, 'Perindo', 'Blue', 740),
('20200318', 754, 812, 'Metformin', 'Green', 992),
('20200414', 263, 812, 'Pred', 'Blue', 234),
('20200414', 263, 812, 'Pred', 'Blue', 279),
('20200414', 263, 812, 'Phen', 'Blue', 605),
('20200414', 263, 812, 'Pred', 'Blue', 979),
('20200414', 263, 812, 'Phen', 'Blue', 513),
('20200414', 263, 812, 'Pred', 'Blue', 127)

When I FULL OUTER JOIN 2 tables, with time filter in WHERE, the result I got lacked the rows of Date 20200318 of Table Item2
SELECT *
FROM master.[dbo].[Demographics2] d
     FULL OUTER JOIN master.[dbo].[Item2] i
     ON d.FirstID = i.FirstID
WHERE CONVERT(date,d.Date) BETWEEN '2020-03-01 00:00:00.000' AND '2020-05-01 00:00:00.000'

-- Result

 Date     FirstID SecondID  FirstName   LastName DCode  Date    FirstID SecondID    ItemNameItemFormICode
2020-04-02  342   812      John         Smith   823     NULL       NULL NULL        NULL    NULL    NULL
2020-04-14  263   812      Jane         Austen  676     2020-04-14  263 812         Pred    Blue    234
2020-04-14  263   812      Jane         Austen  676     2020-04-14  263 812         Pred    Blue    279
2020-04-14  263   812      Jane         Austen  676     2020-04-14  263 812         Phen    Blue    605
2020-04-14  263   812      Jane         Austen  676     2020-04-14  263 812         Pred    Blue    979
2020-04-14  263   812      Jane         Austen  676     2020-04-14  263 812         Phen    Blue    513
2020-04-14  263   812      Jane         Austen  676     2020-04-14  263 812         Pred    Blue    127
2020-04-14  263   812      Jane         Austen  556     2020-04-14  263 812         Pred    Blue    234
2020-04-14  263   812      Jane         Austen  556     2020-04-14  263 812         Pred    Blue    279
2020-04-14  263   812      Jane         Austen  556     2020-04-14  263 812         Phen    Blue    605
2020-04-14  263   812      Jane         Austen  556     2020-04-14  263 812         Pred    Blue    979
2020-04-14  263   812      Jane         Austen  556     2020-04-14  263 812         Phen    Blue    513
2020-04-14  263   812      Jane         Austen  556     2020-04-14  263 812         Pred    Blue    127

Is there any way of putting time filter in WHERE clause but still getting all the rows of 2 tables (My expected result I got from FULL OUTER JOIN 2 tables without time filter in WHERE clause)
-- Expected result
    Date    FirstID SecondID    FirstName   LastName    DCode   Date    FirstID SecondID    ItemName    ItemForm    ICode
2020-04-02  342     812         John        Smith       823     NULL       NULL NULL       NULL         NULL    NULL
2020-04-14  263     812         Jane        Austen      676     2020-04-14  263 812        Pred         Blue    234
2020-04-14  263     812         Jane        Austen      676     2020-04-14  263 812        Pred         Blue    279
2020-04-14  263     812         Jane        Austen      676     2020-04-14  263 812        Phen         Blue    605
2020-04-14  263     812         Jane        Austen      676     2020-04-14  263 812        Pred         Blue    979
2020-04-14  263     812         Jane        Austen      676     2020-04-14  263 812        Phen         Blue    513
2020-04-14  263     812         Jane        Austen      676     2020-04-14  263 812        Pred         Blue    127
2020-04-14  263     812         Jane        Austen      556     2020-04-14  263 812        Pred         Blue    234
2020-04-14  263     812         Jane        Austen      556     2020-04-14  263 812        Pred         Blue    279
2020-04-14  263     812         Jane        Austen      556     2020-04-14  263 812        Phen         Blue    605
2020-04-14  263     812         Jane        Austen      556     2020-04-14  263 812        Pred         Blue    979
2020-04-14  263     812         Jane        Austen      556     2020-04-14  263 812        Phen         Blue    513
2020-04-14  263     812         Jane        Austen      556     2020-04-14  263 812        Pred         Blue    127
NULL    NULL        NULL        NULL        NULL        NULL    2020-03-18  754 812     Perindo         Blue    169
NULL    NULL        NULL        NULL        NULL        NULL    2020-03-18  754 812     Perindo         Blue    156
NULL    NULL        NULL        NULL        NULL        NULL    2020-03-18  754 812     Lipitor         Blue    295
NULL    NULL        NULL        NULL        NULL        NULL    2020-03-18  754 812     Perindo         Blue    627
NULL    NULL        NULL        NULL        NULL        NULL    2020-03-18  754 812     Perindo         Blue    740
NULL    NULL        NULL        NULL        NULL        NULL    2020-03-18  754 812   Metformin        Green    992

A: The WHERE clause filters out records present only in the second table, for those records d.Date is NULL.
You can use OR d.Date IS NULL to include those records too:
SELECT *
FROM master.[dbo].[Demographics2] d
FULL OUTER JOIN master.[dbo].[Item2] i
     ON d.FirstID = i.FirstID
WHERE (CONVERT(date,d.Date) BETWEEN '2020-03-01 00:00:00.000' AND '2020-05-01 00:00:00.000')
     OR d.Date IS NULL

@TimBiegeleisen's answer is also valid, it basically depends on what you want to do.

A: You may try logically filtering on both dates with the help of COALESCE():
SELECT *
FROM master.[dbo].[Demographics2] d
FULL OUTER JOIN master.[dbo].[Item2] i
     ON d.FirstID = i.FirstID
WHERE CONVERT(date, COALESCE(d.Date, i.Date)) BETWEEN '2020-03-01' AND '2020-05-01';


text:
Q: Spark SQL- Running Query in HiveContext vs DataFrame I'm exploring Spark SQL and I've been experimenting with Hive Query Language (HQL) and DataFrames. Some time ago, I performed an experiment comparing the performance of running queries via HiveContext versus that of DataFrames.
I ran a query in a loop
for(i <- 1 to 100){
  val selectQuery : String = s"SELECT * FROM table_1 t1 JOIN table_2 t2 ON t1.col1 = t2.col1 LEFT OUTER JOIN table_3 t3 ON (t1.col1 = t3.col1 and t2.col2 = t3.col2) WHERE t1.col2 = $i"

  hiveContext.sql(s"INSERT INTO resultTable PARTITION(col_res = $i) $selectQuery")
}

It ran for about 4 hours.
Then I loaded the tables in DataFrames and wrote it in the result table
val t1 = hiveContext.sql("SELECT * FROM table_1")
val t2 = hiveContext.sql("SELECT * FROM table_2")
val t3 = hiveContext.sql("SELECT * FROM table_3")

for(i <- 1 to 100){
  val resultDF = t1.filter(s"col2 === $i").join(t2, "col1").join(t3, Seq("col1", "col2"), "left_outer")

  resultDF.write.mode("append").format("parquet").partitionBy("").saveAsTable(resultTable)
}

Which ran for only an hour and a half (I did not cache or persist the DataFrames).
Initially, I thought that in the first way, map/reduce jobs were run because I ran the query through HiveContext in Hive but apparently, this assumption was wrong.
My current theory is that HiveContext has to connect to Hive 100 times in the loop and that's what makes the first method consume so much time.
I've scoured the net looking for the reason behind this difference but haven't found anything yet. Could someone help shed some light on this? I use Spark 1.5.0
PS- The query is just for demonstration. I don't know whether it'll actually work. Please let me know if any more information is required.
Edit This question is about an actual difference observed in code. My question isn't if there will be a difference in time taken for execution. My question is why there was a difference in this particular scenario.


text:
Q: how to display image from xml through php? i have two files note.xml and xml.php
here is my code of note.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<agents>
    <agent>
    <image> img/primary-nav-logo.png</image>
    <name>Tommy Jenkin</name>
    <company>CJenkins Insurance</company>
    <street>Insurance150 S State Stree</street>
    <city>Linkend</city>
    <phone>(773) 561-4331</phone>
    </agent>
    <agent>
    <image> img/primary-nav-logo.png</image>
    <name>Tommy Jenkin</name>
    <company>CJenkins Insurance</company>
    <street>Insurance150 S State Stree</street>
    <city>Linkend</city>
    <phone>(773) 561-4331</phone>
    </agent>
</agents>

and here is my code of xml.php
<?php
                $xml = simplexml_load_file("note.xml")
                or die("Error: Cannot create object");
                function processXML($node){
                    foreach($node->children() as $agent => $data){
                    if(trim($data) != ""){
                        echo $data;
                        echo "
";
                    }
                    else{
                        echo "
";
                    }
                    processXML($data);
                    }
                }
                processXML($xml);

?>

Now i want to display full data of xml  with the image so how can i display it.please help

A: Can you try this,
         $xml = simplexml_load_file("note.xml") or die("Error: Cannot create object");
            function processXML($node){
                foreach($node->children() as $agent => $data){
                      $agent= trim($agent);
                     if($agent!="" && $agent=='image'){
                           echo '';
                     }elseif($agent!=""){
                          echo $data;
                          echo "
";
                     }else{
                          echo "
";
                     }

                processXML($data);
                }
            }
            processXML($xml);


text:
Q: NetBeans IDE 8.0.2 cannot build C++ programs after Windows 10 upgrade My Windows 7 was upgraded to Windows 10 a week ago. Before the upgrade, my NetBeans IDE 8.0.2 with C/C++ plugin worked fine with C++ programs. However, after the Windows 10 upgrade, it cannot build/make C++ programs any more, with the error message below. Note that the Java plugin still works fine, and the C++ editor part is still OK too. The C/C++ Tool Collection is 64-bit Cygwin.
Any clue on what caused this specifically, and any solution on fixing this?
===== Complete Error Message Below: =====

4 [main] make 5900 C:\cygwin64\bin\make.exe: *** fatal error in forked process - fork: can't reserve memory for parent stack 0x600000 - 0x800000, (child has 0x400000 - 0x600000), Win32 error 487

15248 [main] make 5900 cygwin_exception::open_stackdumpfile: Dumping stack trace to make.exe.stackdump

9 [main] make 4464 fork: child -1 - forked process 5900 died unexpectedly, retry 0, exit code 0x100, errno 11

make: nbproject/Makefile-variables.mk:33: fork: Resource temporarily unavailable

43162 [main] make 2164 C:\cygwin64\bin\make.exe: *** fatal error in forked process - fork: can't reserve memory for parent stack 0x600000 - 0x800000, (child has 0x400000 - 0x600000), Win32 error 487

43898 [main] make 2164 cygwin_exception::open_stackdumpfile: Dumping stack trace to make.exe.stackdump

3943868 [main] make 4464 fork: child -1 - forked process 2164 died unexpectedly, retry 0, exit code 0x100, errno 11

make: fork: Resource temporarily unavailable

BUILD FAILED (exit value 2, total time: 9s)


text:
Q: Browser tries to open application/json as a file I'm having a problem with my JSON response in my MVC 3 application. When JSON is responding, my browser cannot handle application/json and tries to open it as a file. However, I'm recieving the correct data in the file.
I've added this to my Global.asax file:
ValueProviderFactories.Factories.Add(new JsonValueProviderFactory());

This is my javascript code:
    $('#register).submit(function () {
        if ($(this).valid()) {
            var ai = {
            Firstname: $("#Firstname").val(),
            Lastname: $("#Lastname").val(),
            Email: $("#Email").val()
            };

            var json = $.toJSON(ai);
            $.ajax({
                url: '/Person/Create',
                type: 'POST',
                dataType: 'json',
                data: json,
                contentType: 'application/json; charset=utf-8',
                success: function (data) {
                    alert("Success");
                },
                error: function (data) {
                    alert("Error");
                }
            })
        }
    });

And this is my ActionResult method:
    [HttpPost]
    public ActionResult Create(Person person)
    {
        if (ModelState.IsValid)
        {
            db.Personer.Add(person);
            db.SaveChanges();
        }

        return Json(new { Success = person.ID > 0, Firstname = person.Firstname, Lastname = person.Lastname });
     }

I've also added .json (application/json) to the MIME-list in IIE.

A: If you're trying to access a file with JSON headers in Firefox directly (meaning: you're entering the URL into the address bar), Firefox will download it as a file. However, when you call your JSON in an AJAX request, it'll work the way you want it to.


text:
Q: Accessing vuex store state array details in another Vue component I have a marketplace and I store chosen products from localstorage in cart in Vuex Store as a JSON to share them with other components. Now when client buys products I want to access cart details and store it in the DB with their name and other info, but I cannot access JSON details I want from Vuex Store.
Vuex:
let cart = window.localStorage.getItem('cart')

const store = createStore({
    state: {
        cart: cart ? JSON.parse(cart) : [],
    },
})

checkout Vue component:
With .map() I get another array and I want to get a single value. I have also tried .forEach() but I get the value of undefined.
export default {
  data() {
    return {

      customers: {
        name:'',
        adress:'',
        town:'',
        email:'',
        phone:'',
        title : this.$store.state.cart.map(function (detail){
          return detail.ropeTitle
        }),
        diameter: this.$store.state.cart.map(function (detail) {
          return detail.ropeDiameter
        }),
        price: this.$store.state.cart.map(function (detail) {
          return detail.ropePrice
        }),
        cartQuantity: this.$store.state.cart.map(function (detail) {
          return detail.ropeQuantity
        })

      },

    }

  },
    methods: {
    async handleSubmitForm() {
      try {
        await axios.post('http://localhost:3000/api/orders/customers', this.customers)
            .then(() => {
              this.$router.push('/customers')
              this.customers = {
                name:'',
                adress:'',
                town:'',
                email:'',
                phone:'',
                title : '',
                diameter: '',
                price: '',
                cartQuantity: '',

              }
              router.go(-1)
            })
      } catch (error) {
        console.log(error)
        console.log(this.customers)

      }
    }
  }

}

Can you please help?

A: so I made details as separate states in getters like this:

 setTitle: state =>{
           let oneItem=''
            state.cart.forEach((item)=>{
                oneItem=item.ropeTitle
            })

            return oneItem
        },

and then I used it in a component like this:
title : this.$store.getters.setTitle,


text:
Q: `ReferenceError: React is not defined` in vue3 jsx files i am trying to implement storybook with antdv, when I import a tsx file which returns jsx inside button.stories.js, I got "ReferenceError: React is not defined"
you can see error here
but react is not the part of this project at all, it is a vue js project and all tsx and jsx is returned from tsx files but under the hood they are all vue js files as they use vue js features.
all kind of help is appreciated

A: Probably its an error with configuration on JSX transpiler,i think a solution can be import react even if you don't use it
import React from 'react';


text:
Q: Is there a solution to this geometry problem?
The point $G$ is centroid in the triangle $ABC$.
$m(BGC)=90^o$
$|AB|=8 \;cm$
$|CG|=? \, cm$
I know that $|GD|=|BD|=|DC|$ and $|AG|=|BC|=2|GD|$. I'm stuck after this point. I've tried to find the answer by solving system of equations, but it didn't work out. How do I solve this question?

A: I'll start by recapping, with explanation, some things OP already knows. (I believe OP made a typo in asserting $|AG|=|BC|=\frac12|GD|$. The "$\frac12$" should (obviously?) be a "$2$".)
Since $\overline{AD}$ is a median, the condition that $\angle BGC$ is right tells us that $D$ is the midpoint of the hypotenuse of right triangle $\triangle BGC$; therefore, $D$ is the circumcenter of that triangle: $|BD|=|GD|$. Moreover, we know that a centroid trisects each median: $|AD|=3\,|GD|$.
Thus, the perpendicular medians tell us this about $D$:
$$|AD| = 3\,|BD|$$
Now, there's a whole family of points $D$ whose distance from $A$ is three-times their distance from $B$: they live on the circle with diameter $\overline{D_1D_2}$ where $D_1$ and $D_2$ are the two easily-located points on $\overleftrightarrow{AB}$ (one between $A$ and $B$, the other on the "far side" of $B$) satisfying that property.
Every point $D$ on this circle (except perhaps $D_1$ and $D_2$ themselves, depending upon the reader's tolerance for degenerate cases) gives rise to a viable $\triangle ABC$.

However, the target distance, $|CG|$, varies, from a minimum of $0$ (when $D=D_1$) to a maximum of $|AB|$ (when $D=D_2$). Consequently, there is no unique solution to the problem described. $\square$

A: Perpendicularity of the two medians $m_b$ and $m_c$ is equivalent to $b^2+c^2=5a^2$
Knowing $c=8$ and $b^2+c^2=5a^2$ does not allow us to determine $2a^2+2b^2-c^2$ (that is, the $4m_c^2$, which we would know if we knew $|CG|$)
Consider two triangles, one having $a=\sqrt{20}, b=6, c=8$ and the other $a= \sqrt{45}, b=\sqrt{161}, c=8$.
Both of them satisfy $b^2+c^2=5a^2$, and yet the quantity $2a^2+2b^2-c^2 = 12a^2 - 3c^2$ is different for them, since their $a$'s differ.

A: The point $D$ is not uniqely determined. Everything is on a picture:

We have $$4b^2+c^2=16$$
but $$ CG = 2c $$


text:
Q: ExpressJs: Istanbul coverage report with mocha I tried to get a coverage report for my test cases, and installed istanbul,
My coverage report works fine for a single test file that is in root folder, else I get "No coverage information was collected, exit without writing coverage information"
My folder structure is
app/
 — node_modules/
 — coverage/
 — server/
 — —  app.js
 — test/
 — — index.test.js
 — test.js

When I run
istanbul cover _mocha test.js

I get a coverage report however If I try to tun
istanbul cover _mocha test/*.js

or
istanbul cover _mocha test/index.test.js

I don't get any coverage report
I tried all hit and trial its not working any work around for the same?
How can I run istanbul to cover report for all the test cases recursively ?

A: So Actually I misunderstood how Istanbul works,
I was running the server as separate instance to run the test case and then running the istanbul.
So I stopped the running instance of the server and then include config to run server for istanbul.
That helps irrespective of the folder structure you keep for your test cases.
Do global installation of mocha and istanbul
npm install -g mocha istanbul

FOR LINUX/MAC
NODE_ENV=testing_coverage istanbul cover _mocha  ./server/tests/*/.js --recursive ./bin/www ;
open coverage/lcov-report/*.html

FOR Windows
SET NODE_ENV=testing_coverage&istanbul cover ./node_modules/mocha/bin/_mocha  ./server/tests/*/.js --recursive ./bin/www&open coverage/lcov-report/*.html

WHERE
    SET

This is to be include in the windows to set the enviorment

&this is to be included in windows to seperate the commands

NODE_ENV=testing_coverage
enviorment set for coverage and add this config in
config.env file

cover
to cover istanbul code coverage, check istanbul help

---recursive
for running recursive test case

_mocha
For mac: mocha file in node_modules/.bin/_mocha

./node_modules/mocha/bin/_mocha
For windows set this path

./bin/www
Main file to start the application

./server/tests/*/.js
test cases folder path from root

open coverage/lcov-report/*.html
To open the coverage report in browser
after all the test case gets completed


text:
Q: Gulp. Конкатенация одного-единственного файла к некоторому их числу Возможно чего-то не понял( скорее всего, так и есть), но так и не удалось выполнить следующую задачу:
Есть каталог /src/js
В нём( безо всяких вложенных каталогов) лежат .js файлы, соответствующие разным страницам. Название каждого из них начинается с названия страницы( т.е для одного-единственного скрипта страницы services.php, будет скрипт services.js)
Практически все эти скрипты используют jQuery.
Поэтому, для наведения порядка в итоговой версии, потребовалось добавить один файл( jquery.min.js ) в начало каждого файла из входного потока( ./src/js/.js* ). Сделать этого не удалось. Собсно, каким образом это( добавить произвольный файл или неск в начало каждого выходного) можно реализовать НЕ прибегая к описанию руками адреса каждого исходного файла и целой горы неведомых трюков, с этим связанных?
П.С: несколько аналогичный вопрос и по CSS:
Есть конторный, специальным образом подготовленный( убран ненужный хлам итд) bootstrap.min.css
Проект делается с применением LESS ( фу, ну да ладно).
Т.е вначале все нужные .less файлы компилятся, потом - минифицируются, на выходе давая конфетку.
Проблема в том, что css файл подрубить в LESS не так уж и просто:
a. если подключать его как css ( @import (css) "адрес";), тогда в итоговом файле CSS будет просто ссылка на него( т.е припишется CSS-ный импорт соотв. файла)
b. если подключать его как less ( @import (less) "блаблабла";), тогда начинают сыпаться ошибки, т.к это, мало того, что не LESS, так ещё и минимизированный. Была идея всё это экранировать, заключив всё содержимое переименованного в bootstrap.min.less в ~"css-код, который никак не проверяется препроцессором, а сразу выплёвывается в выходной файл", однако, это не удалось, ввиду обилия в упомянутом как одинарных, так и двойных кавычек.
Засим, аналогичный вопрос: каким образом к каждому из получаемых css файлов( на одну страницу получается один css файл за исключением бутстраповского), в начало поместить содержимое некоторого файла( bootstrap.min.css) ?

A: Небольшое лирическое отступление
Подход с объединением всех необходимых JS библиотек в один файл вместе с использующими их скриптами имеет как плюсы так и минусы.
Плюсы объединения:

*

*Вам не нужно писать портянку тэгов <script> в HTML коде страниц.

*Вам не нужно беспокоиться, что какая-то библиотека обновилась/добавилась/удалилась а вы забыли изменить/добавить/удалить соответствующий тэг <script>.

*Браузеры имеют ограничения на количество одновременно открываемых соединений. Поэтому, если у вас действительно много библиотек, то загружать один большой файл может быть эффективнее, чем очень много маленьких. Это связано с накладными расходами на открытие/переиспользование соединений.

Минусы такого подхода вполне очевидны:

*

*Вы не можете использовать кэширование отдельных библиотек на уровне HTTP запросов.

*Вы не можете использовать CDN для загрузки сторонних библиотек.

*Вам нужен некий слой сборки, который будет заниматься "склеиванием" библиотек.

*Вам нужно помнить, что при добавлении зависимости в ваш JS код вам нужно будет править сборочные скрипты (конечно, если вы не используете Browserify или аналоги).

В целом, в склеивании библиотек нет ничего страшного, но только если вы склеиваете необходимые для конкретной страницы библиотеки, а не все сразу.
Для решения подобной задачи очень часто используются инструменты, вроде Browserify (который, кстати, неплохо интегрируется с Gulp). Подобные инструменты умеют анализировать ваш код, и генерируют сборку, включающую только необходимые для ее работы библиотеки и модули. Проблема только в том, что для использования Browserify вам скорее всего придется изменить свой подход к написанию JavaScript кода.

Теперь о вашей конкретной проблеме
В экосистеме gulp есть большое количество всевозможных плагинов. Одним из таких плагинов является gulp-header. Этот плагин позволяет вставить произвольное содержимое в начало каждого файла в потоке. А использовать этот плагин можно, например, так:
var fs = require('fs'),
    gulp = require('gulp'),
    header = require('gulp-header');

gulp.task('default', function() {
    return gulp.src('./src/*.js')
        .pipe(header(fs.readFileSync('./libs/jquery.js') + "\n"))
        .pipe(gulp.dest('./dist'));
});

A: Как то так ...
gulp.task('build', function() {

    var fs = require('fs');

    fs.readdir('/src/', function(err, items) {

        console.log(items);

        for (var i=0; i<items.length; i++) {
            if(/^(.*)\.js$/.test(items[i])) {
               gulp.src(['jquery.min.js', items[i]])... и т.д.
            }
        }

    });

});

Но по моему вариант с раздельной склейкой не лучший вариант ...


text:
Q: How to install libxml2 for python when using pyenv Here are the details of my python install:

*

*OS X 10.9

*homebrew used to install pyenv (https://github.com/yyuu/pyenv)

*python was installed  via pyenv install 2.7.6

*custom virtualenv just for this project

Given the above python install, how would someone set up libxml2?
So far, I've tried brew install libxml2, hacking the recipe to have --with-python. That seems to compile, but then python starts having SegFaults when I try to use libxml2.
Thanks in advance!

A: It may possibly be related to packages being compiled against old libxml2. You can check libxml2 origin with gdb, run gdb python and execute command that lead to SegFault.
One option why it is happening is that brew installed libxml2 to local folder, say /usr/local, and your packages are compiled against libraries shipped with OS (usually old and buggy on OSX, not sure  for Mavericks) from /usr/lib are being used.

A: Found the solution.
brew install libxml2 --with-python

Some files were installed into /usr/local/lib/python2.7/site-packages/libxml2*. I copied them to my virtualenv's site-packages and voila things worked!
Symlinking might be something better to try.


text:
Q: How to dynamically create properties in polymer as needed I have a use case where I have a component (like a database) that I would like to expose all the information as bindable properties.  However, only a few of those properties will be need by any particular client who uses it.  There could be 1000's of entries in the database.  How can I figure out which ones are actually needed by the client.
For example:
Polymer('database,
    {
       observer : {
           name : function(oldVal, newVal) { onDataChanged('name', newVal);},
           addr : function(oldVal, newVal) { onDataChanged('addr', newVal);},
           tel.main : function(oldVal, newVal) { onDataChanged('tel.main',
                 etc....
        }
    });

In this case I would like to dynamically create observe handlers only for the data bindings that are actually needed on the fly.

A: If you are willing to have your clients extend your component to specify the desired database fields then you can dynamically create observers only for the fields they specify.
Example
Component
<link rel="import" href="../../webcomponents/bower_components/polymer/polymer.html">
<polymer-element name=demo-dynamicproperties >
 <template>

dynamic properties

   See the console for changes
 </template>

</polymer-element>

Usage
<!DOCTYPE HTML>

  <link rel="import" href="../../webcomponents/bower_components/polymer/polymer.html">
  <link rel="import" href="demo-dynamicproperties.html">
  <title>demo-dynamicproperties test page</title>

<polymer-element name=demo-usedb extends="demo-dynamicproperties" attributes="validitem1 validitem2 invaliditem" noscript>
</polymer-element>

Demo

   <template is="auto-binding">

Dynamic tag

     <demo-usedb validitem1="{{item1choice2}}" item2="setthis"></demo-usedb>

Input

      <input type="text" value="{{item1choice2}}">

Produces

     {{item1choice2}}
  </template>

A: It looks like the answer to the questions is that it cannot be done.  There does not appear to be any hooks or events that a component can use to get notified when properties are bound (or attempted to be bound) to it.  I filed a bug/enhancement request here
https://github.com/Polymer/polymer/issues/1303
to request that this feature be supported in the future.


text:
Q: Scala and exception handling I am curious why exception handling is a topic often ignored in Scala. Is it the goal of the language (or the style) to not rely on exception handling except for external input/code?
I was hoping the style guide had some discussion on exception checking/handling. Is there a good reference that I could consult to understand if there are any differences in handling exceptions in Scala vs. languages I'm more used to (C++/C#/Java/Ruby/etc)?
Would someone with some Scala years under their belt be willing to write down guidelines for exception handling that are Scala specific? or is the answer simply "do as you would in Java"? What is "the functional way"?

A: Good functional style does not need defensive coding nearly as much as the imperative style.  try and catch is not the only control structure which is neglected in Scala (and other functional languages); for and while loops are endangered species and even if...else is used more selectively (although much more effectively, since it returns a value).
In the functional world, you match your code to the shape of the data.  Or you choose a shape which gives your code the structure you want.  This is true not only with Option and Either but List and Set and Map and more.  All of them are paired with powerful Higher Order Functions - map, fold, filter etc.
To take a trivial example, if a Java or C++ coder wants to fetch the first (or all) of the items in a list and manipulate it, they either have to first check that the list is not empty or wrap it in  try/catch to handle the error.  If they have to deal with a collection of lists, the latter option is more likely to be chosen (and even less likely to match the context which might generate an error).
In Scala you can simply do this to the list of Ints called xs:
  xs.headOption map (_ * 2)
  // Returns twice the first item - if there is one - as an Option

or
  xs map (_ * 2)
  // Doubles everything in the list.  Returns a list.

If there is nothing in the list, nothing will happen.  If you want something to happen, you can detect the failure and react.
  xs.headOption map (_ * 2) orElse Some(0)
  // Returns Some(twice the head item) if there is one or Some(0)
  xs.headOption map (_ * 2) getOrElse 0
  // Returns twice the head item or 0 if there is none

Even better, if you are dealing with a lists of lists, any one of which might be empty, mapping over each of them will produced results for every populated list and no problem at all with any empty ones.  That is very powerful when dealing with large collections of unpredictable data.
What these functional types (Option and Either and List and Map and all the other - sorry to use the ugly word - monads) also offer, very importantly, is separation of concerns.  Notice how I used map in all the above examples.  In two examples it is Option.map, while in the other it is List.map.  In all cases, map is doing the same thing: ¨Apply my function to the data inside that container, preserving the context¨.  If it is a list context, you get a list of transformed data back.  If it is a ¨may or may not exist¨ context, you may get your transformed object.  If it is a ¨this could really go badly wrong¨ context, you either get your object or a chance to complain.  And so on.
So you get a separation of concerns between the action you want to perform and the context in which it is applied.  The big advantage is that if you decide to change the context (e.g. Set of unique objects rather than arbitrary List of objects), the rest of the code doesn´t need to change at all.  map will still do the right thing (as will filter, fold and the rest).
Built-in imperative keywords like try..catch or if...else...if...else do not have that power.  For a start, they have no real meaning of their own and have to be bodged together (distorting the code tangled within them) and they offer no guarantee.  Imagine having used those to manage an arbitrary list of objects and then deciding you want to guarantee uniqueness.  How much of that imperative code will you have to change?  How can you be confident it will work?
Leave exceptions to deal with the truly unexpected and unsolveable.  Functional types can be confident about their guarantees, to help you avoid the common and predictable errors.

A: Scala encourages the use of constructs like options and futures for error handling. First of all, lazy evaluation makes exceptions problematic, because there is a different stack when a function is executed than when it's queued to execute. Scala isn't lazy by default, but it can be lazy when you choose.
Also, options and futures are much more powerful than exceptions. You can chain operations on them, and they aren't limited to propagating straight up the stack like exceptions are. You can store them in collections and reduce duplication in handler code.
Pretty much the only time you use exceptions in Scala is for errors you can't handle that will kill your program anyway.


text:
Q: Find size of unknown type memory in kernel I have an unknown void* bufferpointer. Is there away to find the memory size of the buffer. I do not have access to malloc.h, I do however have access to sys/malloc.h in Freebsd kernel.

A: In the Linux kernel, if you have pointer to some virtual memory, it can be reversed back to the struct page * as well as the struct vmap_area or struct vm_area_struct which indicates what mmap-ed region it points to (from which you know the size).
The operating system needs these kinds of reverse mappings because without them it wouldn't be able to do things like, oh, handle a page fault, and then map the memory, and then extend an auto-growing mapping, if necessary and so on.
If you suspect the address is in space allocated by vmalloc (the kernel's own allocator for kernel-owned virtual memory) you can try find_vmap_area which searches through the red-black tree of vmalloc areas and returns a pointer to a struct vmap_area. That will be null if the address is not found there.
If you suspect the address is regular process virtual memory, then find_vma maybe able to find it. It returns a struct vma_struct * pointer, which is null if the lookup fails.
Both these structures give you information about the starting and ending address of the mapping which contains the address.
You're not going to get fine-grained information, like how big of a user-space malloc chunk is referenced by a pointer.
Also, I don't think you can reverse random addresses that point to memory which came from kmalloc to the allocation info.


text:
Q: Usage of "get away with something" in sentences I'm wondering if that's the correct usage of the 'get away with something' phrase:

I still can't believe how I got away with attending philosophy classes only 3 times through the year.

What I mean is I still can't believe I didn't get punished for skipping philosophy classes (I was present only 3 times during the year - I skipped the rest and I'm still amazed I didn't get punished for skipping so many of my classes), but instead of saying I still can't believe how I got away with skipping school so much I wish to say I still can't believe how I got away with attending school so little and I'm wondering if it's the correct usage and if it sounds natural.

A: You use 'got away with' correctly here.
It does sound a little awkward (perhaps colloquial?) because you use how.  I don't think you intend to communicate that you can't believe the manner in which you got away with things.
Using that instead of how is more precise and flows better. (Assuming that you do mean to point out the fact that you weren't punished, not your means of avoiding punishment.)

A: According to the Cambridge Dictionary, the verb believe is normally followed by a that- clause. The clause explains what you believe. According to this approach, the correct form would be:

I still can't believe that I got away with attending philosophy classes only 3 times through the year.

In informal speech, the that is omitted:

I still can't believe I got away with attending philosophy classes only 3 times through the year.

When you have a sentence where the clause expresses the degree or extent of something, it is normal to use how:

I still can't believe how stupid I was - adjective: degree of stupidity
  I still can't believe how badly he reacted - adverb: degree of rudeness
  I can't believe how many pairs of shoes she has - determiner: degree- count

This construction is sometimes used inappropriately when the that-clause is a simple fact, not a matter of degree, as in your sentence, where "I got away with..." is a simple fact:

I still can't believe how I got away with attending philosophy classes only 3 times through the year.

The use of how would be justified if you were to add easily, which would make it a matter of degree:

I still can't believe how easily I got away with attending philosophy classes only 3 times through the year.

This NGram, shows how very uncommon believe how is in writing, and if you look at the actual references you will find that most of them are not relevant- "I want to believe: how can I.." or express degree

I couldn't believe how much money I was making
  I can't believe how blatantly Guy Ritchie ignored this in his film


text:
Q: Selecting Pandas Dataframe by set values Let the Pandas Dataframe df below, how can I find the lines with both values 6 and 10?
    0   1   2   3   4   5   6
0   11  1   3   4   6   8   10
1   11  1   3   4   6   8   11
2   11  1   3   4   6   8   0
3   11  1   3   4   6   9   10
4   11  1   3   4   6   9   11
5   11  1   3   4   6   9   0
6   11  1   3   4   6   10  10
7   11  1   3   4   6   10  11
8   11  1   3   4   6   10  0
9   11  1   3   4   7   8   10

I can obtain these lines with a solution based on sets:
>>> df.iloc[[i for i, s in enumerate(df.itertuples()) if {6, 10} <= set(s)]]

    0   1   2   3   4   5   6
0   11  1   3   4   6   8   10
3   11  1   3   4   6   9   10
6   11  1   3   4   6   10  10
7   11  1   3   4   6   10  11
8   11  1   3   4   6   10  0

My question is: Is there a better way in Pandas to get True in the lines where these given values are present? Something such as:
df.where({6, 10} <= df)

The data example:
pandas.DataFrame.from_dict({0: {0: 11, 1: 11, 2: 11, 3: 11, 4: 11, 5: 11, 6: 11, 7: 11, 8: 11, 9: 11},
 1: {0: 1, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1, 7: 1, 8: 1, 9: 1},
 2: {0: 3, 1: 3, 2: 3, 3: 3, 4: 3, 5: 3, 6: 3, 7: 3, 8: 3, 9: 3},
 3: {0: 4, 1: 4, 2: 4, 3: 4, 4: 4, 5: 4, 6: 4, 7: 4, 8: 4, 9: 4},
 4: {0: 6, 1: 6, 2: 6, 3: 6, 4: 6, 5: 6, 6: 6, 7: 6, 8: 6, 9: 7},
 5: {0: 8, 1: 8, 2: 8, 3: 9, 4: 9, 5: 9, 6: 10, 7: 10, 8: 10, 9: 8},
 6: {0: 10, 1: 11, 2: 0, 3: 10, 4: 11, 5: 0, 6: 10, 7: 11, 8: 0, 9: 10}})

Edit
This dataframe is only a short piece of my real data.
An integer between 0 and 11 can appear from 0 to 2 times in each line. For instance, in these lines, the values 4, 8 and 11 appear two times each.
        0   1   2   3   4   5   6
100     11  1   4   4   8   8   11
343     11  2   4   4   8   8   11
505     11  3   3   4   8   8   11
586     11  3   4   4   8   8   11
1558    1   1   4   4   8   8   11

A: You can use isin to test for membership and then call dropna and pass thresh=2 to show only the rows where at least 2 non-NaN values exist:
In [20]:
df[df.isin([6,10])].dropna(thresh=2)

Out[20]:
    0   1   2   3  4   5   6
0 NaN NaN NaN NaN  6 NaN  10
3 NaN NaN NaN NaN  6 NaN  10
6 NaN NaN NaN NaN  6  10  10
7 NaN NaN NaN NaN  6  10 NaN
8 NaN NaN NaN NaN  6  10 NaN

I think actually it's better to test for each value and apply any:
In [41]:
df.apply(lambda x: (x == 6).any() & (x == 10).any(), axis=1)

Out[41]:
0     True
1    False
2    False
3     True
4    False
5    False
6     True
7     True
8     True
9    False
dtype: bool

For 3 values you can do :
df.apply(lambda x: (x==5).any() & (x == 6).any() & (x == 10).any(), axis=1)


text:
Q: setar background color do radio button via javascript Estou aprendendo php e tentei algo que faço em asp.net mas não está rolando.
Tenho uma página que recebe valores de uma página anterior via _GET. Nela tenho input do tipo rádio que quero, que ao clicar em um submit, o radio selecionado fique vermelho. o problema é que, ao clicar em submit, o valor recebido anteriormente se perde, então, a página não carrega. Como fazer isso sem perder o valor recebido?
a estrutura do código é:
html
head
body
form
Código php:
?php

define('__ROOT__', dirname(dirname(__FILE__)));
require_once(__ROOT__ . '\0 -        Apresentação\Controller\PerguntaController.php');
require_once(__ROOT__ . '\0 -Apresentação\Controller\RespostaController.php');

$Disciplina=$_GET["pergunta"];
$Perguntacontroller = new PerguntaController();
$retorno = $Perguntacontroller->Carregar($Disciplina);

$Respostacontroller = new RespostaController();

$x = 0;
while ($linha1 = mysqli_fetch_array($retorno)) {
    $y=0;
    $Pergunta = $linha1["pergunta"];
    $Id[$x] = $linha1["Id"];
    $certa[$x]=$linha1["certa"];
    $retornoR = $Respostacontroller->Carregar($Id[$x]);

    echo "$Pergunta

";

   while ($linha2 = mysqli_fetch_array($retornoR)) {
        $Resposta = $linha2["Resposta"];
        echo"<input type=\"radio\" name=$x value=$y >$Resposta

";
        echo"<input type=\"hidden\" name=$x value=$certa[$x]>";
        $y++;
    }
    $x++;
}
?>

Código java script:

<input id="submit" type="submit">

A: Analisando o código postado, faço três considerações:
1) se não tiver tag form, pode clicar em submit a vontade que não vai pra lugar nenhum.
2) Não existe nenhum elemento com o id submit na sua página, então seu javascript nunca será executado.
3) Quando um form é enviado com submit, apenas nomes dos elementos do formulário e e seus valores são enviados, formatação css não é enviada.
Respondendo ao título "setar background color via javascript", segue um trecho de código:

<input type="button" value="Me clique" onclick="this.style.backgroundColor='#ff0000'">


text:
Q: What is the recommended way to update the web.config values using release pipeline variables? I am planning to use azure devops release pipeline to deploy a .NET web app into test, uat and prod environments.
I have previously worked on projects which had the appsettings.json file and used variable substitution approach as shown in screenshot below:

When doing the variable replacement for a .NET web app containing the web.config, I am exploring the following options:

*

*Generate web.config parameters section which is shown above the JSON section marked above. But the description says that it is meant for Python, Node.js, Go and Java apps. It doesn't mention .NET.

*In the web.config file, in the value I can add something like XXMARKERXX and then via Powershell script maybe replace the above with the contents from pipeline variable?

A: The web.config file is XML format type file. So you couldn't use JSON variable substitution option in task to update the value.
Here are the methods to update the value in Web.config file:
1.You can use the XML variable substitution option in the Azure App service deploy task or IIS deploy task.

For more detailed steps, refer to this doc: XML variable substitution
2.You can use PowerShell script to modify the value. But you don't need to add any additional characters in web.config file.
Here is the PowerShell script sample:
$myConnectionString = "test";

$webConfig = '$(build.sourcesdirectory)\Web.config'

Function updateConfig($config)
{
$doc = (Get-Content $config) -as [Xml]
$root = $doc.get_DocumentElement();
$activeConnection = $root.connectionStrings.SelectNodes("add");
$activeConnection.SetAttribute("connectionString", $myConnectionString);
$doc.Save($config)
}

updateConfig($webConfig)

3.When you add the mark: #{..}# in web.config file, you can try to use the Replace Token task from Replace Tokens Extension.
Refer to the example in this ticket:How to perform XML Element substitution in web.config using Replace Tokens?


text:
Q: DistributionNotFound: 'six>=1.4.0' is required I'm trying to make an exe out of a Python file that uses apscheduler, sqlalchemy, and Tkinter among other libraries. Once compiled, the majority of the app works fine, except for one function that needs to add jobs to the SQLite database. The most recent error is involving this six library. I've tried downgrading it to 1.4.0, even using '--collect-all six' but that just doesn't launch the app.
I don't know what this six library is really used for.


text:
Q: How to save a JavaDStream as compressed (.gz) file? I am new to spark streaming. I am using spark-streaming 2.3.0.
I have a JavaDStream, and I am saving it as a text file, but I want to save it as a compressed(.gz) file.
Here is my code snipet:
JavaDStream<String> dataStreams = stream.map(new Function<String, String>() {

        public String call(String lines) throws Exception {

            //code

            return lines;
        }

    }  );
dataStreams.dstream().saveAsTextFiles(outputDir, "txt");

A: On each rdd in dstream, call saveAsTextFile() as below:
rdd.saveAsTextFile("Combined", classOf[GzipCodec])
Or at Spark App level:
sc.hadoopConfiguration.setClass(FileOutputFormat.COMPRESS_CODEC, classOf[GzipCodec], classOf[CompressionCodec])


text:
Q: Dovecot, Error: Threading lost Message ID Dovecot generates Error: Threading lost Message ID in dovecot.log
Problem is only with one Maildir. This Maildir cannot be accesed through webmail (in this case Roundcube), error in webmail after log in:
Server Error: UID THREAD: Internal error occured. Refer to server log for more information.

The only suggestion I've found is here: http://www.dovecot.org/list/dovecot/2013-August/091939.html
but I still don't know what causes the problem, how to fix it and how to avoid it in the future, so any suggestion appreciated.
Kind regards!

A: And finaly I've found the solution. Somehow file dovecot.index.thread was corupted and causes the problem. I've deleted file dovecot.index.thread, the file was rebuild then properly, and problem was solved.


text:
Q: Git pull issue with C# function executing batch file I have a simple batch file:
cd <path to my git repository>
git pull

I try to execute it with the following C# function:
private NuGetBO.ShellCommandReturn ExecuteCommand(string path)
{
    ProcessStartInfo processInfo;
    Process process;

    processInfo = new ProcessStartInfo(path);
    processInfo.CreateNoWindow = true;
    processInfo.UseShellExecute = false;

    // *** Redirect the output ***
    processInfo.RedirectStandardError = true;
    processInfo.RedirectStandardOutput = true;

    process = Process.Start(processInfo);
    process.WaitForExit(5000);

    // *** Read the streams ***
    string output = process.StandardOutput.ReadToEnd();
    string error = process.StandardError.ReadToEnd();

    int exitCode = process.ExitCode;
    process.Close();
    return new NuGetBO.ShellCommandReturn { Error = error, ExitCode = exitCode, Output = output };
}

But I get the following error:
"Access is denied.\r\nfatal: Not a git repository (or any of the parent directories): .git\n"

In other words I have tried to execute my batch file from C# without success for hours, however, my batch file works without any problem if I execute it in command line.
How can I get my C# function to work, what should I change in my batch file or C# function? Thanks
EDIT:
I have changed the batch file's content to the following:
cd <path to my git repository> && git pull

But I receive the following error:
Access is denied.

EDIT2:
I've added access to the folder and now I get a new error:
fatal: Not a git repository: "../.git/modules/myProject\n"

EDIT3:
I have given access rights to the folder mentioned in EDIT2, but now I receive the following error:
"error: unable to create directory for C:/myFolder/.git/modules/myProject/ORIG_HEAD\nfatal: Cannot lock the ref 'ORIG_HEAD'.\n"

A: You need to set processInfo.WorkingDirectory to the location of the git repo.

A: It works now. To not have the same nerve-breaking issue I had, any future person who has to do the same should check the following:
There is a user who runs the C# code, let's call him/her User.
1. User must have privileges to the folder where the git pull should be running.
2. User must have privileges to the folder where the git repository is located (its path is described in the .git file located in the folder described at 1.)

A: if you are interested to integrate a whole library maybe it can help this one


text:
Q: webgl strange rendering artifacts UPDATE:
I have posted the code online to demonstrate the issue:
http://cutama.github.io/
To see the problem, position the mouse on the red rectangle and zoom in and out using the mouse scroller. After a while you will see the triangles flickering, then use the left mouse button to rotate.
Controls:
left mouse click&drag: orbit, middle mouse click&drag: pan, mouse scroll: zoom
END UPDATE
I have encountered a strange rendering problem with webgl. Whenever I moved the camera around, some triangles appear to be missing randomly. See pictures below.
I have been digging around but could not find the cause. Any ideas what may be causing this?
This is the normal rendering of the geometry:

Missing triangles:

Another missing triangles:

Did some debugging with webgl inspector.
GL Trace:

Clicking on the missing pixel show that it is being depth culled, but nothing is in front of it...so why is it culled?

Comparison with normal unculled pixel:

Vertex data inside the buffer. The triangles are very small. Is this causing the problem?

A: I don't know what makes this bug. But, I will list what you might need to consider.

*

*Check you specified correct PrimitiveTopology(It should be gl.TRIANGLES in many case)

*Check you rendered wether gl.DrawElements or gl.DrawArrays.
If you are using index buffer, you should use gl.DrawElements

*Check you are using correct culling configuration.

*Check you are using correct depth comparing function.(If you are not using depth test,you don't need to care about this)

A: Found the issue is caused by incorrect triangle indices in the model..still not sure why it would cause flickering.


text:
Q: Create web applications to run R scripts Is there anything similar to the Rwui package to create web applications to run R scripts?

A: Please do not cross-post simultaneously to r-help and StackOverflow.
As I just mentioned in my reply on r-help, there is an entire section of the R FAQ devoted to this question.


text:
Q: Angular directive/child directive transclude inside ng-repeat The problem is that child directive binds to parent however syntax {{name}} gets ignored by ng-repeat. What would be the right way achieving this?
HTML (Main/child directive)
<compact-select
    no-item-selected-text="Add a Customer"
    no-item-selected-icon="fa-user"
    search-placeholder="Type a customer name"
    cs-model="customer"
    cs-items="contacts"
>
    <display-item-template>
        {{name}}
        or
        {{item.name}}
    </display-item-template>
</compact-select>

Directive
angular.module('core').directive('compactSelect', [function($timeout) {
    return {
        templateUrl : 'modules/core/views/components/compact-select-tpl.html',
        bindToController: true,
        transclude: true,
        scope: {
            noItemSelectedText: '@',
            noItemSelectedIcon: '@',
            csModel: '=',
            csItems: '=csItems'
        },
        controllerAs : 'ctrl',
        controller : function($scope) {

        }
    };
}]).directive('displayItemTemplate', function($timeout) {
    return {
        require: '^compactSelect',
        restrict: 'E'
    }
});

Directive Template (modules/core/views/components/compact-select-tpl.html)

        {{item.name}}
        {{item.id}}

        + Click here to add customer {{ctrl.message}}

I can see that
{{item.name}}
{{item.id}}

Gets replaced with

or
{{item.name}}

and not with
{{name}}
or
{{item.name}}

Question: How do I get ng-repeat to respect html bindings syntax from child directive? Or is there is another way to achieve this?

A: If i am not wrong, then you are trying to create a list view such that the template of the list would be provided by the user, but the methods (click,etc) would already be made available through the directive.
Now, since angular 1.3, the transcluded scope is a child of the directive isolated scope,
so, in your case, if you follow the correct hierarchy, you can access the directive scope from within the template provided by the user.
Here is your scope hierarchy:
Directive isolated scope --> ng-repeat new scope for every row --> transcluded scope.
so, if you want to access directive scope from the transcluded scope,
you would need to do $parent (for ng-repeat) and then access item.name, like below:
<display-item-template>
       Item Name: {{$parent.item.name}}
</display-item-template>

Also, you don't need the bindings inside your compact-select-tpl, because you want that content to come from transclusion:

        + Click here to add customer {{ctrl.message}}

A: The displayItemTemplate directive that you transclude inside the other directive has already it's data interpolated {{name}} and {{item.name}}.
If you don't have these variables in the $scope, it will transclude empty strings inside your spans.
Then in your compactSelect directive, the div that gets transcluded will have it's content overridden.
If you move the displayItemTemplate directive inside the other directive's template, the repeat will work. (you will need to remove ng(transclude and transclude: true
Fiddle
Additionally, if you use bindToController, don't put the attributes inside scope.

function compactSelect() {
  return {
    template : [
      '
',
      '
',
        '<display-item-template>',
            '{{item.name}}',
        '</display-item-template>',
      '
',
      '
',
          '+ Click here to add customer {{ctrl.message}}

',
    ].join(''),
    bindToController: {
      noItemSelectedText: '@',
      noItemSelectedIcon: '@',
      csItems: '=csItems'
    },
    scope: {},
    controllerAs : 'ctrl',
    controller : function($scope) {

    }
  }
}
function displayItemTemplate() {
    return {
        require: '^compactSelect',
        restrict: 'E'
    }
}
function SuperController() {
 this.name = "a name";
 this.contacts = [{name:"rob"}, {name:"jules"}, {name:"blair"}];
}
angular.module('myApp', []);
angular
    .module('myApp')
    .controller('SuperController', SuperController)
    .directive('compactSelect', compactSelect)
    .directive('displayItemTemplate', displayItemTemplate);

    <compact-select
        no-item-selected-text="Add a Customer"
        no-item-selected-icon="fa-user"
        search-placeholder="Type a customer name"
        cs-items="s.contacts">
    </compact-select>


text:
Q: reset value of multiple (but not all) form fields with jQuery in one line Is it possible to reset multiple form fields in one line, or one hit, with jQuery. Note: I don't want to reset all form fields, only a specified whitelist (as below):
// reset some form fields
$('#address11').val('');
$('#address21').val('');
$('#town1').val('');
$('#county1').val('');
$('#postcode1').val('');

A: jQuery (and CSS) selector strings can contain multiple selectors using a comma as a delimiter for sub-selectors:
$('#address11, #address21, #town1, #county1, #postcode1').val('');

I'd argue that this is faster than using a class (ID look-ups should perform in essentially constant time, whereas a class look-up will have to visit every DOM node), but perhaps less maintainable if you're going to want to change which elements get reset.

A: If you have a lot of fields i'd label the ones you want to ignore with a class to minimise code:
$('#myForm input:not(.ignore)').val('');

A: It is better to use a class so you do not have to maintain a long list of ids.
HTML
<input type="text" class="resetThis" id="address11" />
<input type="text" class="resetThis" id="address21" />

JavaScript
$(".resetThis").val("");

A: You can use $('#Form_name select:not(.fixed)').val('');


text:
Q: Limiting form number input to 2 Decimals I have a form with 3 number input fields used to input the price,discount, and discounted price of an item, with the discounted price displaying up to 2 decimals.
I've looked around the net, and here on SO for ways to limit the numbers to 2 Decimals places and am currently using the following code
Code:
$('#ItemPercent').change(function(){
        var percent=$('#ItemPercent').val();
        var price=$('#ItemPrice').val();
        var discountpercent=percent / 100;
        var discountamt=price * discountpercent;
        var discountamt=Math.floor(discountamt * 100)/100;
        var discountamtrounded=discountamt.toFixed(2);
        $('#ItemDiscountPrice').val(price - discountamtrounded);
});

However, even when using the code above, the discounted price is not showing 2 decimal places.
E.g
E.g
$129.99 <----ItemPrice
10% <------Discount %
$117.00000000000001 <------ ItemDiscountPrice.

Where the example above is what i am currently getting when i test run my code.
How would i limit the numbers displayed to just 2 decimal places?

A: Try using toFixed:
$('#ItemDiscountPrice').val((price - discountamtrounded).toFixed(2));


text:
Q: Cannot install requests module I tried to install the requests module by using pip install requests, but I got the SyntaxError: invalid syntax all the time.
I'm using Python 3 for Windows.
I've tried on other syntax like py -m pip install requests or apt-get install python3-requests but the problem has persisted.
File "<ipython-input-163-38059570e01a>", line 2
    pip3 install requests
    ^
SyntaxError: invalid syntax

A: *

*Launch windows command line as administrator

*type:  pip3 install requests

*press 'Enter'

*Vote this post as the answer!


text:
Q: ProgressDialog in jetpack compose I want to show Indeterminate progress dialog when user performs some action like signing up. The old way it was possible using ProgressDialog.
For compose, I found this How can I render plain android ProgressBar with Compose? But this is not exactly what I'm looking for as it's just a view. It does not cover the screen like dialog does.
With CircularProgressIndicator I'm able to achieve this:

As you can see it's shown below the views.
I want to create something like this:

It should have:

*

*Dim background

*draw over other views

*Non cancellable

How can I achieve this in Jetpack compose?

A: Dialog with loading text using Dialog component of compose.material.
@Composable
fun DummyProgress() {
    var dialogState by remember { mutableStateOf(false) }
    Button(onClick = { dialogState = !dialogState }) {
        Text(text = "Show Progress")
    }
    if (dialogState) {
        Dialog(onDismissRequest = { dialogState = false },
        DialogProperties(dismissOnBackPress = false, dismissOnClickOutside = false)) {
            Box(
                contentAlignment= Alignment.Center,
                modifier = Modifier
                    .size(100.dp)
                    .background(White, shape = RoundedCornerShape(12.dp))
            ) {
                Column {
                    CircularProgressIndicator(modifier = Modifier.padding(6.dp, 0.dp, 0.dp, 0.dp))
                    Text(text = "Loading...", Modifier.padding(0.dp, 8.dp, 0.dp, 0.dp))
                }
            }
        }
    }
}

A: You can use the Dialog composable:
var showDialog by remember { mutableStateOf(false) }

if (showDialog) {
    Dialog(
        onDismissRequest = { showDialog = false },
        DialogProperties(dismissOnBackPress = false, dismissOnClickOutside = false)
    ) {
        Box(
            contentAlignment= Center,
             modifier = Modifier
                .size(100.dp)
                .background(White, shape = RoundedCornerShape(8.dp))
        ) {
            CircularProgressIndicator()
        }
    }
}


text:
Q: Angular 7 NGRX Store have undefined state My code is in Angular7, using @ngrx/store7, and sometimes I get undefined state (just for a specific state)

It is always the "history" state.
My App State:
export interface IAppState {
  router?: RouterReducerState,
  delivery: IDeliveryState,
  events: IEventsState,
  families: IFamiliesState,
  googleDrive: IGoogleDriveState,
  spinner: ISpinnerState,
  user: IUserState,
  volunteerConstraints: IVolunteerConstraintsState,
  volunteers: IVolunteersState,
  history: IHistoryState
}

export const initialAppState: IAppState = {
  delivery: initialDeliveryState,
  events: initialEventsState,
  families: initialFamiliesState,
  googleDrive: initialGoogleDriveState,
  spinner: initialSpinnerState,
  user: initialUserState,
  volunteerConstraints: initialVolunteerConstraintsState,
  volunteers: initialVolunteersState,
  history: initialHistoryState
};

export function getInitialState(): IAppState {
  return initialAppState;
}

My history state:
export interface IHistoryState {
  familyHistory: Array<FamilyHistoryModel>;
  familyHistoryPending: boolean;

  routeHistory: Array<RouteHistoryModel>;
  routeHistoryPending: boolean;

  deliveryHistory: Array<DeliveryHistoryChartModel>;

  volunteerRating: Array<VolunteerRatingModel>;
  volunteerRatingPending: number;

  initiated: boolean;
}

export const initialHistoryState: IHistoryState = {
  familyHistory: new Array<FamilyHistoryModel>(),
  familyHistoryPending: false,

  routeHistory: new Array<RouteHistoryModel>(),
  routeHistoryPending: false,

  deliveryHistory: new Array<DeliveryHistoryChartModel>(),

  volunteerRating: new Array<VolunteerRatingModel>(),
  volunteerRatingPending: 0,

  initiated: true
};

My History selector:
const selectHistoryState = (state: IAppState) => state.history;

export const selectFamilyHistory = createSelector(
  selectHistoryState,
  (state: IHistoryState) => state.familyHistory
);

export const selectFamilyHistoryPending = createSelector(
  selectHistoryState,
  (state: IHistoryState) => state.familyHistoryPending
);

export const selectRouteHistory = createSelector(
  selectHistoryState,
  (state: IHistoryState) => state.routeHistory
);

export const selectRouteHistoryPending = createSelector(
  selectHistoryState,
  (state: IHistoryState) => state.routeHistoryPending
);

export const selectDeliveryHistory = createSelector(
  selectHistoryState,
  (state: IHistoryState) => state.deliveryHistory
);

export const selectVolunteerRating = createSelector(
  selectHistoryState,
  (state: IHistoryState) => state.volunteerRating
);
export const selectVolunteerRatingPending = createSelector(
  selectHistoryState,
  (state: IHistoryState) => state.volunteerRatingPending
);

My app reducer:
export const appReducers: ActionReducerMap<IAppState, any> = {
  router: routerReducer,
  delivery: deliveryReducer,
  events: eventsReducer,
  families: familiesReducer,
  googleDrive: googleDriveReducer,
  spinner: spinnerReducer,
  user: userReducer,
  volunteerConstraints: volunteerConstraintsReducer,
  volunteers: volunteersReducer,
  history: historyReducer
}

My History reducer:
export function historyReducer(
  state = initialHistoryState,
  action: actions.HistoryActions): IHistoryState {
  switch (action.type) {
    case actions.HistoryActionTypes.Initiate:
      return {
        ...state,
        initiated: true
      };

    case actions.HistoryActionTypes.GetFamilyHistory:
      return {
        ...state,
        familyHistory: initialHistoryState.familyHistory,
        familyHistoryPending:true
      };

    case actions.HistoryActionTypes.GetFamilyHistorySuccess:
      return {
        ...state,
        familyHistory: action.payload,
        familyHistoryPending: false
      };

    case actions.HistoryActionTypes.GetFamilyHistoryFailure:
      return {
        ...state,
        familyHistoryPending: false
      };

    case actions.HistoryActionTypes.GetRouteHistory:
      return {
        ...state,
        routeHistory: initialHistoryState.routeHistory,
        routeHistoryPending: true
      };

    case actions.HistoryActionTypes.GetRouteHistorySuccess:
      return {
        ...state,
        routeHistory: action.payload,
        routeHistoryPending: false
      };

    case actions.HistoryActionTypes.GetRouteHistoryFailure:
      return {
        ...state,
        routeHistoryPending: false
      };

    case actions.HistoryActionTypes.GetDeliveryHistory:
      return {
        ...state,
        deliveryHistory: initialHistoryState.deliveryHistory
      };

    case actions.HistoryActionTypes.GetDeliveryHistorySuccess:
      return {
        ...state,
        deliveryHistory: action.payload
      };

     case actions.HistoryActionTypes.GetVolunteersRating:
      return {
        ...state,
        volunteerRating: initialHistoryState.volunteerRating,
        volunteerRatingPending: state.volunteerRatingPending + 1
      };

    case actions.HistoryActionTypes.GetVolunteersRatingSuccess:
      return {
        ...state,
        volunteerRating: action.payload,
        volunteerRatingPending: state.volunteerRatingPending - 1
      };

    case actions.HistoryActionTypes.GetVolunteersRatingFailure:
      return {
        ...state,
        volunteerRatingPending: state.volunteerRatingPending - 1 < 0 ? 0 :
state.volunteerRatingPending - 1
      };
 }
}

At the beginning the history state is undefined (as shown in the picture), and only after I dispatch an history action and change the state in the reducer, it gets initiated.
How do I fix that to be initiated at the beginning as all other states?
packge.json:
  "dependencies": {
    "@agm/core": "^1.0.0-beta.3",
    "@agm/js-marker-clusterer": "^1.0.0-beta.3",
    "@angular-mdl/core": "^6.0.1",
    "@angular-mdl/datepicker": "^6.0.0",
    "@angular-mdl/expansion-panel": "^6.0.0",
    "@angular-mdl/popover": "^6.0.0",
    "@angular-mdl/select": "^6.0.0",
    "@angular/animations": "~7.1.0",
    "@angular/cdk": "^7.2.2",
    "@angular/common": "~7.1.0",
    "@angular/compiler": "~7.1.0",
    "@angular/core": "~7.1.0",
    "@angular/forms": "~7.1.0",
    "@angular/http": "^7.2.2",
    "@angular/material": "^7.2.2",
    "@angular/platform-browser": "~7.1.0",
    "@angular/platform-browser-dynamic": "~7.1.0",
    "@angular/router": "~7.1.0",
    "@ngrx/effects": "^7.1.0",
    "@ngrx/router-store": "^7.1.0",
    "@ngrx/schematics": "^7.1.0",
    "@ngrx/store": "^7.1.0",
    "@ngrx/store-devtools": "^7.1.0",
    "@ngx-translate/core": "^10.0.2",
    "@ngx-translate/http-loader": "^3.0.1",
    "@swimlane/ngx-charts": "^10.0.0",
    "angular-2-local-storage": "^2.0.0",
    "angular2-moment": "^1.9.0",
    "angular2localization": "^1.4.2",
    "aos": "^2.3.4",
    "core-js": "^2.5.4",
    "crypto-js": "^3.1.9-1",
    "hammer-timejs": "^1.1.0",
    "hammerjs": "^2.0.8",
    "js-marker-clusterer": "^1.0.0",
    "jssha": "^2.3.1",
    "lodash": "^4.17.4",
    "lodash-es": "^4.17.4",
    "moment": "^2.20.1",
    "ngrx-store-freeze": "^0.1.9",
    "ngrx-store-localstorage": "^0.1.8",
    "ngrx-store-logger": "^0.1.8",
    "ngx-chips": "^1.4.5",
    "ngx-device-detector": "^1.3.0",
    "ngx-gallery": "^5.6.2",
    "ngx-infinite-scroll": "^0.5.1",
    "rxjs": "~6.3.3",
    "rxjs-compat": "^6.0.0",
    "sha.js": "^2.4.11",
    "tslib": "^1.9.0",
    "videogular2": "^6.3.0",
    "zone.js": "~0.8.26"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.11.0",
    "@angular/cli": "~7.1.4",
    "@angular/compiler-cli": "~7.1.0",
    "@angular/language-service": "~7.1.0",
    "@types/core-js": "^2.5.0",
    "@types/googlemaps": "^3.30.16",
    "@types/jasmine": "~2.8.8",
    "@types/jasminewd2": "~2.0.3",
    "@types/node": "~8.9.4",
    "codelyzer": "~4.5.0",
    "jasmine-core": "~2.99.1",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~3.1.1",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~1.1.2",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.4.0",
    "ts-node": "~7.0.0",
    "tslint": "~5.11.0",
    "typescript": "~3.1.6"
  }

A: Looks to me like you are missing default case in your history reducer.
switch(...) {
  case: ...
  case: ...
  default: {
    return state;
  }
}


text:
Q: Div heights are different between 2 webpages but coded the same I have 3 webpages. The first is called inventorshome, second PythonTutorialHome, third HTMLTutorialHome. The second and third look the same in the browser. Notice that the code is exactly the same for the pages. They should look exactly the same by that logic. For some reason, the div is larger for inventorshome than in PythonTutorialHome and HTMLTutorialHome. I am using Google Chrome browser, and they are files on my computer.
Here is the code for inventorshome:
<!DOCTYPE html>

            <title>Home</title>
            <base href="file:///C:/Users/David/Documents/Website/Pages/">
            <link rel="stylesheet" type="text/css" href="file:///C:/Users/David/Documents/Website/Pages/inventorshomestyles.css">

Here is the code for PythonTutorialHome:
<!DOCTYPE html>

    <title>Home</title>
    <base href="file:///C:/Users/David/Documents/Website/Pages/">
    <link rel="stylesheet" type="text/css" href="file:///C:/Users/David/Documents/Website/Pages/inventorshomestyles.css">

The CSS linked to these webpages is:
#header {
    position:absolute;
    left:0px;
    top:0px;
    background-color:#8AC007;
    width:100px;
    height:30px;
    }

When I change the width and height to percentages, they are the same across all three pages. When the dimensions to pixels, different results are yielded. What is going on here?


text:
Q: Optional Calendar type field in JSF form I want to make a Calendar input in a JSF form optional. When the user doesn't inform the birth, the Calendar field must stay null.
My code:
@Model
public class Registration {
private User user = new User();

    public void register() {
        // stuff
    }
//getUser
}

The model class:
public class User {
    //other fields
    private Calendar birth;
    // gets and sets
}

The page:
<h:outputLabel for="birth" value="Birth Date" />
<h:inputText id="birth" value="#{registration.user.birth.time}" >
    <f:convertDateTime pattern="dd/MM/yyyy" />
</h:inputText>

The problem here so far is the <f:convertDateTime>, that depends of the getTime() method of Calendar to make the conversion. It throws a NPE (Null Pointer Exception) when executed. I know that if I initialize the birth the problem is solved, but I really want the field to be null when the user does not fill the field.
Any thoughts of a way to achive this?

A: The problem is not related to the convert, but to the expression:
#{registration.user.birth.time}
Infact this is DateTimeConverter code:
 public Object getAsObject(FacesContext context, UIComponent component,
                          String value) {

    ...

    Object returnValue = null;
    DateFormat parser = null;

    try {

        // If the specified value is null or zero-length, return null
        if (value == null) {
            return (null);
        }
        value = value.trim();
        if (value.length() < 1) {
            return (null);
        }

        ...
         returnValue = parser.parse(value);

     } catch (ParseException e) {
       ...
     }
     return returnValue;
  }

As you can notice, null and empty values are managed rightly.
But when the values are applied, the expression birth.time is evaluated, but the birth reference is null, so when the setter on time is called you get NPE.
A possibile solution is to bind the birth field to java.util.Date type directly, which is the type managed by the DateTimeConverter, as below:
public class User {
    //other fields
    private Date birth;
    // gets and sets
}

A: well, I'll post this for posterity. I think this would do the job:
@FacesConverter("CustomCalendarConverter")
public class CalConverter implements Converter{

@Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
    if(value != null && !value.toString().isEmpty()){
        try {
            String pattern = (String) component.getAttributes().get("pattern");
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new SimpleDateFormat(pattern).parse(value));
            return calendar;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    return null;
}

@Override
public String getAsString(FacesContext context, UIComponent component, Object value) {

    if(value != null && !value.toString().isEmpty()){
        Calendar cal = (Calendar) value;
        String pattern = (String) component.getAttributes().get("pattern");
        return new SimpleDateFormat(pattern).format(cal.getTime());
    }
        else return null;
    }
}

And the view should be:
<h:outputLabel for="birth" value="Birth Date" />
<h:inputText id="birth" value="#{registration.user.birth}">
    <f:converter converterId="CustomCalendarConverter" />
    <f:attribute name="pattern" value="dd/MM/yyyy" />
</h:inputText>

You can create a composite component too, something like <custom:inputCalendar> for instance.


text:
Q: Do the brcm80211 drivers need patching to work correctly in airmon etc? I am trying to use the broadcom brcm80211 drivers along with a BCM4313 chip and aircrack-ng suite of programs but airodump only ever lists clients for WEP protected access points. I have setup a WPA2 router and connected another device to it so I know there is definately a client but I never pick it up. Can anyone offer any advice?
sadly there is alot of junk relating to getting this chipset functioning even in a basic way with linux so if you google it you will get hits relating to propietary drivers, b43 legacy and also kernel source which is what currently is in use. The drivers function fantastic in normal operation. Monitor mode obviously works, I'm not certain about the injection, some things hint at it working and others point to it failing.
Network controller: Broadcom Corporation BCM4313 802.11b/g/n Wireless LAN Controller (rev 01)

Update: The kernel driver still needs more development to work for penetration testing purposes but the responsiveness for regular wifi use is far superior to the wl or sta drivers.

A: it is my experience that most Wireless card can not do some of the basic Air-Crack options without been altered in some way with an injection (Take mental note that I do not know what aircrack is or have I ever used it in anyway). if you read the changelog you will see that some drivers for wireless cards receive a "patch" which is the injected code that lets them do.. what they do in air-crack: http://www.aircrack-ng.org/doku.php?id=changelog
Afterwards if you read the compatibility list you will see which ones Air-Crack supports without a patch, which ones need a patch and which ones work mostly: http://www.aircrack-ng.org/doku.php?id=compatibility_drivers
For example, for the Broadcom you can find if it is supported here: http://www.aircrack-ng.org/doku.php?id=b43 and do the injection test in that same page to see if it qualifies.
Also in the air crack forum you can find guides to "patch" the Wireless card. There are other testing softwares like Backtrack which include a lot of patches already or Metasploit. Anyway with this is enough to determine if you need to patch or not. Good luck friend.


text:
Q: Managing users in Ruby on Rails (& ownership) I'm somewhat of a Rails newbie, and am not quite sure what the convention is when tying users to their objects, such as documents. (And I now know how important it is to go with conventions in Rails)
So far, I have come up with 3 potential solutions in my head:

*

*Making every document essentially a child of every user, using has_many and belongs_to

*Giving every document an integer (user_id, or something along the lines of that) that ties it to the user. That way, whenever the user wants an index of their documents, I can identify all those that have the right ID.

*It seems like there's some plugins that do user management completely in their own way that doesn't fit into any of the above.

Additionally, I plan on using Devise for user authentication and management. From my understanding, that seems to be the most popular/widely used authentication gem -- please correct me if I'm wrong.

A: This is primarily an opinion-based question however I tend to see most projects using ActiveRecord's relations (e.g has_many, belongs_to).

A: you can use devise for authentification (or build an own login system there is a railscast and use cancancan for authorization. some defining of abilities you will find in the documentation
just for example
can :update, Article

or if user can just delete own stuff
can :read, Project, active: true, user_id: user.id

i would also use the ActiveRecord relation with has_many e.g. and has_many through

A:
I'm somewhat of a Rails newbie

Welcome to the club, although some people bite, most are totally cool.

tying users to their objects

You've already answered your own question...
#app/models/user.rb
class User < ActiveRecord::Base
   has_many :documents
end

#app/models/document.rb
class Document < ActiveRecord::Base
   belongs_to :user
end

If a user creates a document, surely that would mean that you'd have to associate documents to users via a has_many / belongs_to relationship...
--
To give you some context, you'll have to add the user_id foreign_key to your documents table:
$ rails g migration AddUserForeignKeyToDocuments

#db/migrate/add_user_foreign_key_to_documents______.rb
class AddUserForeignKeyToDocuments < ActiveRecord::Migration
   def change
      change_table :documents do |t|
         t.references :user, index: true
      end
   end
end

$ rake db:migrate

This would allow something like the following (using the current_user helper from Devise):
#config/routes.rb
resources :documents

#app/controllers/documents_controller
class DocumentsController < ApplicationController
   def create
      @document = current_user.documents.new document_params
      @document.save
   end

   private

   def document_params
      params.require(:document).permit(.....)
   end
end

If you're unsure about user authentication, you should go with Devise, although there are other authentication gems such as sorcery
Setting up Devise is simple:
#Gemfile
gem 'devise', '~> 3.5', '>= 3.5.3'

$ rails generate devise:install
$ rails generate devise User
$ rake db:migrate

#config/routes
devise_for :users

#app/controllers/documents_controller.rb
class DocumentsController < ApplicationController
   before_action :authenticate_user!
end

This will make it so only logged-in users can access /documents :)