text:
Q: No thumbnails in GNOME files on a Guix system GNOME Files (Nautilus) fails to generate thumbnails on an up-to-date Guix system, which is a known outstanding issue. Small empty files just go to ~/.cache/thumbnails/fail/gnome-thumbnail-factory. While this is being debugged and fixed, is there another way to browse files with thumbnails being displayed?

A: As a workaround, it is possible to use Thunar instead for browsing the files. For it to generate thumbnails, Tumbler is also needed:
$ guix install thunar tumbler

Once Thunar generated thumbnails in the directories that you browse with it, those thumbnails will also show up in GNOME Files, so you are not restricted to using Thunar with this approach.

A better way to do this is to add (service xfce-desktop-service-type) to the list of operating system services. This allows to augment the environment to provide a better integrated Thunar. (See Desktop Services section in the Guix Manual.) For example, it will remember your zoom level for thumbnails size from the previous run.

A: Another option is to install the development version of Nautilus (org.gnome.NautilusDevel) with Flatpak. The Flatpak version generates thumbnails. (I used the answer to a different question, including comments, to setup Flatpak on Guix. Then I followed the official guide for nightly GNOME apps.) It will not allow you to open any files, unless you install xdg-desktop-portal-gtk.


text:
Q: GIT merge from base branch to "child" branch but maintain some changes in "child" branch I have a base branch with Dolibarr code with custom code.
Then I have 2 branches company_a and company_b.
In branch "custom" I make changes to Dolibarr's base code that we want in both companies.
Then in each branch I make changes that are only specific to each company.
The problem is when I have to touch core code in company_b and later I make a change for both companies in custom.
If I merge custom to company_b (and it just so happens that I don't get a merge conflict) I lose the changes made in company_b.
How can I deal with this?
According to ChatGPT I could do
git switch company_b
git merge custom
git rebase custom

but , who knows. I tried just in case and the changes I made in company_b, specifically deleting a part of the code, are missing and the code I deleted is back.

Am I understanding this right??
Start
▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁
| code from custom branch |
▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁
| code from custom branch | code from company_a branch |
▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁
| code from custom branch | code from company_b branch |
▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔

Start + Merge
▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁
| code from custom branch with changes |
▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁
| code from custom branch | code from company_a branch | code from custom branch with changes |
▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁
| code from custom branch | code from company_b branch | code from custom branch with changes |
▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔

Start + Merge + Rebase
▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁
| code from custom branch with changes |
▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁
| code from custom branch | code from custom branch with changes | code from company_a branch |
▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁
| code from custom branch | code from custom branch with changes | code from company_b branch |
▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔

Start + Rebase
▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁
| code from custom branch with changes |
▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁
| code from custom branch with changes | code from company_a branch |
▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁
| code from custom branch with changes | code from company_b branch |
▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔

Edit:
I think all I need, for my specific case, is to rebase.
That way all changes made in custom will be shared between branches while maintaining branch specific changes.
Can someone confirm?

A:
The problem is when I have to touch core code in company_b and later I make a change for both companies in custom.

If you do rebase company_b on top of the base branch custom (same for company_a), then both branch can benefit from the common evolution.
git switch company_b
git rebase common
git push --force

The drawback of that approach is that you will need to force push company branches, which can be problematic if more than one collaborator is working on those branches: that would need to fetch, then rebase their own local commits on top of origin/company_x, which would have been reset to the new history.
And you might still need to resolve conflicts, but I would look into git rerere that I mentioned in "Are there any downsides to enabling git rerere?" (to avoid having to resolve them on every rebase).
But, depending on your development workflow (meaning if there is no company local development in progress while those branches are rebase/force pushed), that can still be a valid option.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Designing AND gate using transistors I am asked to design AND gate using transistors on Multisim simulator
AND Logic Gate: Design and implement AND Logic Gate, which gives high output voltage if and only if its two inputs are at a high voltage level.
should be implemented using BJT transistors.
High voltage level: 3-5 Volts
Low voltage level: 0-0.7 Volts
Vcc= 5V
I should analyse the circuit and get all the resistors value. Can someone help me doing it please ?

A: Here is a AND gate implemented with a BJT transistor. But I'm pretty sure this is not what you're supposed to do.

simulate this circuit – Schematic created using CircuitLab
Since your question looks much like homework, you should consider (and tell us) what you were taught recently.
You should also tell us what you tried and how far you went.


text:
Q: Dangers/side-effects of using PHP's ternary operator as a control structure A coworker frequently uses PHP's ternary operator as a control structure, rather than the RHS of an expression. One such example:
list==''?list=val:list=list+','+val;

(In that example, the statement is called in a loop to add values to a string, ensuring the comma separator doesn't appear if there's only one item.) In essence, he relies on the expression evaluation to do work, and throws away the expression result.
Aside from the fact that it's hard on the eyes, is there any reason to avoid this construct? It's syntactically legal; and it executes correctly. But I'm certain the ternary operator wasn't designed to be used in this manner, and I wonder if there are consequences to doing so.

A: It will work fine, and I don't see any problem with it apart from readability.
If you think it's hard on the eyes, replace this loop and line with a call to the implode function.


text:
Q: Filtering records in one dataframe based on matching values from another dataframe I have a dataframe, for example:
import pandas as pd
data = {'Name':['Tom', 'nick', 'krish', 'Emma'], 'Age':[20, 21, 19, 18], 'Sex':['M','M','M','F'}
# Create DataFrame
df_all = pd.DataFrame(data)

And another dataframe, for example:
queries= {'Name':['Tom', 'nick']}
df_some = pd.DataFrame(data)

I need a new dataframe that will contain only the records of df_all where the "Name" column in "df_some" matches with "Name" column in "df_all".
For example, the resulting data frame should only have two rows (Tom and nick). For example:
Tom  20 M
nick 21 M


text:
Q: Regular Expression Help for Date Validation - dd/mm/yyyy - PHP Can someone show me the error of my ways when it comes to this regular expression:
if(preg_match("/^[0-9]{1,2}/[0-9]{1,2}/[0-9]{4}$/", $_POST["date"]) === 0) {
   echo 'error';
}

Basically I want this to display an error message each time - unless the format is correct (dd/mm/yyyy).
What am I doing wrong with the above?
Many thanks for any pointers.
-- updated regex above shortly after posting - apologies for inconvenience --

A: You need to escape the slash since you are using it as regex delimiter
/^[0-9]{1,2}\/[0-9]{1,2}\/[0-9]{4}$/

or use different regex delimiters
#^[0-9]{1,2}/[0-9]{1,2}/[0-9]{4}$#

A: You can also use this one:
([0-2]\d|3[0-1])\/(0\d|1[0-2])\/(19|20)\d{2}

if you want to differentiate between dates and months, but also validate only 2 centuries.

A: I use this for checking dates
private function validate_date( $date, $empty_allowed = true ) {

    if ( empty( $date ) ) {
        return $empty_allowed;
    }

    if ( ! strpos( $date, '/' ) ) {
        return false;
    }

    if ( substr_count( $date, '/' ) !== 2 ) {
        return false;
    }

    if ( preg_match( '/(0[1-9]|1[0-9]|3[01])\/(0[1-9]|1[012])\/(2[0-9][0-9][0-9]|1[6-9][0-9][0-9])/', $date ) !== 1 ) {
        return false;
    }

    $split = explode( '/', $date );

    return checkdate( $split[1], $split[0], $split[2] );

}

A: I think you should escape the slashes /^[0-9]{1,2}\/[0-9]{1,2}\/[0-9]{4}$/

A: This is the easiest way to solve your problem.
^([0-2][0-9]|(3)[0-1])(\/)(((0)[0-9])|((1)[0-2]))(\/)\d{4}$

Output looks Like=> 31/12/2019
Test Demo


text:
Q: C++ Read Access Violotion 0xCDCDCDCD I am creating a program for a class where I need to use an array of pointers. When the program is compiled and begins to run, I then receive a error message saying:
 "Unhandled exception thrown: read access violation. this was 0xCDCDCDCD."

Is anyone able to look at the code below and help point me toward the issue? I've gone through it many times and cannot figure it out (I'm using Visual Studio 2019). Any help would be greatly appreciated.
using namespace std;
#include <string>
#include "roster.h"
#include "student.h"
#include <iostream>
#include<iomanip>
#include "degree.h"
#include <array>

//add array of pointers (classRosterArray) to hold data in studentDataTable
//Create student object for each student and populate classRosterArray
    //parse each set of data IDed in studentDataTable
    //add each student object to classRosterArray

Roster::Roster()
{
    this->capacity = 0;
    this->lastIndex = -1;
    this->classRosterArray = nullptr;
}

Roster::Roster(int capacity)
{
    this->capacity = capacity;
    this->lastIndex = -1;
    this->classRosterArray = new Student * [capacity];
}

void Roster::parseAdd(string row)
{
    if (lastIndex < capacity) {
        lastIndex++;
        int parray[Student::daysToCompleteSize];

        if (row[0] == 'S') {
            this->classRosterArray[lastIndex] = new Student();
            classRosterArray[lastIndex]->setDegree(SECURITY);
        }
        else if (row[0] == 'N') {
            this->classRosterArray[lastIndex] = new Student();
            classRosterArray[lastIndex]->setDegree(NETWORKING);
        }
        else if (row[0] == 'S') {
            this->classRosterArray[lastIndex] = new Student();
            classRosterArray[lastIndex]->setDegree(SOFTWARE);
        }
        else if (row[0] == 'U') {
            this->classRosterArray[lastIndex] = new Student();
            classRosterArray[lastIndex]->setDegree(UNDECIDED);
        }

        //ID
        int rhs = studentData[lastIndex].find(",");
        classRosterArray[lastIndex]->setStudentID(studentData[lastIndex].substr(0, rhs));

        //First Name
        int lhs = rhs + 1;
        rhs = studentData[lastIndex].find(",", lhs);
        classRosterArray[lastIndex]->setFirstName(studentData[lastIndex].substr(lhs, rhs - lhs));

        //Email Address
        lhs = rhs + 1;
        rhs = studentData[lastIndex].find(",", lhs);
        classRosterArray[lastIndex]->setEmailAddress(studentData[lastIndex].substr(lhs, rhs - lhs));

        //Age
        lhs = rhs + 1;
        rhs = studentData[lastIndex].find(",", lhs);
        classRosterArray[lastIndex]->setAge(studentData[lastIndex].substr(lhs, rhs - lhs));

        //Days
        lhs = rhs + 1;
        rhs = studentData[lastIndex].find(",", lhs);
        parray[0] = stoi(studentData[lastIndex].substr(lhs, rhs - lhs));

        //Days to Complete
        lhs = rhs + 1;
        rhs = studentData[lastIndex].find(",", lhs);
        parray[1] = stoi(studentData[lastIndex].substr(lhs, rhs - lhs));

        //Days to Complete
        lhs = rhs + 1;
        rhs = studentData[lastIndex].find(",", lhs);
        parray[2] = stoi(studentData[lastIndex].substr(lhs, rhs - lhs));

        //Set all Days
        classRosterArray[lastIndex]->setDaysToComplete(parray);
    }
    else {
        cout << "Error, list has exceeded capacity. Exiting.";
        exit(-1);
    }

}


text:
Q: Who is watching the watchdog? I am looking for an expression that conveys the meaning Who is watching the watchdog?

A: A similar common phrase already exists, "who watches the watchers?" or "who watches the
watchmen?".
This is from the Latin quis custodiet ipsos custodes?.


text:
Q: Is there any way to change wallpaper according to specific clock time? Finding it quite hard to Google this. Between say 9 am and 6pm I want a certain wallpaper to be displayed, and between 6 pm to 12 am I want a different one. So I want it time-specific.
Any way to do this in Ubuntu?

A: DesktopNova  : Click to install

DesktopNova changes the desktop background image after an adjustable time. It can choose the images from single files and folders (with or without subfolders). An autostart feature is also implemented.

*

*Website

*Launchpad
So you add your pictures, and then Check Change wallpaper in intervals.
And there is an indicator for this application.

A: There is also Desktop Drapes
Besides the wallpaper changers in USC (like Desktop Nova and Desktop Drapes) there is also a script called Sunrise that can do this and you can get it here on deviantart.
Instructions:

*

*Copy the file to a new directory.

*Extract the files.

*Inside a terminal, cd into the folder you created.

*Run sh ./install
It has an XML file with the images and in it also a timer (in seconds).
By default it uses the images shown on this blog.
Or course using a script is not as secure as using a package but it's very lightweight.


text:
Q: Help interpreting/converting odd date format I have data pulled from a database and stored in Stata .dta files. But when I read it into R using the foreign package, I get a date format unlike any I've seen. All of the other dates are "%m/%d/%Y" and import correctly.
I have searched the database's documentation, but there's no explanation for the odd date format for "DealActiveDate". The "facilitystartdate" date should be close to the "DealActiveDate", but not necessarily the same. Here are a few rows of these two columns.
facilitystartdate DealActiveDate
1         09/12/1987   874022400000
2         09/12/1987   874022400000
3         09/12/1987   874022400000
4         09/01/1987   873072000000
5         09/08/1987   873676800000
6         10/01/1987   875664000000
7         08/01/1987   870393600000
8         08/01/1987   870393600000
9         10/01/1987   875664000000
10        09/01/1987   873072000000

Please let me know if you have any idea how to convert "DealActiveDate" to a more conventional date. Thanks! (I'm not sure SO is the best venue, but I couln't think of any other options!)

A: Looks like milliseconds since 1960-01-01:
as.POSIXct(874022400000/1000, origin="1960-01-01")
# [1] "1987-09-12 01:00:00 CDT"


text:
Q: Using the new sse registers xmm8 - xmm15 Is it possible to use the new SSE registers from Visual Studio 2010 inline assembler? If so, how and what else conditions must be satisfied? I don't know for example if new registers are available in both x86 and x64 modes.

A: Inline assembly is not allowed when compiling for the x64 platform in Visual Studio (since VS 2005).
I would recommend that you use intrinsics instead. It makes the compiler handle the CPU registers for you, and does some instruction reordering (the optimizer gets to process the code, which is never the case with inline assembly).

A: As regards your 2nd question:

I don't know for example if new
  registers are available in both x86
  and x64 modes.

The 'new' registers xmm8 - xmm15 are only available in 64-bit mode.
Note however, the situation with the new AVX registers (for CPUs and OSes that support AVX, e.g. Sandy Bridge CPU  + Win7 SP1):
ymm0 - ymm7 are available in both 32-bit and 64-bit mode.
ymm8 - ymm15 are available only in 64-bit mode.


text:
Q: Crashes possibly involving FMDB likely due to memory corruption I'm testing on the iOS simulator involving the FMDB distributed along with the MapBox iOS SDK. Here is a bug I can't catch and I wonder if I am breaking some FMDB rules I do not know or I'm having serious memory corruption somewhere (but I've already narrowed the problem down to a few lines). The following code will run into the line that's commented "should not be here". And commenting out any of the lines labeled below would run into "should be here".
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.
    NSString * sql_gdb = @"/Users/t2wu/Library/Application Support/iPhone Simulator/5.1/Applications/BB193B94-2549-49DB-9BBB-C66D76743515/Library/Application Support/Poki.OfflineSpotty/fremont_spatial.gdb";

    FMDatabase * db = [FMDatabase databaseWithPath:sql_gdb];
    if ([db open]) {
        db.shouldCacheStatements = TRUE; // Correct when this line is commented out

        [self fooDB:db];

        FMResultSet * debug1 = [db executeQuery:@"SELECT id, type, state FROM payloads WHERE id=?", [NSNumber numberWithLong:2]];
        BOOL DOESFIND1 = FALSE;
        while ([debug1 next]) {
            DOESFIND1 = TRUE;
            NSLog(@"Does find."); // Should be here.
        }
        if (DOESFIND1 == FALSE) {
            NSLog(@"Does not find"); // Should not be here.
        }
    }

    return YES;
}

