text:
Q: Swift: Using parsed JSON Data outside of a closure I am building a mobile app with swift, and am having some syntax issues as I am not a developer. The structure and logic of the application is really rough and surely incorrect, however we just need something that functions. (It is a school project and my team got no devs).
Anyways, we have a MySQL database that will be used as a middleman between our badge server/admin app, and our mobile app. Currently when you go to https://gatekeeperapp.org/service.php , you will see the current database data, taken by a php script and hosted there as JSON. Currently in Swift I have a struct with a function that takes this JSON data, and maps it to variables. The idea is to then pass these pulled variables into a separate set of functions that will check the pulled long/lat against the mobile devices location, and then return whether they match or not. This value would be updated, re-encoded to JSON, and pushed to a web service that would go about changing the values in the database so the badge server could use them.
Where I am currently I can see that values are being pulled and mapped and I can set a variable in a separate function to the pulled value, but then I can only seem to output this value internally, rather than actually use it in the function. I get a type error saying that the pulled values are of type (). How can I properly use these values? Ultimately I think I would want to convert the () to a double, so I could properly compare it to the Long/Lat of the device, and then will need to re-encode the new values to JSON.
Swift Code -- struct function
Swift code -- JSON struct
Swift code -- using pulled data

A: Your closure is called asynchronously, which means that the outer function where you are expecting to use the values has already returned by the time the closure is called. Instead, you probably need to call some other function from the closure, passing the values you've received.
class MyClass {
    func fetchUserData() {
        UserData().fetchUser { [weak self] user, error in
            DispatchQueue.main.async {
                if let user = user {
                    self?.handleSuccess(userID: user)
                } else if let error = error {
                    self?.handleError(error)
                }
            }
        }
    }

    private func handleSuccess(userID: String) {
        print(userID)
        // Do something with userID. Maybe assign it to a property on the class?
    }

    private func handleError(_ error: Error) {
        print(error)
        // Handle the error. Maybe show an alert?
    }
}


text:
Q: Error adding new models to database Django models.py
class Genre(models.Model):
    name = models.CharField(max_length=30)

    def __unicode__(self):
        return self.name

Genres.py
from MyVideoGames.models import Genre
from ClientIGDB import ClientIGDB

genres = ClientIGDB.api_call("genres", ["name"], 50)

for genre in genres:
    g = Genre.objects.create(name=genre["name"])
    g.save()

When I'm trying to add some models to sqlite db i'm not able to do this import:
from myproj.models import Genre. I don't know why...
When I do it this error is shown:
% (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
If someone can help me I'll be really gratefull

A: Whenever you run a script that uses python models you need to tell python that django exists first. Try this at the beginning of your script:
import os
import sys
import django

sys.path.append("/path/to/your/project")
os.environ["DJANGO_SETTINGS_MODULE"] = "yourProjectName.settings"
django.setup()

It's like a mini settings.py. You are not running something 'inside' django, so you need to start things up first. I wonder if anybody else could refine this to a solution that we don't need to hard code this every time we write a new script.

redpajama_set_name: RedPajamaStackExchange


text:
Q: CSS transition html page from black white to color with css? Just wondering if its possible or not, but I am trying to make my page when loaded, transition from black and white to colour over maybe a 4 second period - the entire page, text, divs, images, everything.
I've made a black and white image that transitions to a coloured version with hover would it be similar to this? But with the wrapper?
img.desaturate {
   animation: toColour 10s;
}

@keyframes toColour {
    0%    { -webkit-filter: grayscale(100%); filter: grayscale(100%); }
    25%   { -webkit-filter: grayscale(75%); filter: grayscale(75%); }
    50%   { -webkit-filter: grayscale(50%); filter: grayscale(50%); }
    50%   { -webkit-filter: grayscale(25%); filter: grayscale(25%); }
    100%  { -webkit-filter: grayscale(0%); filter: grayscale(0%); }
}

Or make each thing with colour individually transition?
Is there a better way or possible way with just css?
Thanks in advance

A: I don't see why not, just use your animation in your wrapper:

jsFiddle

CODE SNIPPET:

@keyframes toColour {
  0% {
    -webkit-filter: grayscale(100%);
    filter: grayscale(100%);
  }
  25% {
    -webkit-filter: grayscale(75%);
    filter: grayscale(75%);
  }
  50% {
    -webkit-filter: grayscale(50%);
    filter: grayscale(50%);
  }
  50% {
    -webkit-filter: grayscale(25%);
    filter: grayscale(25%);
  }
  100% {
    -webkit-filter: grayscale(0);
    filter: grayscale(0);
  }
}
.wrapper {
  background-color: royalblue;
  animation: toColour 4s;
}
p {
  color: cyan;
}

    Example text with color

A: Well you never know unless you try. Check this out

.desaturate, .desaturate *  {
   animation: toColour 7s;
}

@keyframes toColour {
    0%    { -webkit-filter: grayscale(100%); filter: grayscale(100%); }
    25%   { -webkit-filter: grayscale(75%); filter: grayscale(75%); }
    50%   { -webkit-filter: grayscale(50%); filter: grayscale(50%); }
    50%   { -webkit-filter: grayscale(25%); filter: grayscale(25%); }
    100%  { -webkit-filter: grayscale(0%); filter: grayscale(0%); }
}


text:
Q: Merge arrays with control of array position I have two random arrays merged, everything displaying/functioning beautifully.  The one stuck I have is this:
When I merge the two arrays together I need to make sure that every 3 item comes from array2.
array1 (a,b,c,d,e,f,g,h,i,j,k)
array2 (a1,a2,a3,a4)

My desired outcome:
d  k  c  a1  j  i  g  a2   etc.
What I have done so far:
function randomize_blocks($arr, $num = 1) {
shuffle($arr);

$r = array();
for ($i = 0; $i < $num; $i++) {
    $r[] = $arr[$i];
}
return $num == 1 ? $r[0] : $r;
}
 //gather donor blocks into an array
 $donorBlocks = array($blockA, $blockB, $blockC, $blockD, $blockE, $blockF,
 $blockG, $blockH, $blockI, $blockJ, $blockK, $blockL, $blockM, $blockN,
  $blockO);

//gather value blocks into an array
$valueBlocks = array($valueA, $valueB, $valueC, $valueD);

 //shake that shuffler real hard! DT
$shuffled_valueBlocks = randomize_blocks($valueBlocks, 4);
 $shuffled_donorBlocks = randomize_blocks($donorBlocks, 15);

//combine our shuffled arrays together
$combinedArrays = array_merge($shuffled_valueBlocks, $shuffled_donorBlocks);

 //shuffle them all together!
 $shuffled_blocks = randomize_blocks($combinedArrays, 19);

 //display bocks on page
  foreach ($combinedArrays as $key => $value) {
     echo $value;
  }

What is the best way to accomplish this?

A: Here is a way with array_splice to modify the longest of the two arrays into the desired result:
$a = ['a', 'b', 'c', 'd'];
$b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];

foreach ($a as $i => $v)
   array_splice($b, $i*4+3, 0, [$v]);

$b will be:
[1, 2, 3, 'a', 4, 5, 6, 'b', 7, 8, 9, 'c', 10, 11, 12, 'd', 13, 14, 15]

A: What about something like this?
$a1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l'];
$a2 = ['a1', 'a2', 'a3', 'a4'];

$a = [];
shuffle($a1);

foreach ($a1 as $k => $v) {
    $a[] = $v;
    if (($k + 1) % 3 === 0 && $a2) $a[] = array_shift($a2);
}

A: This is based on the assumption that you want both arrays shuffled as well as placed in your desired pattern:
$array_one = array('a','b','c','d','e','f','g','h','i','j','k');
$array_two = array('a1','a2','a3','a4');

function merge_random_interval($array_one = array(), $array_two = array(), $interval = 3) {
    $return_array = array();

    // Shuffle the arrays - that seems to be important?
    shuffle($array_one);
    shuffle($array_two);

    // Go through the first array
    $array_two_index = 0;
    for ($i = 0; $i < count($array_one); $i++) {

        // Every $interval add a value from the second array
        if ($i > 0 && $i % $interval == 0) {

            // Make sure there is a value in the second array
            if (isset($array_two[$array_two_index])) {
                $return_array[] = $array_two[$array_two_index];
                $array_two_index++;
            }
        }

        $return_array[] = $array_one[$i];
    }

    // You may want to check if $array_two has more values that weren't added?
    // Compare $array_two_index against count($array_two)

    return $return_array;
}

$result_array = merge_random_interval($array_one, $array_two, 3);

echo implode(' ', $result_array); // g d c a1 h i j a4 b e a a2 k f


text:
Q: Openlayers vector feature coordinates are not transforming, I have a OpenLayers vector with a single feature [0]. It's coordinates are in the map projection (EPSG:3413) and I want them in WGS84 (EPSG:4326) decimal degrees. I have the following code which executes with no errors.
    // Transform the polygon to WGS84 (EPSG:4326)
        polybound.features[0].geometry.transform(new OpenLayers.Projection("EPSG:3413"),new OpenLayers.Projection("EPSG:4326"));

        // Get the extent/vertices of the polygon drawn
        var polyBounds = polybound.features[0].geometry.getVertices(); alert(polyBounds);
        var polyExt = polybound.features[0].geometry.getBounds(); alert(polyExt);

However both the alerts show the untransformed coordinates.
Eg:
alert(polyBounds);
POINT(-2486558.28125 -1947299.71875),POINT(-4121511.40625 -1737690.34375),POINT(-3555566.09375 -2722854.40625)

alert(polyExt);
-4121511.40625,-2722854.40625,-2486558.28125,-1737690.34375

How do I get the vector feature coordinates to transform correctly?

A: Please refer to the OpenLayer Docs for OpenLayers.Projection.  The docs state the following:

By default, OpenLayers ships with the ability to transform coordinates
  between geographic (EPSG:4326) and web or spherical mercator
  (EPSG:900913 et al.) coordinate reference systems....
Additional transforms may be added by using the proj4js library.  If
  the proj4js library is included, the transform method will work
  between any two coordinate reference systems with proj4js definitions.

So you need to refer to the Proj4JS library and have your projection file for EPSG:3413.
You should read this User Guide. You can download the library from here: Downloads. You will also need the file for your projection in Proj4 format. You can download that from here: Spatial reference.org

