text:
Q: What is the purpose of filesystem.size on a LiveCD? There is /casper/filesystem.squashfs on the most LiveCDs of Ubuntu and derivatives that apparently contains the size value of the filesystem tree before compression. Some LiveCD customization articles mention that this file needs to be present in order for the system to boot correctly, but I managed to run a casper-based LiveCD system without it. And grepping through the contents of the casper package I cannot find it either.
What is it for? Will I benefit from including it into my live distribution?

A: filesystem.size is needed when a LiveCD is used to perform installation.
Ubuntu Community Wiki Help has documented briefly in this page: LiveCDCustomization. Refer to the content under 8. Producing the CD image - Assembling the file system.

Update the filesystem.size file, which is needed by the installer:
sudo su
printf $(du -sx --block-size=1 edit | cut -f1) > extract-cd/casper/filesystem.size
exit

Jump to the content by using Find in This Page... in the web browser: Press Ctrl+F and type filesystem.size as the keyword. That is all.


text:
Q: Query to find "orphaned" rows between cross-referenced tables I have 3 tables (there's more but hopefully the answer to 3 can be scaled easily) and two of the tables (B and C) contain "_id" references (rows) into the other table (A).
Q: I want to find all the entries in (A) (referenced by '_id') which are NOT referenced by B or C (or any other tables with similar relationship).
Here are some exported SQL for the three tables with uninteresting columns removed - (any references to the term "location" should be translated as table "A":
CREATE TABLE `A` (
  `_id` int(11) NOT NULL,
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `B` (
    `_id` int(11) NOT NULL,
    `B_A_id` int(11) NOT NULL DEFAULT '0' COMMENT 'Index into location table (aka A) for planting.'
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='An entry for each specific planting.';

CREATE TABLE `C` (
  `_id` int(11) NOT NULL,
  `C_A_id` int(11) DEFAULT NULL COMMENT 'The location (A) of the marker.',
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='List of markers and their data.';

I see this Q/A  where the Q was asking about 3 tables but the answers provide general syntax for two tables.
Thanks in advance.
I tagged with both [sql] and [mysql] in that it seems a general SQL question but taking note that this is a mysql application.
My attempt produces a correct result but performance woeful:
SELECT * FROM location WHERE NOT EXISTS (SELECT null FROM planting,bed,container,irrigation_line,plant_marker,solar WHERE location._id = planting.pt_loc_id OR bed.bd_loc_id = location._id OR container.cn_loc_id = location._id OR irrigation_line.ir_loc_id = location._id OR plant_marker.pm_loc_id = location._id OR solar.so_loc_id = location._id)

A: Using @Akina advice, I was able to refactor the original query I had come up with (which took > 25 seconds to execute) to the below query which takes 5 milliseconds.
The general form is as follows (where the _id column is used for cross-reference):
SELECT * FROM A WHERE NOT EXISTS (SELECT null FROM B WHERE A._id = B.b_A_id) AND NOT EXISTS (SELECT null FROM C ...) AND NOT EXISTS (...D...) AND ...

So basically separate the cross reference selects (NEGATED) into a series of ANDs and the result is correct and swift.  Here is the refactored form of original query:
SELECT * FROM location WHERE NOT EXISTS (SELECT null FROM planting WHERE location._id = planting.pt_loc_id) AND NOT EXISTS (SELECT null FROM bed WHERE location._id = bed.bd_loc_id) AND NOT EXISTS (SELECT null FROM container WHERE location._id = container.cn_loc_id) AND NOT EXISTS (SELECT null FROM irrigation_line WHERE location._id = irrigation_line.ir_loc_id) AND NOT EXISTS (SELECT null FROM plant_marker WHERE location._id = plant_marker.pm_loc_id) AND NOT EXISTS (SELECT null FROM solar WHERE location._id = solar.so_loc_id)

I admit I can't explain the dramatic difference in execution speed - I even tried to add an index on each of the "loc_id" cross-reference columns but that had no effect.

A: The standard way to find "missing" rows from table b:
SELECT a.id
    FROM a
    LEFT JOIN b ON b.x = a.x
    WHERE b.id IS NULL

redpajama_set_name: RedPajamaStackExchange


text:
Q: C to Python interface - Trying to pass structs I'm currently working on an interface between C and Python and I detected a problem I'm not able to solve: I want to pass a struct to Python. Sounds simple, but somehow I keep getting a SegFault. I already prepared everything so that the object which is returned is usable from Python. If I create an instance of it in Python it works just fine but I somehow can't use it when it is returned from a function. Here's the corresponding code:
typedef struct{
    PyObject_HEAD
    op *grid;
    double beta, *umatrix, *energies, weight;
    int nflavours, opCount;

} SegmentTrace;

typedef struct{
    PyObject_HEAD
    double ratio;
} SegInsert;

static PyObject *segTr_insert(SegmentTrace *self, PyObject *args)
{
    SegInsert *res = (SegInsert*)malloc(sizeof(SegInsert));
    return Py_BuildValue("O", (PyObject*)res);
}

With these definitions (and the corresponding Type definitions) I'm able to do the following:
import cs

obj_1 = cs.segmentTrace(0., mat_a, mat_b)
obj_2 = cs.segInsert()

print obj_2.ratio

but not:
import cs

obj_1 = cs.segmentTrace(0., mat_a, mat_b)
obj_3 = obj_1.insert()

print obj_3.ratio

For some reason a SegFault is popping up - does anybody know why?
Thanks,
lukas.

A: Alright, I figured it out - at least a workaround which will do the trick. Anyway, just for the sake of completeness: It is possible to pass the self-created Python-C-Objects out of Python to some C-routines and use the data there. That is, instead of
obj_1 = cs.segmentTrace(0., mat_a, mat_b)
obj_3 = obj_1.insert()

use:
obj_1 = cs.segmentTrace(0., mat_a, mat_b)
obj_3 = cs.segInsert(obj)

Works just fine ;)
L.


text:
Q: Inserting multiple data values to a field in mysql table I have a table with column
merchant_id | phone
 1          | 879182782
 2          | 324239324

now what i want is a query to insert multiple values for phone field
merchant_id | phone
  1         | 879182782,989838273
  2         | 324239324,849238420,349289393

Can anyone help me with example query? I tried update and all but couldn't work

A: I agree with Gordon, but with you want anyway, you can use "CONCAT", here an example for you:
create table tabla(
    merchant_id int AUTO_INCREMENT PRIMARY KEY,
    phone text
);

insert into tabla(merchant_id,phone)
VALUES (1,'809-541-8935');

insert into tabla(merchant_id,phone)
VALUES (2,'809-541-8935');

insert into tabla(merchant_id,phone)
VALUES (3,'809-541-8935');

UPDATE tabla
SET phone = concat(phone, ',809-537-7791')
where merchant_id = 1

DEMO


text:
Q: Animations with movie15 and swf files I am trying to use movie15 to embed vector animations in my presentation. The trouble is that embedded SWF files refuse to display on Acrobat Reader X sometimes with a "This Media requires an additional player" message. Eg. this example file doesn't work.
Animated GIFs won't display either, with no error message.
Maybe this is an Acrobat issue but I tried the flashmovie package with the same SWF files and that does work (but only with the embedded player option so no controls are visible). But flashmovie is supposedly unstable with beamer so I was wondering if someone had run into the same problem with movie15.
I am using Windows 7, Acrobat 10.1.2 and MiKTeX.

A: The replacement package is available on CTAN. It is called media9 and documented on CTAN.
Use the MiKTeX or TeXLive package managers for installation.
A simple example embedding an SWF would be
\documentclass{article}
\usepackage{media9}
%\usepackage[dvipdfmx]{media9} % only for latex->dvipdfmx

\begin{document}
\includemedia[
  activate=pageopen,
  width=200pt,height=150pt,
]{}{myexample.swf}
\end{document}

A minimal example for embedding a video file, using the video player component VPlayer.swf shipping with media9 and using the pdflatex, lualatex, latex-->dvips-->ps2pdf or latex->dvipdfmx/xelatex work-flows would be
\documentclass{article}
\usepackage{media9}
%\usepackage[dvipdfmx]{media9} % only for latex->dvipdfmx

\begin{document}

\includemedia[
  activate=pageopen,
  width=200pt,height=150pt,
  addresource=Sample.mp4,
  flashvars={%
     source=Sample.mp4% same path as in addresource!
%   &autoPlay=true%    % optional configuration
%   &loop=true%        % variables
  }
]{}{VPlayer.swf}

\end{document}

Video files must be in the MP4 format. Videos in other formats must be converted to MP4, or recreated from the raw material. The H.264 codec gives high quality video at stunningly small file size. With ffmpeg, video files can be created easily.
From an existing video file, such as Sample.avi, re-encoded with 30 frames (entered on a single command line):
ffmpeg -i Sample.avi -vf scale="trunc(iw/2)*2:trunc(ih/2)*2"
    -c:v libx264 -profile:v high -pix_fmt yuv420p
    -g 30 -r 30 video.mp4

From a numbered sequence of bitmaps, such as frame-0.png, frame-1.png, ... :
ffmpeg -i frame-%d.png -vf scale="trunc(iw/2)*2:trunc(ih/2)*2"
    -c:v libx264 -profile:v high -pix_fmt yuv420p
    -g 30 -r 30 Sample.mp4


text:
Q: Only regex to replace string What I need to achieve is the following: I have a few regular expressions to recognize an invoice ID (e.g. fac?tura \w*), which works but I would actually like to get rid of the word "factura" or "fatura" in the result. Can this be done with 100% regex?
I know there are a lot of similar questions around but the vast majority make use of JS's replace method or similar ones for other languages. I do not have this option.


text:
Q: Drupal exposed filter not displaying children Please refer the image
when select the child category it shows "searchfilter?field_category_tid=5"

but when I select the parent it shows nothing "searchfilter?field_category_tid=4"

I know this can be solved by creating contextual filters or some sort of relationship setting. But I have no idea how to do it.

A: Try using grouped filters. When configuring the field in the Filter type to expose chose grouped filters

Then you can enter the parent name and all the children to be filtered.
Also you can enter the child name and only 1 field (the child ) to be filtered.


text:
Q: Is it possible to cast Foo to ubyte[size] at compile time? Is it possible to cast Foo to ubyte[size] at compile time?
Here is a bit more context:
struct Algebraic(Types...)
if(Types.length < char.max - 1){
    import std.traits: Largest;
    import std.meta: IndexOf;
    static immutable maxSize = Largest!(Types).sizeof;

    this(T)(in T t)
    if(IndexOf!(T, Types) !is -1){
        type = IndexOf!(T, Types);
        data = *cast(ubyte[maxSize]*)&t;
    }

    void opAssign(T)(in T t)
    if(IndexOf!(T, Types) !is -1){
        type = IndexOf!(T, Types);
        data = *cast(ubyte[maxSize]*)&t;
    }

    inout(T*) peek(T)() inout{
        if(type is IndexOf!(T, Types)){
            return cast(inout(T*))&data;
        }
        return null;
    }
private:
    ubyte[maxSize] data;
    char type = char.max;
}

struct Branch{
    int index;
    int left;
    int right;
}
struct Leaf{
    int index;
}
struct Foo{
    alias Node = Algebraic!(Branch, Leaf);
    Node n = Branch(1,2,3);
    //Error: cannot convert &const(Branch) to ubyte[12]* at compile time
}

The problem is that I can not cast Branch to ubyte[maxSize] at compile time.

A: I am not aware of any "clean" approach (one that would make use of compiler knowledge of ABI) because CTFE is very conservative in preventing reinterpretation. However, if this is a blocker, it is possible to build up byte array manually making use of the fact struct ABI is very simple:
import std.traits;

ubyte[T.sizeof] reinterpret (T) ( T x )
    if (!hasIndirections!T)
{
    typeof(return) result;

    static if (is(T == struct))
    {
        size_t offset = 0;
        foreach (ref field; x.tupleof)
        {
            result[offset .. offset + field.sizeof] = reinterpret(field);
            offset += field.sizeof;
        }
    }
    else static if (is(T : ulong))
    {
        for (auto i = 0; i < x.sizeof; ++i)
            result[i] = cast(ubyte) (x >> 8*i);
    }
    else
    {
        // handle floating types, arrays etc.
    }

    return result;
}

struct S
{
    int x, y;
}

static immutable bytes = reinterpret(S(42, 42));

pragma(msg, bytes);

There is one huge limitation with this approach: you are required to adjust to proper ABI manually. Stuff like endianess is trivial, but handling field alignment properly is likely to be a pain (I am not even trying to do so in this snippet).


text:
Q: PHP MySQL dropdown population with blank first option Edit: gbalduzzi solved it for me with what you guys call a "dirty fix" - which is now my favorite term in coding. Thank you all so much for the help!
I'm very new to PHP/MySQL - and by new I mean the only experience I have is playing around with our site that was created by someone who didn't really care what his code looked like.
I'm attempting to fix a few issues our old IT guy had on our site. He was self-taught, so I'm sure this code I'm using is probably not up to current standards.
We have a contact list in our database, and that information is connected to this dropdown.
I'm trying to add a blank option so when you first load the page, there is no contact selected.
What I currently have adds a blank dropdown, but ends up selecting the blank option as the first contact, first option as the second contact, and so on.
Is there a way for me to implement the blank option without ruining the contact selection?
<select class="inputbox" id="job_contacts" name="job_contacts" onchange="Choice();">
    <?php
    echo '<option value=""></option>';
    foreach ($uArr as $key=>$value) {
        echo '<option value="'.$key.'">'.$value['contact_name'].'</option>';
    }
    ?>
</select>

Here is the array he created:
<script type="text/javascript">
        var nam = new Array();
        var pho = new Array();
        var email = new Array();
        <?php
            foreach($uArr as $key=>$value) {
                echo "nam[" . $key . "] = '" . $value['contact_name'] . "';\n";
                echo "pho[" . $key . "] = '" . $value['contact_phone'] . "';\n";
                echo "email[" . $key . "] = '" . $value['contact_email'] . "';\n";
            }
            ?>

        function Choice() {
            x = document.getElementById("nam");
            y = document.getElementById("job_contacts");
            x.value = y.options[y.selectedIndex].text;
            document.getElementById("nam").value = nam[y.selectedIndex];
            document.getElementById("pho").value = pho[y.selectedIndex];
            document.getElementById("email").value = email[y.selectedIndex];
        }
    </script>

A: After adding the blank option, you need to  edit the Choice function accordingly:
function Choice() {
            x = document.getElementById("nam");
            y = document.getElementById("job_contacts");
            var index = y.selectedIndex - 1;
            if (index < 0) return
            x.value = y.options[index].text;
            document.getElementById("nam").value = nam[index];
            document.getElementById("pho").value = pho[index];
            document.getElementById("email").value = email[index];
        }

A: Can you try this:
change
echo '<option value=""></option>';

to
echo '<option selected value=""></option>';


text:
Q: Get the ok massage from http posrequest {
  "token_type": "bearer",
  "access_token": "ew0KICAiYWxnIjogIkhTMjU2IiwNCiAgInR5cCI6ICJKV1QiDQp9.ew0KICAidG9rZW5EYXRhIjogInpjeXNxSWcvbnBJTjBZWG5BSlpLa0JJQTRERnVMK2JCcTFrT0VhbWxCbXRieHJITFdhbVZBVnluSzl2U0dQRVpZdW1TZ1dQRERwemU3UEphSWhPTjJIeGgvWURHL09qalFyQXZFSHlRRkRucUFUM05NK3ZhY2RKMnBaTlFrYVpHNEU4MjhkVFZpMnduTml2N1g3OHR4VmkxcS84bnBmN25NcWc1UkZlZ1VockhPUUU1WXJuMlVsRmJTV200dDNsTHoyWTJpa2ZMOURJOTVBTHIvV25rdjdhWkljNlJ1Rld5OThid05ZOHpCMXc9IiwNCiAgImNsaWVudElEIjogImNhNjQ3ZDc3OTZjNTQ4MjA5Y2RkYTllZDAwNGMzOGFhNTI0ODE3MTcwODAyODAwNDYyOCIsDQogICJyZXBseVVybCI6ICJodHRwOi8vbG9jYWxob3N0IiwNCiAgIm5iZiI6IDE1MTMwNTkxMTcsDQogICJleHAiOiAxNTEzMDYwOTE3LA0KICAiaWF0IjogMTUxMzA1OTExNw0KfQ.ixRDlLYfrJ-OQs6LzkLhf07skR9z1i-3w1u7rtRppgE",
  "expires_in": 1800.0,
  "refresh_token": "zcysqIg/npIN0YXnAJZKkBIA4DFuL+bBq1kOEamlBmtbxrHLWamVAVynK9vSGPEZgS5OAD7gpY2OoBSeaHH48aQ/ER3WZOnOijWQrxEFNKU="
}

This is what i have json response. i want to display acces_token from this.so i want code line.
this is the code I try to get this json.
public async Task NewMethodAsync()
{
    try
    {
        HttpClient objClient = new HttpClient();

        Uri requestUri = new Uri("https://approvalbotbeta.azurewebsites.net/api/token");
        Dictionary<string, string> pairs = new Dictionary<string, string>();
        var client_ID = "ca647d7796c548209cdda9ed004c38aa5248171708028004628";
        var client_secret = "QXBwcm92YWxCb3RfVE9H7auiwc6RhE6ldS6WGsqWh2NhNjQ3ZDc3OTZjNTQ4MjA5Y2RkYTllZDAwNGMzOGFhNTI0ODE3MTcwODAyODAwNDYyOA==";
        pairs.Add("grant_type", "client_credentials");
        pairs.Add("reply_url", "http://localhost");
        FormUrlEncodedContent httpContent = new FormUrlEncodedContent(pairs);
        var encordedString = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(client_ID + ":" + client_secret));
        // httpContent.Headers.Add("Authorization", "Basic " + encordedString);
        //httpContent.Headers.Add("Authorization", "Basic " + encordedString);
        // httpContent.Headers.Add["Authorization"] = "Basic" + encordedString;

        objClient.DefaultRequestHeaders.Add("Authorization", "Basic " + encordedString);

        HttpResponseMessage respon = await objClient.PostAsync("https://approvalbotbeta.azurewebsites.net/api/token", httpContent);
        if (respon.IsSuccessStatusCode)
        {
            Console.WriteLine(respon.Content.ReadAsStringAsync().Result);

        }
    }
    catch (Exception ex)
    {

        Console.WriteLine(ex.Message);
    }
}

A: You need to install Newtonsoft.Json library and use this code:
dynamic json = JsonConvert.DeserializeObject(result);
string token = json.refresh_token;

A: Just create response class
public class Response
{
    public string token_type { get; set; }
    public string access_token { get; set; }
    public double expires_in { get; set; }
    public string refresh_token { get; set; }
}

Then use Newstonsoft Json - https://www.nuget.org/packages/newtonsoft.json/
    var response = JsonConvert.DeserializeObject<Response>(result);
    Console.WriteLine(response.access_token);


text:
Q: reCAPTCHA placeholder errors as no captcha on page I keep getting same error, I believe its because this form has no captcha as its not needed on this one page. Is there a way to solve this error ?
I have tried to inject a id if there is non present but this dose not seem to work
recaptcha__en.js:496 Uncaught Error: reCAPTCHA placeholder element must be an element or id
at Object.dF [as render] (recaptcha__en.js:496)
at HTMLFormElement.<anonymous> ((index):973)
at Function.each (jquery.js:365)
at jQuery.fn.init.each (jquery.js:137)
at loadCaptcha ((index):970)
at BK (recaptcha__en.js:501)
at qY (recaptcha__en.js:491)
at recaptcha__en.js:504
at recaptcha__en.js:524


text:
Q: Check Database for Existing Usernames I have registration form, which is saving user info in 'tblusers' -> 'Username', but It doesn't check if the user is already existing, so at the moment users can register with identical usernames, which is a huge mess.
So I need to check MySQL database for existing 'Username' on the registration. Any idea how to do this with PHP - MySQL, even javascript.
This is code I'm executing on form submit:
    check_token ();
    $_SESSION['currency'] = $currency;
    $clientid = addclient ($firstname, $lastname, $companyname, $email, $address1, $address2, $city, $state,
        $postcode, $country, $phonenumber, $password, $securityqid, $securityqans, $sendemail);
    //print "New clientid=" . $clientid . "
";
    update_query ('tblclients', array ('notes' => $notes, 'status' => $status, 'credit' => $credit, 'salesOperatorId' => $salesOperatorId,
        'taxexempt' => $taxexempt, 'latefeeoveride' => $latefeeoveride, 'overideduenotices' => $overideduenotices, 'country' => 'US',
        'language' => $language, 'billingcid' => $billingcid, 'lastlogin' => '00000000000000'), array ('id' => $clientid));
    //print "New clientid now=" . $clientid . "
";
    savecustomfields ($clientid, $customfield);
    $result = select_query ('tblusers', 'ID', array ('ClientID' => $clientid));

    // adding user to the DB at same time as client is being added ...
    $datenowtimestamp = date("Y-m-d H:i:s");
    $table91 = 'tblusers';
    $array91 = array ('ClientID' => $clientid, 'firstname' => $userfirstname, 'lastname' => $userlastname, 'email' => $useremail,
            'username' => $username, 'password' => $password, 'searchdelivery' => 'Criminal', 'reporttiming' => 'Instant',
            'deliverymethod' => 'email', 'Created' => $datenowtimestamp,
            'phonenumber' => $phonenumber, 'orderreports' => 1, 'viewallreports' => 1, 'viewpricing' => 1,
            'restrictreportview' => 0, 'gatewayaccess' => 0);
    insert_query ($table91, $array91);

    if($data = mysql_fetch_array ($result))
        $userid = $data['ID'];
    $header = 'Location: clientsusers.php?clientid=' . $clientid;
    //print $header . "
";
      header ($header);
      exit ();

A: The right way to do this is probably by adding unique indexes on your username column in your users table:
CREATE UNIQUE INDEX username_index ON users (username);

The alternative (checking in your PHP code) is liable to issues with two people trying to register with the same username at the same time.

A: when user enters username while registering, make an ajax check to see if the username already exists and notify the user to choose something else

A: When the form data is accessible in whatever php script gets executed when the form is submitted in a has $_POST['username'] (or if you're using GET, $_GET['username']).  From there, since you're users can register, I'll assume you connect to your DB and run queries.
Query the database for how many entries match $_POST['username'].  If if greater than 0, return the error however you see fit.
The query would look something like SELECT count(*) FROM dbname WHERE username = $_POST['username'].  Of course there is some prep work to do to avoid SQL injection, but that would be the basic process.
This book has everything you need to know about the basics of web programming, and was the text for my web programming class.


text:
Q: R: Convert an incomplete matrix to two or three columns If I have a table
ID   C1   C2   C3   C4   C5
 1
 2    HD   NS   VM
 3                   DH   FV
 4    HD             DH

Now I have to convert it to the following table
ID  C
2   HD
2   NS
2   VM
3   DH
3   FV
4   HD
4   DH

What is the best way to make this conversion in R? This has to be done in R as part of a larger code?

A: We can use dplyr and tidyr.
library(dplyr)
library(tidyr)

dt2 <- dt %>%
  gather(C, Value, -ID, na.rm = TRUE) %>%
  select(-C) %>%
  arrange(ID)
dt2
  ID Value
1  2    HD
2  2    NS
3  2    VM
4  3    DH
5  3    FV
6  4    HD
7  4    DH

DATA
dt <- read.table(text = "ID   C1   C2   C3   C4   C5
 1 NA NA NA NA NA
                 2    HD   NS   VM NA NA
                 3    NA  NA  NA  DH FV
                 4    HD  NA NA   DH NA     ",
                 header = TRUE, stringsAsFactors = FALSE)

A: Using melt
library(reshape)
na.omit(melt(dt,id.var='ID'))
   ID variable value
2   2       C1    HD
4   4       C1    HD
6   2       C2    NS
10  2       C3    VM
15  3       C4    DH
16  4       C4    DH
19  3       C5    FV

A: data <- as.data.frame(list(ID = c(1,2,3,4),
              C1 = c(NA,"HD",NA,"HD"),C2 = c(NA,"NS",NA,NA),C3 = c(NA,"VM",NA,NA),C4 = c(NA,NA,"DH","DH"), C5 = c(NA,NA,"FV",NA)))

You can use unlist, but to have the ID, you previously create a matrix of same size than your data, just with the IDS
plouf = matrix(data$ID,dim(data)[1],dim(data)[2]-1)
data$ID <- NULL

and then you use unlist and select the non NA data:
   result = as.data.frame(list(
  C = unlist(data)[!is.na(unlist(data,use.names = FALSE))],
  ID = unlist(plouf)[!is.na(unlist(data))] ))

which leads :
 C ID
C12 HD  2
C14 HD  4
C22 NS  2
C32 VM  2
C43 DH  3
C44 DH  4
C53 FV  3


text:
Q: How to upload ipa file to Dropbox using fastlane and circleci? I want to use FastLane to upload the IPA file to Dropbox. I follow the Dropbox documentation: https://github.com/tommy071/fastlane-plugin-publish_dropbox and the Circleci has run successfully, but I can't find the IPA file in my dropbox catalog.
The code is as follows:
- run: bundle exec fastlane add_plugin publish_dropbox

publish_dropbox(
    file_path: '/Users/distiller/project/output/gym/xxx.ipa',
    dropbox_path: 'https://www.dropbox.com/home/xxx%20xxx%20xx%20Folder/Development/xxx-IOS',
    app_key: 'xxxxxx',
    app_secret: 'xxxxx'
  )

The progress of circleci is as follows:

In addition, I noticed that there is a dropbox document here. I don't know if it is useful. Should I add my project?
Dropbox document: https://www.dropbox.com/developers/documentation/swift

A: The token created from your api key and secret is stored in the keychain. You need to either pass the keychain_password or set the DROPBOX_KEYCHAIN_PASSWORD environment variable.
In CircleCI, the keychain password is an empty string unless you changed it in the setup_circle_ci action.
As the docs say:

If not provided, the plugin would ask for password

But the plug-in can't ask in CI because the terminal is not interactive.


text:
Q: UnauthorizedAccessException exception in ItemAdded handler in event receiver I am having a sharepoint sitecollection which has two sites say site1 and site2.
I have a user, have contribute premission in site1 and read permission in site2.
I wrote a event receiver on item added in a list1 in site1 for moving the same record in a list2 in site2.
public override void ItemAdded(SPItemEventProperties properties)
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
 using (SPSite site = properties.OpenSite())
 {
   using (SPWeb web = site.OpenWeb("/site2"))
   {
    web.AllowUnsafeUpdates = true;
    SPList list = web.Lists["List2"];
    SPListItem item = list.Items.Add();
    item["Title"] = "test";
    item.Update();
    web.AllowUnsafeUpdates = false;
   }
  }
 });
   }

I tried with RunWithElevatedPrivileges even AllowUnsafeUpdates but Unfortunately it is not working in my case. on Update() it throws UnauthorizedAccessException.
{System.UnauthorizedAccessException:
    <nativehr>0x80070005</nativehr><nativestack></nativestack>

I am using sharepoint 2010 sp1 with aug2012 cumulative updates.

A: you have to initiate the new context of the spsite from the site id:
SPSecurity.RunWithElevatedPrivileges(delegate() {
 using (SPSite site = new SPSite(item.Web.Site.ID))
 {
  using (SPWeb web = site.OpenWeb("1"))
  {
   SPListItem curritem = web.Lists[item.ListItems.List.Title].Items.GetItemById(item.ID);
  }
 }
});

A: In my case, in a dev enviroment, i just put the user that does the deploy, or debug mode in: site collection administrators and it works. No more exceptions like that.
I'm running a PowerShell Script with the user that is in the site collection administrators and doesn't necessary add a SPSecurity or RunWith...


text:
Q: Owner Permissions Set Too Restrictively EDIT: was able to fix this by logging in with another account in the same group, and accessing it that way.  It only worked because I was lucky enough to have that other account in the same group though. I'd still like to know if there's another way around this issue.
hmm...
i meant to do
> chmod 755 <directory>

but I typed
> chmod 75 <directory>

which results in
> d---rwxr-x   5 justin        512 Oct 24 19:35 gallery

I own the directory, but can't access it.
I don't have root.
What to do...

A: You should be able to do:
chmod 755 <directory>

If that does not work, running it as root will work:
sudo chmod 755 <directory>

A: You've managed to give the group owner full access (assuming there is one; your ls output doesn't indicate one).  If there is a group owner, say, group foo, you could log in to the group with newgrp:
$ newgrp foo

This might allow you to issue the corrective chmod 755 <directory>.
You could also try to recursively chmod the parent directory, if you own it.  Be careful to record permissions on other subdirectories and files so you can restore them properly later.
Barring either of those solutions, you'll have to contact the system administrator to fix it for you.  Some breakages just require root to fix.


text:
Q: quantify accuracy of model reconstructed in Meshroom based on ground points? I have ground points placed in the scene with known Pw for each point in the world coordinate system. The P_m in the model coordinate system is calculated from the reconstructed model. However, the O_w and O_m are not aligned.
O_w and O_m are world and model coordinate systems, respectively. Can someone help enlist the steps needed to ensure the difference in real-world units between P_w and P_m?
Thanks in advance.


text:
Q: Losing Kerberos Ticket after SSH to Current Host and Exit I am running on CentOS 7.3.
How may I prevent losing my Kerberos TGT in the scenario below?
I understand the security implications of not destroying Kerberos tickets upon logout, and I will be digging deeper into this. But I want to start with the simplest possible example, which I present below.
user@host.example.com$ klist
klist: Credentials cache keyring 'persistent:25536700022:krb_ccache_h3j7qk7' not found

user@host.example.com$ kinit
Password for user@example.com:

user@host.example.com$ klist
Ticket cache: KEYRING:persistent:25536700022:krb_ccache_h3j7qk7
Default principal: user@example.com

Valid starting       Expires              Service principal
08/03/2018 17:06:45  08/04/2018 17:06:41  krbtgt/example.com@example.com

user@host.example.com$ ssh -K host
Last login: Fri Aug  3 17:06:21 2018 from 10.250.57.186

user@host.example.com$ klist
Ticket cache: KEYRING:persistent:25536700022:krb_ccache_h3j7qk7
Default principal: user@example.com

Valid starting       Expires              Service principal
08/03/2018 17:06:54  08/04/2018 17:06:41  krbtgt/example.com@example.com

user@host.example.com$ exit
logout
Connection to host closed.

user@host.example.com$ klist
klist: Credentials cache keyring 'persistent:25536700022:krb_ccache_h3j7qk7' not found

user@host.example.com$

UPDATE #1
Updating the SSH server configuration as follows solves the problem as presented:
GSSAPICleanupCredentials no

However, doing this unconditionally is undesirable because it has negative security implications. Leaving unexpired tickets resident on a machine after you've done working on it is dangerous.
More Detail About Our Use Case
We are using SSH to execute commands on remote hosts. The commands executed on the remote hosts may, in turn, use SSH to execute remote commands on yet other hosts. This is all scripted / automated, so we can't allow a prompt for a password to occur. This is why I used ssh -K. The -K flag forwards your Kerberos TGT to the host you're SSHing to, thereby enabling you to SSH on to another host from there without being prompted for a password.
In our particular use case, it sometimes happens that one of the "remote" hosts we're using SSH to execute a command on is the host we're already on. Without the configuration change shown above, after the "remote" command finishes executing and the SSH session exits, the Kerberos ticket is destroyed--on the machine we're currently on! We've then lost our ability to SSH in a passwordless manner to all hosts.
Searching For a Secure Solution to Our Use Case
So as to avoid the security implications of unconditionally not destroying Kerberos tickets upon logout, I'd like to dig deeper.
Is there a way to do either of the following?

*

*Forward your Kerberos TGT only if it doesn't already reside on the machine you're SSHing to

*Destroy your Kerberos tickets only when exiting your last shell session

Are there other possibilities that I am not considering?

A: I ended up putting the following in my .bash_profile:
cleanup()
{
   SHELL_COUNT=$(ps -elf | grep bash | grep $(whoami) | grep -v grep | wc -l)

   if [[ "$SHELL_COUNT" -eq 2 ]]; then
      kdestroy -q
   fi
}

trap '
   cleanup
' 0


text:
Q: Meteor: How to point a template prototype at another template? I have a feeling that it must be possible to point to template helpers from one template to another. Does anyone know how to do this?
I see in the console that I have access to the Template I want: i.e. Template.Users_edit_page.
And it looks like there is a __helpers object with all the templates defined (Template.Users_edit_page.__helpers).
How can I do something along the lines of:
Template.User_form.prototype.helpers = Template.Users_edit_page.helpers__
and then ideally any helper called from the User_form template (which is a child of the Users_edit_page) would run the Users_edit_page template helper

A: While I fully encourage digging into the internals of a framework to better understand what it is doing, directly linking into implementation details like this (e.g.  *.__helpers) is generally not a good idea, as framework developers may change implementation details breaking your code.
When you use the public APIs you can expect less breaking changes, and advanced notice before that happens (e.g., APIs marked for future deprecation).
As I mentioned in your other question the most flexible approach to sharing helpers across templates is with Template.registerHelper.
However if you need something more targeted you can define your functions as standalone javascript functions:
passwordSecure = function(password) {
  return password.length > 8;
};
validEmail = function(email) {
  return email.contains('@');
};

Then include them as helpers in all the templates you want them in like this:
Template.User_form.helpers({
  'passwordSecure': passwordSecure,
  'validEmail':  validEmail,
});


text:
Q: MinioClient thread safe I am trying to user minio java sdk. In multi thread environment, can we share MinioClient object between multiple threads simultaneously. Is MinioClient java client object thread safe.

A: Yes, MinioClient is thread-safe
Source: https://github.com/minio/minio-java/issues/975 . So,  MinioClient is thread-safe and they have a functional test runs on every Pull Request.


text:
Q: Physical States has ghost number 1 in String Theory We know by no-ghost theorem (Polchinski I, section 4.4) that the physical Hilbert space have no longitudinal excitations ($X^0, X^1, b, c$). This is obvious by light-cone gauge quantization and in fact BRST cohomology is isomorphic to this space (no-ghost theorem). Witten (beginning of chap. 2) in "Non-commutative geometry and string field theory" also argues that physical states should not contain ghosts "since the traditional covariant quantization did not involve ghosts at all". He then affirm that "Physical States of bosonic Open String has ghost number 1/2" (ghost number 1/2 = annihilated by all ghost (and anti-ghost) annihilation operators AND by zero mode antighost $b_0$). But in the most part of reviews - Ashoke Sen TASI lecture 2003- about STF the statement is that "physical states has ghost number 1". I don't understant this difference on notation. I most agree with Witten argument, but in practicle is very convenient to work with $|\psi\rangle = \int d^{26}k(T(k)c_1 + C(k)c_0 + A_\mu(k)\alpha_{-1}^\mu c_1 + \cdots)|0;k\rangle$, which explicitly have ghost number 1. I know that these ideas are equivalent but I don't know how. I think I don't understant Witten's statement. Can someone help me to understand this equivalence of these different notations?
Thanks

A: This is just a question of convention: Polchinski, Witten  and most older papers quote the ghost number on the cylinder, which is half-integer and such that the ghost vacua have $\pm 1/2$. On the other hand, most recent papers quote the ghost number on the plane, which is an integer and such that the ghost vacua have ghost number $1$ and $2$.
[A small caveat about my last explanation: since the ghost number is an additive number, you can always choose to shift all of them by a constant, which explains why some papers may say that ghost numbers on the plane are half-integers: to obtain this, they shift the ghost number. There is a second point to take care of: when using $A_\infty$ homotopy algebra to describe the open string field theory, it is quite common to not work with the ghost number but with a related number called the degree (they are related by what is called a suspension). One has $\mathrm{degree} = N_{gh} - 1$, in which case the $\mathrm{U}(1)$ charge of the classical string field is $0$ instead of $1$. Details are not important, just to remember that it's another possible source of language mismatch.]
The reason is that the ghost current is not primary, which means that it does not transform covariantly under changes of coordinates:
$$
j(z) = \frac{dw}{dz} \, j'(w) + \frac{q}{2} \, \frac{d}{dz} \, \ln \frac{dw}{dz},
$$
and as a consequence the ghost number is not invariant. Going from the cylinder with coordinates $w$ to the plane with coordinates $z = \mathrm{e}^w$, we find that the ghost number varies as:
$$
N_{\text{gh}}^{\text{plane}} = N_{\text{gh}}^{\text{cyl}} - \frac{q}{2}.
$$
Here, $q$ is the background charge and measures the violation of the ghost charge conservation. We have $q = - 3$ for the ghosts.
You can find more details in the draft of my book, sections 7.2.3 and 7.2.6 (see in particular remark 7.6).


text:
Q: DeSerialization doesn't work though i Implement GetObjectData method and Constructor I have a static generic dictionary in a class. As static memeber cannot serialized so i have implented ISerializable interface and method GetObjectData to serialize. I have a constructor which will also accept SerializationInfo and StreamingContext to deserliaze the dictionay. Now when i try to serialize and  deserialize , it always return 1(thoug i added 2 entries). please find the pseduo code-
[Serializable]
public class MyClass : ISerializable
{
  internal  static Dictionary<long, string> dict = new Dictionary<long,string>();

  public void GetObjectData(SerializationInfo info, StreamingContext context)
  {
   info.AddValue("static.dic", MyClass1.dict, typeof(Dictionary<long, string>));
  }

  public MyClass(SerializationInfo info, StreamingContext context)
  {
    MyClass.dict= (Dictionary<long, string>)info.GetValue("static.dic",
       typeof(Dictionary<long, string>));

  }
  public void Add()
  {
    dict.Add(21, "11");
  }

  public MyClass()
  {
    dict.Add(21, "11");
  }
}

  public class MyClass
  {
        MyClass myClass = new MyClass();

        public static void Main()
        {
           myClass.Add();

           FileStream fileStream = new FileStream("test.binary", FileMode.Create);

           IFormatter  bf = new BinaryFormatter();

           bf.Serialize(fileStream, myClass);

            fileStream.Dispose();

            fileStream.Close();

            fileStream = new FileStream("test.binary", FileMode.Open);

            bf = new BinaryFormatter();

            myClass = (MyClass1)bf.Deserialize(fileStream);
     }
}

A: Never post "pseudo-code" when you can just as easily post working code that exhibits the problem.
Anyway, after cleaning up your code, it works as expected, in the sense that deserializing the object gives me a dictionary with 2 elements. I'm betting the problem is related to your static field dict. You shouldn't use static fields like that.
Can you try the following code and tell us what the problem is? This is working code in the sense that you can paste this into the Program.cs file of a console or winforms application and debug it.
Note the following things:

*

*I removed the static'ness of the dict field

*I fixed the keys you used for the two elements you added (both can't be 21)

*I renamed one of the MyClass classes, and fixed references to MyClass1

*I rewrote the Main code slightly to use using block instead of calls to .Close() and .Dispose().

Here's the code:
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace Test
{
    [Serializable]
    public class MyClass : ISerializable
    {
        internal Dictionary<long, string> dict = new Dictionary<long, string>();

        public void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            info.AddValue("static.dic", dict, typeof(Dictionary<long, string>));
        }

        public MyClass(SerializationInfo info, StreamingContext context)
        {
            dict = (Dictionary<long, string>)info.GetValue("static.dic",
               typeof(Dictionary<long, string>));
        }

        public void Add()
        {
            dict.Add(31, "11");
        }

        public MyClass()
        {
            dict.Add(21, "11");
        }
    }

    public class MyClassTest
    {
        public static void Main()
        {
            MyClass myClass = new MyClass();
            myClass.Add();

            using (FileStream fileStream = new FileStream("test.binary", FileMode.Create))
            {
                IFormatter bf = new BinaryFormatter();
                bf.Serialize(fileStream, myClass);
            }

            using (FileStream fileStream = new FileStream("test.binary", FileMode.Open))
            {
                IFormatter bf = new BinaryFormatter();
                myClass = (MyClass)bf.Deserialize(fileStream);
            }
        }
    }
}

A: This is fundamentally completely wrong.
You are attempting to link the serialization/deserialization of an instance with modification of the static state of a class.
This should not be static state if it is linked with an instance.
If you wish to share this dictionaries state with multiple instances then it must be immutable (so that the creation of one does not affect the others). A decent immutable Map will make this easy (allowing sharing of as much shared state as possible)

A: It almost certainly shouldn't be static!
But; assuming it is instance data, have you tried adding an OnDeserialization callback that calls dict.OnDeserialization?
Until you do that, it may be incomplete...
For an example, see here.

A: You don't want to use static class for this.  You want to use a singleton that loads on the first creation.  You may also want a refresh method on there.


text:
Q: Azure API Management Policy- "rewrite-url" policy I am trying to create a policy, that will pull the insurer ID out of the input body and put it in the URL as shown in the picture below.
Trying to clean up request body and reconstruct URL so the request can successfuly post to our approve endpoint
Expected Result:

https://apimanagement.test.com/consto-123/api/relationship/approve/{id}
Request body:
{
    "insurer_name": "Tony",
    "insurer_id": "12345",
    "comments": "This is test"
}

A: You have to extract the insurer_id from the request-body and store it as a variable:
<set-variable name="insurerId" value="@{
    var body = context.Request.Body.As<JObject>(true);
    return body["insurer_id"].Value<string>();
}" />

Afterwards you can use rewrite-uri with this variable and forward the request to the blackened.
The complete policy:
<policies>
    <inbound>
        <base />
        <set-variable name="insurerId" value="@{
            var body = context.Request.Body.As<JObject>(true);
            return body["insurer_id"].Value<string>();
        }" />
        <rewrite-uri template="@("/api/relationship/approve/" + context.Variables.GetValueOrDefault<string>("insurerId"))" copy-unmatched-params="false" />
        <set-backend-service base-url="https://rfqapiservicey27itmeb4cf7q.azure-api.net" />
    </inbound>
    <backend>
        <base />
    </backend>
    <outbound>
        <base />
    </outbound>
    <on-error>
        <base />
    </on-error>