-(void) fooDB: (FMDatabase *)db
{
    NSLog(@"SELECT id, type, state FROM payloads WHERE id=%@", [NSNumber numberWithLong:1]);
    FMResultSet * result = [db executeQuery:@"SELECT id, type, state FROM payloads WHERE id=?", [NSNumber numberWithLong:1]];   // Correct when changed to "SELECT * FROM"
    while ([result next]) {
        return;  // Correct when this line is commented out.
    }
    return;
}

I've put the code in application:didFinishLaunchingWithOptions just so I can run it as the first thing before any other memory is messed with. (This should come before all views, If I am correct about this.) But I have no idea where the problem is. And again, comment out any of the two lines that says "Correct when" will produce the desired result. Or query with SELECT * instead of SELECT id, type, state will also produce the desired result.

A: I would like to comment that the way you have written the Database code and method, fooDB is a bit difficult to read.
Try the following:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
 [self fooDB];
 return YES;
}

-(BOOL) fooDB
{

   NSString * sql_gdb = @"/Users/t2wu/Library/Application Support/iPhone Simulator/5.1/Applications/BB193B94-2549-49DB-9BBB-C66D76743515/Library/Application Support/Poki.OfflineSpotty/fremont_spatial.gdb";

   FMDatabase * db = [FMDatabase databaseWithPath:sql_gdb];
   if (![db open]) {
      NSLog(@"Could not open DB.");
      return NO;
   }

   FMResultSet * result = [db executeQuery:@"SELECT id, type, state FROM payloads WHERE id = ?", [NSNumber numberWithLong:1]];
  while ([result next]) {
      //DO SOMETHING HERE
  }
  [result close];
  [db close];
  return YES;
}


text:
Q: Split and parse (to new file) string every nth character iterating over starting character - python I asked a more general approach to this problem in a previous post but I am getting stuck with trying to parse out my results to individual files. I want to iterate over a long string, starting at position 1 (python 0) and print out every 100 characters. Then, I want move over one character and start at position 2 (python 1) and repeat the process until I reach the last 100 characters. I want to parse each "100" line chunk into a new file. Here is what I am currently working with:
seq = 7524       # I get this number from a raw_input
read_num=100

for raw_reads in range(100):
    def nlength_parts(seq,read_num):
        return map(''.join,zip(*[seq[i:] for i in range(read_num)]))

f = open('read' + str(raw_reads), 'w')
f.write("read" '\n')
f.write(nlength_parts(seq,read_num))
f.close

The error I am constantly getting now it
f.write(nlength_parts(seq,read_num))
TypeError: expected a character buffer object

Having some issues, any help would be greatly appreciated!

After some help, I have made some changes but still not working properly:
seq = 7524       # I get this number from a raw_input
read_num=100

def nlength_parts(seq,read_num):
    return map(''.join,zip(*[seq[i:] for i in range(read_num)]))

for raw_reads in range(100):   # Should be gene length - 100
    f = open('read' + str(raw_reads), 'w')
    f.write("read" + str(raw_reads))
    f.write(nlength_parts)
    f.close

I may have left out some important variables and definitions to keep my post short but it has caused confusion. I have pasted my entire code below.
#! /usr/bin/env python

import sys,os
import random
import string

raw = raw_input("Text file: " )

with open(raw) as f:
    joined = "".join(line.strip() for line in f)
    f = open(raw + '.txt', 'w')
    f.write(joined)
    f.closed

seq = str(joined)
read_num = 100

def nlength_parts(seq,read_num):
    return map(''.join,zip(*[seq[i:] for i in range(read_num)]))

for raw_reads in range(100):   # ideally I want range to be len(seq)-100
    f = open('read' + str(raw_reads), 'w')
    f.write("read" + str(raw_reads))
    f.write('\n')
    f.write(str(nlength_parts))
    f.close

A: A few things:

*

*You define the variables seq and read_num in the global scope, and then also use the same parameters in your function. What you should be doing is have the names of the parameters in the function definition be different, and then passing those two variables to the function when you call it.

*When you call nlength_parts, you don't pass it either of the parameters you defined it with and you also lack (). Fix that in conjunction with #1.