A: @kpurdon, there is no problem with your code but you have to know that transforming is not overwriting to existed feature. so try the following code:
alert(polybound.features[0].geometry.transform(new OpenLayers.Projection("EPSG:3413"),new OpenLayers.Projection("EPSG:4326")));

i hope it helps you...

A: Try this as same was my case:
var geographic = new OpenLayers.Projection("EPSG:4326");
var mercator = new OpenLayers.Projection("EPSG:3413");

var polygon= polybound.feature.geometry;
    //alert(polygon);
    var bounds=polygon.getBounds();
    var poly = polygon.transform(
            mercator,geographic
        );
alert(poly);

Hope will works!


text:
Q: PHP image upload and crop with url I am using the below upload class for image upload and manipulating.
class.upload.php samples, a files uploading and images manipulation PHP class
Now I want to change form input type="file" to a text field where I will give a Image URL.
How can I make this uploading class to work.
Thanks In Advance.

A: this class seems to accept url's as arguments as well so just change the input type to text, name to for example image_url and use this line to manipulate the image as you wish after submitting the form:
$handle = new upload($_POST['image_url']);

A: Get the file name through text box and in background use php curl function to upload the file in the server and your uploading class will work fine
PHP Curl to upload file


text:
Q: Dropdown MVC4 Bind Default data from database I have a dropdown in which datas are binding from database. its works fine in which I need to display one particular item a first value in the dropdown.
For example dropdown with arun,siva,kumar in which siva must be at the first place note three datas coming from database.
View:
@using (Html.BeginForm()) {

    <fieldset>

        <legend>Multi-Select Demo</legend>

           @Html.DropDownList("FirstName", Model.SelectNameList);

            )

            <input type="submit" value="Save" />

    </fieldset>

}

Controller
  public ActionResult List()
        {
            SqlConnection conn = new SqlConnection(con);
            Patient model = new Patient();
            List<Patient> objUserDetails = new List<Patient>();
            DataTable dt = new DataTable();
            conn.Open();
            SqlCommand cmd = new SqlCommand("select * from Patients", conn);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(dt);
            var studentCount = dt.Rows.Count;
            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    Patient userinfo = new Patient();
                    userinfo.FirstName = dt.Rows[i]["FirstName"].ToString();
                    userinfo.PatientId = Convert.ToInt16(dt.Rows[i]["PatientId"]);
                    objUserDetails.Add(userinfo);
                }
            }

            model.SelectNameList = new SelectList(objUserDetails, "PatientId", "FirstName");

            return View(model);
        }

I want the sixth data of my list as first data in dropdown

A: One option can be to use jquery. You can set id to your dropdownlist and then use that id in document.ready handler to set selected index for dropdownlist
Assign Id to your dropdownlist
@Html.DropDownList("FirstName", Model.SelectNameList,new { id = "drpdwnID" });

Jquery Code
$(document).ready(function(){
$("#drpdwnID option:eq(4)").attr('selected', true)//4 is the index you want to set as selected
})


text:
Q: How do I commit a FullStack app to GitHub? Trying to add a fullstack app to GitHub. In the root I have a client directory (React) and a server directory (Node/Express) and a README.md
When I try git init this and send them to GitHub the Client folder gets an arrow inside of it I cant click it or view it on Github how do I fix this?
This is the arrow on the client folder basically this image:

A:
nested git's are treated as submodules

Not quite, only as gitlinks (reference to a tree SHA1 in the index of the parent repository)
If it was a submodule, the white arrow folder would actually be a link, to the remote submodule repository.
If it is not a link, then, as commented, removing the nested repo .git/ subfolder, adding and committing the folder content, and pushing will be enough.


text:
Q: How to merge conflicted files to my repository I have a master repository that is used by two users, now when I push my code it warns me to resolve conflicts.
I want to merge my code into the existing code with git commands but I don't know how to fix this problem.

A: $ git commit -am <message>       # add & commit your local changes
$ git pull origin master         # pull the latest codes
$ git status                     # see the files that have conflicted (untracked files)

# If you want to keep your changes then
$ git checkout . --ours

# Or, if you want to keep remote changes
$ git checkout . --theirs

$ git commit -am <message>           # add & commit with a new message
$ git push origin master             # push to remote


text:
Q: Standalone jetty with Spring boot management endpoint on different port I have a server running spring boot application 1.2.4 on standalone jetty 9.3.3  with spring boot management opened on port 7080 , accessible by http://localhost:7080/manage/.
Below is the relevant configuration from yml:
management:
  port: 7080
  contextPath: /manage

I'm trying to migrate to spring boot 1.3.8 on this standalone jetty, but spring boot no longer opens the management port on standalone servlet container - https://github.com/spring-projects/spring-boot/issues/3345.
Now, i really need to keep things as they were with my previous version having spring-boot management accessible the same way it was.
What would be the best practice here?
Thanks,


text:
Q: How function reduction in Haskell works? Why it's possible to reduce function in Haskell:
calculate :: Integer -> Integer -> Integer
calculate a b = f 1 a b
  where
     f :: Integer -> Integer -> Integer -> Integer
     f a b c = a + b

into something:
calculate :: Integer -> Integer -> Integer
calculate = f 1
  where
     f :: Integer -> Integer -> Integer -> Integer
     f a b c = a + b

I just need some guidance, any resources where I can find the answer and read more about it would be really helpful.

A: In Haskell there are no functions that take more than one parameter. All functions take exactly one parameter.
So if you have a function like add :: Int -> Int -> Int, then this is actually short for add :: Int -> (Int -> Int).
Why are the brackets important? Because they show how this concept works. If we have this function add, then we can make a function application with for example 14, then we construct a new function, like:
add14 :: Int -> Int
add14 = add 14

so that means that we now have a function that takes again one parameter (here an Int), and now it will produce another Int, it does that by adding 14 to it, so add14 25 will result in 39.
If you write add 14 25, this thus is not a function application with two parameters, what you actually wrote is:
-- add 14 25 is equivalent to
(add 14) 25

You thus first make a call with 14, and the you make a call with the function that comes out of this, and 25 as the parameter.
Why is this important? Because it means that if you thus write
calculate = f 1

it means that your f 1, constructs a function, a function with signature Int -> (Int -> Int). Creating parameters in the head of calculate, and adding these to the end of f 1, thus makes no sense: you already constructed a function that takes such parameters anyway. So it only introduces noise.
In lambda calculus, the rewrite rule where one rewrites λ x . f x to just f is (and vice versa) is called η-conversion [wiki]. In Haskell it comes down to rewriting:
f x = g x

to:
f = g

Operators are no different. In fact if you write a + b in Haskell, you wrote (+) a b, with (+) a function, or more verbose ((+) a) b.
The f in the where clause:
f a b c = a + b

can for example get converted to:
f = (.) ((.) const) (+)

A: It's called eta reduction.
You might also think about it in terms of partial application.
> calculate :: Integer -> Integer -> Integer
> f :: Integer -> Integer -> Integer -> Integer
> (f 1) :: Integer -> Integer -> Integer

Similar question - What does eta reduce mean in the context of HLint


text:
Q: Set an automatic color background depending on the HEX value in the cell? I have figured it out it could be manually done while adding rules to the Conditional Format Rules of a cell: however, I want the all 16,000,000 HEX value colors to appear automatically when I write a HEX value on a cell, so "manually" adding these 16,000,000 HEX values sounds a bit too much! Isn't there a way so all 16,000,000 colors shades automatically find their way in and apply a background color to the cell depending on the HEX value in the cell?
In other word I am trying to get a blue background when I type 0000ff in the cell, then I d like the background to change to the corresponding color when the HEX value of the cell is changed => BGC changes to red when ff0000 is entered, then green when 00ff00, white when ffffff ...etc for the 16,000,000 and up colors possible.

A: In my point of view, the 1st answer is pretty good. I'm not famous a lot with VBA :) But to avoid some issues it's good to start the hex number with # and check is the 1st symbol is #, because we control a range as I see. Then control a full length of value to be equal to 7 symbols and then calculate a colour to set a background.
Cheers!
Private Sub Worksheet_Change(ByVal Target As Range)
    On Error GoTo bm_Safe_Exit
    Application.EnableEvents = False
    Dim rng As Range, clr As String
    For Each rng In Target
        If Left(rng.Value2, 1) = "#" And Len(rng.Value2) = 7 Then
            clr = Right(rng.Value2, 6)
            rng.Interior.Color = _
              RGB(Application.Hex2Dec(Left(clr, 2)), _
                  Application.Hex2Dec(Mid(clr, 3, 2)), _
                  Application.Hex2Dec(Right(clr, 2)))
        End If
    Next rng

bm_Safe_Exit:
    Application.EnableEvents = True
End Sub

A: A Worksheet_Change event macro that converts the hexadecimal to an RGB should do this handily. The worksheet's HEX2DEC function should be able to handle the conversion.
Right click the worksheet's name tab and choose View Code. When the VBE opens, paste the following into the code sheet titled something like Book1 - Sheet1 (Code).
Private Sub Worksheet_Change(ByVal Target As Range)
    On Error GoTo bm_Safe_Exit
    Application.EnableEvents = False
    Dim rng As Range, clr As String
    For Each rng In Target
        If Len(rng.Value2) = 6 Then
            clr = rng.Value2
            rng.Interior.Color = _
              RGB(Application.Hex2Dec(Left(clr, 2)), _
                  Application.Hex2Dec(Mid(clr, 3, 2)), _
                  Application.Hex2Dec(Right(clr, 2)))
        End If
    Next rng

bm_Safe_Exit:
    Application.EnableEvents = True
End Sub

Tap Alt+Q to return to your worksheet. Type any 6 character hexadecimal code into a cell to provide a background color.

A: Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Cells.count <> 1 Then Exit Sub
    Target.Interior.Color = CLng("&H" & Target.Value)
End Sub

It works, but for some reason on the basis of BGR, not RGB: ff0000 gives blue and 0000ff gives red :D


text:
Q: Upload video to facebook error: Video Upload Time Out I tried upload video to Facebook using Graph API and got this error.
code = 390;
error_subcode = 1363030;
error_user_msg = "Your video upload timed out before it could be completed. This is probably because of a slow network connection or because the video you're trying to upload is too large. Please try again.";
 error_user_title = "Video Upload Time Out";
 message = "There was a problem uploading your video file. Please try again.";

Below is my code:
NSData *videoData = [NSData dataWithContentsOfFile:videoURL];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                videoData, @"video.mp4",
                                @"video/mp4", @"contentType",
                                @"message text", @"title",
                                @"title text", @"description",
                                nil];