</policies>


text:
Q: Java: Extracting Instagram likes? So it's a pretty straightforward question, I was just wondering, does anyone know how I would be able to do this, preferably using purely java/at least code that can be executed from a Java program?
Currently I am using the following method in which the webpage is downloaded from the server:
        URL url = new URL(u);
        URLConnection uc = url.openConnection();
        uc.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:25.0) Gecko/20100101 Firefox/25.0");
        InputStream inputStream = uc.getInputStream();

        FileOutputStream outputStream = new FileOutputStream("currentImagePage.html");

        int bytesRead = -1;
        int BUFFER_SIZE = 4096;

        byte[] buffer = new byte[BUFFER_SIZE];
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }

        outputStream.close();
        inputStream.close();

And the resulting HTML document returned can be seen here:
http://pastebin.com/262h22PQ
If you look at line 110, that's the only real thing I can see of any interest:


text:
Q: How can I implement a 1..n bi-directional relationship in Entity Framework Code First I am absolutely stumped in trying to figure out how to implement a bi-directional 1..n relationship in Entity Framework using Code First.  For example, a team (represented by a Team entity) has a coach and a manager (both represented by a Person entity).  So, my Team model could be as follows:
public class Team
{
    public Team()
    {
        Manager = new Person();
        Coach = new Person();
    }

    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int TeamID { get; set; }
    public string Name { get; set; }

