text:
Q: What is solution for error in vector in C++? /*
// Sample code to perform I/O:

#include <iostream>

using namespace std;

int main() {
    int num;
    cin >> num;                                     // Reading input from STDIN
    cout << "Input number is " << num << endl;      // Writing output to STDOUT
}

// Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail
*/

// Write your code here
#include<iostream>
#include<string>
#include<vector>
#include <algorithm>
using namespace std;
typedef long long int ll;
vector<ll> v;
void make(ll num)
{
    if(num>10000000000)
        return ;
    if(num!=0)
        v.insert(num);
     make(num*10+4);
     make(num*10+7);
}
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    ll num=0;
    make(num);
    ll n,ans=0;
    cin>>n;
    for(auto i:v)
    {
        for(auto j:v)
        {
            if(i<=n&&j<=n&&j>=i)
            {
                if(__gcd(i,j)==1)
                    ans++;
            }
        }
    }
    cout<<ans<<endl;

    return 0;
}

Error:
In function 'void make(ll)':
30:21: error: no matching function for call to 'std::vector<long long int>::insert(ll&)'

69:0,
20:
114:5: note: candidate: std::vector<_Tp, _Alloc>::iterator std::vector<_Tp, _Alloc>::insert(std::vector<_Tp, _Alloc>::const_iterator, const value_type&) [with _Tp = long long int; _Alloc = std::allocator<long long int>; std::vector<_Tp, _Alloc>::iterator = __gnu_cxx::__normal_iterator<long long int*, std::vector<long long int> >; typename std::_Vector_base<_Tp, _Alloc>::pointer = long long int*; std::vector<_Tp, _Alloc>::const_iterator = __gnu_cxx::__normal_iterator<const long long int*, std::vector<long long int> >; typename __gnu_cxx::__alloc_traits<typename std::_Vector_base<_Tp, _Alloc>::_Tp_alloc_type>::const_pointer = const long long int*; std::vector<_Tp, _Alloc>::value_type = long long int]
:

114:5: note:   candidate expects 2 arguments, 1 provided
64:0,
20:
1042:7: note: candidate: std::vector<_Tp, _Alloc>::iterator std::vector<_Tp, _Alloc>::insert(std::vector<_Tp, _Alloc>::const_iterator, std::vector<_Tp, _Alloc>::value_type&&) [with _Tp = long long int; _Alloc = std::allocator<long long int>; std::vector<_Tp, _Alloc>::iterator = __gnu_cxx::__normal_iterator<long long int*, std::vector<long long int> >; typename std::_Vector_base<_Tp, _Alloc>::pointer = long long int*; std::vector<_Tp, _Alloc>::const_iterator = __gnu_cxx::__normal_iterator<const long long int*, std::vector<long long int> >; typename __gnu_cxx::__alloc_traits<typename std::_Vector_base<_Tp, _Alloc>::_Tp_alloc_type>::const_pointer = const long long int*; std::vector<_Tp, _Alloc>::value_type = long long int]

1042:7: note:   candidate expects 2 arguments, 1 provided
1059:7: note: candidate: std::vector<_Tp, _Alloc>::iterator std::vector<_Tp, _Alloc>::insert(std::vector<_Tp, _Alloc>::const_iterator, std::initializer_list<_Tp>) [with _Tp = long long int; _Alloc = std::allocator<long long int>; std::vector<_Tp, _Alloc>::iterator = __gnu_cxx::__normal_iterator<long long int*, std::vector<long long int> >; typename std::_Vector_base<_Tp, _Alloc>::pointer = long long int*; std::vector<_Tp, _Alloc>::const_iterator = __gnu_cxx::__normal_iterator<const long long int*, std::vector<long long int> >; typename __gnu_cxx::__alloc_traits<typename std::_Vector_base<_Tp, _Alloc>::_Tp_alloc_type>::const_pointer = const long long int*]

1059:7: note:   candidate expects 2 arguments, 1 provided
1084:7: note: candidate: std::vector<_Tp, _Alloc>::iterator std::vector<_Tp, _Alloc>::insert(std::vector<_Tp, _Alloc>::const_iterator, std::vector<_Tp, _Alloc>::size_type, const value_type&) [with _Tp = long long int; _Alloc = std::allocator<long long int>; std::vector<_Tp, _Alloc>::iterator = __gnu_cxx::__normal_iterator<long long int*, std::vector<long long int> >; typename std::_Vector_base<_Tp, _Alloc>::pointer = long long int*; std::vector<_Tp, _Alloc>::const_iterator = __gnu_cxx::__normal_iterator<const long long int*, std::vector<long long int> >; typename __gnu_cxx::__alloc_traits<typename std::_Vector_base<_Tp, _Alloc>::_Tp_alloc_type>::const_pointer = const long long int*; std::vector<_Tp, _Alloc>::size_type = long unsigned int; std::vector<_Tp, _Alloc>::value_type = long long int]

1084:7: note:   candidate expects 3 arguments, 1 provided
1128:2: note: candidate: template<class _InputIterator, class> std::vector<_Tp, _Alloc>::iterator std::vector<_Tp, _Alloc>::insert(std::vector<_Tp, _Alloc>::const_iterator, _InputIterator, _InputIterator) [with _InputIterator = _InputIterator; <template-parameter-2-2> = <template-parameter-1-2>; _Tp = long long int; _Alloc = std::allocator<long long int>]

1128:2: note:   template argument deduction/substitution failed:
30:21: note:   candidate expects 3 arguments, 1 provided<br>

How to solve the problem

A: In function make(), try using v.push_back(num) instead of v.insert(num) it should work.

A: You lack the first parameter in your vector::insert, the position the new element should be placed after.
If you don't want to use vector::push_back as suggested in the previous answer, here is a MWE:
#include<iostream>
#include<string>
#include<vector>
#include <algorithm>

using namespace std;

typedef long long int ll;
vector<ll> v;

void make(ll num)
{
    if(num>10000000000)
        return;
    if(num!=0)
        v.insert(v.begin(),num);   // iterator to insert position added
    make(num*10+4);
    make(num*10+7);
}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    ll num=0;
    make(num);
    ll n,ans=0;
    cout << "Input number: " << endl;
    cin>>n;
    for(auto i:v)
    {
        for(auto j:v)
        {
            if(i<=n&&j<=n&&j>=i)
            {
                if(__gcd(i,j)==1)
                    ans++;
            }
        }
    }

    cout<< "answer = " << ans <<endl;

return 0;
}

What is this for? A random number generator?


text:
Q: Point of small maximum distance to $n$ arbitrary points in $m$-dimensional unit cube Informally speaking, if $n$ people living at the vertices of the $m$-dimensional unit cube $C_m$ want to have a party at the most convenient vertex of $C_m$ (possibly at one of the $n$ vertices themselves), what is the worst case maximum distance in terms of $m$ and $n$ that any one of them may have to travel in the "Manhattan" or $\ell_1$ metric (that is: along the edges of the cube). Note that this is referring to the best choice of party venue subject to the minimisation of the longest journey, with the worst-case distribution of people in that regard
Formally speaking, I'm defining $D_{m,n} \in \mathbb{N}$ to be minimal such that the following is true:
$$\forall x_1, x_2, ..., x_n \in C_m ~ \exists ~ c\in C_m ~\forall~ 1\leq i \leq n: d_1(x_i,c) \leq D_{m,n}$$
where $(C_m,d_1)$ is the metric subspace $\lbrace0,1\rbrace^m$ of $(\mathbb{R}^m,||\cdot||_1)$.
My limited progress so far:
By the triangle inequality, I can see that $D_{m,2}=\lceil\frac{m}{2}\rceil$. I can see it can't be any smaller in the case $x_1=(0,0,...,0), x_2=(1,1,...,1)$.
The simple example for $m=2$ and $n=4$ where the $x_i$ are all the different vertices of the square shows that $D_{2,4}=2 > D_{2,2}=1$. So $D_{m,n}$ definitely somehow increases with $n$ if $m$ is held constant. I just don't quite see how. For example, I haven't yet managed to construct a distribution showing that $D_{12,4}>6=D_{12,2}$.
I'd be grateful for any suggestions of a way to think about this systematically without exhaustive simulation!

A: By a Chernoff bound, the fraction of locations within $\frac m2 + k \sqrt{\frac m2}$ steps of a given attendee is $p \le e^{-k^2/3}$. Thus, if you have fewer than $e^{k^2/3}$ attendees, you will be able to find a location within $\frac m2 + k\sqrt{\frac m2}$ steps of each of them.
Also, if we put down $n$ attendees at random vertices of the cube, then for each location, the probability that it's within $\frac m2 + k\sqrt{\frac m2}$ steps of each of them is $(1-p)^n < e^{-pn}$, so if we set $n = \frac{m \ln 2}{p}$, this probability is less than $2^{-m}$. Then the expected number of locations that work is less than $1$, so there is some choice of $ \frac{m \ln 2}{p}$ attendees for which no location is this convenient.
So whatever the actual value of $p$ is for a given $m$ and $k$, we have
$$
    D_{m, 1/p} \le \frac m2 + k\sqrt{\frac m2} \quad \text{and} \quad D_{m,m\ln 2/p} \ge \frac m2 + k\sqrt{\frac m2}.
$$
If we fix $k$ and let $m \to\infty$, then $p \to \frac{1-\text{erf}(k)}{2}$, where erf is the error function.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Query update from an Excel File I have an Excel file with a list of datas that I have to import into an Access db created by me. Inside the db I have a column named 'Description'. It can happens, when the description is more long than a cell, that I have to update my field, but I don't know how to write correctly the query.
In my Excel file the description starts from the C column, so when I want to extract the string I write a line of code like this:
cap.Description = grid(r, 3).Text

I tried to write an Update query, but it doesn't works because VS shows me this message: "additional information no value given for one or more required parameters".
Public Sub updateDB(ByVal PathDB As String)
Dim db As New cDB
Dim v As New cVoice

Dim rs As ADODB.Recordset = db.RecordSet
db.connect_DB(PathDB)
db.get_rs("UPDATE Voice SET Description = @v.Description")

db.close_DB()
End Sub

Public Function get_rs(ByVal query As String) As ADODB.Recordset

    If db Is Nothing Then rs = Nothing : Return rs

    rs = New ADODB.Recordset
    rs.CursorType = ADODB.CursorTypeEnum.adOpenStatic
    rs.LockType = ADODB.LockTypeEnum.adLockOptimistic

    rs.Open(query, db)

    Return rs

End Function

 Public Function connect_DB() As ADODB.Connection

    If Not My.Computer.FileSystem.FileExists(pPathDB) Then db = Nothing : Return db

    db = New ADODB.Connection
    db.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & pPathDB & ";Persist Security Info=False"
    db.Open()

    If db.State = ConnectionState.Closed Then db = Nothing

    Return db

End Function

Then I tried to switch, stupidly, Description = @v.Description with Description = grid(r, 3).Text, but obviously this way doesn't work.
So, how can I express that I have to update my db column with C cell in Excel?

A: Try to make the query as:
 db.get_rs("UPDATE Voice SET Description  = '" + v.Description +"'")

As this error means that there is wrong spelling for the value or missed value as mentioned here: no value given for one or more required parameters