[[[FBSDKGraphRequest alloc]
                  initWithGraphPath:@"me/videos"
                  parameters: params
                  HTTPMethod:@"POST"]
                 startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
                     if (!error) {
                         NSLog(@"Post id:%@", result[@"id"]);
                     }
                     else {
                         NSLog(@"video upload error: %@", error.description);
                     }
                 }];

I read questions and answers and I can not found correct solution.
I don't think it is network or video codec issue.
The video file size is below 1MB and it is uploaded without any problem in Facebook app.
What is the issue? Please help me.
Thanks in advance.


text:
Q: total variation of signed measures: $|\nu_1+\nu_2|\leq |\nu_1|+|\nu_2|$ I'm trying to solve exercise 5 of chapter 3 of Folland's:
for $\nu_1,\nu_2$ signed measures which both omit the value $+\infty$ or $-\infty$: $|\nu_1+\nu_2|\leq |\nu_1|+|\nu_2|$
eleged hint (solution with/without the hint would be accepted):
if $\nu=\lambda-\mu$ for $\lambda,\mu$ positive measures, then $\nu^+\leq\lambda$ and $\mu\geq\nu^-$.
What's my thought about it so far:
the hint implies $|\nu|\leq \lambda+\mu$, so it would suffice to show $\nu_1+\nu_2=|\nu_1|-|\nu_2|$. But it doesn't seem so right..
One of my problems with this question is that I don't know how to use the thing about both omitting the same value. perhaps it's only for $\nu_1+\nu_2$ to indeed be a signed measure.
Thanks for any help!

A: We have
$$\nu_1+\nu_2 = \nu_1^+ - \nu_1^- + \nu_2^+ - \nu_2^- = (\nu_1^++\nu_2^+) - (\nu_1^- + \nu_2^-), $$
so by the hint,
$$(\nu_1+\nu_2)^+ \leqslant \nu_1^+ +\nu_2^+$$
and
$$(\nu_1+\nu_2)^- \leqslant \nu_1^- + \nu_2^-.$$
It follows that
$$
\begin{align*}
|\nu_1+\nu_2| &= (\nu_1+\nu_2)^+ + (\nu_1+\nu_2)^-\\
&\leqslant (\nu_1^++\nu_2^+) + (\nu_1^-+\nu_1^-)\\
&= (\nu_1^++\nu_1^-) + (\nu_2^++\nu_2^-)\\
&= |\nu_1| + |\nu_2|.
\end{align*}
$$
The condition that $\nu_1,\nu_2$ both omit $+\infty$ or $-\infty$ is necessary to avoid expressions of the form $\infty-\infty$.

A: I still don't get Folland...
Total Measure
It is dominating:
$$|\mu(E)|\leq|\mu|(E)\quad(E\in\Sigma)$$
It is the smallest:
$$|\mu(E)|\leq\lambda(E)\quad(E\in\Sigma)\implies|\mu|\leq\lambda$$
(This characterizes total measures.)
Problem
By domination one has:
$$|\mu(E)+\nu(E)|\leq|\mu(E)|+|\nu(E)|\leq|\mu|(E)+|\nu|(E)$$
But it is the smallest so:
$$|\mu+\nu|\leq|\mu|+|\nu|$$
(This holds for real and complex measures.)


text:
Q: Swing. Default keybindings in JTextPane Now I working on a C IDE. As it's main theme is Motif, and my problem is how to add default KeyStroke(Ctrl + C - copy, Ctrl + V - paste) to JTextPane. In Motif L&F, JTextPane doesn't react on these KeyStrokes. How to make it perform the desired actions on these keys.

A: What you have to understand is that the KeyStrokes Ctrl + C and Ctrl + V are already catched by the JTextPane, so your listener will never be notified.
The fastest way to get notified is to register to this action via:
myJTextPane.getActionMap().put(DefaultEditorKit.copyAction, myCopyAction);
//and
myJTextPane.getActionMap().put(DefaultEditorKit.pasteAction, myPasteAction);

A:
In Motif L&F, JTextPane doesn't react on these KeyStrokes. How to make it perform the desired actions on these keys.

You need to add your own Key Bindings to bind an Action to a KeyStroke.
Check out Key Bindings for a program to list the existing bindings for any Swing component for a given LAF.
It then shows how to share an Action with a different KeyStroke:
 KeyStroke existingKeyStroke = KeyStroke.getKeyStroke("ENTER");
 KeyStroke addedKeyStroke = KeyStroke.getKeyStroke("control Z");
 InputMap im = component.getInputMap(...);
 im.put(addedKeyStroke, im.get(existingKeyStroke));

Or add a binding to an Action with a KeyStroke:
 KeyStroke addedKeyStroke = KeyStroke.getKeyStroke("control Z");
 InputMap im = component.getInputMap(...);
 im.put(addedKeyStroke, "caret-end-word");

I'll let you run the program to get the existing KeyStroke to use or the "action name" to use.
The above examples show how to change the binding for a single component. The link will also show how you can do it all JTextPanes by accessing the InputMap shared by all the text panes.
InputMap im = (InputMap)UIManager.get("TextField.focusInputMap");

A: This may help:
JTextPane.setKeymap(
  JtextPane.getKeymap().addActionForKeyStroke(
    KeyEvent.VK_V, InputEvent.CTRL_MASK,DefaultEditorKit.CopyAction));


text:
Q: Cleanup/Optimize multiple variable script - download different packages I'm recently jumping back into learning new skills.  Some of which is dipping my toes into scripting.
To start, I want to pull the latest versions of multiple packages, in one script.  I do this by pulling the version number into a variable, and then feeding that variable into the download URL.
So the below "works" (some of y'all might recognize the packages, and know what I'm playing with)...but I know it's not "optimal", and I'm not content with just getting something working and then moving on, when I know I could probably do better.
I don't think I'm truly grasping how the various 'while' options work, as I need the "break" in there in order to stop the loop.  I initially considered nesting 'for' loops...but that seemed even uglier to me.
Or maybe I'm simply using the wrong tool for my task...
while true; do
    crictlver=$(curl -s "https://api.github.com/repos/kubernetes-sigs/cri-tools/releases/latest" | jq -r .tag_name)
    runcver=$(curl -s "https://api.github.com/repos/opencontainers/runc/releases/latest" | jq -r .tag_name)
    cniver=$(curl -s "https://api.github.com/repos/containernetworking/plugins/releases/latest" | jq -r .tag_name)
    containerdver=$(curl -s "https://api.github.com/repos/containerd/containerd/releases/latest" | jq -r .tag_name)
    containerdvernum=$( curl -s "https://api.github.com/repos/containerd/containerd/releases/latest" | jq -r .tag_name | sed 's/^v//')
    k8sver=$(curl -s "https://storage.googleapis.com/kubernetes-release/release/stable.txt")
        wget --timestamping \
        https://github.com/kubernetes-sigs/cri-tools/releases/download/${crictlver}/crictl-${crictlver}-linux-amd64.tar.gz \
        https://github.com/opencontainers/runc/releases/download/${runcver}/runc.amd64 \
        https://github.com/containernetworking/plugins/releases/download/${cniver}/cni-plugins-linux-amd64-${cniver}.tgz \
        https://github.com/containerd/containerd/releases/download/${containerdver}/containerd-${containerdvernum}.linux-amd64.tar.gz \
        https://storage.googleapis.com/kubernetes-release/release/${k8sver}/bin/linux/amd64/kubectl \
        https://storage.googleapis.com/kubernetes-release/release/${k8sver}/bin/linux/amd64/kube-proxy \
        https://storage.googleapis.com/kubernetes-release/release/${k8sver}/bin/linux/amd64/kubelet;
    break
    done

Any thoughts, suggestions, or feedback about how to compact this is appreciated.


text:
Q: Iterate through maven project's dependency jars with eclipse-resource-api (plugin development) I have a maven project. And i want to iterate through its dependency jar projects and read some property files in them.
With eclipse resource api, i can get an IProject instance in workspace and access its classpath file.
Class-path has the following structure.
    <classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
        <attributes>
            <attribute name="maven.pomderived" value="true"/>
            <attribute name="org.eclipse.jst.component.nondependency" value=""/>
        </attributes>
    </classpathentry>

How can i extract the actual dependency jar locations from this?
i was expecting something like this instead
<classpath>
 <classpathentry kind="var" path="M2_REPO/apache-xerces/xercesImpl/2.9.1/xercesImpl-2.9.1.jar"/>
 <classpathentry kind="var" path="M2_REPO/apache-xerces/xml-apis/2.9.1/xml-apis-2.9.1.jar"/>
</classpath>

2.Or is there any better approach than this to read through maven dependency jars programatically?

A: The getResolvedClasspath method of IJavaProject deals with resolving containers:
IProject project = ... get project

IJavaProject javaProject = JavaCore.create(project);

IClasspathEntry[] classPathEntries = javaProject.getResolvedClasspath(true);

The JavaDoc says:

This is a helper method returning the resolved classpath for the
project as a list of simple (non-variable, non-container) classpath
entries. All classpath variable and classpath container entries in the
project's raw classpath will be replaced by the simple classpath
entries they resolve to.


text:
Q: Parse: Create 1-to-1 relation on PFObject with support for multiple class types? I am trying to create a PFObject subclass in Parse that has a one-to-one relation to another PFObject in Parse, but I would like this relation to support any PFObject subclass. Currently, as soon as I create and save my first PFObject to Parse, whatever that PFObject is connected to is set as that relation's one and only accepted type, and creating a second object that connects to a different PFObject subclass for that relation generates an error.
Is there a way either to...

*

*Specify the desired class that a one-to-one relation (i.e., really a pointer) should connect to? And if so, will it support connecting to subclasses of that specified class?

*Create a one-to-one relation easily that supports any kind of PFObject?

Example:
For example, let's say I needed to create a subclass of PFObject called Zookeeper in addition to multiple subclasses of PFObject for various types of animals: Armadillo, Bear, Camel, etc. (and for reasons that we must accept, each animal has to have its own PFObject subclass rather than using a generic Animal class).
Then let's say that each Zookeeper is responsible for exactly one animal. To do this, I want to create a one-to-one relation on Zookeeper called animal so that I can specify a single animal object that each Zookeeper is responsible for.
I create multiple Zookeeper and multiple animals. I successfully save my first animal (an Armadillo) and my first Zookeeper object ("Alice") and my second animal (a Bear), but when I try to save my second Zookeeper object ("Bill") to Parse, I get the following error:
invalid type for key animal, expected *Armadillo, but got *Bear