    [ForeignKey("Manager")]
    public int ManagerID { get; set; }
    public virtual Person Manager { get; set; }

    [ForeignKey("Coach")]
    public int CoachID { get; set; }
    public virtual Person Coach { get; set; }
}

I can implement one-way navigation by implementing the Person Entity as follows:
public class Person
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int PersonID { get; set; }
    public string Name { get; set; }
}

and the fluent API:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Team>()
        .HasRequired(t => t.Manager);

    modelBuilder.Entity<Team>()
        .HasRequired(t => t.Coach);

    base.OnModelCreating(modelBuilder);
}

However, while that allows me to navigate from the Team entity to the related Coach and Manager (both instances of Person), it doesn't allow me to directly navigate from the Coach or Manager to the related Team.  So, to implement 2-way navigation, I modified the Person entity as follows:
public class Person
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int PersonID { get; set; }
    public string Name { get; set; }

    [ForeignKey("Team")]
    public int TeamID { get; set; }
    public virtual Team Team { get; set; }
}

While that builds ok, I get the following runtime error when I try to save to the database:
System.Data.Entity.Core.UpdateException
InnerException: Unable to determine a valid ordering for dependent operations. Dependencies may exist due to foreign key constraints, model requirements, or store-generated values.

So, to specify the ordering between the entities, I tried to modify the fluent API by adding the "WithRequiredPricipal" as follows:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Team>()
        .HasRequired(t => t.Manager)
        .WithRequiredPrincipal(t => t.Team);

    modelBuilder.Entity<Team>()
        .HasRequired(t => t.Coach)
        .WithRequiredPrincipal(t => t.Team);

    base.OnModelCreating(modelBuilder);
}