text:
Q: How Many Sets of 5 Can You Make From 22 Elements? I know you can just say $\large\frac{22!}{(22!-5!)5!}$. My question is deeper than this, however. What if the set of 5 cannot be used again?
For instance, I have 22 coloured balls, my first set of 5 balls is as follows:-
Blue
Red
Green
Yellow
White
Also, I can never have a different combination of the same 5 balls, for instance the following could not be counted either:-
Red
Blue
Green
Yellow
White
I can't use the same set again, but I can replace one of the elements, like so:-
Blue
Red
Green
Purple
White
How many different combinations of 5 can I make from my 22 balls? Is there a formula for this?

A: This is just $\dbinom{22}{5} = \dfrac{22!}{5!(22-5)!}$. It appears you have gotten the formula wrong. Also, the above formula does not count repeats as you are suggesting it does.


text:
Q: Populating Dropdown box from mysql using php Student looking for help.
Trying to populate a dropdown menu from a mysql database, no data being showed in dropdown. Using getCategory function to get data from tables categories. Database is connecting and the particular table is being accessed through another function. I'm lost on this one, been looking and googling for the answer for last number of nights, still no luck. Maybe I've been looking at it too long that my brains fried?
Function Code
public function getCategory()
{
echo $query = "SELECT * FROM `categories`";
$results = mysqli_query($this->_con, $query)  or die(mysqli_error());
$categories = array();
foreach ($results as $result){
$categories[$result['id']] = $result['category_name'];
}
mysqli_close($this->_con);

return $categories;
           echo "<pre>"; print_r($categories); echo "</pre>";
}

Dropdown Code
<select class="form-control" name="category" id="category">
<option value="">Choose your category</option>
<?php  foreach ($categories as $key=>$category){ ?>
<option value="<?php echo $key; ?>"><?php echo $category; ?></option>
<?php } ?>
</select>

Table called categories
Columns are id & category_name

A:  please try the below code in your code in your function

$nums=mysql_num_rows($results);

for($i=0;$i<$nums;$i++)
{
    $id=mysql_result($results,$i,'id');
    $category=mysql_result($results,$i,'category_name');

$categories[$id] = $category;
}

$categories =getCategory() ;

A: I am not sure what you are struggling with, your code is missing a function call to getCategory (should be called getCategories because you are getting plural of objects, not one. Just a sidenote).
Following code is tested and works (save as index.php in your documentRoot to test), please be aware that I cannot declare a function as public when not in a class context, also I could not use $this->_con without a class with _con var, so I used $con instead. You need to adapt it to your context and needs:
index.php:
<?php
$category = filter_input(INPUT_POST,'category');
if($category!=FALSE && $category!=NULL){
    $selectedCategory = $category;
}

function getCategory() {
    $con = mysqli_connect("localhost","root","","categories") or die("Error " . mysqli_error($con));
    echo $query = "SELECT * FROM `categories`";
    $results = mysqli_query($con, $query)  or die(mysqli_error());
    $categories = array();
    foreach ($results as $result){
        $categories[$result['id']] = $result['category_name'];
    }
    mysqli_close($con);

    return $categories;
}
?>

<html>
<head>
<title>Categories Test</title>
</head>
<body>
<?php
if(isset($selectedCategory)){
    echo "last selected category ID: ".$selectedCategory;
}
?>
<form action="index.php" method="POST">
    <select class="form-control" name="category" id="category">
        <option value="">Choose your category</option>
        <?php
        $categories = getCategory();
        foreach ($categories as $key=>$category): ?>
            <option value="<?php echo $key; ?>"><?php echo $category; ?></option>
        <?php endforeach; ?>
    </select>

    <input type="submit" value="send" />
</form>

</body>

A: Here is the example i did it in this way. Hope! it will helps you.
public function GetStates()
{
    $tempgetstates = mysql_query("SELECT * FROM `states`") or die(mysql_error());
    echo '<select name="state" class="sel_reg_form" required />';
    echo '<option value="">...Select...</option>';
    while($getstates = mysql_fetch_object($tempgetstates))
    {
        echo '<option value="'.$getstates->state_code.'">'.$getstates->state.'</option>';
    }
    echo '</select>';
}


text:
Q: SQL: issue joining tables I have the following two tables:
attributevalueassign

itm_id  attr_value_id   attr_id
-----   -------------   -------
396     237             1
396     20              2
715     274             1
715     16              2

attributevalue

attr_id   attr_value_id     attr_value
-------   -------------     ----------
1         237               3055020
1         274               2454518
2         16                Dunlop
2         20                Vogue

I need to be able to write a query that when I supply the item_id (ex:396), I get back the following result:
itm_id  attr_value_id   attr_id   attr_value
------  -------------   -------   ----------
396     237             1         3055020
396     20              2         Vogue

When I try using INNER JOIN, I get more rows than I want:
SELECT     dbo.select_attributevalue.attr_value, dbo.select_attributevalueassign.itm_id
FROM         dbo.select_attributevalueassign INNER JOIN
                      dbo.select_attributevalue ON dbo.select_attributevalueassign.attr_id = dbo.select_attributevalue.attr_id
WHERE     (dbo.select_attributevalueassign.itm_id = 396)

itm_id  attr_value_id   attr_id  attr_value
------  -------------   -------  ----------
396     237             1        3055020
396     237             1        2454518
396     20              2        Dunlop
396     20              2        Vogue

So, my thought is that I probably shouldn't be using a JOIN, but I don't know what the alternative is.  I've dug around on this site looking for a solution, and there are many questions on how to remove duplicate records using a join, but I didn't see one similar to what I was asking.  My knowledge of SQL queries is basic, so I'm not sure what to do.  Any help would be much appreciated!

A: You might need to do inner join by two columns attr_value_id and attr_id. Try this query:
SELECT     dbo.select_attributevalue.attr_value, dbo.select_attributevalueassign.itm_id
FROM         dbo.select_attributevalueassign
    INNER JOIN dbo.select_attributevalue ON
    dbo.select_attributevalueassign.attr_id = dbo.select_attributevalue.attr_id
    AND dbo.select_attributevalueassign.attr_value_id = dbo.select_attributevalue.attr_value_id
WHERE     (dbo.select_attributevalueassign.itm_id = 396)


text:
Q: Pushdown automata - definition and definition of $\vdash$ I am reading about pushdown automata and I don't understand the definition
of $\vdash$.
My book writes that $$(q,aw,Z\alpha)\vdash(p,w,\beta\alpha)$$ if $$(p,\beta)\in\delta(q,a,Z)$$
Can someone please explain to me this definition ?
I understand that the automata is at first in state $q$ and the reminder
of the input is $aw$ (so it starts with $a$ so it fits to the second
argument of $\delta)$,
but I have problems understanding whats happening with $Z\alpha$
and $\beta\alpha$, is the content of the stack $Z\alpha$ or is it
just whats written at the top ? why go from $Z\alpha$ to $\beta\alpha$
? and actually where is $\alpha$, is it in $\Gamma^{*}$?
another small issue I have: does $\Sigma\subset\Gamma$ ? it is not
written in my book but I suspect so.
if it does, does $\Gamma=\Sigma\cup\{\dashv\}$? does $\dashv\not\in\Sigma$
by definition ?
I'm sorry for all this definition questions, it is not defined in
my book.

A: $X \vdash Y$ means that if the automaton was in configuration $X$, then its next configuration will be $Y$.
$Z\alpha$ is the entire content of the stack. The idea is that the top stack symbol is $Z$, and the automaton can't see $\alpha$ because that is underneath. So it pops off the $Z$ and then supplies that as an argument to the transition function $\delta$.  $\delta$ returns a new string of stack symbols, $\beta\in\Gamma^\ast$, and the automaton pushes the $\beta$ symbols onto the stack atop the $\alpha$ that were already there, leaving $\beta\alpha$ on the stack.
You didn't say what you mean $\Sigma$ and $\Gamma$ to be; I guess $\Sigma$ is the input alphabet and $\Gamma$ is the stack alphabet.  In that case yes, we usually take $\Sigma$ to be a subset of $\Gamma$, which means that the automaton can remember input symbols by pushing them onto the stack. But that is just for convenience; if the stack and input alphabets were disjoint we could still have the automaton remember input symbols by encoding them as strings of stack symbols and pushing the codes on the stack.
Is $\dashv$ the special bottom-of-stack symbol?  If so, then yes, $\dashv\not\in\Sigma$.  Some books will take $\Gamma = \Sigma\cup\{\dashv\}$, but others will allow it to be bigger, or to be entirely disjoint from $\Sigma$; it doesn't matter very much in practice.  You should consult your book to find out what your book says. You claim your book doesn't define these things, but I think you should look again.

A: $\Gamma$ is the stack alphabet; it may be entirely disjoint from $\Sigma$, which is the input alphabet.
$(p,\beta)\in\delta(q,a,Z)$ means that if the automaton is in state $q$ with input $a$ and $Z$ on the top of the stack, it goes to state $p$ and replaces $Z$ with $\beta$, where $\beta\in\Gamma^*$ is a finite string of stack symbols. In other words, it pops the single symbol $Z$ and pushes the string $\beta$ onto the stack.
In the statement $(q,aw,Z\alpha)\vdash(p,w,\beta\alpha)$, $\alpha$ is the rest of the stack 'under' $Z$; the statement says that if the automaton is in state $p$ with stack contents $Z\alpha$ (so that $Z$ is on the top of the stack), reading an input $aw$, it can make a direct transition to state $p$, reading an input $w$, with $\beta\alpha$ on the stack. In other words, it has read the single character $a\in\Sigma$, leaving as input the remaining string $w\in\Sigma^*$, it has popped the single character $Z\in\Gamma$ from the stack, leaving $\alpha\in\Gamma^*$ still on the stack, and it has pushed $\beta\in\Gamma^*$ onto the stack as well, so that the stack now contains the string $\beta\alpha\in\Gamma^*$.