A: I am not sure if this is exactly what you want, but could you:

*

*Create an Animal subclass in Parse, with a text field called "type", and one column for each of the different types of animals (yeah, I know this is isn't that elegant).

*The column matching the "type" column contains a pointer to the specific animal object, while the other columns are nil.

*To get the specific animal object, you need to get the Animal object, look at the type column, and then look at the corresponding pointer column to get the specific animal object.
For example, the Zookeeper object contains a pointer to an Animal object.  The "type" column of Animal object contains the text "bear".  You then retrieve the object in the "bear" column of the Animal object, which is a Bear object.  Does this meet your specification?  Yes there is an Animal object, but there is still a notion of specific animal objects like Bear, etc.

A: What I ended up doing was saving the class name and object ID of the desired target object to my object rather than saving it as a pointer; so in the example above, that would mean creating the properties animalType and animalID on Zookeeper and using those properties to query the relevant animal with objectId = animalID. That way I don't have to create any new class types that are purely relational.


text:
Q: VS 2015 Express not discovering/or buggy built in Unit Test my problem is that VS 2015 Express doesn't discover/are buggy the Unit Tests that are built in VS, my code looks like this:
[TestClass]
    public class UnitTest1
    {
        [TestClass]
        public class Service1Test
        {
            [TestMethod]
            public void Test1()
            {
                Assert.IsTrue(true);
            }
        }
    }

Dunno why but VS doesn't discover even this basic Unit Test,nor other ones, interestingly if I let the PC for about 5-10 mins VS finally discover the Unit Tests :

Also if I try to run it I have to wait another 5 to 10 mins just to run this very basic Unit Test, here is a gift to show what I'm talking about :
GIF Buggy Unit Testing
And finally after 5-10 mins the unit test is done:

Can anyone help me? Why does VS behaves like this? At this pace currently I cant work, thanks.

EDIT: Even when I don't nest Test Classes VS doesn't run my Unit Tests


text:
Q: Is moving to Lion a prerequisite for moving to XCode 4.1 (from the app store)? should you only download XCode 4.1 from the app store if you move to Lion?
i.e I am staying on Leopard for a few more weeks, so do I have to stay with XCode 4.0.2 until I move to Lion?

A: Yes. Xcode 4.1 Requires Lion. This has been well documented, but 4.2 is apparently available for Snow Leopard as well.

A: Yes moving to Lion is a requirement.  4.1 brings all of the Lion features into the Xcode environment.  I would say if you aren't ready to move to Lion yet, then just stick with 4.0.2 unless you need to develop for Lion.
UPDATE: As of Xcode 4.2, it is now for both Lion and Snow Leopard.

A: Xcode 4.2 is available for both Lion and Snow Leopard, if you download it from the iOS Developer Centre while logged in as a registered developer. The Mac App Store will only upgrade you to Xcode 4.2 if you upgrade to Lion, but you can manually install it on Snow Leopard by manually downloading it as described here, and it runs just fine on Snow Leopard.

A: Yes, it seems:

This is a pre-release version of Xcode 4.1 for both Mac and iOS development. This release requires Mac OS X Lion and includes iOS SDK 4.2. Continue to use Xcode 3.2.5 on a Snow Leopard partition if you plan to submit Mac or iOS apps to the App Store

Details: http://thetechjournal.com/electronics/computer/software/xcode-4-1-developer-preview-for-mac-os-x-lion-is-available-for-download.xhtml#ixzz1TGiXaC1w
UPDATE: This question was asked in Jul 2011. As of now, Nov 2011, Xcode 4.2 is already released and made available on the Mac App store.


text:
Q: Laravel 5.6 Auth Logout Fail commerce with Laravel. I click the "Log Out" button, but the Exit Process does not work.
I'm not getting any errors. He's just leading me to the homepage.
web.php Code
Route::group(['prefix'=>'kullanici'], function() {
Route::get('/logout', 'KullaniciController@logout')->name('kullanici.logout'); });

Controller Code
    use Illuminate\Auth;

   public function logout() {

    auth()->logout();
     return redirect('/');
}

Html Code
   Çıkış Yap

A: You should try this
public function logout() {
        Auth::logout();
        return redirect('/');
}


text:
Q: How to Convert int into char string How can I convert numbers that are combined with - into a string.
For example: 12-4-30
I need to make all those numbers including the - into one string.
I tried:
string 12-4-30;

but it doesn't seem to work.

A: What?
A character is typically just that, one character. Not seven.
You can do a wide character:
char what = '12-4-30';

but I think that's more bits than most compilers will let you have in a char, so it's not going to work.
If you meant a string of character, you should use snprintf():
char what[32];

snprintf(what, sizeof what, "%d-%d-%d", 12, 4, 30);
printf("built string: '%s'\n", what);

A: You can't. A char by definition stores one character.

A: In the question you said character but character reads only one letter...so you have to declare char array as
char say[32];

Then use sprintf to display string
snprintf(what, sizeof say, "%d-%d-%d", 12, 4, 30);
printf("built string: '%s'\n", say);


text:
Q: Windows service calling WCF service (web http configuration) I've searched all the available question here, I don't know if the problem is specific to my configuration or am I missing something.
Background:
I have a WCF service hosted on IIS 7 using a HTTPS binding. The service is used to send/receive large objects. A windows service uses this WCF service to send these large objects to the it, but I get the 400 Bad Request error. I have enabled tracing in the service and the error is "the maximum message size quota for incoming messages (65536) has been exceeded". Below are the WCF and Windows service configurations and how the wcf service is utilized.
WCF Service configuration.
<system.web>
    <compilation debug="true" targetFramework="4.0" />
    <globalization culture="mk-MK" fileEncoding="windows-1251" />
</system.web>
<system.serviceModel>
<bindings>
  <webHttpBinding>
    <binding name="basicWebHttp" allowCookies="true" closeTimeout="00:59:59" receiveTimeout="00:59:59"
             sendTimeout="00:59:59" maxReceivedMessageSize="2147483647"
             maxBufferSize="2147483647" maxBufferPoolSize="2147483647" >
      <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647"
                    maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
      <security>
        <transport clientCredentialType="None" realm="" proxyCredentialType="None" />
      </security>
    </binding>
  </webHttpBinding>
</bindings>
<behaviors>
  <serviceBehaviors>
    <behavior>
      <serviceMetadata httpGetEnabled="true" />
      <serviceDebug includeExceptionDetailInFaults="true" />
      <serviceTimeouts transactionTimeout="00:10:00"/>
      <serviceThrottling maxConcurrentCalls="20" maxConcurrentSessions="20" maxConcurrentInstances="20" />
      <dataContractSerializer maxItemsInObjectGraph="2147483647"/>
    </behavior>
  </serviceBehaviors>
  <endpointBehaviors>
    <behavior name="WebHttp">
      <webHttp automaticFormatSelectionEnabled="true" faultExceptionEnabled="true" />
      <dataContractSerializer maxItemsInObjectGraph="2147483647" />
    </behavior>
  </endpointBehaviors>
</behaviors>
<client>
  <endpoint address="" binding="webHttpBinding" bindingConfiguration="basicWebHttp"
    contract="Classes.IVisService" name="BasicHttpBinding_IVisService" behaviorConfiguration="WebHttp" />
</client>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
<defaultDocument>
  <files>
    <remove value="default.aspx" />
    <remove value="iisstart.htm" />
    <remove value="index.html" />
    <remove value="index.htm" />
    <remove value="Default.asp" />
    <remove value="Default.htm" />
    <remove value="Default.html" />
    <add value="VisService.svc" />
  </files>
</defaultDocument>
<urlCompression doDynamicCompression="false" />
</system.webServer>
<system.diagnostics>
<sources>
  <source name="System.ServiceModel"
          switchValue="Information, ActivityTracing, Error"
          propagateActivity="true">
    <listeners>
      <add name="traceListener"
          type="System.Diagnostics.XmlWriterTraceListener"
          initializeData= "c:\log\Traces.svclog" />
    </listeners>
  </source>
</sources>
</system.diagnostics>

The service is consumed through a Windows service who has the following configuration :
<system.web>
<httpRuntime maxRequestLength="2147483647" />
</system.web>
<system.serviceModel>
<bindings>
  <webHttpBinding>
    <binding name="basicWebHttp" allowCookies="true" closeTimeout="00:59:59" receiveTimeout="00:59:59"
              sendTimeout="00:59:59"
              maxReceivedMessageSize="2147483647" maxBufferSize="2147483647" maxBufferPoolSize="2147483647">
      <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647"
                    maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
      <security mode="Transport">
        <transport clientCredentialType="None"></transport>
      </security>
    </binding>
  </webHttpBinding>
</bindings>
<behaviors>
  <endpointBehaviors>
    <behavior name="basicWebHttpBehaviour">
      <dataContractSerializer maxItemsInObjectGraph="2147483647" />
      <webHttp />
    </behavior>
  </endpointBehaviors>
</behaviors>
<client>
  <endpoint address="" behaviorConfiguration="basicWebHttpBehaviour"
            binding="webHttpBinding" bindingConfiguration="basicWebHttp"
            contract="labis.IVisService" name="BasicHttpBinding_IVisService" />
</client>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>

The service is called like this :
System.Net.ServicePointManager.ServerCertificateValidationCallback += (se, cert, chain, sslerror) => { return true; };
WebChannelFactory<IVisService> factory = new WebChannelFactory<IVisService>(
                                "BasicHttpBinding_IVisService",
                                new Uri("https://some_ip/service.svc"));
IVisService service = factory.CreateChannel();
service.PostData(large_object);

I've enabled tracing and from the log I can see that the server throws the exception :
the maximum message size quota for incoming messages (65536) has been exceeded
I think I've set all the needed properties for this to work, but no luck.
Also in the IIS configuration editor I've set the system.webServer/security/requestFiltering - requestLimits property to maximum
Any help ?
Thanks :)
EDIT 1
I pasted the wrong endpoint configuration element. The original lacked the behaviorConfiguration="WebHttp" part but I've tested it with this property included.