*You don't seem to define the string you are slicing. You slice seq in your function, but seq is an integer in your code. Is seq the processed output of the file you were talking about in your comment? If so, is it much larger in your actual code?

That being said, I believe this code will do what you want it to do:
def nlength_parts(myStr, length, paddingChar=" "):
    if(len(myStr) < length):
        myStr += paddingChar * (length - len(myStr))
    sequences = []
    for i in range(0, len(myStr)-length + 1):
    sequences.append(myStr[i:i+length])
    return(sequences)
foo = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
nlengthfoo = nlength_parts(foo, 10)
for x in range(0, length(nlengthfoo):
    with open("read" + (x+1), "w") as f:
        f.write(nlengthfoo[x])

EDIT: Apologies, changed my code in response to your comment.

A: Edit in response to clarifying comment:
Essentially, you want a rolling window of your string. Say long_string = "012345678901234567890123456789..." for a total length of 100.
In [18]: long_string
Out[18]: '0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789'

In [19]: window = 10

In [20]: for i in range(len(long_string) - window +1):
   .....:     chunk = long_string[i:i+window]
   .....:     print(chunk)
   .....:     with open('chunk_' + str(i+1) + '.txt','w') as f:
   .....:         f.write(chunk)
   .....:
0123456789
1234567890
2345678901
3456789012
4567890123
5678901234
6789012345
7890123456
8901234567
9012345678
0123456789
1234567890
2345678901
3456789012
4567890123
5678901234
6789012345
7890123456
8901234567
9012345678
0123456789
1234567890
2345678901
3456789012
4567890123
5678901234
6789012345
7890123456
8901234567
9012345678
0123456789
1234567890
2345678901
3456789012
4567890123
5678901234
6789012345
7890123456
8901234567
9012345678
0123456789
1234567890
2345678901
3456789012
4567890123
5678901234
6789012345
7890123456
8901234567
9012345678
0123456789
1234567890
2345678901
3456789012
4567890123
5678901234
6789012345
7890123456
8901234567
9012345678
0123456789
1234567890
2345678901
3456789012
4567890123
5678901234
6789012345
7890123456
8901234567
9012345678
0123456789
1234567890
2345678901
3456789012
4567890123
5678901234
6789012345
7890123456
8901234567
9012345678
0123456789
1234567890
2345678901
3456789012
4567890123
5678901234
6789012345
7890123456
8901234567
9012345678
0123456789

Finally,
In [21]: ls
chunk_10.txt  chunk_20.txt  chunk_30.txt  chunk_40.txt  chunk_50.txt  chunk_60.txt  chunk_70.txt  chunk_80.txt  chunk_90.txt
chunk_11.txt  chunk_21.txt  chunk_31.txt  chunk_41.txt  chunk_51.txt  chunk_61.txt  chunk_71.txt  chunk_81.txt  chunk_91.txt
chunk_12.txt  chunk_22.txt  chunk_32.txt  chunk_42.txt  chunk_52.txt  chunk_62.txt  chunk_72.txt  chunk_82.txt  chunk_9.txt
chunk_13.txt  chunk_23.txt  chunk_33.txt  chunk_43.txt  chunk_53.txt  chunk_63.txt  chunk_73.txt  chunk_83.txt
chunk_14.txt  chunk_24.txt  chunk_34.txt  chunk_44.txt  chunk_54.txt  chunk_64.txt  chunk_74.txt  chunk_84.txt
chunk_15.txt  chunk_25.txt  chunk_35.txt  chunk_45.txt  chunk_55.txt  chunk_65.txt  chunk_75.txt  chunk_85.txt
chunk_16.txt  chunk_26.txt  chunk_36.txt  chunk_46.txt  chunk_56.txt  chunk_66.txt  chunk_76.txt  chunk_86.txt
chunk_17.txt  chunk_27.txt  chunk_37.txt  chunk_47.txt  chunk_57.txt  chunk_67.txt  chunk_77.txt  chunk_87.txt
chunk_18.txt  chunk_28.txt  chunk_38.txt  chunk_48.txt  chunk_58.txt  chunk_68.txt  chunk_78.txt  chunk_88.txt
chunk_19.txt  chunk_29.txt  chunk_39.txt  chunk_49.txt  chunk_59.txt  chunk_69.txt  chunk_79.txt  chunk_89.txt
chunk_1.txt   chunk_2.txt   chunk_3.txt   chunk_4.txt   chunk_5.txt   chunk_6.txt   chunk_7.txt   chunk_8.txt

Original response
I would just treat the string like a file. This lets you avoid any slicing headaches and is pretty straightforward because the file API lets you "read" in chunks easily.
In [1]: import io

In [2]: long_string = 'a'*100 + 'b'*100 + 'c'*100 + 'e'*88

In [3]: print(long_string)
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbcccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccceeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee

In [4]: string_io = io.StringIO(long_string)

In [5]: chunk = string_io.read(100)

In [6]: chunk_no = 1

In [7]: while chunk:
   ....:     print(chunk)
   ....:     with open('chunk_' + str(chunk_no) + '.txt','w') as f:
   ....:         f.write(chunk)
   ....:     chunk = string_io.read(100)
   ....:     chunk_no += 1
   ....:
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee

Note, I'm using ipython terminal, so you can use terminal commands inside the interpreter session!
In [8]: ls chunk*
chunk_1.txt  chunk_2.txt  chunk_3.txt  chunk_4.txt

In [9]: cat chunk_1.txt
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
In [10]: cat chunk_2.txt
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
In [11]: cat chunk_3.txt
cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
In [12]: cat chunk_4.txt
eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee
In [13]:


text:
Q: Where can I find good instructions on how to add in-app subscriptions to my Android app using Google Market Billing APIv2? I have been trying to make sense of Android's developer docs concerning the in-app subscriptions capability that was included in the Market Billing API v2 earlier this year.  All of the documentation seems to talk about in-app billing and only briefly mentions subscriptions implementation and testing.
I have downloaded the Dungeons sample application which does not implement subscriptions.  I have set up a test app which defines two of my own subscription products.  When I purchased a $9.99/year subs, it did charge me.  I failed to store the purchase token correctly, so there was no actual delivery (my fault).  I then attempted to refund my order through Google Checkout so I could restart the test, and it did not give me a refund.  It actually charged my credit card, and I did not capture the purchase token, so there is no way for me to revive the old transaction that I know of.  Does anyone know of any VERY CLEAR documentation of the process for Google Play in-app subscriptions and a solid and repeatable testing process?  The android documentation on this one is tough for me.  I have been using the following links as reference thus far:
http://developer.android.com/guide/google/play/billing/billing_subscriptions.html
http://developer.android.com/guide/google/play/billing/billing_overview.html
Thank you for any help that anyone can provide.


text:
Q: Unusual Deserialization Error from JSON to C# .Net Fiddle 1
I have a JOSN received from external API as follows
[{
    "assignedto": "MAIN STAFF",
    "createduser": "API-71",
    "departmentid": "1",
    "observations": [{
        "abnormalflag": "abnormal",
        "analytename": "HGB A1C",
        "value": "5"
    }],
    "pages": [],
    "priority": "2",
    "status": "REVIEW"
}]

I did a Paste Special in Visual Studio and got following classes
public class Rootobject
{
    public Class1[] Property1 { get; set; }
}

public class Class1
{
    public string assignedto { get; set; }
    public string createduser { get; set; }
    public string departmentid { get; set; }
    public Observation[] observations { get; set; }
    public object[] pages { get; set; }
    public string priority { get; set; }
    public string status { get; set; }
}

public class Observation
{
    public string abnormalflag { get; set; }
    public string analytename { get; set; }
    public string value { get; set; }
}

When I do a deserialization, I am getting following error

Run-time exception (line 24): Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'Rootobject' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
  Path '', line 1, position 1.

C# Code
public static void Main(string[] args)
{

    var json = @"[{
                    ""assignedto"": ""MAIN ST (HUB) STAFF"",
                    ""createduser"": ""API-7127"",
                    ""departmentid"": ""1"",
                    ""observations"": [{
                        ""abnormalflag"": ""abnormal"",
                        ""analytename"": ""HGB A1C"",
                        ""value"": ""5""
                    }],
                    ""pages"": [],
                    ""priority"": ""2"",
                    ""status"": ""REVIEW""
                }]";

    Rootobject resultObj = JToken.Parse(json).ToObject<Rootobject>();

}

I referred similar questions like Create a strongly typed c# object from json object with ID as the name - but that is a different issue.
Any idea how to fix this? Also what is the better way to generate C# classes from   JSON?
Note: I also tried with class I got from http://json2csharp.com/. That also faield - Fidlle 2

A: I would use Newtonsoft / Json convert and change this:
Rootobject resultObj = JToken.Parse(json).ToObject<Rootobject>();

to:
using Newtonsoft.Json;
-- snip --
    var resultObj = JsonConvert.DeserializeObject<List<Class1>>(json);

    Console.WriteLine(resultObj.Count); // 1
    Class1 result = resultObj[0];
    Console.WriteLine(result.assignedto); // "MAIN ST (HUB) STAFF"

This will give you a collection of RootObject
As @JeffMeracdo states above - you are providing a collection of object and trying to parse as though it is a single object

A: As @JeffMeracdo states above, try this:
List<Example> resultObj = JsonConvert.DeserializeObject<List<Example>>(json);

Following using statement and package along with Newtonsoft.Json Nuget package:
using Newtonsoft.Json;

Classes:
public class Observation
{
    public string abnormalflag { get; set; }
    public string analytename { get; set; }
    public string value { get; set; }
}

public class Example
{
    public string assignedto { get; set; }
    public string createduser { get; set; }
    public string departmentid { get; set; }
    public List<Observation> observations { get; set; }
    public List<object> pages { get; set; }
    public string priority { get; set; }
    public string status { get; set; }
}


text:
Q: Java: How to find index of last element of partially initialized sorted array Suppose I create an int array of size N. Then I fill up the array with sorted numbers until index x, where 0 <= x < N-1. How can I find the index x?
Here's one of the examples of the array: {0,1,2,3,4,0,0,0,0,0}, and here's how I generated the array:
int[] arr = new int[10];
for (int i = 0; i < 5; i++) {
    arr[i] = i;
}