text:
Q: Could not find method android() for arguments in Android Studio project I am trying to do a grade sync on my android studio project and I keep getting this error in the title.  My build.gradle file is
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
    jcenter()
}
dependencies {
    classpath 'com.android.tools.build:gradle:2.2.1'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}
}
allprojects {
repositories {
    jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}

android {
compileSdkVersion 24
buildToolsVersion '24.0.0'
}
dependencies {

}

My error message is
Gradle sync failed: Could not find method android() for arguments [build_aiwlctiq29euo9devcma4v4r7$_run_closure3@22efc0bc] on root project 'MyRadio

I have looked online and tried multiple solutions but nothing seems to work.  What does this even mean?  Any help would be appreciated.

A: Move your android{} part to this file

A:
currently you are editing top level gradle file but you have to edit App level

add dependencies over there.

A: Each module you add in your Android Studio Project has its own build.gradle file. Any dependencies that you want to add is added in associated module build.gradle file.
So in your case you have to add your dependencies in your app's build.gradle file.
Here is an image showing where you should add that.

A: Refresh gradle after deleting the below
android {
compileSdkVersion 24
buildToolsVersion '24.0.0'
}
dependencies {

}

It works for me

A: Check if your APP Level Build.Gradle is missing Plugin
then Add apply plugin: 'com.android.application'
in APP Level Build.Gradle
From My solution.


text:
Q: iPhone App how to post Youtube video link using facebook graph Api in iPhone App how to post Youtube video link  using facebook graph Api to FaceBook Wall post?

A: You can try this :
-(IBAction)postMeFeedButtonPressed:(id)sender {

NSMutableDictionary *variables = [NSMutableDictionary dictionaryWithCapacity:4];

[variables setObject:@"#Your Message" forKey:@"message"];
[variables setObject:@"#http://Your Youtube Link" forKey:@"link"];
[variables setObject:@"#This is the bolded copy next to the image" forKey:@"name"];
[variables setObject:@"#This is the plain text copy next to the image.  All work and no play makes Jack a dull boy." forKey:@"description"];

FbGraphResponse *fb_graph_response = [fbGraph doGraphPost:@"me/feed" withPostVars:variables];
NSLog(@"postMeFeedButtonPressed:  %@", fb_graph_response.htmlResponse);

//parse our json
SBJSON *parser = [[SBJSON alloc] init];
NSDictionary *facebook_response = [parser objectWithString:fb_graph_response.htmlResponse error:nil];
[parser release];

//let's save the 'id' Facebook gives us so we can delete it if the user presses the 'delete /me/feed button'
self.feedPostId = (NSString *)[facebook_response objectForKey:@"id"];
NSLog(@"feedPostId, %@", feedPostId);
NSLog(@"Now log into Facebook and look at your profile...");

}

A: Try this to post youtube video
ACAccountStore *accountStore = [[ACAccountStore alloc] init];
    ACAccountType *accountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
    [accountStore requestAccessToAccountsWithType:accountType options:@{ACFacebookAppIdKey : facebookAppKey, ACFacebookPermissionsKey : [NSArray arrayWithObjects:@"publish_stream", nil], ACFacebookAudienceKey : ACFacebookAudienceOnlyMe} completion:^(BOOL granted, NSError *error) {
        if(granted ) {

            NSArray  *accountsArray = [accountStore accountsWithAccountType:accountType];
            NSDictionary *postDict = @{
                                       @"link": youtubeurl,//URL of youtube video
                                     };
            ACAccount *facebookAccount = [accountsArray objectAtIndex:0];
            SLRequest *facebookRequest = [SLRequest requestForServiceType:SLServiceTypeFacebook
                                                            requestMethod:SLRequestMethodPOST
                                                                      URL:[NSURL URLWithString:@"https://graph.facebook.com/me/feed"]
                                                               parameters:postDict];

            [facebookRequest setAccount:facebookAccount];

            [facebookRequest performRequestWithHandler:^( NSData* responseData, NSHTTPURLResponse* urlResponse, NSError* error ) {

                dispatch_async(dispatch_get_main_queue(), ^{

                    [self.view setUserInteractionEnabled:true];
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Posted Successfully on Facebook" message:@"" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles: nil];
                    [alert show];
                });
            }];

        } else {
            NSLog(@"Error %@", error.description);
            dispatch_async(dispatch_get_main_queue(), ^{

                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Account not found" message:@"Please log in to Facebook account from Settings" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles: nil];
                [alert show];
            });
        }
    }];


text:
Q: Is there a way to access compute quotas with the Azure CLI or Python SDK? I want to tabulate the compute quotas for each Azure ML workspace, in each Azure location, for my organization's Azure subscription. Although it is possible to look at the quotas manually through the Azure Portal (link), I have not found a way to do this with the Azure CLI or Python SDK for Azure. Since there are many resource groups and AML workspaces for different teams under my Azure subscription, it would be much more efficient to do this programmatically rather than manually through the portal. Is this even possible, and if so how can it be done?

A: It does look like these commands are currently in the CLI or the Python SDK. The CLI uses the Python SDK, so what's missing from one does tend to be missing from the other.
Fortunately, you can invoke the rest endpoints directly, either in Python or by using the az rest command in the CLI.
There are a few commands that may interest you:
Usage and Quotas for a region:
/subscriptions/{subscriptionId}/providers/Microsoft.MachineLearningServices/locations/{location}/usages?api-version=2019-05-01
/subscriptions/{subscriptionId}/providers/Microsoft.MachineLearningServices/locations/{location}/quotas?api-version=2020-04-01
The process for updating REST specs to the offical documentation is fairly lengthy so it isn't published yet, but if you are willing to use Swagger docs to explore what is available, the 2020-06-01 version of the API is on Github, which includes endpoints for updating quotas as well as retrieving them: https://github.com/Azure/azure-rest-api-specs/tree/master/specification/machinelearningservices/resource-manager/Microsoft.MachineLearningServices/stable/2020-06-01


text:
Q: Propfind: Windows Explorer not showing first file I'm implementing a WebDAV server and I'm currently working on the PROPFIND method.
It works fine in Cyberduck and also in BitKinex.
But the problem occurs when I use Windows Explorer:
the Windows Explorer always shows one item (file or folder) too few.
In the following XML, you can see that there are two folders (or collections) in the current directory. But when you open the Windows Explorer, only the second folder is shown.
<D:multistatus xmlns:D="DAV:">
    <D:response>
        <D:href>http://localhost:8888/Folder/Folder1</D:href>
        <D:propstat>
            <D:prop>
                <D:creationdate>2014-04-22T12:30:31+02:00</D:creationdate>
                <D:displayname>Folder1</D:displayname>
                <D:getcontentlanguage />
                <D:getcontentlength />
                <D:getcontenttype />
                <D:getetag />
                <D:getlastmodified>
                    Tue, 22 Apr 2014 12:30:31 GMT
                </D:getlastmodified>
                <D:lockdiscovery />
                <D:resourcetype><D:collection /></D:resourcetype>
                <D:supportedlock />
                <D:ishidden>0</D:ishidden>
            </D:prop>
            <D:status>HTTP/1.1 200 OK</D:status>
        </D:propstat>
    </D:response>
    <D:response>
        <D:href>http://localhost:8888/Folder/Folder2</D:href>
        <D:propstat>
            <D:prop>
                <D:creationdate>2014-04-22T12:30:44+02:00</D:creationdate>
                <D:displayname>Folder2</D:displayname>
                <D:getcontentlanguage />
                <D:getcontentlength />
                <D:getcontenttype />
                <D:getetag />
                <D:getlastmodified>
                    Tue, 22 Apr 2014 12:30:44 GMT
                </D:getlastmodified>
                <D:lockdiscovery />
                <D:resourcetype><D:collection /></D:resourcetype>
                <D:supportedlock />
                <D:ishidden>0</D:ishidden>
            </D:prop>
            <D:status>HTTP/1.1 200 OK</D:status>
        </D:propstat>
    </D:response>
</D:multistatus>

What should I do to make Windows Explorer show both items ?

A: I have found the solution to this problem.
The current folder must be included in the response body, and not only it's children.
And Windows Explorer doesn't show the first response element.
What the XML from above should be:
<D:multistatus xmlns:D="DAV:">
<D:response>
        <D:href>http://localhost:8888/Folder/</D:href>
        <D:propstat>
            <D:prop>
                <D:creationdate>2014-04-22T12:30:30+15:00</D:creationdate>
                <D:displayname>Folder1</D:displayname>
                <D:getcontentlanguage />
                <D:getcontentlength />
                <D:getcontenttype />
                <D:getetag />
                <D:getlastmodified>
                    Tue, 22 Apr 2014 12:29:41 GMT
                </D:getlastmodified>
                <D:lockdiscovery />
                <D:resourcetype><D:collection /></D:resourcetype>
                <D:supportedlock />
                <D:ishidden>0</D:ishidden>
            </D:prop>
            <D:status>HTTP/1.1 200 OK</D:status>
        </D:propstat>
    </D:response>
    <D:response>
        <D:href>http://localhost:8888/Folder/Folder1</D:href>
        <D:propstat>
            <D:prop>
                <D:creationdate>2014-04-22T12:30:31+02:00</D:creationdate>
                <D:displayname>Folder1</D:displayname>
                <D:getcontentlanguage />
                <D:getcontentlength />
                <D:getcontenttype />
                <D:getetag />
                <D:getlastmodified>
                    Tue, 22 Apr 2014 12:30:31 GMT
                </D:getlastmodified>
                <D:lockdiscovery />
                <D:resourcetype><D:collection /></D:resourcetype>
                <D:supportedlock />
                <D:ishidden>0</D:ishidden>
            </D:prop>
            <D:status>HTTP/1.1 200 OK</D:status>
        </D:propstat>
    </D:response>
    <D:response>
        <D:href>http://localhost:8888/Folder/Folder2</D:href>
        <D:propstat>
            <D:prop>
                <D:creationdate>2014-04-22T12:30:44+02:00</D:creationdate>
                <D:displayname>Folder2</D:displayname>
                <D:getcontentlanguage />
                <D:getcontentlength />
                <D:getcontenttype />
                <D:getetag />
                <D:getlastmodified>
                    Tue, 22 Apr 2014 12:30:44 GMT
                </D:getlastmodified>
                <D:lockdiscovery />
                <D:resourcetype><D:collection /></D:resourcetype>
                <D:supportedlock />
                <D:ishidden>0</D:ishidden>
            </D:prop>
            <D:status>HTTP/1.1 200 OK</D:status>
        </D:propstat>
    </D:response>
</D:multistatus>

More information here: http://www.webdav.org/specs/rfc2518.html#rfc.section.8.1.2


text:
Q: Different lists in Python in size and content still share the id, does memory matter? I have read the answer from this question as well as the related questions about the issue of having different objects sharing the same id (which can be answered by this Python docs about id). However, in these questions, I notice that the contents of the objects are the same (thus the memory sizes are the same, too). I experiment with the list of different sizes and contents on both the IPython shell and .py file with CPython, and get the "same id" result, too:
print(id([1]), id([1,2,3]), id([1,2,3,4,1,1,1,1,1,1,1,1,1,1,1,1]))
# Result: 2067494928320 2067494928320 2067494928320

The result doesn't change despite how many elements or the size of the number (big or small) I add to the list
So I have a question here: when an id is given, does the list size have any effect on whether the id can be reused or not? I thought that it could because according to the docs above,

CPython implementation detail: This is the address of the object in memory.

and if the address does not have enough space for the list, then a new id should be given. But I'm quite surprised about the result above.

A: Make a list, and some items to it.  the id remains the same:
In [21]: alist = []
In [22]: id(alist)
Out[22]: 139981602327808
In [23]: for i in range(29): alist.append(i)
In [24]: id(alist)
Out[24]: 139981602327808

But the memory use for this list occurs in several parts.  There's some sort storage for the list instance itself (that's that the id references).  Python is written in C, but all items are objects (as in C++).
The list also has a data buffer, think of it as a C array with fix size.  It holds pointers to objects elsewhere in memory.  That buffer has space for the current references plus some sort of growth space.  As you add items to list, their references are inserted in the growth space.  When that fills up, the list gets a new buffer, with more growth space.  List append is relatively fast, with periodic slow downs as it copies references to the new buffer.  All that occurs under the covers so that the Python programmer doesn't notice.
I suspect that in my example alist got a new buffer several times, but I don't there's any way to track or measure that.
Storage for the objects referenced by the list is another matter.  cython creates small integer objects (up to 256) at the start, so my list (and yours) will have references to those unique integer objects.  It also maintains some sort of cache of strings.  But other things, such as larger numbers, other lists, dicts, custom class objects, are created as needed.  Identically valued objects might well have different id.
So while the data buffer of the list is contiguous, the items referenced in the buffer are not.
By and large, that memory management is unimportant to programmers.  It's only when data structures get very large that we need to worry.  And that seems to occur more with object classes like numpy arrays, which have a very different memory use.