A: After trying all the possibilities, the solution was really simple.
I added the following configuration to the WCF service
<protocolMapping>
  <add scheme="https" binding="webHttpBinding" bindingConfiguration="basicWebHttp" />
  <add scheme="http" binding="webHttpBinding" bindingConfiguration="basicWebHttp" />
</protocolMapping>

Read more about it here http://msdn.microsoft.com/en-us/library/ee816881.aspx
I guess this worked because the service uses HTTPS binding so it needed an explicit mapping of the binding.
At least this worked for me

A: In you WCF Service configuration
you forgot to add the behaviour configuration(you named it "WebHttp") to the endpoint
try this :
<endpoint address="" binding="webHttpBinding" bindingConfiguration="basicWebHttp"
    contract="Classes.IVisService" name="BasicHttpBinding_IVisService" behaviorConfiguration="WebHttp" />

A: <system.web>
<httpRuntime maxRequestLength="2147483647" /  >
</system.web>

put the above conf into web.config where your service is hosted.

A: You can try something like this :
Try providing the endpoint in the constructor of your WebChannelFactory.
But first you have to pull out your configuration and create an instance of your endpoint and provide the behaviour manually.
http://weblogs.asp.net/cibrax/archive/2010/05/11/getting-wcf-bindings-and-behaviors-from-any-config-source.aspx is a great resource on how to do that.
public Binding ResolveBinding(string name)
    {
    Configuration appConfig = System.Configuration.ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

ServiceModelSectionGroup serviceModel = ServiceModelSectionGroup.GetSectionGroup(appConfig);

      BindingsSection section = serviceModel.Bindings;

      foreach (var bindingCollection in section.BindingCollections)
      {
        if (bindingCollection.ConfiguredBindings.Count > 0

    && bindingCollection.ConfiguredBindings[0].Name == name)
        {
          var bindingElement = bindingCollection.ConfiguredBindings[0];
          var binding = (Binding)Activator.CreateInstance(bindingCollection.BindingType);
          binding.Name = bindingElement.Name;
          bindingElement.ApplyConfiguration(binding);

          return binding;
        }
      }

      return null;
    }

public List<IEndpointBehavior> ResolveEndpointBehavior(string name)
{
     Configuration appConfig = System.Configuration.ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

ServiceModelSectionGroup serviceModel = ServiceModelSectionGroup.GetSectionGroup(appConfig);

      BindingsSection section = serviceModel.Behaviors;
  List<IEndpointBehavior> endpointBehaviors = new List<IEndpointBehavior>();

  if (section.EndpointBehaviors.Count > 0

&& section.EndpointBehaviors[0].Name == name)
  {
    var behaviorCollectionElement = section.EndpointBehaviors[0];

    foreach (BehaviorExtensionElement behaviorExtension in behaviorCollectionElement)
    {
      object extension = behaviorExtension.GetType().InvokeMember("CreateBehavior",
            BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Instance,
            null, behaviorExtension, null);

      endpointBehaviors.Add((IEndpointBehavior)extension);
    }

   return endpointBehaviors;
 }

 return null;
}

THEN USE :
    var binding = ResolveBinding("MyBinding");
    var behaviors = ResolveEndpointBehavior("MyBehavior");
    System.ServiceModel.Description.ContractDescription contract = System.ServiceModel.Description.ContractDescription.GetContract(typeof(IVisService));
     System.ServiceModel.Description.ServiceEndpoint ep = new System.ServiceModel.Description.ServiceEndpoint(contract, binding, "https://some_ip/service.svc");
                    foreach (var behavior in behaviors)
                    {
                        ep.Behaviors.Add(behavior);
                    }

System.ServiceModel.Web.WebChannelFactory<IVisService> t = new System.ServiceModel.Web.WebChannelFactory<IVisService>(ep);

A: Last 2 weeks before i faced the same issue, even i have updated the configuration at both service and client side, same as your but code did not work we got the same exceed size message.
Then we performed the below operations
1. Updated the webconfig file of service
2. Reset IIS of service
3. Created a proxy for service
4. updated client web.config file
5. reset the iis of client(webapplication)

then it worked for me.


text:
Q: Index was out of range. Must be non-negative and less than the size of the collection, Error appears when try to delete a row from a DB Connection();
int Menu_Id = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value);

SqlCommand com = new SqlCommand("Delete from menu where menu_id  =" + Menu_Id, con);
com.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter("Select * from menu", con);
DataTable dt = new DataTable();
da.Fill(dt);
this.GridView1.DataSource = dt;
this.GridView1.DataBind();
con.Close();

I want to delete a row in gridview but this error appears,

Index was out of range. Must be non-negative and less than the size of the collection.

On line,
int Menu_Id = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value);

A: The number in e.RowIndex is either negative or larger than the number of items in your GridView1.DataKeys collection. Use a debugger to find out why.

A: If you just want to delete it from the grid view, why not just do Gridview.Row.Visible = false; ? Otherwise check your rowIndex to make sure it is being set correctly. If you're using Visual Studio, while debugging there is a window called watch, just type your variable in there and it will update as it changes.


text:
Q: #->php -v и #->php -r "phpinfo();" | php возвращают разные версии PHP Есть VPS от reg.ru под centos6_php_selector с модулем переключения PHP.
Настроил для пользователя все как в инструкции
Устанавливаю например при помощи composer yii2 он выдает ошибку что версия PHP ниже необходимой. Заливаю yii2 из архива, смотрю requirements.php там версия PHP уже та что надо.

A: В системе установлено одновременно несколько версий PHP, что является частой практикой для хостеров. Один из них вызывается при запуске в консоли php (чтобы узнать, какой именно, попробуйте набрать which php). Какой-то другой работает с веб-сервером.
Чтобы работать в консоли с тем же PHP, с которым работает веб-сервер, нужно просто узнать путь до его бинарника и подложить себе в $PATH. Путь можно спросить у саппорта хостинга.


text:
Q: Finding the flux of a cylinder using the Divergence Theorem I have to calculate the flux of the
$$F(x,y,z)=(x+\ln(yz^{2}),y+e^{-(x^{2}+z^{2})},2z)$$
through the cylinder (without its bases):
$$\frac{x^{2}}{4}+\frac{y^{2}}{9}=1$$
for $z\in[0,4]$.
I know that if $S_{1}, S_{2}$ are the cylinder bases and $S_{3}$ its "body", then let
$$S=S_{1}\cup S_{2}\cup S_{3}$$
so I can apply the divergence theorem in $S$. When I do it, I get:
$$\iint \limits_{S} F\;dS=96\pi$$
But I know that
$$\iint \limits_{S} F\;dS=\iint \limits_{S_{1}} F\;dS+\iint \limits_{S_{2}} F\;dS+\iint \limits_{S_{3}} F\;dS$$
So, to finish my exercise, I have to evaluate
$$\iint \limits_{S_{1}} F\;dS\quad\text{and}\quad\iint \limits_{S_{2}} F\;dS$$
Let $S_{1}$ be parameterized by
$$\sigma(r,\theta)=(2r\cos\theta,3r\sin\theta,4)$$
When I use this parameterization to calculate $\iint \limits_{S_{1}} F\;dS$, I get
$$\sigma_{r}\times\sigma_{\theta}=(0,0,6)$$
If I use this vector above in the formula of the flux through a surface, I get:
$$\iint \limits_{S_{1}} F\;dS=288\pi$$
My question is: my teacher used this parameterization for $S_{1}$:
$$\sigma(u,v)=(u,v,4)$$
and then he got
$$\iint \limits_{S_{1}} F\;dS=48\pi$$
So, which parameterization should I use? Could he do like that? Just take $(u,v,4)$?

A: Note that the flux component along $z$ is equal to $0$ for $z=0$ and it is equal to $8$ for $z=4$. Thus the overal flux through the bases is
$$8\cdot A=48 \pi$$
Note that with your first parameterization we obtain the same result, that is
$$\iint \limits_{S_{1}} F\;dS=\int_0^{2\pi}d\theta\int_0^1 (F_x,F_y,8)\cdot (0,0,6r)\,dr=2\pi\cdot 48\cdot[r^2/2]_0^1=48\pi$$


text:
Q: Add new row on load programmatically on material-table The goal would be to trigger the Add row function which show a new row form with inputs and all given a certain condition. Is this possible at all ? How would I go about achieving this ?
An example of the behavior I want to achieve can be found in the documentation under "Editable Example - Editable Preview" : https://material-table.com/#/docs/features/editable .
The only difference is that I would not need to click on the button to trigger the add new row function.

A: I checked the documentation and didn't see an API reference (what internal methods can be called) so I am not sure the correct function to call, but I am sure this can be done with forwardRefs.
const ParentComponent = () => {
    const tableRef = React.createRef();

    const handleButtonClick = () => {
        tableRef.current.addNewRow(); // addNewRow probably not the name of the function
    }

<MaterialTable
  title="Editable Preview"
  tableRef={tableRef} // you need this
  columns={columns}
  data={data}
  editable={{
    onRowAdd: newData =>
      new Promise((resolve, reject) => {
        setTimeout(() => {
          setData([...data, newData]);

          resolve();
        }, 1000)
      }),
    onRowUpdate: (newData, oldData) =>
      new Promise((resolve, reject) => {
        setTimeout(() => {
          const dataUpdate = [...data];
          const index = oldData.tableData.id;
          dataUpdate[index] = newData;
          setData([...dataUpdate]);

          resolve();
        }, 1000)
      }),
    onRowDelete: oldData =>
      new Promise((resolve, reject) => {
        setTimeout(() => {
          const dataDelete = [...data];
          const index = oldData.tableData.id;
          dataDelete.splice(index, 1);
          setData([...dataDelete]);

          resolve()
        }, 1000)
      }),
  }}
/>

    <Button onClick={handleButtonClick}>Add Row</Button>;
}

You can use the javascript debugger to see what methods are available on tableRef.current and find the correct "add row" function.


text:
Q: Bar in Bar Chart with ggplot2 Is it possible to plot bar in bar chart in R with ggplot2 like the figure below. I want to compare expected and actual values and I want to generate a figure similar to the figure below. I have provided some dummy code:
 library(tidyverse)

df = data_frame(name = letters[1:10],profit = rnorm(mean = 100, sd = 20, n = 10),
            target = profit + rnorm(mean = 10, sd = 10, n = 10))

   df %>% ggplot(aes(x = name, y = profit)) + geom_bar(stat = "identity")

A: Yes it is possible, look at ggplot documentation
library(tidyverse)