Is there any Java syntax for this? I am specifically talking about Array not ArrayList.
====UPDATE====
Sorry for the confusion, the above array was just an example. Suppose the partially initialized array is given, such that we don't know how it was generated. Again, to be clear, the array can also be initialized as {0,0,0,1,2,6,7,0,0,0,0} where the last 0,0,0,0 part is the part from being uninitialized, whereas the first 0,0,0 is deliberately written by somebody else.

A: You said your array is sorted. So, you can search for the biggest element into the array and then uses Arrays.asList(arr).indexOf(biggestElement);
int biggetsElement = arr[0];
for(int i=1; i < arr.length; i++){
    if(arr[i] > biggestElement){
        biggestElement = arr[i];
    }
}

int index = Arrays.asList(arr).indexOf(biggestElement);

I'm not sure if it will work with int elements, if not you can use Integer elements instead.

A: You should use Integer class and not int primitive data type. Read about more things you can do with Integer class
Integer arr[] = new Integer[10];

This is initialized to null for each element. Now you can add number to it.
public int indexOfArray(Integer [] arr) {
    int i=0;
    while(arr[i]!=null) {
        i++;
    }
    return i;
}

A: Not possible as specified.  What if the "sorted values" are all negative and end at -1, e.g.:
[-5,-4,-3,-2,-1,     0,0,0,0]

vs. "sorted values" that are all non-positive but end in 0  (spaces added to emphasize the end of the initial sorted numbers)
[-5,-4,-3,-2,-1,0,    0,0,0]

There's no way to tell afterwards which 0 is the "first" unsorted one.

A: Assuming you dont know what x is, and assuming that the only value of uninitialized elements is 0, and that all initialized elements cant have the value 0 (which is not true in your case), then you will just have to do a linear search for it -
int i=0;
while(arr[i]!=0) i++;
return i

A: You can use this :
int index = Arrays.binarySearch(theArray, 0);

Condition : the array must be sorted
edit
Use Integer :
Integer[] theArray =  {0, 0, 0, 1, 2, 4, 7, null, null, null};
 int index = Arrays.binarySearch(theArray, null);

A: Create for loop and put in it condition that will check if next element is sorted
Code:
int x

for(int i=0;i<arr.length;i++)
   if(arr[i+1]-arr[i]!=1)
      x=i;


text:
Q: Sencha: How to use data from one file to another Im new at this sencha thingy and im trying to experiment a bit with it. I've been making some very simple tests and now i've reached the point where i want to pass the data from one file to another. To make it easier to understand im trying to get the data from the following text box to make a simple filter tool.

the textfield has been created in the following piece of code in the file Filters.js
Ext.define('Prj01Filtro.view.main.Filters', {
    extend:'Ext.form.Panel',
    xtype: 'Filters',
    alias: 'form.formFilter',

    requires: [
        'Prj01Filtros.view.main.FilterController'
    ],

    controller: 'controllerFilter',

    items:[
        {
            margin: '0 0 10 0',
            buttons: [
                {
                    xtype: 'textfield',
                    fieldLabel: 'Filter',
                    name: 'textFieldSearch'
                }, {
                    name: 'buttonSearch',
                    text: 'Buscar',
                    listeners: {
                        click: 'onClickFilter'
                    }
                }, {
                    name: 'buttonRemoveFilter',
                    text: 'X',
                    listeners: {
                        click: 'onClickRemove'
                    }
                }
            ]

        }
    ]

The code of the buttons have been located in a file named FilterController.js
Ext.define('Prj01Filtros.view.main.FilterController',{
    extend: 'Ext.app.ViewController',
    alias: 'controller.controllerFilter',

    onClickFilter: function() {
        //Code to apply the filter
    },

    onClickRemove: function() {
        //code to remove the filter
    }
})

Finally the code of the table is located in a file named List.js
Ext.define('Prj01Filtros.view.main.List', {
    extend: 'Ext.grid.Panel',
    xtype: 'mainlist',
    plugins: 'gridfilters',

    requires: [
        'Prj01Filtros.store.Personnel'
    ],

    title: 'Personnel',

    store: {
        type: 'personnel'
    },

    columns: [
        { text: 'Name',  dataIndex: 'name', align: 'left', filter: {
            type: 'string'
        }},
        { text: 'Email', dataIndex: 'email', flex: 1, align: 'left', filter: {
            type: 'string'
        }},
        { text: 'Phone', dataIndex: 'phone', flex: 1, align: 'left', filter: {
            type: 'string'
        }},
    ],

    listeners: {
        select: 'onItemSelected'
    },
});

So my goal is to make a function in FilterController.js that can be called from Filters.js which sets the value for the filters applied in the columns of List.js but im kind of stuck on how to set the value property for the filter from the function that i have created. If someone knows how to do it i would appreciate the help. Thanks!
I've tried many things but since im new to sencha im pretty much sure that they were incorrect anyways.

A: I suggest to study View Models & Data Binding and ViewModel Internals sections of Ext JS documentation. These are among the most powerful features of Ext JS so it good to develop a deep understanding.
For you current question, you need to access the store behind your List view  to manage the filters, not the list itself. Once you get the store, you can set / clear the filters with setFilters and clearFilter methods on the store:
store.setFilter([{
  property: 'email',
  value: '<search term here>',
  operator: 'like'
}]);

store.clearFilter();

To easily access the store, define the store in the view model of a view that is above both List and Filters view. This is the important part because this way you can take advantage of inheriting the view model from the container parent. Let's say you have a panel which contains both List and Filters. Define the store in the view model:
stores: {
  personnel: {
    type: 'personnel'
  }
}

Use bind config when assigning the store in your List:
Ext.define('Prj01Filtros.view.main.List', {
  ...
  bind: {
    store: '{personnel}'
  }
  ...
});

After all this, you can access the store from the Filters view controller's methods:
onClickFilter: function() {
  this.getViewModel().getStore('personnel').setFilters(...);
}

You need the get the value the user entered into the field. You can access it from the controller with querying the textfield component, but you can also do it with the view model.


text:
Q: Our app using Azure to authenticate Office 365 users is not supporting 2-step authentication We have a multi-tenant Windows Azure app.  We use it to authenticate Office 365 users, and grant us access to the user's calendars.
We had a support question today saying:
I then click the office 365 button, am taken to
the Microsoft Office 365 login screen where it
tells me I'm already logged in with my office 365
account. I click "remain signed in with this
account", put in my password again, then am just
shown a blank screen (and microsoft sends me a text
with my two-factor authentication code, but nowhere
to input it).

We did not test any 2-factor authentication users when testing our new office 365 login.  But it seems to me like there is an issue on Microsoft's side in this scenario.
Is there something special we need to do on our end ( a setting in our Azure app maybe? ) to support 2-factor authentication for our users?


text:
Q: Problem with USB installation (xbmcbuntu) This question is about XBMCbuntu, which is basically ubuntu - So I hope it is okay to ask:
Iv'e been trying for the last many hours to install xbmcbuntu. I've downloaded to ISOs 12.2 and 12 - Both in Intel&Nvidia editions (Intel proc. & nvidia gfx). Ive tried formatting my USBpen to FAT, FAT32, NTFS. Used Universal USB Tool, UNetbootin and Lili. None of which have worked.
First of all, my windows 7 is install via USB - the same USB key, so I know what i'm doing.
When i first started trying to install via USB I got a Syslinux error, which caused me to try the different USB tools. None of which worked. Then I tried formatting the drive to different settings, which now has resulted in to different outcomes.
Either I get stuck when I try to boot from the USB - Nothing happens(No text or anything) and then it freezes and needs a hard reboot. Or it simply ignores the USBstick and starts booting windows as normal.
Now - I'm very confused - Can ANYONE tell my how to install this?
Also - have tried LiLi from windows - thought I'd might be able to install it from windows. But no drives show up when I get to it in the installer.
Hopefully some of you know what to do...

A: When i first tried instaling winXP in mi laptop i had to inject the sata drive drivers in the instalation image. So, question 1, have you installed any other distro to that same machine? If not, try and do that with a more mainstream and complete distro and see if it works. If you did and it worked, mi guess is that the problem is with your machine and that distro.

A: well if it's basically an Ubuntu you could follow this instructions
Ubuntu LiveUSB installation

A: You can instead use the MinimalCD and install only the packages you want. Download the MinimalCD from here and select the packages you would want for your system. This install Ubuntu in a baremetal-like, which only have the minimum packages installed.


text:
Q: What options do we have to generate a PDF from an ASP.NET Core Web Api I need to generate a PDF from a HTML Canvas, but the process must complete on the server side which is an ASP.NET Core Web Api.

A: On the server-side, you can output HTML of a view as string and can use any library that generate PDF from HTML string.
to render a view into string see this link Return View as String in .NET Core
after you got HTML, you need to pass it to the library see this link to convert HTML to string
Convert HTML to PDF in .NET
1 Create a C# extension method to render view to string
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewEngines;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using System.IO;
using System.Threading.Tasks;

namespace CC.Web.Helpers
{
    public static class ControllerExtensions
    {
        public static async Task<string> RenderViewAsync<TModel>(this Controller controller, string viewName, TModel model, bool partial = false)
        {
            if (string.IsNullOrEmpty(viewName))
            {
                viewName = controller.ControllerContext.ActionDescriptor.ActionName;
            }

            controller.ViewData.Model = model;

            using (var writer = new StringWriter())
            {
                IViewEngine viewEngine = controller.HttpContext.RequestServices.GetService(typeof(ICompositeViewEngine)) as ICompositeViewEngine;
                ViewEngineResult viewResult = viewEngine.FindView(controller.ControllerContext, viewName, !partial);

                if (viewResult.Success == false)
                {
                    return $"A view with the name {viewName} could not be found";
                }

                ViewContext viewContext = new ViewContext(
                controller.ControllerContext,
                viewResult.View,
                controller.ViewData,
                controller.TempData,
                writer,
                new HtmlHelperOptions()
            );

                await viewResult.View.RenderAsync(viewContext);

                return writer.GetStringBuilder().ToString();
            }
        }
    }
}

2) Render view to string
viewHtml = await this.RenderViewAsync("Report", model);

3) Use HTML to create PDF
    Byte[] res = null;
    using (MemoryStream ms = new MemoryStream())
    {
        var pdf = TheArtOfDev.HtmlRenderer.PdfSharp.PdfGenerator.GeneratePdf(viewHtml, PdfSharp.PageSize.A4);
        pdf.Save(ms);
        res = ms.ToArray();
    }