text:
Q: How to update a table row with save button using .ajax I have a table which has one row and only one cell will be editable.  I have accomplished this with the following code.
$("td#effEndDate").click(function() {
            if (!$(this).hasClass("edit")) {
                var value = jQuery.trim($(this).html());
                $(this).html("<input id=\"txtEdit\" type=\"text\" value=\"" + value + "\" />");
                $(this).addClass("edit");
                $("#txtEdit").focus();
            }
        });

Now this is the part where i'm stuck.
After the field is updated a save button must be clicked to call the proper .ajax method to update the database. But how can I compare the previous value to the current value on a button press? Since i'm not using the onblur property where I could have saved the old value and passed it to the update function.

A: I would store the original value somewhere in a variable, and compare the two in the submission function before sending the .ajax call.

A: There are two possibilities.

*

*Pass the variable around in between functions

*Make the variable global

if you want the variable global do not use the "var" keyword
Change:
var value = jQuery.trim($(this).html());

To this:
value = jQuery.trim($(this).html());

Edit
If the click function is getting hit more then once before a page refresh and assuming you want to keep a copy of the original table rows you can try this. Save a copy of the original table in a variable then you can query the original table for the html using the ID number. Here is a quick mock
first store the table in a variable upon the page loading. This will save an original copy of the table
 //get a copy of the table
 var GetCopyofOriginalTable = function() {
      var TableToBeCopied = $('the appropriate selector');
      CopyOfTable = JQuery.extend(true, {}, TableToBeCopied);  //Notice no var, its global
 }

 //Now store the variale
 GetCopyofOriginalTable();

 var FindTableRowByID = function(trID) {
      return $('table:has(tr#' + trID));
 }

Now you can loop through the new table test its value agaisnt the old table. This methed make use alot of memory depending on how big the table is.


text:
Q: Test if a regexp does not match the beginning of a string without using .nil? I'm testing some strings to make sure they start with a letter:
name =~ /\A[a-zA-Z].*/

but since in Ruby this evaluates to either nil or 0 and both cast to false, I need to put an additional .nil? test:
if(name =~ /\A[a-zA-Z].*/).nil? ...

Is this the proper way or am I missing something?
EDIT:
Thanks for the replies, in my ignorance I made wrong assumptions, oversimplified the example. It should read (note the negation):
name !=~ /\A[a-zA-Z].*/

irb(main):001:0> a = "abc"
=> "abc"
irb(main):006:0> (a !=~/\Aabc/)
=> true
irb(main):007:0> (a !=~/\Ab/)
=> true

A:
but since in Ruby this evaluates to either nil or 0 and both cast to false

wrong, only nil (and false, to be precise) are treated as false in conditionals. 0 is treated as true. So
if name =~ /\A[a-zA-Z].*/

is perfectly ok.
About your edited question, you're not allowed to add exclamation sign (!) to any operator to make it negated operator. There's no such operator (BTW, these 'operators' are actually methods) as !=~, so to achieve your goal. you should do:
if !(name =~ /\A[a-zA-Z].*/)

or you can use unless instead:
unless name =~ /\A[a-zA-Z].*/


text:
Q: Java regex to escape pipe I am trying to parse account no and balance from bank sms using java regex group. I am able to successfully parse account no but not able to get the balance as it is always getting null value maybe due to pipe
Sms I am trying to parse is :
Balances for Ac XXXXXXXX0000 on 16/12/2020 11:37:14 AM ISTTotal Avbl. Bal: INR|980310.28Avbl. Bal: INR 980310.28Linked FD bal: INR|0.0

Regex I am using is:
Balances for Ac (?groupname.+?) on 16/12/2020 11:37:14 AM ISTTotal Avbl. Bal: INR|980310.28Avbl. Bal: INR (?groupname[0-9.]+)Linked FD bal: INR|0.0

Any help would be highly appreciated!

A: *

*Escape the pipe like you probably have already tried using a backslash \\|.

*Your problem is with what comes next. It will only match for an amount of 0.0.

Try this:
INR (?<groupname>[0-9.]+)Linked FD bal: INR\\|(?<amount>[0-9.]+)


text:
Q: Is there a regex which will generate a String array by splitting a line for the first two spaces (" ") and then adding the rest to one array index? I have the following text file:
25678399287 James Hi there!
24467448489 Randy yo, how are you?
36373783388 Fred Ciou amigos!