df = data_frame(name = letters[1:10],profit = rnorm(mean = 100, sd = 20, n = 10),
                target = profit + rnorm(mean = 10, sd = 10, n = 10))

ggplot(df,aes(x=name,y=profit))+geom_bar(stat= "identity")+
geom_bar(aes(x= name,y=target),stat= "identity", width = 0.1,col = "green",fill="green")


text:
Q: How to Pick Image From Google Photos App Only? Android Google Photos Intent I am trying to get an image directly from the Google Photos app. I wish to bypass the app chooser usually started when using Intent.ACTION_GET_CONTENT and instead go directly to Google Photos if the user has it installed and allow the user to select an image which would then be returned to my app in an ActivityResult.
I have attempted to do this in the following manner:
if (callingActivity != null && isGooglePhotosInstalled(callingActivity)) {
    Intent intent = callingActivity.getPackageManager().getLaunchIntentForPackage(GOOGLE_PHOTOS_PACKAGE_NAME);
    intent.setAction(Intent.ACTION_GET_CONTENT); // ALSO TRIED Intent.ACTION_PICK
    intent.setType("image/*");
    try {
        callingActivity.startActivityForResult(intent, MediaPickerActivity.REQUEST_PHOTO_FROM_GOOGLE_PHOTOS);
    } catch (ActivityNotFoundException e) {
        showErrorMsgDialog(callingActivity, "You don't have Google Photos installed! Download it from the play store today.");
        e.printStackTrace();
    }
}

To check if Google Photos is installed I am using:
private static final String GOOGLE_PHOTOS_PACKAGE_NAME = "com.google.android.apps.photos";
public static boolean isGooglePhotosInstalled(Context context) {
    PackageManager packageManager = context.getPackageManager();
    try {
        return packageManager.getPackageInfo(GOOGLE_PHOTOS_PACKAGE_NAME, PackageManager.GET_ACTIVITIES) != null;
    } catch (PackageManager.NameNotFoundException e) {
        return false;
    }
}

Using this method I am able to successfully open Google Photos in selection mode, but upon selecting an image the Google Photos app crashes.
How can I accomplish this?
EDIT:
If it helps, I have created a sample app project on Github to help with troubleshooting. The stacktrace of the crash from Google Photos is the following:
09-01 21:30:25.081    1109-1109/? E/Binder﹕ Unbound type: dli
Searched binders:
com.google.android.apps.photos.home.HomeActivity ->
com.google.android.apps.photos.PhotosApplication ->
com.google.android.apps.photos.PhotosApplication
java.lang.IllegalStateException: Unbound type: dli
Searched binders:
com.google.android.apps.photos.home.HomeActivity ->
com.google.android.apps.photos.PhotosApplication ->
com.google.android.apps.photos.PhotosApplication
        at noy.a(PG:210)
        at noy.a(PG:485)
        at hmm.b_(PG:1061)
        at myf.a(PG:54)
        at myc.a(PG:36)
        at hlm.d(PG:242)
        at hll.b(PG:2232)
        at fns.onClick(PG:1375)
        at fnr.onClick(PG:1408)
        at android.view.View.performClick(View.java:4761)
        at android.view.View$PerformClick.run(View.java:19767)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5312)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)

Sample Project Found Here:
https://github.com/michaelgarnerdev/GooglePhotosIntent

A: Try the following code:
public void launchGooglePhotosPicker(Activity callingActivity) {
    if (callingActivity != null && isGooglePhotosInstalled()) {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_PICK);
        intent.setType("image/*");
        List<ResolveInfo> resolveInfoList = callingActivity.getPackageManager().queryIntentActivities(intent, 0);
        for (int i = 0; i < resolveInfoList.size(); i++) {
            if (resolveInfoList.get(i) != null) {
                String packageName = resolveInfoList.get(i).activityInfo.packageName;
                if (GOOGLE_PHOTOS_PACKAGE_NAME.equals(packageName)) {
                    intent.setComponent(new ComponentName(packageName, resolveInfoList.get(i).activityInfo.name));
                    callingActivity.startActivityForResult(intent, REQUEST_PHOTO_FROM_GOOGLE_PHOTOS);
                    return;
                }
            }
        }
    }
}

A: You could just use intent.setPackage():
Intent intent = new Intent();
intent.setAction(Intent.ACTION_PICK);
intent.setType("image/*");
intent.setPackage(GOOGLE_PHOTOS_PACKAGE_NAME);
callingActivity.startActivityForResult(intent, REQUEST_PHOTO_FROM_GOOGLE_PHOTOS);


text:
Q: Variable declaration in an if statement In C# for a relatively simple program I am writing I am trying to create an event handler function that will handle multiple sources, like so:
private void fooHandler(object sender, RoutedEventArgs e)
{
    fooObject objectFoo = (fooObject)sender;
    if (objectFoo.name == "bla1"){
        bla1Window bla = new bla1Window();
    }
    if (objectFoo.name == "bla2"){
        bla2Window bla = new bla2Window();
    }
    .
    .
    .
    else{
        //default stuff happens
    }
bla.Left = this.Left
bla.Top = this.Top
bla.Show();
this.Close();
}

The function is for window switching.
The problem is the variable falls out of scope as soon as I exit the if-statement. I'm doing it this way because, looking at the series of functions I've defined to handle each event individually, they are all the same with the exception of the one variable declaration. Is there a way to make this work, or am I just going to have to stick with a function for each event handler?

A: If bla1Window and bla2Window both share a base class or interface, you can refer to them that way.  In this case, it looks like you're just accessing properties of Window, so you could do:
Window window = null;
fooObject objectFoo = (fooObject)sender;
if (objectFoo.name == "bla1"){
    window = new bla1Window();
}
else if (objectFoo.name == "bla2"){
    window = new bla2Window();
}
.
.
.
else{
    //default stuff happens
}

window.Left = this.Left
window.Top = this.Top
window.Show();
this.Close();

A: Consider:
private void fooHandler(object sender, RoutedEventArgs e)
{
    fooObject objectFoo = (fooObject)sender;
    Window bla; // a super-type or interface, don't assign a value here
                // so there will be a compile error if it was
                // forgotten below
    if (objectFoo.name == "bla1"){
        bla = new bla1Window();
    } else if (objectFoo.name == "bla2"){
        bla = new bla2Window();
    } else {
        // just make sure to assign to bla
        // or there will a compiler error later
    }
    bla.Left = this.Left
    bla.Top = this.Top
    bla.Show();
    this.Close();
}

I would generally write it similar to this, however:
Window CreateFromName(string name) {
    if (name == "bla1"){
        return new bla1Window();
    } else if (name == "bla2"){
        return new bla2Window();
    } else {
        // just make sure to return a value
        // or there will a compiler error later
    }
}

private void fooHandler(object sender, RoutedEventArgs e)
{
    fooObject objectFoo = (fooObject)sender;
    Window bla = CreateFromName(objectFoo.name);
    bla.Left = this.Left
    bla.Top = this.Top
    bla.Show();
    this.Close();
}

Happy coding.

A: The solution is to simply hoist the variable into the scope it needs to be in to be used after the if statement(s).  It's really that simple.  I would however suggest you take a stab at refactoring this, or at least post your real code so we can give it a shot.  When you have a bunch of code that is repeated in multiple if statements one after another like that it can usually be simplified into a single method or two.
private void fooHandler(object sender, RoutedEventArgs e)
{
    fooObject objectFoo = (fooObject)sender;

    // use the base class and work with that.
    // all windows have the properties you use
    // below, so there is no need to declare it
    // as a more specific type.
    blahWindow bla = null;
    if (objectFoo.name == "bla1"){
        bla = new bla1Window();
    }
    if (objectFoo.name == "bla2"){
        bla = new bla2Window();
    }
    .
    .
    .
    else{
        //default stuff happens
        bla = new BlahDefault();
    }

    // 'bla' cannot be nbull here if each branch above assigns it
    bla.Left = this.Left
    bla.Top = this.Top
    bla.Show();
    this.Close();
}

A: All your windows should have a shared parent.  Use the child constructor and assign it to the parent object which can be singly declared outside of the 'if' statement.
private void fooHandler(object sender, RoutedEventArgs e)
{
    Window bla = null;
    fooObject objectFoo = (fooObject)sender;
    if (objectFoo.name == "bla1"){
        bla = new bla1Window();
    }
    if (objectFoo.name == "bla2"){
        bla = new bla2Window();
    }
    .
    .
    .
    else{
        //default stuff happens
    }
    if(bla != null)
    {
        bla.Left = this.Left
        bla.Top = this.Top
        bla.Show();
        this.Close();
    }
}

A: You really want to make this an interface and declare the interface before the if code. It looks like all of the methods that are called on bla below are common which is a great candidate for an interface (or abstract class if that is more appropriate).
In fact, it would be best if your code didn't switch at all in this file and you through it inside of a Factory or something. There is a lot of information on the internet about that if you decide to go that route.

A: I think you should just make sure you declare the variable before the if statement.
That should solve your problem.
Example
public string IfStatement()
{
    string myValue = null;

    bool condition = true;
    if (condition)
    {
        myValue  = "something";
    }
    else
    {
        myValue  = "something else";
    }
    return myValue;
}


text:
Q: Proxying Kibana I'm having some(a lot of) difficulties, trying to setup a reverse proxy for Kibana.
The general idea is that we want to set up a reverse proxy so select customers have access to Kibana. E.g. when customer A goes to "kibana.company.com/ customera" he is automatically forwarded to Kibana and has access to logistics about their data. We have multiple customers we need to proxy, so eventually we will set up ldap or AD, to help us handle this.
So far i've tried both Apache2 and Nginx, but i've run into problems using both of them. I'm currently working on Apache, with a very simple configuration.
http://pastebin.com/1gt5KLyP
When i go to localhost/kibana/ i'm forwarded to localhost/app/kibana, but i get a URL not found message.
As far as NginX goes, i run into a problem where i forward to Kibana, but it get's indefinitely stuck in a loading loop. ("Kibana is loading blablabla... good stuff will be cached"), but i never actually shows the dashboard, no matter which configuration i tried, i could never get the dashboard to show. This is a sample config, but it's changed a lot during testing.
http://pastebin.com/PP4Fu1Cs
Am i going about it the right way or is their a simpler way to do what i'm trying to do.
EDIT: I'm now getting the same results with Apache after adding
ProxyPass /kibana/ http:// ip /app/kibana
ProxyPassReverse /kibana/ http:// ip /app/kibana