However, when I attempt to execute "add-migration" in the Package Manager Console, I get the following error:
System.InvalidOperationException: The navigation property 'Team' declared on type 'RelatedEntities.Models.Person' has been configured with conflicting foreign keys.

What I'm attempting to achieve seems like a straightforward requirement but I've done heaps of searching for a solution without yet finding an answer.  Am I missing something in the fluent API or the annotations?
(I don't want to implement a workaround, such as implementing separate models for Coach and Manager because a team may have numerous other roles (eg, Assistant Coach, Public Relations Manager, etc). I would want each to simply be an instance of a Person entity.)

A: You didn't define your foreign key constraints.
.HasRequired(t => t.Manager)
.WithMany()
.HasForeignKey(t => t.ManagerId)

As a side note. If your manager was managing multiple teams the WithMany would be .WithMany(m => m.Teams) and your manager model would need something like this:
private ICollection<Team> _teams
public ICollection<Team> Teams
{
    get { return _teams ?? (teams = new List<Team>()); }
    protected set { _teams = value; }
}

Sorry for formatting. On my phone. Good luck.

A: Ok, I can now answer my own question in case anyone else encounters the same problem.
Firstly, as I mention in my comment above, the problem that I described in my question turns out to be a recognized shortcoming in Entity Framework that the EF Triage Team has flagged to be addressed in a future release of EF.
In the meantime, the workaround that has been suggested by a number of contributors in response to questions about how to implement circular dependencies in EF (which is what my example above is trying to do) is to do it in stages as follows:

*

*Create the principal entity

*Call SaveChanges() on DbContext

*Create the dependent entity and set the foreign key before calling SaveChanges() again (at some subsequent point)

So, using the Team example in my original question above, instead of creating the dependent Manager and Coach entities in the Team constructor, the first change was to make the Team's foreign keys to the Coach and Manager optional (instead of required), so that the Team could be instantiated without the Coach and Manager, and then call SaveChanges():
Team team = Teams.Add(new Team());
SaveChanges();

After that, I then create the dependent Manager and Coach entities and set their foreign keys to the ID of the Team instance:
team.Manager = new Person();
team.Manager.TeamID = team.TeamID;

team.Coach = new Person();
team.Coach.TeamID = team.TeamID;

At any time after that, SaveChanges() can be called without causing a runtime error as previously.
When this issue is addressed in a future release of EF, it should be possible to create the principal and dependent entities without having to call SaveChanges() in between.


text:
Q: how to move jpg and jpeg files whose size is greater than 10kb I want to move all .jpg and .jpeg files whose size is more than 10 kb.
The code below moves only jpg with size greater than 10 kb. All .jpeg files are moved regardless of the size.
#!/bin/bash

mkdir notmyprograms

cd testprog

for file in $(find -name "*.jpeg" -o -name "*.jpg" -a -size +10k)
do
mv $file /home/rayan-ali/Desktop/notmyprograms/
done


text:
Q: pivot_longer and uncount a dataset with many columns in R This is a chunk of a huge dataset I have:
appartments <- structure(list(year = c(2003L, 2012L, 2014L, 2011L, 2009L), city = c("A",
"B", "C", "D", "E"), rooms = c(1L, 2L, 5L, 2L, 4L), empty = c(4L,
1L, 1L, 2L, 3L), spacebel30 = c(0L, 0L, 0L, 0L, 0L), space3150 = c(0L,
0L, 0L, 0L, 0L), space5170 = c(0L, 1L, 0L, 0L, 0L), space7190 = c(0L,
0L, 0L, 0L, 0L), space91110 = c(0L, 0L, 0L, 0L, 0L), space111130 = c(0L,
0L, 1L, 0L, 0L), space131plus = c(0L, 0L, 0L, 0L, 0L), spaceunknown = c(4L,
0L, 0L, 2L, 3L), bighouse = c(0L, 0L, 0L, 0L, 0L), smallhouse = c(4L,
1L, 1L, 2L, 2L), bothhouse = c(0L, 0L, 0L, 0L, 1L), otherhouse = c(0L,
0L, 0L, 0L, 0L), before1920 = c(0L, 0L, 0L, 0L, 0L), b19211950 = c(0L,
0L, 0L, 0L, 0L), b19511980 = c(4L, 1L, 0L, 2L, 1L), b19811910 = c(0L,
0L, 1L, 0L, 2L), b2011 = c(0L, 0L, 0L, 0L, 0L), renovated = c(0L,
0L, 0L, 1L, 1L), old = c(4L, 1L, 1L, 1L, 2L), new = c(0L, 0L,
0L, 0L, 0L), rent = c(4L, 1L, 1L, 2L, 3L), sale = c(0L, 0L, 0L,
0L, 0L), rentsale = c(0L, 0L, 0L, 0L, 0L), r1000 = c(3L, 1L,
0L, 1L, 0L), r10001250 = c(1L, 0L, 0L, 0L, 0L), r12511500 = c(0L,
0L, 0L, 1L, 0L), r15011750 = c(0L, 0L, 0L, 0L, 1L), r17512000 = c(0L,
0L, 0L, 0L, 2L), r20012250 = c(0L, 0L, 0L, 0L, 0L), r2251b2500 = c(0L,
0L, 0L, 0L, 0L), `25012750` = c(0L, 0L, 0L, 0L, 0L), r27513000 = c(0L,
0L, 0L, 0L, 0L), r30003250 = c(0L, 0L, 0L, 0L, 0L), r32513500 = c(0L,
0L, 0L, 0L, 0L), runknown = c(0L, 0L, 0L, 0L, 0L), r3500plus = c(0L,
0L, 1L, 0L, 0L)), row.names = c(NA, 5L), class = "data.frame")

It has information about flats for every year, a certain city and the number of rooms. But after that, the sum is already aggregated: The number of empty flats, after that the number of certain spaces (from 30qm till unkown), then the number of four different types of house, after that the number of old/new/renovated, then rent/sale/both and finally the number of priceranges from <1000 till >3500.
Or in short: It's an ugly mixture of tidy and wide, of raw and aggregated data.
So I wanted to pivot_longer the last five groups first, but thats immpossible to achive(at least for me). Uncount first does not work either, I get instantly thousand of repeating rows. Put it in five separate df does not work, because I have nothing to join it afterwards.
My goal: thousands of simple records, one for each flat:

year
city
rooms
empty
space
housetype
buildyear
old-new
payrent

2003
A
2
no
space3150
bighouse
before1920
old
r1000

2020
B
4
no
space91110
smallhouse
b2011
new
r15011750

2011
C
1
yes
space5170
otherhouse
b19511980
renovated
r12511500

2020
B
3
no
space91110
otherhouse
b2011
new
r15011750

...and so on.
It's probably a bit like unscramble scrambled eggs, but still: Is it possible to achive?

A: Here is a try:
Please check double. I am not sure about the result, because in all groups there is the same data.
library(tidyverse)

appartments %>%
  pivot_longer(
    cols = -c(year, city, rooms, empty)
  ) %>%
  mutate(space = ifelse(str_detect(name, "space"), name, NA_character_),
         housetype = ifelse(str_detect(name, "house"), name, NA_character_),
         buildyear = ifelse(str_detect(name, "before|b\\d+"), name, NA_character_),
         old_new = ifelse(str_detect(name, "old|new|renovated"), name, NA_character_),
         payrent = ifelse(str_detect(name, "r\\d+"), name, NA_character_)) %>%
  select(-name, -value) %>%
  pivot_longer(-c(year, city, rooms, empty)) %>%
  drop_na() %>%
  group_by(year, city, rooms, empty, name) %>%
  mutate(row = row_number()) %>%
  pivot_wider(names_from = name, values_from = value) %>%
  select(-row) %>%
  data.frame()

   year city rooms empty        space  housetype  buildyear   old_new    payrent
1  2003    A     1     4   spacebel30   bighouse before1920 renovated      r1000
2  2003    A     1     4    space3150 smallhouse  b19211950       old  r10001250
3  2003    A     1     4    space5170  bothhouse  b19511980       new  r12511500
4  2003    A     1     4    space7190 otherhouse  b19811910      <NA>  r15011750
5  2003    A     1     4   space91110       <NA>      b2011      <NA>  r17512000
6  2003    A     1     4  space111130       <NA> r2251b2500      <NA>  r20012250
7  2003    A     1     4 space131plus       <NA>       <NA>      <NA> r2251b2500
8  2003    A     1     4 spaceunknown       <NA>       <NA>      <NA>  r27513000
9  2003    A     1     4         <NA>       <NA>       <NA>      <NA>  r30003250
10 2003    A     1     4         <NA>       <NA>       <NA>      <NA>  r32513500
11 2003    A     1     4         <NA>       <NA>       <NA>      <NA>  r3500plus
12 2012    B     2     1   spacebel30   bighouse before1920 renovated      r1000
13 2012    B     2     1    space3150 smallhouse  b19211950       old  r10001250
14 2012    B     2     1    space5170  bothhouse  b19511980       new  r12511500
15 2012    B     2     1    space7190 otherhouse  b19811910      <NA>  r15011750
16 2012    B     2     1   space91110       <NA>      b2011      <NA>  r17512000
17 2012    B     2     1  space111130       <NA> r2251b2500      <NA>  r20012250
18 2012    B     2     1 space131plus       <NA>       <NA>      <NA> r2251b2500
19 2012    B     2     1 spaceunknown       <NA>       <NA>      <NA>  r27513000
20 2012    B     2     1         <NA>       <NA>       <NA>      <NA>  r30003250
21 2012    B     2     1         <NA>       <NA>       <NA>      <NA>  r32513500
22 2012    B     2     1         <NA>       <NA>       <NA>      <NA>  r3500plus
23 2014    C     5     1   spacebel30   bighouse before1920 renovated      r1000
24 2014    C     5     1    space3150 smallhouse  b19211950       old  r10001250
25 2014    C     5     1    space5170  bothhouse  b19511980       new  r12511500
26 2014    C     5     1    space7190 otherhouse  b19811910      <NA>  r15011750
27 2014    C     5     1   space91110       <NA>      b2011      <NA>  r17512000
28 2014    C     5     1  space111130       <NA> r2251b2500      <NA>  r20012250
29 2014    C     5     1 space131plus       <NA>       <NA>      <NA> r2251b2500
30 2014    C     5     1 spaceunknown       <NA>       <NA>      <NA>  r27513000
31 2014    C     5     1         <NA>       <NA>       <NA>      <NA>  r30003250
32 2014    C     5     1         <NA>       <NA>       <NA>      <NA>  r32513500
33 2014    C     5     1         <NA>       <NA>       <NA>      <NA>  r3500plus
34 2011    D     2     2   spacebel30   bighouse before1920 renovated      r1000
35 2011    D     2     2    space3150 smallhouse  b19211950       old  r10001250
36 2011    D     2     2    space5170  bothhouse  b19511980       new  r12511500
37 2011    D     2     2    space7190 otherhouse  b19811910      <NA>  r15011750
38 2011    D     2     2   space91110       <NA>      b2011      <NA>  r17512000
39 2011    D     2     2  space111130       <NA> r2251b2500      <NA>  r20012250
40 2011    D     2     2 space131plus       <NA>       <NA>      <NA> r2251b2500
41 2011    D     2     2 spaceunknown       <NA>       <NA>      <NA>  r27513000
42 2011    D     2     2         <NA>       <NA>       <NA>      <NA>  r30003250
43 2011    D     2     2         <NA>       <NA>       <NA>      <NA>  r32513500
44 2011    D     2     2         <NA>       <NA>       <NA>      <NA>  r3500plus
45 2009    E     4     3   spacebel30   bighouse before1920 renovated      r1000
46 2009    E     4     3    space3150 smallhouse  b19211950       old  r10001250
47 2009    E     4     3    space5170  bothhouse  b19511980       new  r12511500
48 2009    E     4     3    space7190 otherhouse  b19811910      <NA>  r15011750
49 2009    E     4     3   space91110       <NA>      b2011      <NA>  r17512000
50 2009    E     4     3  space111130       <NA> r2251b2500      <NA>  r20012250
51 2009    E     4     3 space131plus       <NA>       <NA>      <NA> r2251b2500
52 2009    E     4     3 spaceunknown       <NA>       <NA>      <NA>  r27513000
53 2009    E     4     3         <NA>       <NA>       <NA>      <NA>  r30003250
54 2009    E     4     3         <NA>       <NA>       <NA>      <NA>  r32513500
55 2009    E     4     3         <NA>       <NA>       <NA>      <NA>  r3500plus


text:
Q: Stored procedures and the tables used by them Is there a way to know what are the tables used by one stored procedure by doing an SQL query?
Best regards, and thanks for the help.
P.S.: I'm using SQL Server 2005.

A: This article on TechRepublic
Finding dependencies in SQL Server 2005
describes a way to do that:

This tutorial will show how you can
  write a procedure that will look up
  all of the objects that are dependent
  upon other objects.

Here is the code to create the system stored procedure for finding object dependencies:
USE master
 GO
 CREATE PROCEDURE sp_FindDependencies
 (
         @ObjectName SYSNAME,
         @ObjectType VARCHAR(5) = NULL
 )
 AS
 BEGIN
     DECLARE @ObjectID AS BIGINT

         SELECT TOP(1) @ObjectID = object_id
         FROM sys.objects
         WHERE name = @ObjectName
         AND type = ISNULL(@ObjectType, type)

     SET NOCOUNT ON ;

       WITH DependentObjectCTE (DependentObjectID, DependentObjectName, ReferencedObjectName, ReferencedObjectID)
         AS
         (
         SELECT DISTINCT
                sd.object_id,
                OBJECT_NAME(sd.object_id),
                ReferencedObject = OBJECT_NAME(sd.referenced_major_id),
                ReferencedObjectID = sd.referenced_major_id
         FROM
                sys.sql_dependencies sd
                JOIN sys.objects so ON sd.referenced_major_id = so.object_id
         WHERE
                sd.referenced_major_id = @ObjectID
         UNION ALL
         SELECT
                sd.object_id,
                OBJECT_NAME(sd.object_id),
                OBJECT_NAME(referenced_major_id),
                object_id
         FROM
                sys.sql_dependencies sd
             JOIN DependentObjectCTE do ON sd.referenced_major_id = do.DependentObjectID
         WHERE
                sd.referenced_major_id <> sd.object_id
         )
         SELECT DISTINCT
                DependentObjectName
         FROM
                DependentObjectCTE c
 END

This procedure uses a Common Table
  Expression (CTE) with recursion to
  walk down the dependency chain to get
  to all of the objects that are
  dependent on the object passed into
  the procedure. The main source of data
  comes from the system view
  sys.sql_dependencies, which contains
  dependency information for all of your
  objects in the database.

A: Try sp_depends, although you should probably recompile the stored procedure to update the statistics in the database.

A: Look up sp_depends system stored proc.

A: I think that as long as the stored procedure and the tables are all in the same database then you can right click on the procedure in SSMS and click "View Dependencies".  I don't know the query behind the dialog though...

A: As others indicated you can use the Dependancies stored procedures; however, in my experience and this was back on SQL Server 2000, the depandancies were not always reliable. In some cases they weren't being updated. You can always go to the sysComments table assuming your schema is not encrypted.
declare @crlfSearch varchar(max),@objectSearch varchar(max),@escapeSearch varchar(max)

set @crlfSearch=('%bid' + char(13)+'%')
set @objectSearch='%bid %'
set @escapeSearch ='%[[]Bid]%'
select distinct so.name
from syscomments sc
inner join sysobjects so
on sc.id=so.id
where text like @objectSearch or text like @crlfSearch
or text like @escapesearch

This query looks for three common cases you might have to add some but basically we find where the table name has a space after it, (This helps to limit cases where the table name is part of another table name), Has a return at the end of it, or is escaped within brackets.


text:
Q: ngFor produces empty content - Angular 7 IVY I'm playing around with angular 7 and ivy, and I cannot get a for loop to spit out any values.
My code:
@Component({
  selector: 'app-asset-list',
  templateUrl: './asset-list.component.html',
  styleUrls: ['./asset-list.component.scss']
})
export class AssetListComponent implements OnInit {

  asset = {name: 'test'};
  assets: Asset[] = [this.asset];
  cols: any[] = [];

  colors: any[] = ['red', 'blue', 'yellow']; // EDIT: added this for debug

  constructor(private assetService: AssetService) {

  }

  ngOnInit() {
    // this.assetService.getAssets().subscribe((value => this.assets = value));
    this.cols = [
      {field: 'name', header: 'Name'}
    ];
  }

}

my html:

Asset List

{{ assets | json }}
{{ cols |json}}

 0">
  Oh, its greater than 0.

    {{a}}

    {{c}}

    {{c}}

  <ng-template pTemplate="header">

        {{col.header}}

  </ng-template>
  <ng-template pTemplate="body" let-asset>

        {{asset[col.field]}}

  </ng-template>

and the output:

As you can see, I ripped out the Observable returned from the service, and it still does not work. I'd expect to see something on the screen since the debug line shows stuff. What am I missing?
I added an array of strings colors just for more sanity checks... that still does not display. No errors in the console.
My package.json dependencies:
"dependencies": {
    "@angular/animations": "7.2.4",
    "@angular/common": "7.2.4",
    "@angular/compiler": "~7.2.4",
    "@angular/core": "7.2.4",
    "@angular/forms": "7.2.4",
    "@angular/platform-browser": "~7.2.0",
    "@angular/platform-browser-dynamic": "~7.2.0",
    "@angular/router": "~7.2.0",
    "core-js": "^2.5.4",
    "primeicons": "^1.0.0",
    "primeng": "^7.0.5",
    "rxjs": "~6.3.3",
    "tslib": "^1.9.0",
    "zone.js": "~0.8.26"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.13.0",
    "@angular/cli": "~7.3.1",
    "@angular/compiler-cli": "7.2.4",
    "@angular/language-service": "7.2.4",
    "@types/node": "~8.9.4",
    "@types/jasmine": "~2.8.8",
    "@types/jasminewd2": "~2.0.3",
    "codelyzer": "~4.5.0",
    "jasmine-core": "~2.99.1",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~3.1.1",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~1.1.2",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.4.0",
    "ts-node": "~7.0.0",
    "tslint": "~5.11.0",
    "typescript": "~3.2.2"
  }

I couldn't replicate in a stackblitz... problem is related to ivy I believe. That being said, here is a stackblitz.

A: I ran into the same exact issue when running the --experimentalIvy flag in a new CLI project.
I've also created an issue:
https://github.com/angular/angular/issues/30081
With that said,
I've tried to update core and cli to the next version using:
ng update @angular/core@next @angular/cli@next

And it works on V8.0.0-beta.14, so...I'm not sure someone will fix it in version 7 while 8 is close to release.
Also created a Github repo with separated branches for easy reproduce, you can check it here: https://github.com/eliraneliassy/ivy-ngfor-bug

A: You might need to access a property using the dot operator inorder to see the output, otherwise it will be just [Object Object]

    {{a.name}}

STACKBLITZ


text:
Q: react navigation version 5, hide top bar when render tab screen I've created nested navigation using react-navigation version 5, But when tab screen render I need to hide top bar, I've follow step from here https://reactnavigation.org/docs/hiding-tabbar-in-screens/ but still not working
import * as React from 'react';
import {NavigationContainer} from '@react-navigation/native';
import {createStackNavigator} from '@react-navigation/stack';
import {createBottomTabNavigator} from '@react-navigation/bottom-tabs';

import {navigationRef} from './NavigationService';

import {Home, Appointment, Settings, Map, ProviderDetails} from 'app/screens';
import {PRIMARY_COLOR, SECONDARY_COLOR} from '../config/color';
import ThemeController from '../components/ThemeController';
import {StatusBar} from 'react-native';
import FontAwesome5 from 'react-native-vector-icons/FontAwesome5';
import MaterialIcons from 'react-native-vector-icons/MaterialIcons';

const Stack = createStackNavigator();

const homeOptions = {
  title: 'Home',
  headerTitleStyle: {
    fontWeight: 'bold',
  },
  headerRight: () => <ThemeController />,
};

const HomeStack = () => {
  return (
    <Stack.Navigator>
      <Stack.Screen name="Home" component={Home} />
    </Stack.Navigator>
  );
};

const MapStack = () => {
  return (
    <Stack.Navigator>
      <Stack.Screen name="Map" component={Map} />
      <Stack.Screen name="ProviderDetails" component={ProviderDetails} />
    </Stack.Navigator>
  );
};

const Tab = createBottomTabNavigator();

function App(props) {
  const {theme} = props;

  return (
    <NavigationContainer ref={navigationRef} theme={theme}>
      <StatusBar barStyle={theme.dark ? 'light-content' : 'dark-content'} />
      <Tab.Navigator
        screenOptions={({route}) => ({
          tabBarIcon: ({focused, color, size}) => {
            if (route.name === 'Home') {
              return <MaterialIcons name="home" size={size} color={color} />;
            } else if (route.name === 'Map') {
              return (
                <FontAwesome5 name="map-marked-alt" size={size} color={color} />
              );
            } else if (route.name === 'Appointment') {
              return (
                <FontAwesome5 name="calendar-alt" size={size} color={color} />
              );
            } else if (route.name === 'More') {
              return (
                <MaterialIcons name="more-horiz" size={size} color={color} />
              );
            }
          },
        })}
        tabBarOptions={{
          activeTintColor: PRIMARY_COLOR,
          inactiveTintColor: SECONDARY_COLOR,
        }}>
        <Tab.Screen name="Home" component={HomeStack} />
        <Tab.Screen name="Map" component={MapStack} />
        <Tab.Screen name="Appointment" component={Appointment} />
        <Tab.Screen name="More" component={Settings} />
      </Tab.Navigator>
    </NavigationContainer>
  );
}

export default App;

Create HomeStack and MapStack stack navigator and pass that value to Tab Navigator,
In bellow image you can see in Home and Map tab display top bar.

A: Use headerShown option
const HomeStack = () => {
  return (
    <Stack.Navigator>
      <Stack.Screen name="Home" options={{ headerShown: false }} component={Home} />
    </Stack.Navigator>
  );
};


text:
Q: inconsistent rounding in R for the same value I'm getting some very bizarre behaviour in R and I cannot figure it out for the life of me.  Minimum viable example follows:
x <- c(1, 1, 6, 1)
y <- c(0, 5)
z <- c(4, 0, 0, 2, 0, 5)

x90 <- quantile(x, 0.9)
y90 <- quantile(y, 0.9)
z90 <- quantile(z, 0.9)

c(x90, y90, z90)
round(c(x90, y90, z90), 0)

The output is:
> c(x90, y90, z90)
90% 90% 90%
4.5 4.5 4.5
> round(c(x90, y90, z90), 0)
90% 90% 90%
  5   4   4

Can someone tell me why 4.5 sometimes rounds to 4, but not always, please?
Some system info:

*

*R version: 3.6.2 (2019-12-12)

*RStudio version: 1.1.456

*Platform:
i386-w64-mingw32/i386 (32-bit)

Thanks in advance,

A: By default, R only shows 7 digits of precision; all of x90, y90, and z90 are equal to 4.5 to 7 significant digits, but printing more significant digits shows that x90 is slightly greater than 4.5 (because floating point math is imprecise).
print(c(x90,y90,z90),digits=20)
                  90%                   90%                   90%
4.5000000000000008882 4.5000000000000000000 4.5000000000000000000

For deeper understanding you would have to dig into the details of the quantile calculation, but most people (including me) usually leave it at "floating point math is imprecise, live with it".


text:
Q: How can I control formatting of a Property Mapping in a Content by Search Web Part? (SP2013) I am currently having fun formatting a Content by Search web part in SharePoint 2013, but the formatting of individual values (through Property Mappings) has got me properly stuck.
I already have myself a custom Control_Custom.js and Item_Custom.js using the HTML display templates but there doesn't seem to be anything in there that governs how these property mappings are formatted / rendered.
Lets take a look at the formatting of a Date/Time field which always outputs in the format "dddd, MMMM d, yyyy".
For example - Tuesday, February 5, 2013
I have tried pulling through various different Property Mappings into my Content by Search including both:

*

*Created

*CreatedOWSDATE

Both of these output exactly the same format.
I ran into exactly the same problem when trying to work with user accounts (say, show the person who last edited a document, or wrote a blog post).
With Person fields the formatting appears to always output the Display Name of the user account (e.g. "Martin Hatch"). Again this was identical for:

*

*Author

*AuthorOWSUSER

*DisplayAuthor

I basically want to have more control over how these values are output and formatted. In the case of date fields I want to reformat the date (which I'm sure I could work out using substring functions then and converting it to a date object, but that seems FAR too messy for me).
For the user field I really want the login name (or ideally their profile picture) but with just the display name there is very little I can do with it.
Any ideas? How on earth do these property mapping values get formatted?

A: You can override rendering of different field formats, have a look here http://blog.jussipalo.com/2013/03/sharepoint-2013-overriding-value.html

A: Welcome to SharePoint StackExchange!
If you set the webpart to render server side, you can control the formatting with xslt.
RenderOnServer=true

You can then format dates and things as you need them:
<xsl:value-of select="ddwrt:FormatDate(@Created, 1033, 2)"/>

This will do a short date with a time for example.
As for the usernames, I don't think that anything other that what is stored is accessible. The value which would be stored is the user id and the display name only I think. I will take a look and amend this if I am wrong.
HTH

A: First thing I would suggest is to check what do you get from search as the values for Author and Created managed properties. Probably, an easiest way to do it is REST search api. Say, you added an item named 'qwerty' to a list, and you crawled it. This is how you can get the value of Author and Created managed properties:
http://myServer/sites/mySite/_api/search/query?Querytext='qwerty'&SelectProperties='Author,Created'

Now, if you inspect the values for Author and Created, you would see that Author contains only display name of a user, and Created contains a string in specific date/time format.
If you are not satisfied with what value is stored in Author managed property, you can do the following:

*

*Create site column of type 'Person or Group' and name 'MyUser'

*Add site column to the list with your item

*Add value for list item manually

*Crawl

*The value of user will be available in property 'MyUserOWSUSER' and should contain more than just display name

You can still change rendering of any values shown by Content Search web-part via client-side rendering with Display Templates (you don't necessarily need to use server-side rendering). I believe that Display Templates is an easier option than XSLT (but that's just my point of view).


text:
Q: Whatever item in a table is clicked, put that value on a hidden input I need whatever item clicked on a table to be captured and putted in a hidden input.
This is as far as I got:

var $rows = $('#table tbody tr');
$('#search').keyup(function() {
    var val = '^(?=.*\\b' + $.trim($(this).val()).split(/\s+/).join('\\b)(?=.*\\b') + ').*$',
        reg = RegExp(val, 'i'),
        text;

    $rows.show().filter(function() {
        text = $(this).text().replace(/\s+/g, ' ');
        return !reg.test(text);
    }).hide();
});
$('td').click(function() {
    var txt = $('td:first-child').text();
    $('#tipo').val(txt);
});

    Filtrar:
    <input type="text" class="form-control" placeholder="" aria-describedby="rotulo" id="search">

        1st Value

        2nd Value

        3rd Value

<input type="text" id="tipo" value="">

The problem is, whatever value I click, many items in the table are selected, even when this first item is hidden.
Jquery is being used.

A: td:first-child is selecting the first child td, that's why you are always getting the first element.
The clicked element text can be retrieved by using $(this).text()

A: You can also do the following:
$('td').click(function() {
  var txt = $('.table').find('td:visible:first').text();
  $('#tipo').val(txt);
});

It will find the first visible element in the table and outputs its text.
Working fiddle here.


text:
Q: Flickering animation with UIViewAnimationTransitionFlip I have a containerview with 2 subviews. I want to flip from one to another. The problem is that some kind of flickering appears. It doesn't happen on the iPhone 3GS, but on the Simulator and the iPhone 3G:
http://www.hanspinckaers.com/upload/Flickering.png
Does anyone know why this happens?
This is the code:
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration: 0.75];
[UIView setAnimationDidStopSelector:@selector(afterAnimationProceed)];
[UIView setAnimationDelegate:self];
[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:self.containerView cache:YES];

if(self.mapViewController.view.superview){
    [self.mapViewController.view removeFromSuperview];
    [self.containerView addSubview:self.tableController.view];
} else {
    [self.tableController.view removeFromSuperview];
    [self.containerView addSubview:self.mapViewController.view];
}

[UIView commitAnimations];

Thanks in advance!
Hans

A: fyi flickering usually happens when you have 2+ seperate caanimations working, try to put them all into a single animation block and commit the groups animations.

A: I can't reproduce your problem but I do get issues if the tableview or mapview is scrolling when the transition starts.
Perhaps disabling user interaction and stopping any scrolling etc just before doing the transition will help?
Apart from that, sorry!
Sam


text:
Q: Angular JS calculation based on input boxes I read this thread:
Simple Percentage Calculation of an Input Field with JQuery
But can't seem to get it to work for my situation. I have two input boxes, Wholesale and Sell Price, and I want to calculate the markup (difference) on the fly as the user is changing their Sell Price.  I've built a simplified version of what I'm trying to do here:
http://jsfiddle.net/schuss/rp0brqj1/2/
And below is the JS - can anyone see what I'm doing wrong?  Thanks!!

$(function() {

    // cache elements that are used at least twice
    var $sellprice = $("#SellPrice"),
        $markup = $("#markup"),
        $wholesale = $("#wholesale");

    // attach handler to input keydown event
    $sellprice.keyup(function(e){
        if (e.which == 13) {
            return;
        }
        var sellprice = parseFloat($sellprice.val()),
            markup = sellprice-wholesale;

        if (isNaN(sellprice)) {
            $markup.hide();
            return;
        }
        else {

        $markup.fadeIn().text(markup.toFixed(2));

        }
    });

});

A: You want to set the value of input field, so in this case you need to use $.fn.val method:
$markup.fadeIn().val(markup.toFixed(2));

Demo: http://jsfiddle.net/rp0brqj1/6/

A: Try this (I haven't included the else - and don't forget to include JQuery in your fiddles!):
$(function() {

  var $sellprice = $("#SellPrice"),
    $markup = $("#markup"),
    $wholesale = $("#Wholesale");
  $sellprice.on('keyup', function(){
     $markup.val(parseFloat($sellprice.val()-$wholesale.val()))
  });

});

Fiddle


text:
Q: access specific cell from CSV file in Matlab I want to access specific cell from CSV file table in Matlab.
For example, the CSV file is 4x4, and I want to access cell 1,3
1;1;5;1
1;1;1;1
1;1;1;1
1;1;1;1

Which is 5 in this example

A: Something like that?
data = csvread(filename); % whatever your filename is, see doc on csvread
data_of_interest = data(1,3);


text:
Q: Get list of objects that support getDeleted() We are trying to capture the deletes for certain objects in Salesforce. For most of the objects we can use the queryAll() to get the isDeleted column. For the ones that don't have the isDeleted column, we check if that object is replicateable, if so, we make calls to the getDeleted() API to get the deleted records.
The problem is that for certain objects like CurrencyType, salesforce documentation does not have getDeleted in the supported calls list - https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_objects_currencytype.htm
For such entities, the getDeleted() API does not throw an error. Instead, it captures the changes to the object in the result.
So, coming to the question is there a way to tell if we should not query getDeleted() for certain objects like the CurrencyType?

A: After lot of research and as per this doc: https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/object-specific_requirements_for_data_replication.htm, I came to know that field "replicateable" is responsible for getUpdated() and getDeleted() calls i.e if field "replicateable" is true then these calls are supported.
But problem arises when one call is supported and another one not; in this case still "replicateable" is true.
So would be better if you contact salesforce to confirm this.


text:
Q: Relation of Higgs couplings to masses of fundamental particles The standard model has 12 massive leptons and 2 massive bosons other than the Higgs. My understanding of the Higgs mechanism is at about the level of this article, which goes as follows. Start with the massless Klein-Gordon equation for two fields, H and Z: $\nabla^2 H=0$ and $\nabla^2 Z=0$. Then modify the two equations to let H (the Higgs) have a v.e.v., and by adding an interaction term to the Z field's wave equation, $\nabla^2 Z=kH^2Z$. Since $H$ has a v.e.v., this looks exactly like the Klein-Gordon equation for a particle of mass $m$, with $m^2=kH^2$.
So extrapolating naively, I'd guess we have 14 coupling constants, $k_1$ through $k_{14}$, that have to be put in arbitrarily by hand and that determine the 14 masses that we observe in the low-energy limit for the standard model's 14 massive, fundamental particles.
Is this naive extrapolation accurate, or does $m_j$ actually depend not just on $k_j$ but also on the $k_i$ with $i\ne j$? If there is an interdependence, is it something that can be expressed linearly? Does chiral symmetry breaking (which I know nothing about) change the whole picture qualitatively? If there is an interdependence, do we get any prospect of a natural explanation for the features of the mass spectrum we see (e.g., why the masses cover such a huge range, from meV to TeV)?
Regardless of whether there is interdependence, is there any naturalness argument to explain why we see real-valued masses, as opposed to, say, imaginary masses, which would seem perfectly natural if there were no reason to prefer $k>0$?

A: You ask good questions.

*

*The massive gauge bosons, the $W$ and the $Z$, obtain their masses from electroweak gauge interactions with the Higgs field
$$
\sim g^2 H^2 A^2
$$
Upon $H\to v+ h$, the boson acquires a mass. Such terms were already present, and thus we require no extra couplings.

*The massive fermions, leptons and quarks (but in the Standard Model neutrinos are massless), obtain their masses from Yukawa interactions
$$
YH\psi\psi
$$
Upon $H\to v+ h$, the fermion acquires a mass. The Yukawa couplings, Y, are without loss of generality $3\times 3$ complex matrices: one for up-type quarks $(u,c,t)$, down-type quarks $(d,s,b)$  and leptons $(e,\mu,\tau)$. We do not need a fourth matrix, because neutrinos are massless. In princple, it looks like we have $2\times3\times3\times3=54$ new real parameters.
Now, we can be clever and rotate the fields $\psi$ so that the
Yukawa matrices are real and diagonal (and hence the masses are
real). For the leptons, its easy, we can remove all complex phases
and off-diagonal elements leaving 3 diagonal elements - the three
real lepton masses.
For the quarks, its more difficult, because we want to
simultaneously diagonalize the up-type quarks $(u,c,t)$ and
down-type quarks $(d,s,b)$ matrices. In fact, it's impossible,
because of the structure of the electroweak interaction. We rotate
the up-type fields so that their matrix is real and diagonal, with
three real masses. We then see what we can do with the down-type
matrix. It turns out, that along with its three masses, we are left
with $4$ angles.
So it turns out we have no new parameters for the gauge bosons, 3 for the three lepton masses, 6 for the six for the quark masses plus 4 angles that we couldn't get rid of by field rotations, making 13 in total.
Note that of the $4$ angles that we couldn't get rid of, $3$ are just rotation angles in a $3\times3$ matrix, but the final one is a complex phase that is the only source of CP-violation in the Standard Model.


text:
Q: how to add self define tag attribution for UIView with Objective C Assume that there is property like this:
@property (nonatomic, copy) NSString* tag;

What I wanna implement is make any subclass of UIView can set there tag, like this:
UIButton * btn = [UIButton alloc] init...];
UILabel *lbl = [UILabel alloc]init...];
btn.tag = @"1";
lbl.tag = @"2";