I want to split each line into:
1. the number
2. the name
3. the message.
I have so far been able to split the line into number name and message by using string.split(" "). However this only gets the first word of the message... How do I get the rest of the message?
 String line;

            while ((line = r.readLine()) != null) {
                String[] split = line.split(" ");
                Arrays.stream(split)
                        .forEach(System.out::println);
                messages.add(new Message(Instant.ofEpochSecond(Long.parseUnsignedLong(split[0])), split[1], split[2]));

Current output: 25678399287 James Hi

A: I would use a formal regex here, and then repeatedly apply it for each line in your file:
String input = "25678399287 James Hi there!\n24467448489 Randy yo, how are you?\n36373783388 Fred Ciou amigos!";
String pattern = "(\\d+) (\\S+) (.*)";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(input);
while (m.find()) {
    System.out.println("number: " + m.group(1) + ", name: " + m.group(2) + ", message: " + m.group(3));
}

This prints:
number: 25678399287, name: James, message: Hi there!
number: 24467448489, name: Randy, message: Randy yo, how are you?
number: 36373783388, name: Fred, message: Ciou amigos!

A: You can try this regex:
(\\d+) ([A-Z][a-z]+) (.+)

https://regex101.com/


text:
Q: Упрощение алгоритма для диагонального поиска Задача простая донельзя, но я что-то застрял.
Имеется поле H на W

Нужно пройтись по координатам по диагонали, как показано на картинке.
Вот мой код, но мне кажется задачу можно решить элегантнее, без лишних переменных.
H = 11
W = 14

for j in range(0,H+1):
    i = 0
    for k in range(j,-1,-1):
        print(i,k)
        i+=1

for j in range(W,-1,-1):
    i = 0
    for k in range(j,W+1):
        print(i,k)
        i+=1

for j in range(0,H+1):
    i = 0
    for k in range(j,-1,-1):
        print(i,k)
        i+=1

for j in range(W,-1,-1):
    i = H
    for k in range(j,W+1):
        if i<0:
            break
        print(i,k)
        i-=1

Подскажите пожалуйста, как это сделать.

A: Двумерный массив table создаю для демонстрации результата.
#!/usr/bin/python3

from pprint import pprint

h = 11
w = 14
table = [[0 for j in range(w + 1)] for i in range(h + 1)]

x, y = 0, 0
step_num = 18
num = 1

while num <= step_num:
    x_tmp = x
    while x_tmp >= 0 and num <= step_num:
        table[y][x_tmp] = num
        x_tmp, y = x_tmp - 1, y + 1
        num += 1

    x, y = x + 1, 0

pprint(table)

Output
[[1, 2, 4, 7, 11, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [3, 5, 8, 12, 17, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [6, 9, 13, 18, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [10, 14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]

A: Если я правильно понял вопрос, то вот, что вам нужно:
H = 11
W = 14

for k in range(0, H+W+1):
    for i in range(0, min(k+1, H+1)):
        y = i
        x = k - i
        if x > W:
            continue
        print(y, x)

A: Объединил два предыдущих ответа в один и дописал поиск для остальных углов:
H = 11
W = 14
from pprint import pprint

table = [[0 for j in range(W + 1)] for i in range(H + 1)]
c = 1
for k in range(0, H+W+1):
    for i in range(0, min(k+1, H+1)):
        y = i
        x = k - i
        if x > W:
            continue
        table[y][x] = c
        c+=1

pprint(table)
print()

table = [[0 for j in range(W + 1)] for i in range(H + 1)]
c = 1
for k in range(H+W+1,-1,-1 ):
    for i in range(0, min(k+1, H+1)):
        y = H-i
        x = k - i
        if x > W:
            continue
        table[y][x] = c
        c+=1

pprint(table)
print()

table = [[0 for j in range(W + 1)] for i in range(H + 1)]
c = 1
for k in range(0, H+W+1):
    for i in range(0, min(k+1, H+1)):
        y = H-i
        x = k - i
        if x > W:
            continue
        table[y][x] = c
        c+=1

pprint(table)

table = [[0 for j in range(W + 1)] for i in range(H + 1)]
c = 1
for k in range(H+W+1,-1,-1 ):
    for i in range(0, min(k+1, H+1)):
        y = i
        x = k - i
        if x > W:
            continue
        table[y][x] = c
        c+=1

pprint(table)
print()


text:
Q: Should I reference assemblies from the WinSxS folder? I want to use the Microsft.Web.Administration.dll Assembly. On my Windows 7 the file is located only in the folder c:\windows\winsxs. Why is the assembly in this folder and is it reccomended to reference from there?

A: I'd rather copy it somewhere locally and reference it from there if you really need it.


text:
Q: Linking tables where record in one table has a prefix and other does not I am creating a report which will allow me to reprint invoices using information from two different tables from Sage 300 accounting/job costing sofware.
I have one table that has an invoice number of "123456" and another table that has an invoice number of "SM123456" referring to the same invoice.  The second tables adds the "SM" so that it knows that the invoices was sourced from a particular module.  Is there any way to link these?
I have tried creating a report with a formula to remove the SM from one of the tables so that it can be linked to a subreport.  However the subreport that I want to print is already using subreports and the second tier subreports are not printing data that is needed.
I am open to any other suggestions.
Thank you,


text:
Q: How can I make an RPM depend on package a OR package b? This seems like a simple question, but the docs don't seem to have anything to say on the subject.  I would like to do something like Requires: vim or emacs but when I do that, I in fact depend on vim, or and emacs.  What is the syntax for depending on one or another of two packages?

A: If packages don't have common Provide, and you don't want to rebuild and maintain forks of that packages, but they both do provide same file, you can depend on a file. For example:
Requires: /usr/bin/pear

That way your package won't matter if pear binary is provided by php-pear or php53-pear.

A: There is no such capability in rpm. Require a virtual provides that the packages have in common, if there is one.

A: The standard way to do this is via virtual provides: the providing RPMs each state that they provide a virtual package, and the dependent RPM requires that virtual package.  So, in your example, vim and emacs both Provides: text-editor, and your package would Requires: text-editor.
If the packages that you're depending on don't provide an appropriate virtual package, you could probably hack around this by making up your own.  Make dummy my-package-vim-mode and my-package-emacs-mode RPMs that Requires: vim and Requires: emacs, respectively, and Provides: my-package-text-editor, then have your package Requires: my-package-text-editor.


text:
Q: Output JSON-LD script, loaded via angularjs $http I'm trying to get and output JSON-LD data on the page via $http as follow:

angular.element(document).ready(function(){
        $http({
            url:'/product-init',
            method:'POST',
            data:{product_id:$scope.product_id}
        }).then(function(d){
            $scope.product= d.data;
            $scope.jsonLd={
              "@context":"http://schema.org",
              "@type":"Product"
              // atc.....
            }
            $('#json-ld-content').html(JSON.stringify($scope.jsonLd));
        },function(d){
            alert('product init error');
        });
    });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script type="application/ld+json" id="json-ld-content"></script>

I can see the output in web inspector (on the "Elements" tab), but when I run a [check],1 it shows nothing.
Creating script tag by javascript and then setting html, doesn't help as well.
Also I've found example of loading JSON-LD via AJAX: it works fine.
What's the difference between my case and example above? How to fix my code?
Thanks in advance.

A: The structured data linter you referenced doesn't evaluate JavaScript. Try Google's Structured Data Testing Tool instead.


text:
Q: Error apt-key(8) en instalación de docker Estoy tratando de instalar docker en kubuntu 20.10 en el momento en el que ingreso la llave pública me sale este error:

Warning: apt-key is deprecated. Manage keyring files in trusted.gpg.d instead (see apt-key(8)).

A: Hay varias maneras de instalarlo en versiones de ubuntu (Focal > 20.04) segun se indica en la documentación: https://docs.docker.com/engine/install/ubuntu/
Puedes intentar instalarlo usando el script descargable
curl -fsSL https://get.docker.com -o get-docker.sh
sudo sh get-docker.sh

EDIT:
Para completar la respuesta, el mensaje esta diciendo que ya no se debe usar apt-key para manejar claves. Se debe manejar desde la carpeta /etc/apt/trusted.gpg.d/ donde residen las claves .gpg/.asc, ya sea para agregar, quitar o modificarlas. Por ello, sugiero para este error en particular que se instale docker usando otra opcion (dicha opcion debe ser actualizada para reflejar los cambios recientes en apt-key). Del manual:

Tenga en cuenta que una distribución no necesita y de hecho no debe
usar este comando más largo y en su lugar enviar archivos de
claves en el directorio /etc/apt/trusted.gpg.d/ directamente ya que
esto evita una dependencia de gnupg y es más fácil administrar las
claves simplemente agregando y eliminando archivos para los encargados
del mantenimiento y los usuarios.
http://manpages.ubuntu.com/manpages/bionic/man8/apt-key.8.html#commands

A: Tuve un problema similar al momento de instalar Brave, según los foros de la comunidad solo hace falta continuar con los pasos de instalación debería funcionar... a mi me funciono con Brave, puede que con Docker también funcione


text:
Q: create zip file in .net with password I'm working on a project that I need to create zip with password protected from file content in c#.
Before I've use System.IO.Compression.GZipStream for creating gzip content.
Does .net have any functionality for create zip or rar password protected file?

A: Unfortunately there is no such functionality in the framework. There is a way to make ZIP files, but without password. If you want to create password protected ZIP files in C#, I'd recommend SevenZipSharp. It's basically a managed wrapper for 7-Zip.
SevenZipBase.SetLibraryPath(Path.Combine(
        Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) ?? Environment.CurrentDirectory,
        "7za.dll"));

SevenZipCompressor compressor = new SevenZipCompressor();

compressor.Compressing += Compressor_Compressing;
compressor.FileCompressionStarted += Compressor_FileCompressionStarted;
compressor.CompressionFinished += Compressor_CompressionFinished;

string password = @"whatever";
string destinationFile = @"C:\Temp\whatever.zip";
string[] sourceFiles = Directory.GetFiles(@"C:\Temp\YourFiles\");

if (String.IsNullOrWhiteSpace(password))
{
    compressor.CompressFiles(destinationFile, sourceFiles);
}
else
{
    //optional
    compressor.EncryptHeaders = true;
    compressor.CompressFilesEncrypted(destinationFile, password, sourceFiles);
}

A: DotNetZip worked great in a clean way.
DotNetZip is a FAST, FREE class library and toolset for manipulating zip files.

Code
static void Main(string[] args)
{
        using (ZipFile zip = new ZipFile())
        {

            zip.Password = "mypassword";

            zip.AddDirectory(@"C:\Test\Report_CCLF5\");
            zip.Save(@"C:\Test\Report_CCLF5_PartB.zip");
        }
 }

A: I want to add some more alternatives.
For .NET one can use SharpZipLib, for Xamarin use SharpZipLib.Portable.
Example for .NET:
using ICSharpCode.SharpZipLib.Zip;

// Compresses the supplied memory stream, naming it as zipEntryName, into a zip,
// which is returned as a memory stream or a byte array.
//
public MemoryStream CreateToMemoryStream(MemoryStream memStreamIn, string zipEntryName) {

    MemoryStream outputMemStream = new MemoryStream();
    ZipOutputStream zipStream = new ZipOutputStream(outputMemStream);

    zipStream.SetLevel(3); //0-9, 9 being the highest level of compression
    zipStream.Password = "Your password";

    ZipEntry newEntry = new ZipEntry(zipEntryName);
    newEntry.DateTime = DateTime.Now;

    zipStream.PutNextEntry(newEntry);

    StreamUtils.Copy(memStreamIn, zipStream, new byte[4096]);
    zipStream.CloseEntry();

    zipStream.IsStreamOwner = false;    // False stops the Close also Closing the underlying stream.
    zipStream.Close();          // Must finish the ZipOutputStream before using outputMemStream.

    outputMemStream.Position = 0;
    return outputMemStream;

    // Alternative outputs:
    // ToArray is the cleaner and easiest to use correctly with the penalty of duplicating allocated memory.
    byte[] byteArrayOut = outputMemStream.ToArray();

    // GetBuffer returns a raw buffer raw and so you need to account for the true length yourself.
    byte[] byteArrayOut = outputMemStream.GetBuffer();
    long len = outputMemStream.Length;
}

More samples can be found here.
If you can live without password functionality, one can mention ZipStorer or the built in .NET function in System.IO.Compression.

A: Take a look at DotNetZip (@AFract supplied a new link to GitHub in the comments)
It has got pretty geat documentation and it also allow you to load the dll at runtime as an embeded file.


text:
Q: How to actually use a color palette generated by Material Design tool in Android? I have recently used the material palette generator found at https://material.io/tools/color/ to generate a palette.
This tool is an official tool on Material.io, as you can see. It generated several colors - a primary and secondary, including two variations of each. This led me to create something like this in my colors.xml file.
<!-- Color palette -->
<!-- ... -->

<!-- Colors by usage -->
<color name="colorPrimary">@color/black</color>
<color name="colorPrimaryDark">@color/blackDark</color>
<color name="colorPrimaryLight">@color/gray</color>
<color name="colorSecondary">@color/red</color>
<color name="colorSecondaryDark">@color/maroon</color>
<color name="colorSecondaryLight">@color/redLight</color>
<color name="colorTextOnPrimary">@color/white</color>
<color name="colorTextOnSecondary">@color/white</color>

How can I apply these colors in my theme though? The Android support material (AppCompat) theme only expects/allows three colors - primary, secondary, and accent. Is there another theme I should use where I can apply these attributes? Or am I just doing something wrong here?
I'd like to avoid having to create an entirely new theme here and have to manually set colors for every component that I might want to use.

A: Since I see you're using light and dark colors, I suppose the generator is expecting you to use the DayNight theme. As you're already using AppCompat, I guess you're dealing with the support libraries, so you can easily use those colors with something like this:
     <style name="AppTheme" parent="Theme.AppCompat.DayNight">
        <item name="colorPrimary">...</item>
        <item name="colorPrimaryDark">...</item>
        <item name="colorAccent">...</item>
        ...
     </style>

It's just a matter of finding the right attributes to set.
A quick Google search will bring you many useful resources, check for example this other post that also has a link to the official android developer blog.


text:
Q: is there a toggleSrc method in jQuery? Does jQuery have something like toggleSrc :-p ??
I want to change src of an image on slideToggling of a div.is there something like that give me the chance of not writing conditional statement to check the src of image to change to another src.
(I am not lazy !!!)

A: There isn't a built-in method for this, but you could make a plugin for it, for example:
$.fn.toggleSrc = function(onSuffix, offSuffix) {
  return this.attr("src", function(i, src) {
    return src.indexOf(onSuffix) != -1 ? src.replace(onSuffix, offSuffix)
                                       : src.replace(offSuffix, onSuffix);
  });
};

Then you'd call it like this:
$("img").toggleSrc("_on", "_off");

...or a big safer:
$("img").toggleSrc("_on.jpg", "_off.jpg");

You can test it out here. There are (as usual) 10 other ways to do this as well, this is just one example of how to do this and save you some code repetition.


text:
Q: Getting on 500 Internal Server Error On PHP saving Canvas as Image Trying to save Raphael Paper on Server as an Image I have following code:
$(function() {

$("#printBtn").click(function() {

var svg1 = $("#map > svg").get();
var svg = $('#map').html().replace(/>\s+/g, ">").replace(/\s+</g, "<").replace(/<canvas.+/g,"");
// strips off all spaces between tags

canvg('cvs', svg, {
ignoreMouse: true,
ignoreAnimation: true
});
var canvas  = document.getElementById('cvs');
var img = canvas.toDataURL("image/png");
});
});

});
</script>

and on my process.php I have :
<?php
$data = substr($_POST['imageData'], strpos($_POST['imageData'], ",") + 1);
$decodedData = base64_decode($data);
fclose();
echo "/canvas.png";

but I am getting 500 Internal Server Error from process.php

Can you please let me know why this is happening and how can I stop it?
Thanks

A: Your error is coming from the server, not from javascript which runs in the browser. So the problem is in your php script.
There you have a simple syntax error:
data = substr($_POST['imageData'], strpos($_POST['imageData'], ",") + 1);

Should be:
$data = substr($_POST['imageData'], strpos($_POST['imageData'], ",") + 1);
^ here

By the way, when you get 500 errors, you should always check the server error log and / or display errors in php:
ini_set('display_errors', 1);

Possibly combined with something like:
error_reporting(E_ALL | E_STRICT);


text:
Q: Records of custom objects imported to salesforce have currency code that cannot be updated to the same code as in csv file I have already imported a list of records of a custom object to salesforce via data loader. Now the imported records have currency fields in ISO code(THB) that we imported to salesforce. Unfortunately the currency is reflecting as US dollars(USD) value in salesforce after being imported. Other existing records (already there in application) are having the currency field as THB .
I would want to have the currency code in the imported records to be THB instead of USD. Kindly guide the detailed steps.
Regards,
Moyumi


text:
Q: Saving models and their relationships using the new Ember Data JSONAPISerializer/Adapter I have implemented a JSON-API backend and I'm using ember (1.13.4) and ember data (1.13.5) to pull my data in to the store using the new JSONAPIAdapter / JSONAPISerializer. All is working well and the store is populated with all of the models and their attributes/relationships.
However, when I call the .save() method on my models the JSON-API-formatted request that is generated doesn't contain the "included" key with all related models inside it.  This means that if I modify an attribute in a related model and then save the primary model I don't see the changed attribute from the related model in the JSON payload.
What is the correct way to save models and their relationships so they are embedded using the new JSONAPIAdapter / JSONAPISerializer?  I tried the EmbeddedRecordsMixin but this resulted in null attribute values within the "attributes" key of the payload.
If anyone can assist me with this I'd be grateful.
Thanks.

A: Ok, this has been answered on the Ember forum as follows:

"The standard does not support this at the moment and is scheduled for v1.1 (http://discuss.jsonapi.org/t/json-api-weekly-meeting-june-22nd-2015/23).
Your best bet would be to inherit from the serializer and implement your own standard for now. Just remember to include the included paths in your URL so that your server can reply with all the updated entities."

More information can be found here.


text:
Q: Usar o PDO do PHP para search Onde está o erro em meu código. Não sei o motivo do porquê ele não retorna o resultado da pesquisa.
<?php
require_once('db_connect.php');
$conectar = new
PDO("mysql:host=$host;bancodedados=$bancodedados;charset=utf8",
$usuario, $senha);

$nomeProduto = $_POST['nomeProduto'];
$sql = "SELECT * FROM nilo_db.nilo_tb WHERE nomeProduto =
:nomeProduto";
$queryResult = $conectar->prepare($sql);
$queryExec = $queryResult-
>execute(array(":nomeProduto"=>$nomeProduto));
if($queryExec){
    if($queryResult->rowCount()>0){
        foreach($queryResult as $row){ ?>

                    <?php echo $row['nomeProduto'] ?>
                    <?php echo $row['codigoProduto'] ?>

        <?php }
       }
    }
?>

A: *

*Na string de conexão mude bancodedados=$bancodedados para dbname=$bancodedados

*Caso isso não tenha sido ao colar o código aqui, acerte essa linha de código
$queryExec = $queryResult-
>execute(array(":nomeProduto"=>$nomeProduto));

para evitar erros do tipo PHP Parse error:  syntax error, unexpected '>' in ....

O correto é sem quebra de linha -> e sem espaços

$queryExec = $queryResult->execute(array(":nomeProduto"=>$nomeProduto));
Código corrigido
    $conectar = new PDO("mysql:host=$host;dbname=$bancodedados;charset=utf8", $usuario, $senha);

    $nomeProduto = $_POST['nomeProduto'];
    $sql = "SELECT * FROM nilo_db.nilo_tb WHERE nomeProduto = :nomeProduto";

    $queryResult = $conectar->prepare($sql);
    $queryExec = $queryResult->execute(array(":nomeProduto"=>$nomeProduto));
    if($queryExec){
        if($queryResult->rowCount()>0){
            foreach($queryResult as $row){ ?>

                        <?php echo $row['nomeProduto'] ?>
                        <?php echo $row['codigoProduto'] ?>

            <?php }
           }
        }

Como conectar um banco de dados MySQL utilizando PHP

Utilizando PDO

$conectar = new PDO("mysql:host=HOST;dbname=NOME_DB", "USUARIO", "SENHA");

*

*HOST: Host de conexão com o banco de dados;

*USUARIO: Usuário de acesso ao banco de dados da conexão;

*SENHA: Senha de acesso ao banco de dados especificado na conexão;

*NOME_DB: Nome da base a qual você deseja fazer acesso.


text:
Q: Typeorm: insert with foreign key when cascade enabled - not working I have 2 entities with a ManyToOne/OneToMany Relation with cascade enabled.
< One: Sender ---- Many: Transfer (cascade insert) >
I would like to insert 2 Transfers with the same sender but I'm getting an error that the uniqueness constraint of the sender address is being violated on the second insert.
@Entity()
export class Transfer extends BaseEntity {
  // Each transfer has an id and the sender
  @PrimaryGeneratedColumn()
  id!: number;

  @ManyToOne(() => Sender, (sender) => sender.sends, {
      nullable: false,
      eager: true,
      cascade: ["insert"] })
  sender!: Sender
}

@Entity()
export class Sender extends BaseEntity {
  // Each address has an id and a value of the address
  @PrimaryGeneratedColumn()
  id!: number;

  @Column({ unique: true, nullable: false })
  address!: string;

  @OneToMany(() => Transfer, (transfer) => transfer.sender, {
      eager: false,
      cascade: false })
  sends!: Transfer[]
}

// get typeorm EntityManager
const em = dataSource.manager

const a = 'test_address'

// save the first transfer - cascade will also insert the sender
await em.save(Transfer, { sender: { address: a}})

// save a new transfer by the same sender
const s = await em.findOneBy(Sender, { address: a })
await em.save(Transfer, { sender: s })

How can I insert a new transfer without triggering an insert of a new sender if the sender already exists?

A: A few points:

*

*You can set the eager: true on one side of the relationship only.

*The problem here is that if the sender is not the primary key, how should TypeOrm know at all that we are referencing the same sender? It just cannot tell, hence it produces a new entry (which is wrongly called "duplicate"). The solution I would recommend is using the unique value (in this case, the sender) as a primary key.

*Cascade insert here means if there is a new Sender instance set on this relation, it will be inserted automatically to the db when you save this transfer entity
    @ManyToOne(() => Sender, (sender) => sender.sends, {
          nullable: false,
          eager: true,
          cascade: ["insert"] })
      sender!: Sender

*Try doing this:

 @OneToMany(() => Transfer, (transfer) => transfer.sender)
      sends!: Transfer[]

A: I believe what's happening is when the second Transfer gets created, TypeORM tries to insert a new Sender with the same address as the existing sender and that then conflicts with your Sender.address unique string constraint:
  @Column({ unique: true, nullable: false })
  address!: string;

TypeOrm Insert does not check if the object exists, it's the unique flag for Sender.address that is checking uniqueness.
TypeORM Upsert is used to check if the object exists and do an insert, although I don't see a way to use that in the same way you've done a cascade insert: cascade: ["insert"] }). See some docs from https://orkhan.gitbook.io/typeorm/docs/relations

cascade: boolean | ("insert" | "update")[] - If set to true, the
related object will be inserted and updated in the database. You can
also specify an array of cascade options.

It worries me that there's an open issue for cascade inserts on TypeOrm Github (example uses User / Color entities, where Color is uniquely identified by a string; similar to your Sender.address)
https://github.com/typeorm/typeorm/issues/7171
So I suggest two options:

*

*Remove cascade: ["insert"] from Sender.entity and on Transfer.save, have additional logic to create the sender if it does not already exist. You could use subscribers to listen for Transfer insertions (within Transfer entity) and implement logic there to insert a Sender: https://github.com/typeorm/typeorm/blob/master/docs/listeners-and-subscribers.md -

*Ask the question on TypeOrm Github (use above issue link) to see if there's a better workaround.


text:
Q: What is the $ in Syntactic sugar of Java? //source code
int[] s = new int[]{1,2,3,4};
for(int i:s){
    System.out.println(i);
}
----------------------------
//below is in the class file
for(int i$ = 0; i$ < b; ++i$) {
    int i = a[i$];
    System.out.println(i);
}

what's the use of the $?  i$ is a pointer like c?

A: In this case, it is literally a variable named i$. JLS-3.8. Identifiers reads (in part)

The "Java letters" include uppercase and lowercase ASCII Latin letters A-Z (\u0041-\u005a), and a-z (\u0061-\u007a), and, for historical reasons, the ASCII underscore (_, or \u005f) and dollar sign ($, or \u0024). The $ sign should be used only in mechanically generated source code or, rarely, to access pre-existing names on legacy systems.


text:
Q: NSFileManager UUID app directory I'm using NSFileManager and i'm trying to copy a file to path "/var/mobile/Applications/7AC2295E-2775-41EA-B017-AB4048A09F0C/Document" the file will copy fine.
but the path of "7AC2295E-2775-41EA-B017-AB4048A09F0C" is randomly changed in every time i delete and install the app again. So, is there a way to get the correct path of my app or search for file name, If file exist then replace\delete..etc the file? thanks alot.

A: You don't have to use the absolute path, use something like
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
[[NSFileManager defaultManager] copyItemAtPath:[[NSBundle mainBundle]pathForResource:@"test" ofType:@"txt"] toPath:[documentsDirectory stringByAppendingPathComponent:@"test.txt"] error:nil];

This demonstrates copying the file test.txt from the apps bundle to the documents directory.
Do something like this to create a file test.txt
[[NSFileManager defaultManager] createFileAtPath:[documentsDirectory stringByAppendingPathComponent:@"test.txt"] contents:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://a-cstudios.com/text.json"]] attributes:nil];

EDIT
If your using this and want to use it on a jailbroken device, to put something in the sandbox is the same as I said before, so you still don't have to use the UUID. If you want to put something in a system directory, that is when you would use something like /usr/include/, or wherever you want to. To put something in another apps sandbox, you would have to use the complete path, and you would have to know the UUID, as thats not part of your sandbox. So, unless you're copying a file to an app that you made, you have to use the complete path.

A: The proper way to get access to the Documents directory in your app's sandbox is:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = paths[0];

Then you create your path:
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"filename.ext"];

A: If your application needs to write a file to its Documents directory.
use something like :
NSString  *filePath = NSHomeDirectory();

then append your actual file name to filePath.
then use filePath in your FileManager calls.


text:
Q: Exiting while loop by pressing enter without blocking. How can I improve this method? So I've been doing a little bit of reading up on how to exit a while loop by the user pressing the enter key and I've come up with the following:
import sys, select, os

switch = 1
i = 1
while switch == 1:
    os.system('cls' if os.name == 'nt' else 'clear')
    print "I'm doing stuff. Press Enter to stop me!"
    print i
    while sys.stdin in select.select([sys.stdin], [], [], 0)[0]:
        line = raw_input()
        if not line:
            print "Finished! =]"
            switch = 0
        else:
            print "Finished! =]"
            switch = 0
    i = i+1

Is there a way to tidy this up? In particular the "if not line" and the following "else" look messy. Can they be combined into one? A better alternative to using "switch"?
Initially if I typed a bunch of characters and then hit enter it didn't stop the loop. I would have to press enter again. The if not and else components are intended to set it up such that it would exit on the first press of enter.

A: This worked for me:
import sys, select, os

i = 0
while True:
    os.system('cls' if os.name == 'nt' else 'clear')
    print "I'm doing stuff. Press Enter to stop me!"
    print i
    if sys.stdin in select.select([sys.stdin], [], [], 0)[0]:
        line = raw_input()
        break
    i += 1

You only need to check for the stdin being input once (since the first input will terminate the loop).  If the conditions line/not line have result for you, you can combine them to one if statement.  Then, with only one while statement being used, you can now use break instead of setting a flag.


text:
Q: Cannot convert from Map.Entry to String I'm posting after 2 hours of trying to solve it but I'd like some help here. The task is the following:

Create a method getHeaviest which takes no parameters and returns a string. When called, the method should return the name of the heaviest dinosaur in the database. How you achieve this is up to you. If no dinosaurs are in the database, return an empty string instead. Don't worry about dinosaurs having the same weight.

   import java.util.Map;
import java.util.Collections;
import java.util.HashMap;
import java.util.Set;
import java.util.Map.Entry;

public class randomdamdam {

    private Map<String, Integer> dinos;

    public randomdamdam () {
        dinos = new HashMap<>();
    }

    public int size(){
        return dinos.size();
    }

    public void addDino(String newDino, int weight){
        if (!dinos.containsKey(newDino)) {
            dinos.put(newDino, weight);
            System.out.println(newDino + " added. Weight: " + newDino + "kg");
        } else {
            System.out.println(newDino + " cannot be added. It is already in the database!");
        }
    }

    public void updateDino (String updatedDino, int newWeight){
        if (dinos.containsKey(updatedDino)){
            System.out.println(updatedDino + "updated. Weight: " +newWeight+ "kg");
        } else {
            String line = updatedDino + "cannot be updated. It is not in the database!";
            System.out.println(line);
        }
    }

    public void removeDino (String removedDino) {
        if (dinos.containsKey(removedDino)){
            System.out.println(removedDino + "removed");
    } else {
        String line2= removedDino +"cannot be removed. It is not in the database!";
        System.out.println(line2);
    }
}

    public int getWeight (String existingDinosaur) {
        if (dinos.containsKey(existingDinosaur)){
            return dinos.get(existingDinosaur);
    } else {
        String ofweight = existingDinosaur + "cannot be found in the database!";
        System.out.println(ofweight);
        return 0;
    }
    }

    public Set<String> getDinoNames(){
        Set<String> names = dinos.keySet();
        return names;
    }

    public String getHeaviest () {
        int max = Collections.max(dinos.values());

        for (Entry<String, Integer> heaviestBoi : dinos.entrySet()) {
            if (heaviestBoi.getValue() == max ) {
                String heavy = heaviestBoi.toString();

            return heaviestBoi;
        }}
    }

So the thing is that I'd like to get the heaviest dino out of every dino and I've tried multiple times to do that but I actually can't.

A: I think you were already close. Looking at your getHeaviest method, within the if statement, you have essentially to get the key element of the "Entry" object (which is the name of the dino). You cannot simply return the whole heaviestBoi object as it is of type Entry.
Solution
public String getHeaviest () {
    int max = Collections.max(dinos.values());

    for (Entry<String, Integer> heaviestBoi : dinos.entrySet())
    {
        if (heaviestBoi.getValue() == max ) {
             return heaviestBoi.getKey();
        }
    }
}

Additional Comment
Please note that you wrote the following within your if statement:
String heavy = heaviestBoi.toString();
return heaviestBoi;

Hence, the first line has actually no effect in respect of the returned object.

A: Key of the map must be the name of the dinosaur and value must be its key. So instead of casting amp to String (which is failing) you must return the key which is name of the dinosaur
Replace
String heavy = heaviestBoi.toString();

with
String heavy = heaviestBoi.getKey();

and return that string instead of map object

A: Please refactor the getHeaviest() method like below.Complete source code is given below for your better understandings.
Extra: Please follow the Java naming conventions when you are naming classes .Ex:Starting letter of a class name should be always Capital.
public class randomdamdam {

    private Map<String, Integer> dinos;

    public randomdamdam () {
        dinos = new HashMap<>();
    }

    public int size(){
        return dinos.size();
    }

    public void addDino(String newDino, int weight){
        if (!dinos.containsKey(newDino)) {
            dinos.put(newDino, weight);
            System.out.println(newDino + " added. Weight: " + newDino + "kg");
        } else {
            System.out.println(newDino + " cannot be added. It is already in the database!");
        }
    }

    public void updateDino (String updatedDino, int newWeight){
        if (dinos.containsKey(updatedDino)){
            System.out.println(updatedDino + "updated. Weight: " +newWeight+ "kg");
        } else {
            String line = updatedDino + "cannot be updated. It is not in the database!";
            System.out.println(line);
        }
    }

    public void removeDino (String removedDino) {
        if (dinos.containsKey(removedDino)){
            System.out.println(removedDino + "removed");
    } else {
        String line2= removedDino +"cannot be removed. It is not in the database!";
        System.out.println(line2);
    }
}

    public int getWeight (String existingDinosaur) {
        if (dinos.containsKey(existingDinosaur)){
            return dinos.get(existingDinosaur);
    } else {
        String ofweight = existingDinosaur + "cannot be found in the database!";
        System.out.println(ofweight);
        return 0;
    }
    }

    public Set<String> getDinoNames(){
        Set<String> names = dinos.keySet();
        return names;
    }

    public String getHeaviest () {//Here is your method which returns the heaviest dino's name
        int max = -1;
        String name= null;

        for (Map.Entry<String, Integer> heaviestBoi : dinos.entrySet()) {
            if (heaviestBoi.getValue() >max ) {
                max = heaviestBoi.getValue();
                name = heaviestBoi.getKey();

        }}
       return name;

    }

    public static void main(String[] args) {
        randomdamdam m1 = new randomdamdam();
        m1.addDino("Dino1", 450);
        m1.addDino("Dino2",455);
        m1.addDino("Dino3",700);

        System.out.println("Heaviest Dino: "+ m1.getHeaviest() );//Calling the method
    }
}

Output:
Dino1 added. Weight: Dino1kg
Dino2 added. Weight: Dino2kg
Dino3 added. Weight: Dino3kg
Heaviest Dino: Dino3 //Heaviest one's name returned


text:
Q: javascript object differences with deleted row There are many excellent SO & npm solutions for object differences, but I was unable to find one that dealt successfully with a deleted row.  The solutions I found would show a deleted row by showing all the following(subsequent) array elements moved up a level.
the original object might look something like this:

[   { id : 1    , 'data' : 'one'               }
,   { id : 22   , 'data' : 'two two'           }
,   { id': 333  , 'data' : 'three three three' }
]

and the new object may look like this:

[   { id : 1     , 'data' : 'one'               }
,   // notice missing "two" data element
,   { id : 333   , 'data' : 'three three three' }
]

I am looking for a solution that resembles how the unix diff works using ordinary text:
 /usr/bin/cat   lhs.txt;
 {id:1,data:'one'}
 {id:22,data:'two two'}
 {id:333,data:'three three three'}

 /usr/bin/cat   rhs.txt;
 {id:1,data:'one'}
 {id:333,data:'three three three'}

 /usr/bin/diff    lhs.txt    rhs.txt;
 2d1
 < {id:22,data:'two two'}

It would appear that the optimum solution is to look for the missing data element, and splice in an undefined data element for object comparison purposes.  I came up with this using underscore pluck and differences:
if  ( lhs.length > rhs.length)    {
    var lhsKeys     = _.pluck(lhs,"id")     ;
    var rhsKeys     = _.pluck(rhs,"id")     ;
    for ( var id of _.difference(lhsKeys, rhsKeys)  )      {
        rhs.splice((_.pluck(lhs, 'id').indexOf(id)),0,undefined);
                // replace missing array element with an undefined one
    }
}

and now the two objects will be of equal length, so I can compare them with either deep-object-diff or deep-diff
Ideally, there would be an npm module or an underscore function to simply determine the array element row number of the missing element.
Is there a better, shorter, or more efficient solution?
Thank you very much.


text:
Q: Where are the WordPress capabilities stored? I know the roles and capabilities are stored in the wp_options table with the option_name = wp_user_roles. It has a list of roles assigned with all the capabilities.
So my question is, if I want to just get the list of all the available capabilities, do I need to go through each of the roles and its' capabilities to get the full list or is it all stored somewhere?

A: Since 'Administrator' has all capabilities (unless you have a Multisite setup), just get a list of all the caps in the Admin role:
$admin_caps = get_role('administrator')->capabilities;


text:
Q: JQuery Validate Plugin - AllowIng Submission Using the JQuery Validate plug in to validate some input forms, works great.
Have a form that one piece of information is desired but not required to submit the form.
Lets say for example the form has name, address and boat name.  Name and address are required to complete entry,  boat name is needed before the event but we don't want to hold up the entry if they don't know it yet.
Is there a easy way to use the Validate plug in to pop up a message that say something like:
Boat name must be supplied prior to the event, you may complete registration with out it but please ......  Then maybe have 2nd submit button that bypasses the JQ Validate routines??
Dave

A: You have not show us any code to work with here, but basically, you could do something like this...
There is no method available to turn validation on/off on demand.   Since the plugin is designed to handle the click and intercept the submit event, you could remove the second button from the form (to avoid a submit) and handle the data separately, using ajax to send the data to the server.
$('#save').click(function() {
    var data = $('#myform').serialize();
    // ajax code to send the serialized data to the server
});

Simple DEMO:  http://jsfiddle.net/wnwT9/


text:
Q: In this problem, why is the work done by the spring not equal to the line integral of the spring force over its displacement? Problem statement:

In the given figure, two blocks A and B, each having a mass of 320 grams are connected by a light string passing over a smooth light pulley. The horizontal surface on which block A can slide is smooth. The block A is attached to a spring of spring constant 40$\frac{N}m$ whose other end is fixed to a support 40cm above the horizontal surface. Initially, the spring is vertical and unstretched when the system is released to move. Find the velocity of the block A at the instant it breaks off the surface below it. Take g=10$\frac{m}{s^2}$.
What I have got till now:
After drawing the free body diagram of the block at the instant it breaks off the surface, I found these pieces of data:

*

*The block breaks off when the smaller angle of spring with the ground is $\sin^{-1}\frac{4}5$

*The distance that the block covers till this point is 0.3m

*The elongation in the spring is equal to 0.1m
The part that I am confused with:
Now, according to what I have learned, the work done by any force on an object is $\vec{F}•d\vec{r}$. So this means that we have to take the varying angle between the spring and the displacement of the block into account while calculating the work done by it. So, the work done by spring should be:
$\int\ k\Delta s\cos\theta dx$Here, $\Delta s$ is the elongation of the spring, $\theta$ is the smaller angle made by the spring with the ground, and we are integrating in terms of the displacement of the block.After a bit of observation, I found that $dx$ is equal to -0.4$d\theta$. and $\Delta s$ is equal to 0.4$\frac{1-sin\theta}{sin\theta}$. Now, we can integrate in terms of $\theta$ and find the work done by the spring, which comes to about 2.32 Then, we can factor in the potential energy and find the kinetic energy from that.But this is not the solution that I found when I searched through the internet. A couple of solutions I found online:
https://www.toppr.com/ask/question/figure-shows-two-blocks-a-and-b-each-having-a-mass-of-320-gram-connected/
https://www.sarthaks.com/44038/figure-8-e12-shows-two-blocks-a-and-b-each-having-a-mass-of-320-g-connected-by-a-lightAt the end of both the solutions, the work done by spring is given as $\frac{1}2kx^2$. Which should not be correct as the force is not acting parallel or anti parallel to displacement. The final answer is correct:$1.5\frac{m}{s}$, and the one I got is wrong. But, it does not make sense to me to put the work done by spring as $\frac{1}2kx^2$.So, am I making a very stupid mistake here, or is there something else going on?Question from: HC Verma- Concepts of Physics Part 1 Chapter 8 Q.50

A: In the formula $W= \frac {kx^2}{2}$, the $x$ is the extension in the spring, not the displacement of the block. As the spring is pivoted and free to rotate, even if the displacement of the block is making some angle with the force, the extension in the spring is always parallel to the force. Thus, the assumptions made while deriving the formula still hold true.
The answer can also be obtained by the method you tried, however you made a mistake in the derivation. From the figure, I got the equation
$$x= 0.4 \cot {(\theta)}$$
$$\therefore dx = -0.4 \csc ^2 {(\theta )}d\theta$$
While you seem to have got
$$dx = -0.4 \: d \theta$$

A: In this example, we have to assume that the spring is is attached to the block in such a way that it allows free rotation of lower end of the spring as if it is hinged to the block. In this case the spring will apply force longitudinally so that the elongation produced in the spring will be equal to the difference between its final and initial lengths. This will give us the correct elongation because if the lower end of the spring is free to rotate then the elongation produced and the spring force will always remain inline. So no need to use integration.

A: With Hooke's law, we model the spring as supplying a conservative force. Because of this, we can calculate the work done on a spring by looking just at its final state, regardless of the history that resulted in that state. It's similar to finding the work done on a car on a roller coaster track. You can express its velocity in terms of $t$, take the dot product with the force of gravity, and integrate, or you can just take the net change in height times its weight. You might find it a useful exercise to work out the spring problem the "hard way", though, to understand how these calculations are done. Your explanation of how you did this has several problems.

After a bit of observation, I found that dx is equal to -0.4dθ.

It would help if you showed how you calculated that. If $x$ is the horizontal distance that the block has traveled from the start, I have that if $s$ is the original spring length, then $s+\Delta s$ makes up the hypotenuse of a right triangle with legs $s$ and $x$, and angle $\theta$. Since $\tan (\theta)$ is the ratio between the legs, we have $\tan (\theta) = \frac s x$, or $x = s\cot(\theta)$. This gives $dx = -s\csc^2(\theta)d\theta$. You have a $.4$ in your expression, which matches $s$, but you don't have $\csc^2(\theta)$. You seem to have not noticed that $\frac{d\theta}{dx}$ is not constant with respect to $x$.
So converting to $\theta$ gets rather nasty. Suppose we instead integrate with respect to $l$, where $l$ is the total length of the spring. Then $s^2+x^2=l^2$ and implicit differentiation gives us $2sds+2xdx=2ldl$. $s$ is a constant, so $ds = 0$. This gives $dx = \frac l x dl$. We have that $\cos (\theta) = \frac x l$, so $\cos(\theta)dx = dl$. Now $\int k(\Delta s)\cos(\theta) dx$ becomes just $\int k (\Delta s) dl$. Since $l = s+\Delta s$, $\Delta s = l-s$, giving $\int k (l-s)dl$. You could also integrate with respect to $\Delta s$, but I didn't want to write $\int k (\Delta s)d(\Delta s)$.
Also a few notes on MathJax: the formatting system "knows" some math terms, such as "cos", and putting a backslash before them will put them in non-italic font. That, as well as enclosing things in parentheses, makes expressions easier to read. For instance, \int k(\Delta s)\cos(\theta) dx rather than \int k\Delta s cos\theta dx.


text:
Q: How to trigger an Onkeydown event on a WebView I have an Android apllication which has a Webview Controller and i want to trigger an Onkeydown event to this Webview programatically from the wrapping activity.
How do I do this?
thanks in advance
kobi

A: A WebView doesn't seem to send click events to an OnClickListener. If you want to achieve this behavior you can use either OnTouchListener or warp the webView in some component and process the click events there..

A: You can override a Webviews on TouchEvent like this. :)
wv = new WebView(getActivity()){
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        td.onTouchEvent(event);
        return super.onTouchEvent(event);
    }
};

And you can hand of the oNKeyDown event from the wrapping Activity to the WebView.

A: Try out as below:

  @Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if ((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()) {
        webview.goBack();
        return true;
    }
    return super.onKeyDown(keyCode, event);
}


text:
Q: Build Treeview with parent, child tables I am building treeview using asp.net 2.0/3.5 from master detail table.
ParentTable Value
 ---ChildTable Value
      ---GrandChildTable1 Node
           ---GrandChildTable1 Value
      ---GrandChildTable2 Node
            ---GrandChildTable1 Value
I have created something like this to populate node values. But I am not sure how to display GrandChildNode and values. Could you please let me know if there are any ideas?
Thank you for any help.
protected void TreeView1_TreeNodePopulate(object sender, TreeNodeEventArgs e)
{
    switch (e.Node.Depth)
    {
        case 0:
            GetParentTableValues(e.Node);
            break;
        case 1:
            GetChildTableValues(e.Node);
            break;
        case 2:

    }
}

A: Here is my solution:
string NodeText = string.Empty;
string NodeKey = string.Empty;
TreeRolesList.Nodes.Clear();

DataTable dtEnqRoles = bllENQRolesMaster.GetENQRolesMasterByRolesDetail();

if (dtEnqRoles.Rows.Count > 0)
{
    for (int i = 0; i < dtEnqRoles.Rows.Count; )
    {
        NodeText = dtEnqRoles.Rows[i]["RoleDescriptionMaster"].ToString().Trim();
        NodeKey = dtEnqRoles.Rows[i]["RoleMasterID"].ToString();
        TreeNode pNode = new TreeNode(NodeText, NodeKey);
        TreeRolesList.Nodes.Add(pNode);

        foreach (DataRow dr in dtEnqRoles.Select("RoleMasterID = " + NodeKey))
        {
            TreeNode childNode = new TreeNode(dr["RoleDescriptionDetail"].ToString().Trim(), dr["RoleDetailID"].ToString());
            pNode.ChildNodes.Add(childNode);
            i++; //incrementing the outer loop here
        }

    }
    TreeRolesList.ExpandAll();
}


text:
Q: Dataframe substitution of For loop I have a dataframe with Latitude, Longitude, summedDistance and runingDistance columns.
I used the code bellow and it works:
summedDistance = 0
for i in range(0, len(dfLatLong)-1):
    fromLocation = (dfLatLong.loc[i, "Latitude"], dfLatLong.loc[i, "Longitude"])
    toLocation = (dfLatLong.loc[i+1, "Latitude"], dfLatLong.loc[i+1, "Longitude"])
    summedDistance += Helper.fromtoDistance(fromLocation, toLocation)
    dfLatLong.loc[i, 'runingDistance'] = Helper.fromtoDistance(fromLocation, toLocation)
    dfLatLong.loc[i, 'summedDistance'] = summedDistance

(the Helper function uses the geodesic distance between sequential rows of latitudes and longitudes)
Is there a way to use map or apply so I can eliminate the For loop?
Thanks

A: Use from_lat , from_long instead of merging I to a single column. You need to pick up the latitude column from 1:n-1 and add a null at the end and assign it to the to_lat column in one go.
You can then use the apply function once all data is well aligned.


text:
Q: No update $scope in view after function I have an array in my controller called this.selectedCourses. This array have some items which are showed in my view as a list.
After some steps I have this:
this.checkAddedCourses = function(studentCourses){
        ...

        if(repeatedCourses.length != 0){
            sweetAlert({
                  title: title,
                  text: text + ' ' + courseList,
                  type: "warning",
                  showCancelButton: true,
                  confirmButtonColor: "#DD6B55",
                  confirmButtonText: confirmButtonText,
                  closeOnConfirm: false,
                  html: true
                },
                function(){
                    angular.forEach(repeatedCourses, function(repeatedCourse){
                        this.removeCoursePurchase(repeatedCourse);
                    }.bind(this));
                    swal("Deleted!", "Your purchase has been refreshed.", "success");
            }.bind(this));
        }
    }

When the user click on button 'Remove' the items are removed fine from the array, I've already checked, but in my view I still seeing those items until I do something with that array. Is like it isn't refreshing the array after remove the elements.
Thanks.
PD: sweetAlert is a library for alerts.

A: Use $scope instead of this for data-binding on your view - so $scope.selectedCourses. Remember to pass $scope into your controller as a dependency.

A: Ok I've solved with the ´$apply´ function using it like this:
sweetAlert({
                  title: title,
                  text: text + ' ' + courseList,
                  type: "warning",
                  showCancelButton: true,
                  confirmButtonColor: "#DD6B55",
                  confirmButtonText: confirmButtonText,
                  closeOnConfirm: false,
                  html: true
                },
                function(){
                    angular.forEach(repeatedCourses, function(repeatedCourse){
                        $rootScope.$apply(function() {
                            this.removeCoursePurchase(repeatedCourse);
                        }.bind(this));
                    }.bind(this));
                    swal("Deleted!", "Your purchase has been refreshed.", "success");
            }.bind(this));


text:
Q: How to use multiple parameter in swiftui i want to ask how can i add multiple parameters into my qr code generator function? i have created qr code generator and trying to add more parameter for picker, because i already created a date picker, but i don't know how to add more parameter in swiftui and i am new to swift.
Here is my code:
import Foundation
import SwiftUI
import CoreImage.CIFilterBuiltins

struct ContentView: View {
    @State var start = Date()

    var body: some View {
        VStack {
            DatePicker("", selection: $start, displayedComponents: [.hourAndMinute])
                .datePickerStyle(.wheel)
            Generate(start: $start)
        }
    }
}

struct GenerateQRCode: View {
    @Binding var start: Date

        let filter = CIFilter.qrCodeGenerator()
        let cont = CIContext()

        var dateFormatter: DateFormatter {
            let df = DateFormatter()
            df.dateFormat = "HH:mm"
            return df
        }

    var body: some View {
        NavigationView{
            Image(uiImage: imageGenerate(start))
                .interpolation(.none)
                .resizable()
                .frame(width: 150, height: 150, alignment: .center)
        }.navigationBarBackButtonHidden(true)
    }

    func imageGenerate(_ start: Date)-> UIImage {     //<--here how to add integer parameter?
        let str = dateFormatter.string(from: start)
        let data = str.data(using: .utf8)
        filter.setValue(data, forKey: "inputMessage")   //
        if let qr = filter.outputImage {
            if let qrImage = cont.createCGImage(qr, from: qr.extent){
                return UIImage(cgImage: qrImage)
            }
        }
        return UIImage(systemName: "xmark") ?? UIImage()
    }
}

i have try to add parameter in the code but didn't work i think i missed some part of the code to complete it
here is the part i want to do
func imageGenerate(start: Date, time: Int)-> UIImage {     //<--here how to add integer parameter?
        let str = dateFormatter.string(from: start)
        let data = str.data(using: .utf8)
        filter.setValue(data, forKey: "inputMessage")   //
        if let qr = filter.outputImage {
            if let qrImage = cont.createCGImage(qr, from: qr.extent){
                return UIImage(cgImage: qrImage)
            }
        }
        return UIImage(systemName: "xmark") ?? UIImage()
    }

and it show error after i add another parameter

A: You need a JSON or some other recognized form of data transfer.
struct ComboQRView: View {
    @Binding var start: Date

    let filter = CIFilter.qrCodeGenerator()
    let cont = CIContext()

    var dateFormatter: DateFormatter {
        let df = DateFormatter()
        df.dateFormat = "HH:mm"
        return df
    }

    var body: some View {
        NavigationView{
            Image(uiImage: imageGenerate(start: start, time: 1))
                .interpolation(.none)
                .resizable()
                .frame(width: 150, height: 150, alignment: .center)
        }.navigationBarBackButtonHidden(true)
    }
    func imageGenerate(start: Date, time: Int) -> UIImage {
        do{
            let str = dateFormatter.string(from: start)
            //Create dictionary with parameters
            let params: [String : Any] = ["start": str, "time": time]
            //Get data by encoding to JSON
            let data = try JSONSerialization.data(withJSONObject: params, options:.prettyPrinted)
            //See what the data looks like
            print(String(data: data, encoding: .utf8)!)
            filter.setValue(data, forKey: "inputMessage")   //
            if let qr = filter.outputImage {
                if let qrImage = cont.createCGImage(qr, from: qr.extent){
                    return UIImage(cgImage: qrImage)
                }
            }
            return UIImage(systemName: "xmark") ?? UIImage()
        }catch{
            print(error)
            return UIImage(systemName: "xmark") ?? UIImage()

        }
    }
}

The inputMessage will look something like below with this code
{
  "start" : "09:07",
  "time" : 1
}