A: Can you do a FIDDLER and see where it is stuck.
I did a Reverse Proxy using Apache with the following config successfully.
ProxyPreserveHost ON

ProxyPass /portal1     http://IP1/home

ProxyPassReverse /portal2   http://IP2/home

These are the modules I loaded
LoadModule proxy_module modules/mod_proxy.so

LoadModule proxy_http_module modules/mod_proxy_http.so

<IfModule mod_proxy.c>
ProxyVia On
<Proxy *>
Order Allow,Deny
Allow from all
</Proxy>
</IfModule>

A: To get rid of the problem where Kibana is stuck forever on the loading screen, you can try the following:

*

*Stop the Kibana service, on Ubuntu:
sudo service kibana stop

*Delete optimize/bundles directory:
sudo rm -rf /opt/kibana/optimize/bundles

*Start the Kibana service, on Ubuntu:
sudo service kibana start

*Wait for a minute or so before reloading the browser (you can keep an eye on the log at /var/log/kibana.log to see when the server is ready again).

A: I think your proxy is blocking some of kibana's requests. Check in your browser inspector all requests and responses there shouldn't be any errors.
There is a simple configuration in nginx:
location ~ (|/app/kibana|/bundles/|/status|/plugins|/elasticsearch/|)  {
    proxy_pass http://kibana:5601;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
    proxy_set_header Host $host;
    rewrite /(.*)$ /$1 break;
}

If you want to show just charts without any additional buttons and panels, just add ?embed=true parameter to your url e.g.
http://kibana/app/kibana#/visualize/edit/chart?embed=true&_g=(refreshInterval:(display:Off,pause:!f,value:0),...


text:
Q: Restrict Capability of Administrator to Create, Edit and Delete Pages in Multisite In my multisite installation, I need to restrict administrators from being able to create, edit, and delete pages. That is, I need all pages to be created/edited/deleted by superadmins while administrators continue to have all other default administrator capabilities except those three.
The plugin User Role Scoper is not working for me and while I have seen this Q&A about removing an administrator capability, I am too new to coding to know how to modify this advice for this situation.
Any guidance about how to proceed here would be most appreciated!

A: I use Advanced Access Manager plugin to manage rights and permissions with users and roles.
First, don't change administrator capabilities or you also lose those.
Instead, select the User you want to change the permissions for and adjust that person's Admin settings.


text:
Q: Getting values for nulls from two different tables? I have a large table (main) like so
person_id    fee        ref_id    <otherfields>
1           foo        23
1            bar        null
1            abc        23
2            xyz        34

Many of the values for ref_id are null which I need to retrieve. Btw, I need to select, not update.
I have two other tables d1, d2 that contain the necessary missing ref_id (along with different fields) and they can be referenced using the person_id. The person_id might not exist in one of the tables (e.g. it might not be in d1, but it is in d2)
I can fill in some of the ref_id using one of the tables, but how would I then use the other table to retrieve the values for the remaining nulls? Union sounds right to me? But I'm struggling with it since it's giving me more rows than I originally had, which can't be right.
SQL Server 2008
edit: d1,d2 have the same (person_id,ref_id) tuple

A: You want a join, and you probably want to use COALESCE, like:
SELECT person_id, fee,
   COALESCE (m.ref_id, d1.ref_id, d2.ref_id) as 'ref_id',
   ...
FROM table t
LEFT JOIN d1
  ON d1.person_id = t.person_id
LEFT JOIN d2
  ON d2.person_id = t.person_id
WHERE ...

This will give you the first Non-NULL value for ref_id from those 3 tables.
Edit:
To clarify what you were thinking, a UNION connects data sets or tables vertically, as in
SELECT 1,2,3
UNION
SELECT 4,5,6

Will give you
1,2,3
4,5,6

A JOIN connects tables by the row, linking a row in one table to a row in another table to "extend" the row out with values from both tables.

A: JNK's answer is the best, I think.  But just to show another approach, you could do it as a single join with a UNION.  Depending on the data set, one method or the other may be more efficient.
SELECT person_id, fee,
   COALESCE (m.ref_id, d.ref_id) as 'ref_id',
   ...
FROM table t
LEFT JOIN (SELECT person_id, ref_id FROM d1 UNION ALL SELECT person_id, ref_id FROM d2) d
  ON d.person_id = t.person_id

If d1 and d2 have rows for the same person_id, this will return more rows than are in the original table.  If they have the same (person_id,ref_id) tuple, then changing the UNION ALL to a simple UNION should address that problem; otherwise, you need to be more specific in your question since you could get different results from d1 or d2.

A: Something like below. Please note you may still get more rows than in main table if any of d1 or d2 has multiple rows for same person_id. If not, it should not give you more rows.
Select
      m.*
    , d1.*
    , d2.*
From
    main m
Left Join
    d1
On
    m.person_id = d1.person_id
    And
    m.ref_id Is Null
Left Join
    d2
On
    m.person_id = d1.person_id
    And
    m.ref_id Is Null
    And
    d1.ref_id Is Null