A: using IronPdf;
IronPdf.HtmlToPdf Renderer = new IronPdf.HtmlToPdf();
// Render an HTML document or snippet as a string
Renderer.RenderHtmlAsPdf("
Hello World
").SaveAs("html-string.pdf");
// Advanced:
// Set a "base url" or file path so that images, javascript and CSS can be loaded
var PDF = Renderer.RenderHtmlAsPdf("",@"C:\site\assets\");
PDF.SaveAs("html-with-assets.pdf");

IronPDF for .NET Core


text:
Q: Why did Superman and Batman fight in Justice League: War? In Justice League: War, why did Superman and Batman fight and how did Green Lantern know Batman? Was this some kind of alternate universe or something?

A: Most movies and cinematic retelling of stories may change what is currently established by the more recent or relevant timelines. In Justice League: War, the story is a retelling of the New52 Justice League's first meeting with Darkseid.

*

*The comic pretty much acts as a storyboard for the confrontation: Here are two panels indicating the scene just before Superman wipes the floor with Green Lantern and Batman. One is from Justice League #1 and the second is from Justice League: War.

This is the setup right before Batman and Superman fight in Justice League #2.

The story is a retelling of Justice League #1 and #2 (2011):

*

*In this story, Batman, Superman and Green Lantern don't really know each other from first hand experience, only what they have heard on modern media. Batman tends to know about EVERYONE before they know about him. Green Lantern didn't know Batman, he only knew OF Batman, primarily as an urban legend.

*The first confrontation between Superman and Batman takes place because Superman is an alien and Batman suspects the invasion that is taking place is also an alien event. It takes a minute before he realizes Superman is not involved in it.

*Superman, on the other hand is not sure what is happening and is trying to figure out which side everyone is on. Batman and Green Lantern's unexpected visitation to Metropolis starts them off on his bad side because he just discovered the aliens as well.

*This is the comic trope: Mistaken Identity - Superheroes fight before teaming up. A standard method for introducing new characters to each other and to new readers. Since this story was directly after a major DC reboot, none of the characters are familiar with each other, so it gives us a chance to see how powerful they are and what their capabilities might look like in this new DC Universe.


text:
Q: How to make the TextBox border become red when a validation happens to it in asp.net? This what i want to do.click to view photo
I tired many options but all did not work. like overriding JS methods and custom methods. i will be thankful for a clear, working response.

     <asp:Label ID="Label2" runat="server" Text="Name"
        CssClass="style3" AssociatedControlID="TextBoxName"></asp:Label>

        <asp:TextBox ID="TextBox2" runat="server"
            CssClass="TextBox"></asp:TextBox>

        <asp:RequiredFieldValidator ID="RequiredFieldValidator3"
            runat="server" ErrorMessage="Field required"
            ControlToValidate="TextBoxName" Text="Required"
            ForeColor="Red" Font-
            Strikeout="False" Font-Underline="False" Font-
            Overline="False" Font-Bold="True" BackColor="Red">
        </asp:RequiredFieldValidator>

A: This is a script I use for this purpose.


text:
Q: How to get json data from nested dictionary in swift How can I access data from a nested dictionary - when I want to save all data from "CourseDates"?  CourseDates = NSArrayM

let json = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments)

if let test = json[0]["CourseDates"] as? [[String : AnyObject]] {
// heres my problem
 }

A: You can create a function that returns NSDictionary like this:
func parseJSON(data: NSData) -> NSDictionary{
        var dic: NSDictionary!
        do {
            boardsDictionary = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary

        } catch let error as NSError {
            print(error.localizedDescription)
            print("Error could not parse JSON data, it's null maybe?!!")
        }
        //'\(jsonStr)'

        return dic
    }

UPDATE:
Add This:
public class func jsonToNSData(json: AnyObject) -> NSData?{
    return NSJSONSerialization.dataWithJSONObject(json, options: .allZeros, error: nil)
}

let dic = parseJSON(jsonToNSData(YourJsonData)) as! NSDictionary

A: Hi you can try SwiftyJson, It is a great source through which you can deal with complex JSON in a much more simpler way then you ever thought. For example
{
    "metadata":{
        "responseInfo":{
            "status":200,
            "developerMessage":"OK",
        }
    },
    "results":[
        {
            "title":"Legal immigrants should get freedom before undocumented immigrants – moral, just and fair",
            "body":"I am petitioning President Obama's Administration to take a humane view of the plight of legal immigrants. Specifically, legal immigrants in Employment Based (EB) category. I believe, such immigrants were short changed in the recently announced reforms via Executive Action (EA), which was otherwise long due and a welcome announcement.",
            "issues":[
                {
                    "id":"28",
                    "name":"Human Rights"
                },
                {
                    "id":"29",
                    "name":"Immigration"
                }
            ],
            "signatureThreshold":100000,
            "signatureCount":267,
            "signaturesNeeded":99733,
        },
        {
            "title":"National database for police shootings.",
            "body":"There is no reliable national data on how many people are shot by police officers each year. In signing this petition, I am urging the President to bring an end to this absence of visibility by creating a federally controlled, publicly accessible database of officer-involved shootings.",
            "issues":[
                {
                    "id":"28",
                    "name":"Human Rights"
                }
            ],
            "signatureThreshold":100000,
            "signatureCount":17453,
            "signaturesNeeded":82547,
        }
    ]
}

From this JSON if you want to extract the result you can do easily like this
func parseJSON(json: JSON) {
for result in json["results"].arrayValue {
    let title = result["title"].stringValue
    let body = result["body"].stringValue
    let sigs = result["signatureCount"].stringValue
    let obj = ["title": title, "body": body, "sigs": sigs]
    objects.append(obj)
}

}

A: Here is the simple example how can we extract data from the NSDictionary. And this is simple and i'm not following any standards...
I considered json data in String format.
var data = "{\"data\":{\"fName\":\"naveen\",\"lName\":\"kumar\"},\"friend\":[{\"name\":\"manju\",\"male\":true},{\"name\":\"tanuja\",\"male\":false}]}"

After that you can do
var nsdata = data.dataUsingEncoding(NSUTF16StringEncoding)
if let json = try? NSJSONSerialization.JSONObjectWithData(nsdata!, options: .MutableContainers) as! NSDictionary {
    if let some = json["friend"]![0]["name"]! {
        print(some) // prints -- manju
    }
}

By using the subscipt we can get the data.


text:
Q: Obj-C, how to stop NSURLConnection behind NSData? how can I stop NSURLConnection behind NSURLConnection ?
code:
 NSData *sendreq = [NSURLConnection sendSynchronousRequest:urlreq returningResponse:nil error:nil];
 NSString *responseStr =[[NSString alloc] initWithBytes:[sendreq bytes] length:[sendreq length] encoding:NSUTF8StringEncoding];

I use the NSData to store the response from my server, but in this way I cant use "[sendreq cancel]"
so if the NSURLConnection is making a long connection and the user is go to anther VC I want to stop the NSURLConnection, so how can I do it ?

A: If you want to be able to cancel your request, do not use sendSynchronousRequest, but instead use the asynchronous, delegate-based rendition NSURLConnection. (Frankly, you should avoid using synchronous requests, from the main thread at least, for a variety of reasons.) If you use the delegate-based rendition, you can then call NSURLConnection method cancel when needed.
So, define properties to hold the data and connection reference:
@property (nonatomic, strong) NSMutableData *responseData;
@property (nonatomic, weak) NSURLConnection *connection;

Then start the connection:
self.responseData = [NSMutableData data];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:urlreq delegate:self];
self.connection = connection;

You obviously have to implement the NSURLConnectionDataDelegate methods:
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [self.responseData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSString *responseStr = [[NSString alloc] initWithData:self.responseData encoding:NSUTF8StringEncoding];

    // you can use `responseStr` here

    // now that we're done with `responseData`, we might want to release it

    self.responseData = nil;
}

You want to detect/handle errors, too, with the NSURLConnectionDelegate method:
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    // do whatever you want when error occurs
    NSLog(@"%s: %@", __FUNCTION__, error);
}

If you need to cancel it, it's
[self.connection cancel];

You could also use AFNetworking, which uses delegate-based NSURLConnection, but keeps you out of the weeds of the implementation.
You can also use the newer NSURLSession which offers block-based renditions that are still can be cancelled. But that depends upon what OS versions you're trying to support.


text:
Q: How to run a Python script in a web page I'm very new to Python. I just know what Python is.
I have created the below code (in Python IDLE):
print "Hi Welcome to Python test page\n";
print "Now it will show a calculation";
print "30+2=";
print 30+2;

Then I saved this page in my localhost as index.py
I run the script using
http://localhost/index.py
But it does not show the executed Python script. Instead, it showed the above code as HTML. Where is the problem? How can I run a Python file in a web page?