what I try to resolve this is using category, however, it's difficult to implement setter method for instance in Category except use " Associated Objects".
Are there any other method to implement this function?


text:
Q: jQuery/Ajax like button not working properly second time I'm trying to create an Ajax like button for my Django project(Python's framework). Basically, what I'm doing is making a partial update on index.html when the Ajax call is a success. It works fine the first time, but when a button with the same id is clicked for the second time, it will reload the entire page, which is not what I expect. Could anyone teach me how to prevent this from happening?
I'm not sure if the Python side has anything to do with this, but I'm going to paste some of the codes anyway. Thank you.
main.js
  $('button').on('click', function(event){
      event.preventDefault();
      var element = $(this);
      $.ajax({
        url : element.attr("data-id") + '/like/',
        type : 'POST',
        data : { card_id : element.attr("data-id")},
        success : function(response){
          console.log(response);
          $('#like-area-' + element.attr("data-id")).load(document.URL +  ' #like-area-' + element.attr("data-id"));
        }
      })
    })

// using jQuery
function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}
var csrftoken = getCookie('csrftoken');

function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    }
});

templates/index.html
{% for card in cards %}

......

        <form  method="post">
                {% csrf_token %}
                <button data-id="{{ card.id }}" class="btn btn-default">いいね</button>
        </form>