text:
Q: MySQL Number in KEY parameter creation I looked and some SQL scripts and wondered what the number in the braces behind the KEY operator means?
I provided a truncated sample of the script (from Wordpress), where you can see this in the 4th line.
CREATE TABLE IF NOT EXISTS `wp_usermeta` (
  `umeta_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`umeta_id`),
  KEY `meta_key` (`meta_key`(191))
) ENGINE=InnoDB;

A: From the MySQL Documentation:

Indexes can be created that use only the leading part of column
values, using col_name(length) syntax to specify an index prefix
length:

*

*Prefixes can be specified for CHAR, VARCHAR, BINARY, and VARBINARY columns.

*BLOB and TEXT columns also can be indexed, but a prefix length must be given.

*Prefix lengths are given in characters for nonbinary string types and in bytes for binary string types. That is, index entries consist of the first length characters of each column value for CHAR, VARCHAR, and TEXT columns, and the first length bytes of each column value for BINARY, VARBINARY, and BLOB columns.


text:
Q: Dax for knowing if a phone number is active or not I have a table that has all the calls all my phone numbers make.
Every now and then a phone number becomes inactive (for some reason there is no column showing active/inactive numbers).
I thought I could make a Dax function or a calculated column (I don't know what's better) that will determine what is active or not.
If a number isn't making any calls for the past 3 weeks (not including this week) it is a dead number.
but I don't know where to start.
I crated the table:

each row is a phone number
each column is a week
the values count the amount of answered calls the number made
any ideas?


text:
Q: Crear array sin método map ¿Cómo podría crear un array con los name nada mas pero sin el metodo map, o sea yo crear mi propio map utilizando el metodo push?

*

*Lista de personas:

    let sujetos = [
    {
        id: 1,
        name: 'Daniel',
        edad: 18,
        pais: 'Venezuela'
    },
    {
        id: 2,
        name: 'Jose',
        edad: 16,
        pais: 'Uruguay'
    },
    {
        id: 3,
        name: 'Carlos',
        edad: 20,
        pais: 'Colombia'
    },
    {
        id: 4,
        name: 'Sebastian',
        edad: 15,
        pais: 'Ecuador'
    },
    ]

Aquí es donde no se como hacer para que solo me estraiga las propiedades name de los objetos, solamente estoy extrayendo todas las propiedas y e intentado todo pero nose no me da la lógica:
    let aggObject = (nombres) => {
        let arr = []
        for(i=0; i<nombres.length; i++){
             arr.push(nombres[i])
        }
       return arr
    }

*

*Aquí lo imprimo:

    console.log(aggObject(sujetos))

A: Dada tu lista llamada sujetos
const arr = []
for(i=0; i<sujetos.length; i++){
     arr.push(sujetos[i].name)
}

No tengo muy claro porque no quieres usar map, ya que map crea un nuevo array también.
const arr = sujetos.map( (v) => v.name )

A: Tal y como lo tienes, tendrías que cambiar la línea:
arr.push(nombres[i])

A:
arr.push(nombres[i].name)

Te faltaba acceder a la key name donde se encuentra el nombre.

*

*Si quisieras acceder al id:

nombres[i].id

*

*Si quisieras acceder al país:

nombres[i].pais

Y así sucesivamente.
De esta manera al hacer el console.log te devolverá:
(4) ["Daniel", "Jose", "Carlos", "Sebastian"]

Por lo que quedaría finalmente:
let aggObject = (nombres) => {
    let arr = []
    for(i=0; i<nombres.length; i++){
         arr.push(nombres[i].name)
    }
    return arr
}

Más información:

*

* Array

*Trabajando con JSON

A: Tu propio método map: Simplemente recorre el array y ejecuta para cada elemento la función que te pasen, guardando en un nuevo array los resultados de la función. En este caso, sólo necesitas una función que devuelva el cambo nombre de cada elemento:

function miMap(array, funct) {
  const resultado = [];
  for (let i = 0; i < array.length; i++) {
    resultado.push(funct(array[i]));
  }
  return resultado;
}

//función para extraer el nombre de un elemento:
function extraeNombre(elemento) {
  return elemento.name;
}

let sujetos = [
  {    id: 1,    name: 'Daniel',    edad: 18,    pais: 'Venezuela'},
  {    id: 2,    name: 'Jose',    edad: 16,    pais: 'Uruguay'},
  {    id: 3,    name: 'Carlos',    edad: 20,    pais: 'Colombia'},
  {    id: 4,    name: 'Sebastian',    edad: 15,    pais: 'Ecuador'}
]

console.log(miMap(sujetos, extraeNombre));


text:
Q: Removing Duplicates From 2 Arrays I have 2 arrays that I'm trying to compare and get the unique values from:
arr1 = [
   'Material',
   'Style',
   'Size',
   'add another item',
   'THIS IS A TEST OPTION',
   'Title',
   'Color',
   'dfgdfs',
   'teststststst',
   'THIS IS A NEW OPTION'
]

arr2 = [
   { option: 'Title', product: [ [Object] ] },
   { option: 'Style', product: [ [Object] ] },
   { option: 'Material', product: [ [Object] ] },
   { option: 'Size', product: [ [Object], [Object] ] },
   { option: 'Color', product: [ [Object], [Object] ] },
   { option: 'THIS IS A NEW OPTION', product: [ [Object] ] },
   { option: 'THIS IS A TEST OPTION', product: [ [Object] ] },
   { option: 'add another item', product: [ [Object] ] }
]

Expected output:
['dfgdfs','teststststst']

I have no issue pulling out unique values when the arrays are 1 level deep. However, I'm having issues with arr2 being an array of objects.
I've tried:
arr1 = arr1.filter(val => !arr2.includes(val));

Which obviously doesn't work because arr2 is an array of objects.
I've also tried:
 arr1.filter((val, index) => {
      if (arr2[index]) {
        !arr2[index].option.includes(val);
      }
    });

As well as:
arr1.filter((val, index) => {
      allUniqueOptions.forEach((option) => {
        !option.option.includes(val);
      });
    });

This seems like it should be so simple but I've been racking my head for hours. Any idea what I'm doing wrong?

A: Your filter functions need to return true if the item is to be included, and false if not.  Note that your last two examples don't return anything.
The logic that I used in the filter function is -- Does the current element appear as a "option" property in arr2?  if yes return false, if no return true.

arr1 = [
   'Material',
   'Style',
   'Size',
   'add another item',
   'THIS IS A TEST OPTION',
   'Title',
   'Color',
   'dfgdfs',
   'teststststst',
   'THIS IS A NEW OPTION'
]

arr2 = [
   { option: 'Title', product: {}},
   { option: 'Style', product: {} },
   { option: 'Material', product: {} },
   { option: 'Size', product: {} },
   { option: 'Color', product: {} },
   { option: 'THIS IS A NEW OPTION', product: {} },
   { option: 'THIS IS A TEST OPTION', product: {} },
   { option: 'add another item', product: {} }
]

const uniques = arr1.filter(item => !arr2.find(el => el.option === item));
console.log(uniques);

A: You need filter the arr1 and check with some method on each item in the array if there are no equalivient to it exist in the arr2 options.

const arr1 = [
    'Material',
    'Style',
    'Size',
    'add another item',
    'THIS IS A TEST OPTION',
    'Title',
    'Color',
    'dfgdfs',
    'teststststst',
    'THIS IS A NEW OPTION'
 ]

 const arr2 = [
    { option: 'Title', product: [ [ {} ] ] },
    { option: 'Style', product: [ [ {} ] ] },
    { option: 'Material', product: [ [ {} ] ] },
    { option: 'Size', product: [ [ {} ], [ {} ] ] },
    { option: 'Color', product: [ [ {} ], [ {} ] ] },
    { option: 'THIS IS A NEW OPTION', product: [ [ {} ] ] },
    { option: 'THIS IS A TEST OPTION', product: [ [ {} ] ] },
    { option: 'add another item', product: [ [ {} ] ] }
 ]

const result =  arr1.filter(i => !arr2.some(o => i === o.option))

console.log(result)

A: To add to the above answers.
Another reason your filters didn't work is because
arr2[index] will go out of range.
arr1 had more indexes than arr2


text:
Q: iOS 9 app download from Amazon S3 SSL error: TLS 1.2 support I get

An SSL error has occurred and a secure connection to the server cannot
  be made.

on iOS 9 if I try to download a file from amazon s3:
https://s3.amazonaws.com/xyz/qer/IMG_0001.JPG
From what I understand Amazon s3 supports TLS 1.2
see: https://forums.aws.amazon.com/thread.jspa?threadID=192512
S3 and Kinesis support TLS 1.2 at this time.
"S3 and Kinesis support TLS 1.2 at this time." Aug 23, 2015 9:19 PM
Not sure then why do I get this SSL error. The account should be configured to take advantage of TLS 1.2?
I would've guessed that this should be 'on' by default.
I don't want to put this domain on the info plist.
EDIT:
I ended up using
<key>NSAppTransportSecurity</key>
<dict>
  <key>NSExceptionDomains</key>
  <dict>
    <key>s3.amazonaws.com</key>
    <dict>
      <key>NSExceptionRequiresForwardSecrecy</key>
        <false/>
      <key>NSIncludesSubdomains</key>
        <true/>
    </dict>
  </dict>
</dict>

A: Just posting to point out that the issue with amazon's certificates are they use SHA-1 and the app transport security requires SHA-2/256.
The fact that NSExceptionRequiresForwardSecrecy works is a bug documented here at apple dev forums.  According to the documentation and an Apple engineer in the linked thread a "better" solution would be
<key>NSAppTransportSecurity</key>
<dict>
    <key>NSExceptionDomains</key>
    <dict>
        <key>s3.amazonaws.com</key>
        <dict>
            <key>NSIncludesSubdomains</key>
            <true/>
            <key>NSExceptionAllowsInsecureHTTPLoads</key>
            <true/>
        </dict>
    </dict>
</dict>

I use the term "better" very loosely and only mean a solution that does not exercise a bug that Apple will eventually fix. Now this is a fix for the certificate issue only :)

A: Edit 2016-01-03: The renewed certificate for s3.amazonaws.com uses the SHA256 algorithm and complies with ATS requirements.
Original answer: s3.amazonaws.com uses a SHA1 cerificate that does not meet ATS requirements, resulting in a hard failure. Per the App Transport Security Technote, ATS in iOS9 has the following requirements:

*

*The server must support at least Transport Layer Security (TLS) protocol version 1.2.

*Connection ciphers are limited to those that provide forward secrecy, namely,

TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384
    TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256
    TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384
    TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA
    TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256
    TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA
    TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384
    TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
    TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384
    TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256
    TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA

*Certificates must be signed using a SHA256 or better signature hash algorithm, with either a 2048 bit or greater RSA key or a 256 bit or greater Elliptic-Curve (ECC) key.
Invalid certificates result in a hard failure and no connection.

SSL Labs' SSL server test (https://www.ssllabs.com/ssltest/analyze.html?d=s3.amazonaws.com) includes a handshake simulation for ATS in iOS 9 that indicates a failure for s3.amazonaws.com.

A: You need two things to have iOS 9 app successfully reaching SSL endpoint (S3 is just an example):

*

*Forward Secrecy (https://www.wikiwand.com/en/Forward_secrecy) enabled on the server.
This feature is currently not supported by AWS S3. The workaround for that is that you can configure AWS CloudFront service (which supports FS) in front of your S3 bucket.
Set up is fairly easy. If you're using CORS, please keep in mind that proper headers need to be passed through the CloudFront proxy.

*SHA-256 protected SSL certificate on the server.
Once you'll have your files available via Cloudfront, when hitting URL (https://somethinghashed1234wasdfawer421.cloudfront.net) you'll notice that the SSL certificate over there uses SHA-1. How bad...
The solution for that is to protect this with your private, SHA-256 SSL cert. To do that you need to specify CNAME for Cloudfront endpoint in your domain. This will allow you to secure the bucket with your own SSL certificate. Simply configure your DNS to have entry pointing cloudfront-bucket.mydomain.com to that ugly somethinghashed1234wasdfawer421.cloudfront.net. Upload your SSL cert to amazon and set SSL protection in Cloudfront distribution settings. Voila!
All things mentioned are easily clickable from AWS console (apart from uploading SSL cert, which needs to be done via AWS CLI).

A: Since S3 is not currently fully compliant, according to this post on the AWS blog, their official recommendation is to exclude S3 from App Transport Security by adding this set of keys to your Info.plist:
<key>NSAppTransportSecurity</key>
<dict>
      <key>NSExceptionDomains</key>
      <dict>
            <key>amazonaws.com</key>
            <dict>
                  <key>NSThirdPartyExceptionMinimumTLSVersion</key>
                  <string>TLSv1.0</string>
                  <key>NSThirdPartyExceptionRequiresForwardSecrecy</key>
                  <false/>
                  <key>NSIncludesSubdomains</key>
                  <true/>
            </dict>
            <key>amazonaws.com.cn</key>
            <dict>
                  <key>NSThirdPartyExceptionMinimumTLSVersion</key>
                  <string>TLSv1.0</string>
                  <key>NSThirdPartyExceptionRequiresForwardSecrecy</key>
                  <false/>
                  <key>NSIncludesSubdomains</key>
                  <true/>
            </dict>
      </dict>
</dict>

UPDATE 10/27/15: As Pol points out in the comments, even though this is an official answer from AWS, an Apple Engineer in the support forums says this is actually a bug:

It turns out that the fact that NSExceptionRequiresForwardSecrecy relaxes the SHA-2/256 requirement is a bug; the intended behaviour of NSExceptionRequiresForwardSecrecy is the behaviour documented in the App Transport Security Technote, namely that it should just enable specific cypher suites.
Our plan is to fix this bug at some point in the future.  We expect to fix this in some compatible fashion, so folks who've mistakenly used NSExceptionRequiresForwardSecrecy to disable the SHA-2/256 requirement won't break.  However, predicting the future is always a challenge.
  Which brings us to what you should do right now.  [A previous version of this post gave less concrete advice.  The following is an update that tightens things up.]  After discussing this with ATS Engineering our recommendations are:
If you're using a specific hosting service, you should consult your hosting service to get the latest advice.
In situations like this, where the server is fully compatible with ATS except for the SHA-2/256 certificate signing requirement, we recommend that you accurately document that state of affairs by using NSExceptionAllowsInsecureHTTPLoads.
You should attempt to make your server fully compatible with ATS as soon as possible.
When that happens, you should update your app with the more secure ATS settings.
I should stress that NSExceptionAllowsInsecureHTTPLoads isn't actually insecure.  It's just as secure as your app currently is when it's running on iOS 8.  Rather, it means that your app doesn't benefit from the extra security provided by ATS.
  Share and Enjoy

Emphasis mine. Note that the current plan is to fix the bug in a way that will not break the behavior for people who have used NSExceptionRequiresForwardSecrecy to solve this issue, so the above is still a viable answer.

A: Until Amazon gets their head out of their *ss on this one, as @Zsolt suggested insert the following keys and value in your plist file.
BUT be sure to set the NSExceptionDomain to amazonaws.com instead of s3.amazonaws.com, depending on how your assets are served and from which region amazon may serve them such as this s3-us-west-1.amazonaws.com, so not explicitly setting the subdomain will allow assets to be properly served from any AWS region identifier.
<key>NSAppTransportSecurity</key>
<dict>
    <key>NSExceptionDomains</key>
    <dict>
        <key>amazonaws.com</key>
        <dict>
            <key>NSExceptionRequiresForwardSecrecy</key>
            <false/>
            <key>NSIncludesSubdomains</key>
            <true/>
        </dict>
    </dict>
</dict>