A: If you are using your own computer, install a software called XAMPP (or WAMP either works). This is basically a website server that only runs on your computer. Then, once it is installed, go to the xampp folder and double click the htdocs folder. Now you
need to create an HTML file (I'm going to call it runpython.html). (Remember to move the Python file to htdocs as well.)
Add in this to your HTML body (and inputs as necessary).
<form action = "file_name.py" method = "POST">
   <input type = "submit" value = "Run the Program!!!">
</form>

Now, in the Python file, we are basically going to be printing out HTML code.
# We will need a comment here depending on your server. It is basically telling the server where your python.exe is in order to interpret the language. The server is too lazy to do it itself.

    import cgitb
    import cgi

    cgitb.enable() # This will show any errors on your webpage

    inputs = cgi.FieldStorage() # REMEMBER: We do not have inputs, simply a button to run the program. In order to get inputs, give each one a name and call it by inputs['insert_name']

    print "Content-type: text/html" # We are using HTML, so we need to tell the server

    print # Just do it because it is in the tutorial :P

    print "<title> MyPythonWebpage </title>"

    print "Whatever you would like to print goes here, preferably in between tags to make it look nice"

A: In order for your code to show, you need several things:
Firstly, there needs to be a server that handles HTTP requests. At the moment you are just opening a file with Firefox on your local hard drive. A server like Apache or something similar is required.
Secondly, presuming that you now have a server that serves the files, you will also need something that interprets the code as Python code for the server. For Python users the go to solution is nowadays mod_wsgi. But for simpler cases you could stick with CGI (more info here), but if you want to produce web pages easily, you should go with a existing Python web framework like Django.
Setting this up can be quite the hassle, so be prepared.

A: Well, the OP didn't say server or client side, so I will just leave this here in case someone like me is looking for client side:
Skulpt is a implementation of Python to run at client side. Very interesting, no plugin required, just simple JavaScript code.

A: As others have pointed out, there are many web frameworks for Python.
But, seeing as you are just getting started with Python, a simple CGI script might be more appropriate:

*

*Rename your script to index.cgi. You also need to execute chmod +x index.cgi to give it execution privileges.

*Add these 2 lines in the beginning of the file:

#!/usr/bin/python
print('Content-type: text/html\r\n\r')

After this the Python code should run just like in terminal, except the output goes to the browser. When you get that working, you can use the cgi module to get data back from the browser.
Note: this assumes that your webserver is running Linux. For Windows, #!/Python26/python might work instead.

A: Using the Flask library in Python, you can achieve that.
Remember to store your HTML page to a folder named "templates" inside where you are running your Python script.
So your folder would look like

*

*templates (folder which would contain your HTML file)

*your Python script

This is a small example of your Python script. This simply checks for plagiarism.
from flask import Flask
from flask import request
from flask import render_template
import stringComparison

app = Flask(__name__)

@app.route('/')
def my_form():
    return render_template("my-form.html") # This should be the name of your HTML file

@app.route('/', methods=['POST'])
def my_form_post():
    text1 = request.form['text1']
    text2 = request.form['text2']
    plagiarismPercent = stringComparison.extremelySimplePlagiarismChecker(text1,text2)
    if plagiarismPercent > 50 :
        return "
Plagiarism Detected !
"
    else :
        return "
No Plagiarism Detected !
"

if __name__ == '__main__':
    app.run()

This a small template of HTML file that is used:
<!DOCTYPE html>

Enter the texts to be compared

    <form action="." method="POST">
        <input type="text" name="text1">
        <input type="text" name="text2">
        <input type="submit" name="my-form" value="Check !">
    </form>

This is a small little way through which you can achieve a simple task of comparing two strings and which can be easily changed to suit your requirements.

A: With your current requirement, this would work:
    def start_html():
        return ''

    def end_html():
        return ''

    def print_html(text):
        text = str(text)
        text = text.replace('\n', '
')
        return '
' + str(text) + '
'
if __name__ == '__main__':
        webpage_data =  start_html()
        webpage_data += print_html("Hi Welcome to Python test page\n")
        webpage_data += fd.write(print_html("Now it will show a calculation"))
        webpage_data += print_html("30+2=")
        webpage_data += print_html(30+2)
        webpage_data += end_html()
        with open('index.html', 'w') as fd: fd.write(webpage_data)

Open the index.html file, and you will see what you want.


text:
Q: C++ transform T4 template ignore output file I'm using TextTransform.exe to generate multiple C++ files. Since the tool is not supported directly within Visual Studio for C++ projects I call it by command line (inspired by T4 Generating C++ Code).
In order to generate multiple files I use https://github.com/areve/Entity-Framework-T4-Templates/blob/master/src/dev/MultiOutput.tt that's why I don't need the standard output which is normal generated by the tool.
I call TextTransform.exe like:
"C:\Program Files (x86)\Common Files\microsoft shared\TextTemplating\14.0\TextTransform.exe"
-out "<what to put here that NO file is generated?>"
C:\Test.tt

I'm using Microsoft Windows. Maybe there is a "hack" to provide any kind of special char which would be accepted by the program but it wouldn't be possible to actually create a file out of it.
Is there a possibility to provide any command which generates NO file when I execute this command?

Update
As mentioned by @ImprobabilityCast using NUL is a way to go. It's not producing any file but the custom build where I run the tt file with is failing with the message:
Performing Custom Build Tools
CUSTOMBUILD : error : FileStream will not open Win32 devices such as disk partitions and tape drives. Avoid use of "\\.\" in the path.

I reach what I want but it's not so "nice" that the build action is failing.

A: Not sure why you don't want the files, but...
In linux we have a wonderful thing called /dev/null that is essentially an empty void just for things like this. I did a quick search, and Windows has it's own equivilent: NUL
Thus, the command you want is:
"C:\Program Files (x86)\Common Files\microsoft shared\TextTemplating\14.0\
TextTransform.exe" -out NUL C:\Test.tt

A: No. The way text transformation was built was only thought to produce a single output file. Multi output was a logical evolution for T4 templates but Microsoft has not evolved it for years now.
The code that you're using (as am I) is basically a hack around that. It uses a very ugly way of using the EnvDTE to manipulate the project system that will probably end up not working one of these days when MS decides to rewrite that system (and one could argue that day is coming).
T4-editor, for example, has a slightly different way of achieving the same thing but you can see that the output still produces the "dummy file":
http://t4-editor.tangible-engineering.com/blog/how-to-generate-multiple-output-files-from-a-single-t4-template.html

A: I've found a satisfing solution for my problem. Since Microsoft Visual Studio allows for custom build tools to enter multiple lines I realized that I can delete the file generated by the TextTransform.exe I don't need.
So the command I put into "Command Line" contains two lines now:
"C:\Program Files (x86)\Common Files\microsoft shared\TextTemplating\14.0\TextTransform.exe" -out "%(DefiningProjectDirectory)$(TempOutputFile)" C:\Test.tt
DEL /F "%(DefiningProjectDirectory)$(TempOutputFile)"

*

*The first line is the actual TextTransform call which produces me all the files I want including the output file I don't need but can't stop to be created.

*The second line just deletes me the file I don't need.

This command expects a project variable calles "TempOutputFile". In this way I skip any typo's. For example:
<PropertyGroup Label="Globals">
  <TempOutputFile>DoNotCheckin.h</TempOutputFile>
</PropertyGroup>


text:
Q: SQL - Find pairs and update + insert i have a table like this
ID  |  map       |   status       |
===================================
1   |      1     |   searching    |
2   |      1     |   searching    |
3   |      2     |   searching    |
4   |      2     |   searching    |
5   |      1     |   searching    |
6   |      3     |   searching    |

I want to go trough the table and find pairs (only 2) where status is searching and they are having the same map. Then update their status and INSERT some information from the two rows into another table.
EDIT: The values in map are unknown. So i need to get them first and "iterate" to find pairs.

A: This will pair each ID with the next matching ID;  if there are more than 2 you will get some overlap.
Select * from
    TableName as t1
    inner join
    TableName as t2
on
    t1.status= 'searching'
and t2.status = 'searching'
and t1.map=t2.map
and t1.id<t2.id


text:
Q: how to run mahout kmeans algorithm in local mode Is it possible to run a mahout k mean java program on local, so that it will read the data from local and save it back to local file system instead of hdfs.
All examles on internet are working on hdfs.
https://github.com/tdunning/MiA/blob/master/src/main/java/mia/clustering/ch07/SimpleKMeansClustering.java

A: Yes, it is possible - checkout SequenceFileWriter. See the following code example, which writes clustered data points to a file. Here is a blog post that describes this in great detail:
public static void writePointsToFile(List<Vector> points,
                                     String fileName,
                                     FileSystem fs,
                                     Configuration conf) throws IOException {
    Path path = new Path(fileName);
    SequenceFile.Writer writer = new SequenceFile.Writer(fs, conf,
            path, LongWritable.class, VectorWritable.class);
    long recNum = 0;
    VectorWritable vec = new VectorWritable();
    for (Vector point : points) {
        vec.set(point);
        writer.append(new LongWritable(recNum++), vec);
    }
    writer.close();
}


text:
Q: How to call the same function repeatedly? I want to call a function twice but not through the traditional way. A quick example of what I would be looking to do is below:
    var myfunc = {
        copy: function(message){
            console.log(message);
        }
    }

    myfunc.copy('hello').copy('world');

    // result 'hello'
    // result 'world'

Is this even possible?

A: Yes, but you should return the correct object:
var myfunc = {
    copy: function(message){
        console.log(message);
        return this;
    }
};
myfunc.copy('hello').copy('world');
// hello
// world

This technique is also known as Method chaining.

A: No, this will fail because .copy() doesn't return anything, so the second .copy() would throw an undefined error.
Try this:
var myfunc = {
    copy: function(message){
        console.log(message);
        return this;
    }
}

A: It's called method chaining. Here's a blog that talks about this that you should be able to read and use to answer your question.
Basically you will need to use return this; to return the current object so the next method can use it.
// define the class
var Kitten = function() {
  this.name = 'Garfield';
  this.color = 'brown';
  this.gender = 'male';
};

Kitten.prototype.setName = function(name) {
  this.name = name;
  return this;
};

Method chaining in JavaScript

A: You need to chain this, You can also look up to jquerys $.fn how they create method chaining simply return this as this object is your myFunc variable and is used again by the next function
var myfunc = {
   copy: function(message){
       console.log(message);
       return this;
   }
};
myfunc.copy('hello').copy('world');

A: As other answers have pointed out, you need to return this in order to be able to call the same or additional functions on the same object.
You can do this a bit more easily (?) via a higher-order function which we will call "chainify", which takes care of returning this for you:
function chainify(fn) {
  return function() {
    fn.apply(this, arguments);
    return this;
  };
}

You can chainify your object methods in various ways, but here's one:
var myfunc = {
  init: function() {
    this.copy = chainify(this.copy);
    return this;
  },

  copy: function(message){
      console.log(message);
  }
}.init();

This has the minor advantage that each and every method does not need to be cluttered with the return this at the end, and you don't run the risk of forgetting to do so.

A: This is known a Builder design pattern where in you cascade methods. Google it if it helps.


text:
Q: Angular 2 iframe to parent communication in my current project I have multiple Angular 2 applications which should be served by a portal application (also Angular 2). So the portal app has a header area with links to all underlying apps. When the user clicks on one app link, the corresponding angular 2 app gets loaded in an iframe of the portal body.

Now I develop a central authorization service. In the portal I have a service which holds the permissions of the current logged-in user. My question is: Is it possible to access angular 2 services / components of the parent (portal) within the individual apps (iframe)? It seemed to be possbile in angular 1 via scope

A: Hi really appreciate the solution given by @jazza1000 it helped me out.
Our problem was in the current (to date) version of angular cli there is a bug  that prevents the use of external JS files even with allowJs. We would be using jsplumb (external js) to represent some flow charts. (Actual issue on stack overflow)
So we decided to go with the approach of hosting the functionality that uses external JS in an additional angular 4 application. And the parent angular 5 application will bring in the angular 4 application with iFrame. So when the user would want to view the flowchart we would open angular4 application in iframe then once he is done he would click save in the angular 4 application that would save all his modification followed by sending the message to parent window that would close/hide the div with iframe.
Our parent application in angular 5 has the code
 @HostListener('window:message', ['$event'])
  onMessage(e) {
    debugger;
    if (e.origin != "http://localhost:4201") { // set your origin
      return false;
    }
    if (e.data.for == "user") {
      alert('here i am');
    }
  }

Our iFrame angular 4 application on save button has the code (we are starting the application with --port 4201)
window.parent.window.postMessage({"for":"user","data":"anything"}, 'http://localhost:4200')

A: I am looking at doing something similar at the moment (a portal application with sub apps in an iFrame)
You can communicate between your server and client (in either direction) by using window.postMessage to send data.
So for example on the server app:
var iframe = document.getElementById('useriframe');
    if (iframe == null) return;
    var iWindow = (<HTMLIFrameElement>iframe).contentWindow;

    iWindow.postMessage({"for":"user","data":"anything"}, 'http://localhost:4001');

and on the client app (hosted within the iFrame)
export class AppComponent {

@HostListener('window:message',['$event'])
onMessage(e)
{
if (e.origin!="http://localhost:4200")
  {
  return false;
  }
if (e.data.for=="user")
  {
  alert('here i am');
  }
}

Showing child frame routes in the parent
So, in my implementation we pass tokens and user information from the shell application to the child iFrame, and we pass routing information from the child applications back to the shell so that the url reflects the route selected in the child application.
In a child application you may have a route such as:

[userapp]/edituser/username

, and we wish to post it to the parent application and display the route like:

http://mywebsite/main/application/user#edituser/bob

Note that we use hashtag to mark a child route, and in your child applications you intercept every navigation event and post the new route via
export class MyRoutingComponent implements OnInit {
constructor(private router: Router) {
router.events.subscribe((event: Event)=>{
  if (event instanceof NavigationEnd){
        let url=(<NavigationEnd>event).url;
        if (url.length>1)//don't post message about base route '/'
          window.parent.postMessage({"for":"dashboard", "operation":"changeroute","route":url},'*')
  }

})
}

and then in the parent application parse the message and use it to update the location path displayed.
    url = url +'#' + route;
    this.location.go(url);


text:
Q: clone sharepoint enviroments? We are under process of clone on QA environments to new environments. machines and urls will changes. How we can configure these changes in central admin level in new environment?
Please advice me.

A: Short of buying a 3-rd party tool, your best bet is to do a backup-and-restore into the new environment. It's not easy to keep them in sync after that, so you'll want to develop and enforce some kind of workflow that requires the new stuff going through your qa env.  Here's a great article about using CA for backup-and-restore in various scenarios>
http://blah.winsmarts.com/2007-10-Backup_and_Restore_Strategies_in_MOSS_2007.aspx

A: I recommend going about it differently. You can put all your customizations into a SharePoint Solution in Visual Studio, setup a separate brand new SharePoint Server, then Deploy all your Customizations to the new Environment using WSP Installer / Deployment. If you try to clone an existing environment you will spend a lot of unnecessary time trying to reconfigure the old environment to work on the new Server, and it will be an ongoing recurring headache to try and keep them in sync that way.
If you setup your solution correctly, you should be able to include all your changes that way easily, which will then allow you to install updates to the second environment with one Power Shell Command and you are done!

A: I maintain pre-production and development environments that are as close to a mirror of production as possible.  With this setup, I use one forest per pre-production environment in order to be able to reuse hostnames for Web Applications.
http://sharepoint.nauplius.net/p/sharepoint-test-environments.html


text:
Q: Как обрабатывать динамические url в Angular? Есть адреса вида example.com/2015/04/20/,  example.com/2015/04/,  example.com/2015/ Как обрабатывать такие адреса в роутах? Т.е. необходимо что-то вроде (r'(\d{4}-\d{2}-\d{2})/?', DaysHandler) (как это делается в python фреймворках)?

A: Если для роутинга используете angular-ui-router https://github.com/angular-ui/ui-router , то так - в $stateProvider:
.state('something', {
                url: '/something/:year/:month/:day'

В контроллере вьюхи инжектим $stateParams, в котором параметры будут доступны по их именам.


text:
Q: get unique records between two fields from mysql in php I have a table where my private message are stored which I done with my friends.

I have table structure as shown in image
Suppose my logged user_id is 1, Now I want show his last five unique conversations with last message of each conversation.

A: Not very elegant but working:
SELECT m1.*
    FROM private_msgs m1 LEFT OUTER JOIN private_msgs m2
    ON (m1.message_from_uid=m2.message_from_uid AND m1.message_to_uid=m2.message_to_uid AND m1.message_time<m2.message_time)
WHERE m2.message_id IS NULL AND m1.message_from_uid=$uid
ORDER BY message_time DESC;

Add limit to 5 or whatever you want
EDIT. Sorry I didn't notice that UID can be as sender or receiver. Can you publish table with sample data for example here: http://sqlfiddle.com?
Anyway that should to the trick:
WHERE m2.message_id IS NULL AND (m1.message_from_uid=$uid OR m1.message_to_uid=$uid)

A: Here it is, long and ugly. You can replace temporary tables as subqueries in one big final query. Explanations are at the end.
CREATE TEMPORARY TABLE IF NOT EXISTS t1 AS
    (SELECT message_id, message_from_uid, message_to_uid, message_time
    FROM private_msgs
    WHERE message_from_uid=$UID)
 UNION
    (SELECT message_id, message_to_uid, message_from_uid, message_time
    FROM private_msgs
    WHERE message_to_uid=$UID);

CREATE TEMPORARY TABLE IF NOT EXISTS t2 AS SELECT * FROM t1;

SELECT m.*
    FROM (t1 LEFT OUTER JOIN t2
    ON (t1.message_from_uid=t2.message_from_uid AND t1.message_to_uid=t2.message_to_uid AND t1.message_time<t2.message_time))
JOIN private_msgs m ON t1.message_id=m.message_id
WHERE t2.message_id IS NULL AND t1.message_from_uid=$UID
ORDER BY t1.message_time DESC;

DROP TABLE IF EXISTS t1;
DROP TABLE IF EXISTS t2;

t1 temporary table takes all messages where $UID is a sender and union them with messages where $UID is receiver, but puts $UID as sender. In t1 doesn't matter who is sender/receiver. What does matter that these are conversations between $UID and someone else.
t2 is copy of t1, because in MySQL you can't join temporary table with itself.
And finally we do the query. We join t1 and t2, take only newest messages in every conversation and sort it from latest to oldest. As in t1 and t2 sender and receiver are mixed we do the last join with private_msg to get original data.
PS. Sorry for my english, I'm not native speaker.

A: Found among my old code:
    select m.*
        from private_messages m
        join user_table s ON m.sender_id = s.id
        join user_table r ON m.receiver_id = r.id
        join (select if(sender_id = $UID, receiver_id, sender_id) as user_id_other,
            max(posted_at) AS date_time_max from private_messages
                where (sender_id = $UID OR receiver_id = $UID)
                group by if(sender_id=$UID, receiver_id, sender_id)
                ) AS t
        on if(m.sender_id = $UID, m.receiver_id, m.sender_id) = user_id_other
        AND m.posted_at=date_time_max
    where m.sender_id = $UID OR m.receiver_id = $UID
    order by m.posted_at desc

Not responsible for result, but this can help. By itself variables must be replaced, I did not modify the code very much, as you can see. But this piece of... code... worked.
In your case smths like:
select m.*
    from YOUR_MESSAGES_TABLE m
    --- OPTIONAL: join YOUR_USER_TABLE s ON m.message_from_uid = s.id
    --- OPTIONAL: join YOUR_USER_TABLE r ON m.message_to_uid = r.id
    join (select if(message_from_uid = $YOUR_USER_ID, message_to_uid, message_from_uid) as user_id_other,
        max(message_time) AS date_time_max from YOUR_MESSAGES_TABLE
            where (message_from_uid = $YOUR_USER_ID OR message_to_uid = $YOUR_USER_ID)
            group by if(message_from_uid=$YOUR_USER_ID, message_to_uid, message_from_uid)
            ) AS t
    on if(m.message_from_uid = $UID, m.message_to_uid, m.message_from_uid) = user_id_other
AND m.message_time=date_time_max
where m.message_from_uid = $UID OR m.message_to_uid = $UID
order by m.message_time desc limit 5

Test: http://sqlfiddle.com/#!9/f66fd8/4


text:
Q: Can a class specialize a template class and inherit from it at the same time? Let's say I have a template base class that looks like this:
template <typename T>
class Base
{
    public:
         virtual void somefunc() =0;
};

I want to make a concrete derived class, for which of course I would need to implement somefunc. I could do it like this:
class Derived : public Base<int>
{
    public:
        virtual void somefunc() { std::cout << "hello\n";}
        void otherfunc() {std::cout << "Hello\n";}
};

But this creates an annoyance when I try to expose these things to Python via Boost Python. Even though I've only defined two classes here, Base and Derived, I need to explicitly expose Base<int> to Python, even though I'll never instantiate it. What I'm wondering is, is there some way I can inherit from the template class at the same time that I instantiate it? Essentially, can I treat Base as a derived class of Base?

A: You can make a type that represents Base<int> using a typedef
typedef BaseInt Base<Int>;

You should be able to use BaseInt in however you are exporting your information to Boost Python.

A: You can just specialize the template if you don't need the interface class.
// No definition required
template <typename T>
class Base;

// Specialization
template <>
class Base<int> {
    public:
        virtual void somefunc();
        void otherfunc();
}


text:
Q: how can i translate c# funcion to excel I am new to functions in excel (I am c# developer).
I got a function that my boss told me to write and I have no clue in excel(VBA?).
This is the question:
1 xlsx file, with 2 tabs:

Each tab contains a table with 3 columns:
Name, id, yesOrNo(string)

*

*yesOrNo(string) column in "a" tab is empty (at first)
I need to fill it with data from the table in "b" tab

Tab "a":

Tab "b":

•   In Each table there can be lot of rows...
The function need to do that(I'll write an pseudo code in c#):
•   a=tab a
•   b= tab b
•   a.name = tab "a" column "name"

function ab(){
    For(i=2; I < a.name.length; i++){
        For(j=2; j < a.name.length; j++){
            if( b.name[j].contains(a.name[i]) ){
                if(a.id[i] == b.id[j]){
                    b.yesOrNo(string)[i] = a.yesOrNo(string)[j];
                }
            }
       }
    }
}

So in the end, table in tab a will look like this:

Is there any way to convert c# code o vba?
Where should I actually  write the code?

A: I think this is what you want.
Option Explicit

Sub Test()

    Dim lastrowA As Long
    Dim lastrowB As Long
    Dim rowA As Long
    Dim rowB As Long
    Dim nameA As String
    Dim nameB As String

    ' Get last row on sheet A
    lastrowA = Worksheets("A").Cells.Find("*", SearchOrder:=xlByRows, searchdirection:=xlPrevious).row

    ' Get last row on sheet B
    lastrowB = Worksheets("B").Cells.Find("*", SearchOrder:=xlByRows, searchdirection:=xlPrevious).row

    ' For each row on sheet A
    For rowA = 2 To lastrowA

        ' Get name (A)
        nameA = Worksheets("A").Cells(rowA, 1).Value

        ' For each row on sheet B
        For rowB = 2 To lastrowB

            ' get name (B)
            nameB = Worksheets("B").Cells(rowB, 1).Value

            ' if name (B) starts with name (A)...
            If Mid(nameB, 1, Len(nameA)) = nameA Then

                ' Update yes or no
                Worksheets("A").Cells(rowA, 3).Value = Worksheets("B").Cells(rowB, 3).Value

                ' Exit inner for loop
                Exit For

            End If

        Next rowB

    Next rowA

End Sub

Where should you write the code? (1) Alt+F11 to open the VBA editor. (2) In the project explorer, right click, Insert Module. (3) Paste the code into the new module.
You can run it by (1) Select developer tab, (2) click macros button, (3) select the macro and click Run.

A: This is how I eventually solved this:

*

*click on the column that you want the result to appear

*write this formula =XLOOKUP(B1,'b'!B:B,'b'!C:C)
Explanation:
xlookup( the value you eant to search, where do you want to search, what resuls to show )

*

*the answer based ov the images i adde added in the question body.

*be sure that you have XLOOKUP installed, I downloaded it according to this video:
youtube video
** I am not sure why it wasn't installed already, I am using office 2019..


text:
Q: Rails: destroying multiple user-to-user associations I have a model called Block that has a blocker_id (a user_id) and a blocked_user_id field (also a user_id). The Block model lets one user block another. When one user blocks another, I want it to destroy the Relationship between them using a before_save method for the Block class. The Relationship table has a follower_id and a followed_id.
This is where things get tricky. I know I could achieve this goal by using multiple return if Relationship.xyz.nil? statements and then using multiple Relationship.find_by(follower_id:  , followed_id:  ).destroy statements, but this gets to be way over complicated because each blocker and blocked_user could be either the follower and followed id, both, or neither. Is there any easier way to do this?
Here's my models for reference: (also the Block class has a blocked_post field, which I'm having no trouble with)
class Block < ActiveRecord::Base

validates :blocker_id, presence: true
validates :blocked_user_id, uniqueness: {scope: :blocker_id}, allow_nil: true
validates :blocked_post_id, uniqueness: {scope: :blocker_id}, allow_nil: true
validate  :blocked_user_or_post
after_validation :validate_block
before_save :destroy_blocked_relationships

belongs_to(
    :blocker,
    class_name: "User"
    )

has_one(
    :blocked_user,
    class_name: "User"
    )

has_one(
    :blocked_post,
    class_name: "Post"
    )

private

def blocked_user_or_post
  blocked_user_id.blank? ^ blocked_post_id.blank?
end

def validate_block
  if blocked_user_id.present?
    !(blocker_id == blocked_user_id)
  elsif blocked_post_id.present?
    blocked_post = Post.find_by(id: self.blocked_post_id).user_id
    !(blocker_id == blocked_post)
  else
    false
  end
end

def destroy_blocked_relationships
  #my over-complex code was here
end

end

relationship.rb:
class Relationship < ActiveRecord::Base

validates :follower_id, :followed_id, presence: {message: 'Need an eligible follower and followee id'}
validates :followed_id, uniqueness: { scope: :follower_id}

belongs_to(
   :follower,
   class_name: "User"
   )

belongs_to(
   :followed,
   class_name: "User"
   )
end

If there is any way to do this that doesn't require massive amounts of code, I'd really like to know. Thanks in advance.

A: I'm not sure of your exact use case, but my thoughts about a system where people can follow each other, it seems that the blocker would always be the person being followed.  If this is the case, here's an implementation:
def destroy_blocked_relationships
  Relationship.where(follower_id:blocked_user_id, followed_id:blocker_id).destroy_all
  true
end

If it makes sense to also block someone from being being followed, you could add this:
Relationship.where(follower_id:blocker_id, followed_id:blocked_user_id).destory_all

Here it is all together, and stopping the save of the Block if there are no relationships:
before_save :destroy_blocked_relationships

def destroy_blocked_relationships
  relationships = Relationship.where("(follower_id = ? AND followed_id = ?) OR (followed_id = ? AND follower_id = ? )", blocked_user_id, blocker_id, blocked_user_id, blocker_id)
  relationships.destroy_all
  relationships.present?  # Omit this line if the save should continue regardless
end

A: here is my understanding:

*

*a Block is a relationship between two users, OR between a User and a Post

*when a Block is created between user A and Post X, an implicit block is also created between User A and User B, where User B is Post X's author

Consider making two models, BlockedPost and BlockedUser. Then, make two #make methods. This makes all the related logic easier to reason about.
# class BlockedPost
def make(user, post)
  transaction do
    create!(user: user, post: post)
    BlockedUser.make(user, post.author)
  end
end

# class BlockedUser
def make(user, blocked_user)
  transaction do
    create!(user: user, blocked_user: blocked_user)
    Relationship.where(follower: user, following: blocked_user).destroy_all
    Relationship.where(follower: blocked_user, following: user).destroy_all
  end
end


text:
Q: Git lab showing "There are no commits yet" after my git reset? I have three branches in my GitLab

*

*Main

*ppp7

*ppp7-master

ppp7---> ppp7-master---> main

every day I'm pushing my new code into ppp7 branch.if code is running fine in ppp7 branch, i create new merge request to ppp7-master branch.until here all three branches are have same code only. whats happen yesterday i pushed a wrong code into ppp7 branch.after i merge that ppp7 code into other two branches.but that code failing on all environment. so here i reset ppp7 branch code to previous commit using below comments.
$ git reset --hard 725bb8011bbb2535053feffd441f01d3059fea56
HEAD is now at 725bb80 Update emp.sql
$ git add .

$ git commit -m "where condition removed"
On branch ppp7
Your branch is behind 'origin/ppp7' by 1 commit, and can be fast-forwarded.
  (use "git pull" to update your local branch)

nothing to commit, working tree clean

$ git push -f origin ppp7
Total 0 (delta 0), reused 0 (delta 0), pack-reused 0
remote:
remote: To create a merge request for ppp7, visit:

 + 2cb0310...725bb80 ppp7 -> ppp7 (forced update)

now my ppp7 branch have working code, other two branches have wrong code. so i'm creating new merge request to ppp7-master. but I'm cant merge gitlab showing "There are no commits yet."
There are no commits yet
why I'm cant merge both branches have different code.also when i compare both branches its showing  "Showing with 0 additions and 0 deletions". how its possible both branches have different code.

*

*when comparing ppp7 branch with
ppp7-master

*when i comparing ppp7-master with
ppp7
I'm needed to merge new reset code into ppp7-master and why this error showing.

A: You cannot use Pull/Merge Request functionality to update a branch with a reset. Pull/Merge Requests can only add new commits to a branch; you can't remove commits. Instead you have two options:

*

*Force push all of the branches that need to be reset.

*Use git revert instead of git reset. In Git, "revert" will create a new commit that effectively undoes the changes of a specific commit (or multiple commits if undoing a merge commit).

A:
Below one working for me.

git checkout 725bb8 .
git commit -m "rollback to 725bb8 "
git push origin ppp7

now my working code with new commit.Now i able to create a merge request with ppp7-master.
when i use this comment

*

*no need to use force push

*no need for reset and revert comment

A: Note: the right command nowadays would be git restore
As its name suggests, git restore... restores files (in the working tree and/or the index), and opposed to git switch, which switches branches. (While the old git checkout can do both and is therefore confusing)
In your case:
git switch ppp7
git restore --source=725bb8 --staged --worktree -- .

Or, abbreviated form:
git restore -s 725bb8 -SW

Then you can commit, push, and make your pull requests.