.....

{% endfor %}

views.py
def like_post(request, card_id):
    if Like.objects.filter(liker=request.user, liked_post = card_id).exists():
        existing_like = Like.objects.get(liker=request.user, liked_post = card_id)
        existing_like.delete()
        likes = Like.objects.all()
        is_liked = 0
        # return HttpResponse(likes)
        return HttpResponse(is_liked) #not really using this yet
    else:
        card = Card.objects.get(id=card_id)
        new_like = Like(liker=request.user, liked_post = card)
        new_like.save()
        # likes = Like.objects.all()
        likes = Like.objects.all()
        is_liked = 1
        return HttpResponse(is_liked) #not really using this yet

urls.py
url(r'^(?P<card_id>[0-9]+)/like/$', views.like_post, name='like-post'),

A: I just read your request: ajax cần't click 2 time (need reload or it auto reload page)
~> Create a var for ajax and abort it.
var ajaxcall1
def ...
if (ajaxcall1)
        ajaxcall1.abort();
# some more code

You can try it, i just think you don't check the status. If not, i will check for more detail late


text:
Q: MasterPage with multiple contentplaceholders I have a default.aspx file that is tied to the MasterPAge and ContentPlaceHolder1 and displays fine, is there a way to have another page say info.aspx auto display in ContentPlaceHolder2?

A: Think of ContentPlaceHolder's as "fill-in-the-blanks" for MasterPages.  I think what you're looking for is more along the lines of a User Control, which is a piece of content/functionality that you can plug in anywhere you want.

A: If there a way you can turn the content of Info.aspx into a usercontrol( should be very easy ),
if so this is an easy problem to solve, put that new ascx in the placeholder on the masterpage.
On Master:

    <asp:ContentPlaceHolder ID="cph_MainContent" runat="server">
    </asp:ContentPlaceHolder>

    <asp:ContentPlaceHolder ID="cph_BottomContent" runat="server">

    </asp:ContentPlaceHolder>

then you just comment out or delete the tags for the 2nd place holder on you Content Pages:
<asp:Content ID="Content2" ContentPlaceHolderID="cph_MainContent" runat="server">
 you page content
</asp:Content>

<%--
this will make the master use the content inside the holder on its own page

<asp:Content ID="Content3" ContentPlaceHolderID="cph_BottomContent" runat="server">

</asp:Content>
--%>


text:
Q: Limit output framerate to maximum 30 I have a bunch of videos in a folder to convert. The videos come in a variety of container formats - mp4, mkv, avi, mpg, etc. All I would do is to drag videos into this folder and I run a script to read each file in the folder and execute ffmpeg to convert each video to a specific setting.
What I want to do is to set the output framerate of each video to the following logic:

*

*if the input framerate is 30 fps or less, keep the output framerate to the input file framerate, eg. if the input framerate is 24 fps.

*if the input framerate is more than 30, set the output framerate to 30 fps, eg. if the input framerate is 60 fps.

eg. something like: if=input<=30fps -r input_framerate else=input>30fps -r 30
I have read the documentation and more than two hours of Googling, but did not find a suitable command to do this.
Please enlighten.


text:
Q: How can I make my PhoneGap android app onPause by overwriting BackButton? I'm trying to develop an android app with phonegap and LocalNotification plugin.
I want to running my app in onPause ,
On my index.html
document.addEventListener("pause", onPause, false);

function onPause() {
    // Handle the pause event
setInterval( function() {
    Ext.data.JsonP.request({
            url: 'http://convert4mobile.net/backend/API/qr/push.php',
            callbackKey: 'callback',
            success: function(data)
            {

                if(data.success == true)
                {
                    if (typeof plugins !== "undefined") {
              window.plugins.localNotification.add({
                        date : new Date(),
                        message : data.time+"\r\n"+data.msg,
                        ticker : "A new code was generated",
                        repeatDaily : false,
                        id : 4
                });
                }
                }
            }
           });
} , 2000);

}
It works fine when the app was closed/minimized by home button/end call button.
I want to do the same thing by BackButton tapping.
Any idea??

A: Enter whatever code you want in this method:
@Override
public void onBackPressed() {
    // TODO Auto-generated method stub
    super.onBackPressed();
}

Tutorial Here: http://chrisrisner.com/31-Days-of-Android--Day-10%E2%80%93The-Back-Button


text:
Q: Getting absolute values of double array in Swift I have a double array of the type:
    let a = [-1.0, 2.0, 3.4, -4.12, -0.05, 5.5]

Is there an easy way to get its absolute values:
    let aAbs = [1.0, 2.0, 3.4, 4.12, 0.05, 5.5]

Thanks!

A: A simple map will do it:
let a = [-1.0, 2.0, 3.4, -4.12, -0.05, 5.5]
let aAbs = a.map { abs($0) }

A: Even simpler, you can pass the abs function directly:
let absolutes = inputs.map(abs)


text:
Q: Habilitar SSL3 en java Tengo un programa que se conecta a casillas de correo, a través de IMAP, pero hay algunas casillas de clientes que, cuando el programa intenta establecer la conexión, arroja la siguiente excepción:

Server choose SSLv3, but that protocol version is not enabled or not
  supported by the client.

Quisiera saber cómo puedo habilitar ese protocolo desde mi programa, si existe alguna propiedad o algo así que se pueda establecer. Ya busqué en varios lados pero no he dado con la solución.
La aplicación está hecha con java 8 u66.

A: Ve a la carpeta de instalación del JRE

*

*Abre este archivo en un editor de texto: $JRE_HOME\lib\security\java.security

*Busca la linea que dice jdk.tls.disabledAlgorithms=SSLv3 y coméntala o elimínala.

Luego vuelve a intentarlo.
Por cierto, tanto desde Java 8 update 31/Java 7 update 76 que SSLv3 viene deshabilitado por defecto. 1
Cabe destacar que SSLV3 esta obsoleto y no deberia usarse salvo que sea absolutamente necesario debido a vulnerabilidades.

A: Al final quité unas líneas del código, donde ponía que usara seguridad, y funcionó correctamente. Las líneas que saqué fueron las siguientes:
propiedades.put("mail.imap.ssl.enable", "true");
propiedades.setProperty("mail.imap.ssl.trust", servidor);

Al final el cliente no tenía habilitada la seguridad, pero el java me arrojaba como que estaba usando SSLv3.


text:
Q: Find out the current size of Collection and size of each module inside a collection of a TFS repository I am using Team Foundation Server in my project. The requirement is to find out the

*

*Current size of Collection

*Current size of each module inside a Collection

A: Each team project collection has a database. Each database stores the data for the team projects (version control, builds, and work items) in that collection.

You can run reports for the collection database to check collection size and table size. But we always not recommend to deal with database directly, make sure you have full backup of database before any operation on it.


text:
Q: Matrix multiplication using hdf5 I'm trying to multiplicate 2 big matrices with memory limit using hdf5 (pytables)
but function numpy.dot seems to give me error:

Valueerror: array is too big

I need to do matrix multiplication by myself maybe blockwise or there is some another python function similar to numpy.dot?
import numpy as np
import time
import tables
import cProfile
import numexpr as ne

n_row=10000
n_col=100
n_batch=10

rows = n_row
cols = n_col
batches = n_batch

atom = tables.UInt8Atom()  #?
filters = tables.Filters(complevel=9, complib='blosc') # tune parameters

fileName_a = 'C:\carray_a.h5'
shape_a = (rows*batches, cols)  # predefined size

h5f_a = tables.open_file(fileName_a, 'w')
ca_a = h5f_a.create_carray(h5f_a.root, 'carray', atom, shape_a, filters=filters)

for i in range(batches):
    data = np.random.rand(rows,cols)
    ca_a[i*rows:(i+1)*rows]= data[:]
#h5f_0.close()

rows = n_col
cols = n_row
batches = n_batch

fileName_b = 'C:\carray_b.h5'
shape_b = (rows, cols*batches)  # predefined size

h5f_b = tables.open_file(fileName_b, 'w')
ca_b = h5f_b.create_carray(h5f_b.root, 'carray', atom, shape_b, filters=filters)

#need to batch by cols
sz= rows/batches
for i in range(batches):
    data = np.random.rand(sz, cols*batches)
    ca_b[i*sz:(i+1)*sz]= data[:]
#h5f_1.close()

rows = n_batch*n_row
cols = n_batch*n_row

fileName_c = 'C:\carray_c.h5'
shape_c = (rows, cols)  # predefined size

h5f_c = tables.open_file(fileName_c, 'w')
ca_c = h5f_c.create_carray(h5f_c.root, 'carray', atom, shape_c, filters=filters)

a= h5f_a.root.carray#[:]
b= h5f_b.root.carray#[:]
c= h5f_c.root.carray

t0= time.time()
c= np.dot(a,b) #error if aray is big
print (time.time()-t0)

Update: so here is the code.It's interesting but using hdf5 it works even faster.
import numpy as np
import tables
import time

sz= 100 #chunk size
n_row=10000 #m
n_col=1000 #n

#for arbitrary size
A=np.random.rand(n_row,n_col)
B=np.random.rand(n_col,n_row)
# A=np.random.randint(5, size=(n_row,n_col))
# B=np.random.randint(5, size=(n_col,n_row))

#using numpy array
#C= np.zeros((n_row,n_row))

#using hdf5
fileName_C = 'CArray_C.h5'
atom = tables.Float32Atom()
shape = (A.shape[0], B.shape[1])
Nchunk = 128  # ?
chunkshape = (Nchunk, Nchunk)
chunk_multiple = 1
block_size = chunk_multiple * Nchunk
h5f_C = tables.open_file(fileName_C, 'w')
C = h5f_C.create_carray(h5f_C.root, 'CArray', atom, shape, chunkshape=chunkshape)

sz= block_size

t0= time.time()
for i in range(0, A.shape[0], sz):
    for j in range(0, B.shape[1], sz):
        for k in range(0, A.shape[1], sz):
            C[i:i+sz,j:j+sz] += np.dot(A[i:i+sz,k:k+sz],B[k:k+sz,j:j+sz])
print (time.time()-t0)

t0= time.time()
res= np.dot(A,B)
print (time.time()-t0)

print (C== res)

h5f_C.close()

A: I don't know of a np.dot that work without loading into memory.  I think blocking would work pretty well.  Create a an output array (called "c" below) as pytables CArray and fill in blocks.  You should choose the chunkshape when you create it to match your blocking scheme.  Something like
atom = tables.Float32Atom() # you have UInt8Atom() above.  do you mean that?
shape = (a.shape[0], b.shape[1])

# you can vary block_size and chunkshape independently, but I would
# aim to have block_size an integer multiple of chunkshape
# your mileage may vary and depends on the array size and how you'll
# access it in the future.

Nchunk = 128  # ?
chunkshape = (Nchunk, Nchunk)
chunk_multiple = 1
block_size = chunk_multiple * Nchunk
c = h5f.create_carray(h5.root, 'c', atom, shape, chunkshape=chunkshape)

for i_start in range(0, a.shape[0], block_size):
    for j_start in range(0, b.shape[1], block_size):
        for k_start in range(0, a.shape[1], block_size):
            c[i_start:i_start+block_size, j_start:j_start + block_size] += \
                    np.dot(a[i_start:i_start + block_size, k_start:k_start + block_size],
                           b[k_start:k_start + block_size, j_start:j_start + block_size]